From c9f48ca50407c8e16bfedac27dfcc819fe16f26a Mon Sep 17 00:00:00 2001 From: Florian Hines Date: Tue, 8 Sep 2026 12:07:55 -0500 Subject: [PATCH 1/5] feat(auth): extract remaining token families --- .../hooks/use-kilo-chat-token.test.ts | 22 +- .../src/components/login-screen.test.ts | 16 +- apps/mobile/src/components/login-screen.tsx | 58 +- .../quick-chat-screen.mounted.test.tsx | 5 +- .../components/quick-chat/use-quick-chat.ts | 4 +- .../mobile/src/lib/auth/auth-context.test.tsx | 556 +- apps/mobile/src/lib/auth/auth-context.tsx | 319 +- apps/mobile/src/lib/auth/auth-user-id.ts | 30 + apps/mobile/src/lib/auth/credentials.ts | 196 +- .../src/lib/auth/device-auth-poll.test.ts | 42 + apps/mobile/src/lib/auth/device-auth-poll.ts | 7 +- apps/mobile/src/lib/auth/device-auth-state.ts | 30 +- .../src/lib/auth/exchange-legacy-token.ts | 55 +- .../src/lib/auth/native-auth-contract.ts | 72 +- .../auth/native-credential-lifecycle.test.ts | 204 + apps/mobile/src/lib/auth/token-owner.test.ts | 66 +- apps/mobile/src/lib/auth/token-owner.ts | 75 +- .../mobile/src/lib/auth/use-auth-bootstrap.ts | 133 + .../use-device-approval-persistence.test.ts | 192 + .../auth/use-device-approval-persistence.ts | 102 + .../src/lib/auth/use-device-auth.test.ts | 2 + .../src/lib/auth/use-native-auth.test.ts | 86 +- apps/mobile/src/lib/auth/use-native-auth.ts | 91 +- .../lib/hooks/use-available-models.test.ts | 50 +- .../src/lib/hooks/use-available-models.ts | 11 +- apps/mobile/src/lib/storage-keys.ts | 1 + apps/mobile/src/lib/trpc.test.ts | 7 +- .../api/auth/native/exchange/route.test.ts | 47 +- .../src/app/api/auth/native/exchange/route.ts | 43 +- .../app/api/auth/native/refresh/route.test.ts | 37 + .../src/app/api/auth/native/refresh/route.ts | 26 +- .../route.credentials.integration.test.ts | 236 + .../app/api/auth/native/token/route.test.ts | 67 + .../src/app/api/auth/native/token/route.ts | 135 +- .../src/app/api/auth/resource-token/route.ts | 53 + .../app/api/device-auth/token/route.test.ts | 52 + .../src/app/api/device-auth/token/route.ts | 30 +- apps/web/src/app/api/gastown/token/route.ts | 51 +- .../token/route.test.ts | 218 +- .../auto-routing-benchmark/token/route.ts | 101 +- apps/web/src/app/api/kilo-chat/token/route.ts | 4 +- .../[id]/user-tokens/route.test.ts | 63 + .../organizations/[id]/user-tokens/route.ts | 67 +- apps/web/src/app/api/wasteland/token/route.ts | 51 +- apps/web/src/lib/auth/device-sessions.test.ts | 103 +- apps/web/src/lib/auth/device-sessions.ts | 48 +- .../auth/native-access-credentials.test.ts | 108 + .../src/lib/auth/native-access-credentials.ts | 68 + ...tive-credential-routes.integration.test.ts | 272 + apps/web/src/lib/device-auth/device-auth.ts | 28 +- apps/web/src/lib/kilo-chat/token.test.ts | 141 + apps/web/src/lib/kilo-chat/token.ts | 66 +- apps/web/src/lib/wasteland/server-resolve.ts | 20 +- apps/web/src/routers/kilo-chat-router.ts | 4 +- docs/token-issuance-policy.md | 101 + packages/app-shared/package.json | 3 +- packages/app-shared/src/native-auth.test.ts | 94 + packages/app-shared/src/native-auth.ts | 73 + pnpm-lock.yaml | 3 + services/gastown/src/dos/Town.do.ts | 193 +- services/gastown/src/dos/town/config.ts | 6 +- .../src/dos/town/legacy-token-renewal.test.ts | 132 + .../src/dos/town/legacy-token-renewal.ts | 128 + .../dos/town/runtime-authorization.test.ts | 333 + .../src/dos/town/runtime-authorization.ts | 285 + .../dos/town/unattended-token-renewal.test.ts | 369 + .../src/dos/town/unattended-token-renewal.ts | 129 + services/gastown/src/gastown.worker.ts | 8 + .../src/handlers/org-towns.handler.test.ts | 133 + .../gastown/src/handlers/org-towns.handler.ts | 83 +- .../town-runtime-authorization.handler.ts | 61 + .../gastown/src/handlers/towns.handler.ts | 27 + .../middleware/org-auth.middleware.test.ts | 86 + .../src/middleware/org-auth.middleware.ts | 33 +- .../middleware/town-auth.middleware.test.ts | 67 + .../src/middleware/town-auth.middleware.ts | 38 +- services/gastown/src/trpc/init.ts | 2 + services/gastown/src/trpc/router.ts | 395 +- .../trpc/town-authorization.router.test.ts | 409 + .../src/types.runtime-authorization.test.ts | 15 + services/gastown/src/types.ts | 125 +- .../src/util/town-authorization.util.test.ts | 165 + .../src/util/town-authorization.util.ts | 140 + .../integration/town-private-identity.test.ts | 79 + services/gastown/vitest.workers.config.ts | 15 + .../src/callbacks.lifecycle.test.ts | 20 +- .../security-auto-analysis/src/callbacks.ts | 11 +- .../security-auto-analysis/src/db/queries.ts | 18 +- .../security-auto-analysis/src/launch.test.ts | 46 +- services/security-auto-analysis/src/launch.ts | 29 +- .../src/manual-analysis.ts | 8 +- .../security-auto-analysis/src/remediation.ts | 16 +- .../src/session-result.ts | 7 +- .../security-auto-analysis/src/token.test.ts | 99 + services/security-auto-analysis/src/token.ts | 84 +- .../worker-configuration.d.ts | 1 + .../security-auto-analysis/wrangler.jsonc | 2 + services/webhook-agent-ingest/package.json | 3 +- .../webhook-agent-ingest/src/db/queries.ts | 23 +- .../src/queue-consumer.test.ts | 51 + .../src/queue-consumer.ts | 18 +- .../src/routes/callbacks.ts | 3 +- .../services/token-minting-service.test.ts | 137 + .../src/services/token-minting-service.ts | 45 +- .../webhook-agent-ingest/src/util/auth.ts | 3 +- .../webhook-agent-ingest/src/util/secret.ts | 3 + services/webhook-agent-ingest/tsconfig.json | 1 + .../worker-configuration.d.ts | 12029 +--------------- services/webhook-agent-ingest/wrangler.jsonc | 3 +- 109 files changed, 7880 insertions(+), 13081 deletions(-) create mode 100644 apps/mobile/src/lib/auth/auth-user-id.ts create mode 100644 apps/mobile/src/lib/auth/native-credential-lifecycle.test.ts create mode 100644 apps/mobile/src/lib/auth/use-auth-bootstrap.ts create mode 100644 apps/mobile/src/lib/auth/use-device-approval-persistence.test.ts create mode 100644 apps/mobile/src/lib/auth/use-device-approval-persistence.ts create mode 100644 apps/web/src/app/api/auth/native/token/route.credentials.integration.test.ts create mode 100644 apps/web/src/app/api/auth/resource-token/route.ts create mode 100644 apps/web/src/app/api/organizations/[id]/user-tokens/route.test.ts create mode 100644 apps/web/src/lib/auth/native-access-credentials.test.ts create mode 100644 apps/web/src/lib/auth/native-access-credentials.ts create mode 100644 apps/web/src/lib/auth/native-credential-routes.integration.test.ts create mode 100644 apps/web/src/lib/kilo-chat/token.test.ts create mode 100644 packages/app-shared/src/native-auth.test.ts create mode 100644 packages/app-shared/src/native-auth.ts create mode 100644 services/gastown/src/dos/town/legacy-token-renewal.test.ts create mode 100644 services/gastown/src/dos/town/legacy-token-renewal.ts create mode 100644 services/gastown/src/dos/town/runtime-authorization.test.ts create mode 100644 services/gastown/src/dos/town/runtime-authorization.ts create mode 100644 services/gastown/src/dos/town/unattended-token-renewal.test.ts create mode 100644 services/gastown/src/dos/town/unattended-token-renewal.ts create mode 100644 services/gastown/src/handlers/org-towns.handler.test.ts create mode 100644 services/gastown/src/handlers/town-runtime-authorization.handler.ts create mode 100644 services/gastown/src/middleware/org-auth.middleware.test.ts create mode 100644 services/gastown/src/middleware/town-auth.middleware.test.ts create mode 100644 services/gastown/src/trpc/town-authorization.router.test.ts create mode 100644 services/gastown/src/types.runtime-authorization.test.ts create mode 100644 services/gastown/src/util/town-authorization.util.test.ts create mode 100644 services/gastown/src/util/town-authorization.util.ts create mode 100644 services/gastown/test/integration/town-private-identity.test.ts create mode 100644 services/security-auto-analysis/src/token.test.ts create mode 100644 services/webhook-agent-ingest/src/services/token-minting-service.test.ts create mode 100644 services/webhook-agent-ingest/src/util/secret.ts diff --git a/apps/mobile/src/components/kilo-chat/hooks/use-kilo-chat-token.test.ts b/apps/mobile/src/components/kilo-chat/hooks/use-kilo-chat-token.test.ts index 5166dc5be1..a2f64802ea 100644 --- a/apps/mobile/src/components/kilo-chat/hooks/use-kilo-chat-token.test.ts +++ b/apps/mobile/src/components/kilo-chat/hooks/use-kilo-chat-token.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ - getItemAsync: vi.fn<() => Promise>(), + getItemAsync: vi.fn<(key: string) => Promise>(), getTokenQuery: vi.fn<() => Promise<{ token: string; userId: string; expiresAt: string }>>(), })); @@ -13,8 +13,11 @@ vi.mock('expo-secure-store', () => ({ getItemAsync: mocks.getItemAsync, })); +vi.mock('@/lib/config', () => ({ E2E_SECURE_STORE_FAULT_MS: 0 })); + vi.mock('@/lib/storage-keys', () => ({ AUTH_TOKEN_KEY: 'auth-token', + NATIVE_CREDENTIAL_BUNDLE_KEY: 'native-credential-bundle', })); vi.mock('@/lib/trpc', () => ({ @@ -30,6 +33,8 @@ vi.mock('@/lib/trpc', () => ({ describe('useKiloChatTokenResponseGetter', () => { beforeEach(async () => { vi.clearAllMocks(); + const { clearActiveToken } = await import('@/lib/auth/token-owner'); + clearActiveToken(); const { clearKiloChatTokenCache } = await import('./use-kilo-chat-token'); clearKiloChatTokenCache(); }); @@ -42,7 +47,10 @@ describe('useKiloChatTokenResponseGetter', () => { }; const seenUserIds: string[] = []; - mocks.getItemAsync.mockResolvedValue('auth-token-1'); + mocks.getItemAsync.mockImplementation(async key => { + await Promise.resolve(); + return key === 'auth-token' ? 'auth-token-1' : null; + }); mocks.getTokenQuery.mockRejectedValueOnce(new Error('network down')); mocks.getTokenQuery.mockResolvedValueOnce(response); @@ -69,7 +77,10 @@ describe('useKiloChatTokenResponseGetter', () => { expiresAt: '2099-03-13 14:30:00+00', }; - mocks.getItemAsync.mockResolvedValue('auth-token-2'); + mocks.getItemAsync.mockImplementation(async key => { + await Promise.resolve(); + return key === 'auth-token' ? 'auth-token-2' : null; + }); mocks.getTokenQuery.mockResolvedValueOnce(response); const { useKiloChatTokenResponseGetter } = await import('./use-kilo-chat-token'); @@ -98,7 +109,10 @@ describe('useKiloChatTokenResponseGetter', () => { expiresAt: '2099-03-13 14:30:00+00', }; - mocks.getItemAsync.mockResolvedValue('auth-token-3'); + mocks.getItemAsync.mockImplementation(async key => { + await Promise.resolve(); + return key === 'auth-token' ? 'auth-token-3' : null; + }); mocks.getTokenQuery.mockResolvedValueOnce(firstResponse); mocks.getTokenQuery.mockResolvedValueOnce(secondResponse); diff --git a/apps/mobile/src/components/login-screen.test.ts b/apps/mobile/src/components/login-screen.test.ts index 48d8a30e13..ee2bccbff4 100644 --- a/apps/mobile/src/components/login-screen.test.ts +++ b/apps/mobile/src/components/login-screen.test.ts @@ -23,10 +23,8 @@ import { errorMessage } from './login-screen-state'; const deviceAuth = vi.hoisted(() => ({ status: 'idle' as string, - token: undefined as string | undefined, code: undefined as string | undefined, - refreshToken: undefined as string | undefined, - expiresIn: undefined as number | undefined, + credentials: undefined, error: undefined as string | undefined, verificationUrl: undefined as string | undefined, resumed: false, @@ -74,10 +72,8 @@ vi.mock('@/lib/auth/auth-context', () => ({ vi.mock('@/lib/auth/use-device-auth', () => ({ useDeviceAuth: () => ({ status: deviceAuth.status, - token: deviceAuth.token, code: deviceAuth.code, - refreshToken: deviceAuth.refreshToken, - expiresIn: deviceAuth.expiresIn, + credentials: deviceAuth.credentials, error: deviceAuth.error, verificationUrl: deviceAuth.verificationUrl, resumed: deviceAuth.resumed, @@ -270,10 +266,8 @@ describe('login-screen language globe', () => { beforeEach(() => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; deviceAuth.status = 'idle'; - deviceAuth.token = undefined; deviceAuth.code = undefined; - deviceAuth.refreshToken = undefined; - deviceAuth.expiresIn = undefined; + deviceAuth.credentials = undefined; deviceAuth.error = undefined; deviceAuth.verificationUrl = undefined; deviceAuth.resumed = false; @@ -350,10 +344,8 @@ describe('login-screen idle skeleton', () => { beforeEach(() => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; deviceAuth.status = 'idle'; - deviceAuth.token = undefined; deviceAuth.code = undefined; - deviceAuth.refreshToken = undefined; - deviceAuth.expiresIn = undefined; + deviceAuth.credentials = undefined; deviceAuth.error = undefined; deviceAuth.verificationUrl = undefined; deviceAuth.resumed = false; diff --git a/apps/mobile/src/components/login-screen.tsx b/apps/mobile/src/components/login-screen.tsx index 10247c17c2..7c9a31e8bb 100644 --- a/apps/mobile/src/components/login-screen.tsx +++ b/apps/mobile/src/components/login-screen.tsx @@ -1,15 +1,13 @@ -/* eslint-disable max-lines -- The login screen keeps its device-auth branches, keyboard padding, and language picker together. */ import * as Clipboard from 'expo-clipboard'; import { type Href, useRouter } from 'expo-router'; import { ExternalLink, Globe } from '@/components/ui/icons'; -import { useCallback, useEffect, useState } from 'react'; +import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { AppState, I18nManager, Keyboard, KeyboardAvoidingView, - type KeyboardEvent, Platform, Pressable, ScrollView, @@ -33,10 +31,10 @@ import { Skeleton } from '@/components/ui/skeleton'; import { Text } from '@/components/ui/text'; import { announcingToast } from '@/lib/a11y/announcing-toast'; import { useAuth } from '@/lib/auth/auth-context'; +import { useDeviceApprovalPersistence } from '@/lib/auth/use-device-approval-persistence'; import { useDeviceAuth } from '@/lib/auth/use-device-auth'; import { useThemeColors } from '@/lib/hooks/use-theme-colors'; import { - clearLoginDrafts, clearPersistedLoginDrafts, persistLoginDrafts, restoreLoginDrafts, @@ -44,30 +42,14 @@ import { } from '@/lib/login-draft'; import { setLanguagePickerBridge } from '@/lib/picker-bridge'; -function keyboardHeightFromEvent(event: KeyboardEvent): number { - return event.endCoordinates.height; -} - export function LoginScreen() { const { sessionEnded, signIn } = useAuth(); const router = useRouter(); - const { - status, - token, - code, - refreshToken, - expiresIn, - error, - verificationUrl, - resumed, - start, - cancel, - openBrowser, - } = useDeviceAuth(); + const { status, code, credentials, error, verificationUrl, resumed, start, cancel, openBrowser } = + useDeviceAuth(); const colors = useThemeColors(); const insets = useSafeAreaInsets(); const { t } = useTranslation(); - const [persistError, setPersistError] = useState(undefined); const [androidKeyboardHeight, setAndroidKeyboardHeight] = useState(0); const [authFormBusy, setAuthFormBusy] = useState(false); const [draft, setDraft] = useState<{ @@ -75,18 +57,12 @@ export function LoginScreen() { ssoRecovery: SsoRecoveryDraft | null; } | null>(null); - const persistToken = useCallback( - async (tokenValue: string, refreshTokenValue?: string, expiresInValue?: number) => { - setPersistError(undefined); - try { - await signIn(tokenValue, refreshTokenValue, expiresInValue); - clearLoginDrafts(); - } catch { - setPersistError(t('login.couldNotCompleteSignIn')); - } - }, - [signIn, t] - ); + const { persistError, isPersisting, persistToken } = useDeviceApprovalPersistence({ + status, + credentials, + signIn, + couldNotCompleteSignIn: t('login.couldNotCompleteSignIn'), + }); useEffect(() => { let cancelled = false; @@ -116,13 +92,6 @@ export function LoginScreen() { } }, [sessionEnded, t]); - useEffect(() => { - if (status === 'approved' && token) { - void persistToken(token, refreshToken, expiresIn); - } - // eslint-disable-next-line react-hooks/exhaustive-deps -- persistToken is stable except for signIn identity; only re-run on a newly approved token - }, [status, token]); - // Android shell keyboard pad: under API 35+ EDGE_TO_EDGE_ENFORCED the window // never resizes for the IME, so KeyboardAvoidingView is inert. keyboardDidShow // still fires with real heights; consume them here (r0b: zero layout shift for @@ -144,7 +113,7 @@ export function LoginScreen() { currentPadding: current, event: { type: 'keyboard-visible', - keyboardHeight: keyboardHeightFromEvent(event), + keyboardHeight: event.endCoordinates.height, }, }) ); @@ -181,11 +150,12 @@ export function LoginScreen() { {persistError} diff --git a/apps/mobile/src/components/quick-chat/quick-chat-screen.mounted.test.tsx b/apps/mobile/src/components/quick-chat/quick-chat-screen.mounted.test.tsx index 9fc89ac0b2..e1c0d462c3 100644 --- a/apps/mobile/src/components/quick-chat/quick-chat-screen.mounted.test.tsx +++ b/apps/mobile/src/components/quick-chat/quick-chat-screen.mounted.test.tsx @@ -116,9 +116,8 @@ vi.mock('@/lib/utils', () => ({ vi.mock('@/lib/auth/auth-context', () => ({ useAuth: () => ({ authEpoch: authEpoch.value, token: 'token' }), })); -vi.mock('@/lib/auth/token-owner', () => ({ - getAuthTokenForRequest: () => 'token-1', -})); +vi.mock('@/lib/auth/token-owner', () => ({})); +vi.mock('@/lib/auth/credentials', () => ({ getGatewayAuthTokenForRequest: () => 'token-1' })); vi.mock('@/lib/organization-context', () => ({ useOrganization: () => ({ organizationId: organizationId.value, diff --git a/apps/mobile/src/components/quick-chat/use-quick-chat.ts b/apps/mobile/src/components/quick-chat/use-quick-chat.ts index e7f323ad4f..1335841f3b 100644 --- a/apps/mobile/src/components/quick-chat/use-quick-chat.ts +++ b/apps/mobile/src/components/quick-chat/use-quick-chat.ts @@ -6,7 +6,7 @@ import { ulid } from 'ulid'; import { i18n } from '@/i18n'; import { useAuth } from '@/lib/auth/auth-context'; -import { getAuthTokenForRequest } from '@/lib/auth/token-owner'; +import { getGatewayAuthTokenForRequest } from '@/lib/auth/credentials'; import { useOrganization } from '@/lib/organization-context'; import { trpcClient, useTRPC } from '@/lib/trpc'; @@ -266,7 +266,7 @@ export function useQuickChat(model: string) { void (async () => { try { - const authToken = await getAuthTokenForRequest(); + const authToken = await getGatewayAuthTokenForRequest(); if (abortRef.current !== controller) { return; } diff --git a/apps/mobile/src/lib/auth/auth-context.test.tsx b/apps/mobile/src/lib/auth/auth-context.test.tsx index dda160f0e3..69b1c3eff5 100644 --- a/apps/mobile/src/lib/auth/auth-context.test.tsx +++ b/apps/mobile/src/lib/auth/auth-context.test.tsx @@ -2,6 +2,7 @@ /* oxlint-disable typescript-eslint/no-deprecated -- react-test-renderer is the DOM-free renderer for RN trees under vitest (node env, no jsdom) */ /* oxlint-disable @typescript-eslint/no-unsafe-call @typescript-eslint/no-unsafe-member-access */ /* eslint-disable max-lines -- one cohesive auth-context suite: sign-out teardown ordering and stale sign-in fencing share the provider mount and the SecureStore mock */ +import { type NativeTokenPair } from '@kilocode/app-shared/native-auth'; import { createElement } from 'react'; import TestRenderer, { act } from 'react-test-renderer'; import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'; @@ -21,29 +22,39 @@ vi.setConfig({ testTimeout: 30_000 }); const hoisted = vi.hoisted(() => { const callOrder: string[] = []; + const secureStoreValues = new Map(); const secureStore = { - getItem: vi.fn().mockReturnValue(null), - getItemAsync: vi.fn().mockResolvedValue(null), - setItem: vi.fn().mockReturnValue(undefined), - setItemAsync: vi.fn().mockResolvedValue(undefined), - // eslint-disable-next-line require-await -- mock returning a resolved promise + getItem: vi.fn((key: string) => secureStoreValues.get(key) ?? null), + getItemAsync: vi.fn(async (key: string) => { + await Promise.resolve(); + return secureStoreValues.get(key) ?? null; + }), + setItem: vi.fn((key: string, value: string) => { + secureStoreValues.set(key, value); + }), + setItemAsync: vi.fn(async (key: string, value: string) => { + await Promise.resolve(); + secureStoreValues.set(key, value); + }), deleteItemAsync: vi.fn().mockImplementation(async (_key: string) => { + await Promise.resolve(); // Track the call in callOrder for ordering checks. callOrder.push('SecureStore.deleteItemAsync'); + secureStoreValues.delete(_key); }), }; const posthog = { - // eslint-disable-next-line require-await -- mock returning a resolved promise discardPostHog: vi.fn().mockImplementation(async () => { + await Promise.resolve(); callOrder.push('discardPostHog'); }), captureEvent: vi.fn().mockImplementation(() => { callOrder.push('captureEvent'); }), - // eslint-disable-next-line require-await -- mock returning a resolved promise flushLastPostHogEvent: vi.fn().mockImplementation(async () => { + await Promise.resolve(); callOrder.push('flushLastPostHogEvent'); }), }; @@ -95,6 +106,7 @@ const hoisted = vi.hoisted(() => { return { callOrder, + secureStoreValues, secureStore, posthog, appsflyer, @@ -305,6 +317,7 @@ vi.mock('@/lib/storage-keys', () => ({ PICKER_LAUNCH_CONTEXT_KEY: 'picker-launch-context', REFRESH_TOKEN_KEY: 'refresh-token', LIVE_SESSION_FILTERS_KEY: 'live-session-filters', + NATIVE_CREDENTIAL_BUNDLE_KEY: 'native-credential-bundle', SESSION_FILTERS_KEY: 'session-filters', TOKEN_EXPIRES_AT_KEY: 'token-expires-at', })); @@ -331,7 +344,7 @@ type AuthContextValue = { isSigningOut: boolean; restoreFailed: boolean; retryRestore: () => void; - signIn: (token: string) => Promise; + signIn: (pair: NativeTokenPair) => Promise; signOut: (ended?: boolean) => Promise; }; @@ -345,6 +358,17 @@ function makeToken(payload: Record): string { return `${base64url('{"alg":"none"}')}.${base64url(JSON.stringify(payload))}.signature`; } +function tokenPair(token: string): NativeTokenPair { + return { token }; +} + +function useSecureStoreMap(): void { + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + await Promise.resolve(); + return hoisted.secureStoreValues.get(key) ?? null; + }); +} + /** Load the auth-context module from a fresh module registry so * module-level state (preloadedToken) is clean. Returns the module * and a helper to extract the context value from a mounted tree. */ @@ -436,7 +460,8 @@ describe('sign-out teardown ordering', () => { beforeEach(() => { vi.clearAllMocks(); hoisted.callOrder.length = 0; - hoisted.secureStore.getItemAsync.mockResolvedValue(null); + hoisted.secureStoreValues.clear(); + useSecureStoreMap(); }); it('orders capture, cleanup, flush, clearTelemetryDecision, then Sentry.setUser', async () => { @@ -584,7 +609,7 @@ describe('sign-out teardown ordering', () => { const { ctx, unmount } = await mountAndGetContext(); await act(async () => { - await ctx.signIn(makeToken({ kiloUserId: 'user-1' })); + await ctx.signIn(tokenPair(makeToken({ kiloUserId: 'user-1' }))); }); expect(hoisted.deepLinkLaunch.setCurrentDeepLinkUserId).toHaveBeenCalledWith('user-1'); @@ -596,7 +621,7 @@ describe('sign-out teardown ordering', () => { const { ctx, unmount } = await mountAndGetContext(); await act(async () => { - await ctx.signIn(makeToken({ kiloUserId: 'user-2' })); + await ctx.signIn(tokenPair(makeToken({ kiloUserId: 'user-2' }))); }); // The switch unregisters the prior scope's activity tokens (tombstone on @@ -614,7 +639,7 @@ describe('sign-out teardown ordering', () => { const imageConfirm = await import('@/components/agents/markdown-image-confirm'); await act(async () => { - await ctx.signIn(makeToken({ kiloUserId: 'user-2' })); + await ctx.signIn(tokenPair(makeToken({ kiloUserId: 'user-2' }))); }); expect(trustedHosts.clearTrustedHosts).toHaveBeenCalled(); @@ -754,7 +779,8 @@ describe('stale sign-in continuation', () => { beforeEach(() => { vi.clearAllMocks(); hoisted.callOrder.length = 0; - hoisted.secureStore.getItemAsync.mockResolvedValue(null); + hoisted.secureStoreValues.clear(); + useSecureStoreMap(); }); /** Mount the provider with a consumer that re-captures the context on @@ -807,7 +833,7 @@ describe('stale sign-in continuation', () => { // Whole-body FIFO: the sign-in completes first (its credentials publish // and its login side effects run), then the sign-out runs the full // teardown of that new session. - const signInPromise = getCtx().signIn('stale-token'); + const signInPromise = getCtx().signIn(tokenPair('stale-token')); const signOutPromise = getCtx().signOut(true); await act(async () => { @@ -836,8 +862,8 @@ describe('stale sign-in continuation', () => { // FIFO serialization means the first sign-in is NOT fenced by the second: // both publish and run their login side effects in queue order, and the // newer sign-in owns the final token. - const firstSignIn = getCtx().signIn('first-token'); - const secondSignIn = getCtx().signIn('second-token'); + const firstSignIn = getCtx().signIn(tokenPair('first-token')); + const secondSignIn = getCtx().signIn(tokenPair('second-token')); await act(async () => { await Promise.all([firstSignIn, secondSignIn]); @@ -881,7 +907,7 @@ describe('stale sign-in continuation', () => { await getCtx().signOut(); }); await act(async () => { - await getCtx().signIn('new-token'); + await getCtx().signIn(tokenPair('new-token')); }); expect(getCtx().isSigningOut).toBe(false); const { isSignOutActive } = await import('@/lib/auth/sign-out-state'); @@ -890,7 +916,7 @@ describe('stale sign-in continuation', () => { // FIFO: the sign-in runs its whole body (the fence opens), then the // sign-out queued behind it runs the full teardown and closes the fence // again — the final state is signed out. - const signInPromise = getCtx().signIn('stale-token'); + const signInPromise = getCtx().signIn(tokenPair('stale-token')); const signOutPromise = getCtx().signOut(true); await act(async () => { await Promise.all([signInPromise, signOutPromise]); @@ -914,7 +940,7 @@ describe('stale sign-in continuation', () => { expect(isSignOutTeardownActive()).toBe(true); await act(async () => { - await getCtx().signIn('new-token'); + await getCtx().signIn(tokenPair('new-token')); }); // The published sign-in ends the teardown window: refresh may rotate the // new session again. @@ -928,13 +954,12 @@ describe('bootstrap and foreground race fencing', () => { beforeEach(() => { vi.clearAllMocks(); hoisted.callOrder.length = 0; - hoisted.secureStore.getItemAsync.mockResolvedValue(null); + hoisted.secureStoreValues.clear(); + useSecureStoreMap(); }); - /** Reset the module registry and mount the provider so the bootstrap load - * runs against the caller-installed SecureStore mock queue. The queue is - * consumed in this order: preloadedToken, preloadedRefreshToken, the - * bootstrap expiry read, then the bootstrap credential re-read. */ + /** Reset the module registry and mount the provider against the caller's + * key-addressed SecureStore fixture. */ async function mountProvider(): Promise<{ getCtx: () => AuthContextValue; unmount: () => void; @@ -977,25 +1002,199 @@ describe('bootstrap and foreground race fencing', () => { }; } + const modernCredentialBundle = { + token: 'api-owner-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-request-token', + expiresAt: '2030-01-01T00:00:00.000Z', + }, + } satisfies NativeTokenPair; + + it('restores an API/gateway bundle ahead of stale legacy keys and does not restore it after sign-out', async () => { + hoisted.secureStoreValues.clear(); + hoisted.secureStoreValues.set( + 'native-credential-bundle', + JSON.stringify(modernCredentialBundle) + ); + // A process killed after the modern bundle write but before the legacy + // deletes leaves these stale values behind. The bundle remains authoritative. + hoisted.secureStoreValues.set('auth-token', 'stale-legacy-api-token'); + hoisted.secureStoreValues.set('refresh-token', 'stale-legacy-refresh-token'); + hoisted.secureStoreValues.set('token-expires-at', '9999999999999'); + + const firstMount = await mountProvider(); + const firstTokenOwner = await import('@/lib/auth/token-owner'); + const { getGatewayAuthTokenForRequest } = await import('@/lib/auth/credentials'); + + expect(firstMount.getCtx().token).toBe(modernCredentialBundle.token); + await expect(firstTokenOwner.getAuthTokenForRequest()).resolves.toBe( + modernCredentialBundle.token + ); + await expect(getGatewayAuthTokenForRequest()).resolves.toBe( + modernCredentialBundle.metadata.gatewayToken + ); + + await act(async () => { + await firstMount.getCtx().signOut(); + }); + firstMount.unmount(); + + // A relaunch gets a new module-level preload. The deleted bundle must not + // be recreated from stale legacy-key fixtures or from the prior owner. + const remount = await mountProvider(); + const remountedTokenOwner = await import('@/lib/auth/token-owner'); + expect(remount.getCtx().token).toBeUndefined(); + await expect(remountedTokenOwner.getAuthTokenForRequest()).resolves.toBeNull(); + expect(hoisted.secureStoreValues.has('native-credential-bundle')).toBe(false); + + remount.unmount(); + }); + + it('restores a modern bundle when the legacy refresh-key preload rejects', async () => { + hoisted.secureStoreValues.set( + 'native-credential-bundle', + JSON.stringify(modernCredentialBundle) + ); + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + await Promise.resolve(); + if (key === 'refresh-token') { + throw new Error('keychain unavailable'); + } + return hoisted.secureStoreValues.get(key) ?? null; + }); + + const { getCtx, unmount } = await mountProvider(); + const tokenOwner = await import('@/lib/auth/token-owner'); + + expect(getCtx().token).toBe(modernCredentialBundle.token); + expect(getCtx().restoreFailed).toBe(false); + await expect(tokenOwner.getAuthTokenForRequest('gateway')).resolves.toBe( + modernCredentialBundle.metadata.gatewayToken + ); + expect( + hoisted.secureStore.getItemAsync.mock.calls.filter(([key]) => key === 'refresh-token') + ).toHaveLength(1); + + unmount(); + }); + + it.each([ + ['invalid JSON', '{not-json'], + [ + 'an unknown credential format', + JSON.stringify({ + ...modernCredentialBundle, + metadata: { ...modernCredentialBundle.metadata, credentialFormat: 'unknown-v1' }, + }), + ], + [ + 'incomplete metadata', + JSON.stringify({ + ...modernCredentialBundle, + metadata: { credentialFormat: 'api-gateway-v1', expiresAt: '2030-01-01T00:00:00.000Z' }, + }), + ], + ])( + 'fails closed for a versioned bundle with %s even when legacy keys remain', + async (_case, rawBundle) => { + hoisted.secureStoreValues.set('native-credential-bundle', rawBundle); + hoisted.secureStoreValues.set('auth-token', 'legacy-api-token'); + hoisted.secureStoreValues.set('refresh-token', 'legacy-refresh-token'); + const fetch = vi.spyOn(globalThis, 'fetch'); + + const { getCtx, unmount } = await mountProvider(); + const tokenOwner = await import('@/lib/auth/token-owner'); + + expect(getCtx().token).toBeUndefined(); + expect(tokenOwner.getActiveToken()).toBeNull(); + await expect(tokenOwner.getAuthTokenForRequest()).resolves.toBeNull(); + expect(tokenOwner.getActiveToken()).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); + + fetch.mockRestore(); + unmount(); + } + ); + + it('does not publish an old modern API credential when sign-out and an account switch win a delayed bundle read', async () => { + hoisted.secureStoreValues.clear(); + const oldBundle = { + ...modernCredentialBundle, + token: 'old-api-token', + metadata: { ...modernCredentialBundle.metadata, gatewayToken: 'old-gateway-token' }, + } satisfies NativeTokenPair; + const replacementBundle = { + ...modernCredentialBundle, + token: 'new-api-token', + metadata: { ...modernCredentialBundle.metadata, gatewayToken: 'new-gateway-token' }, + } satisfies NativeTokenPair; + hoisted.secureStoreValues.set('native-credential-bundle', JSON.stringify(oldBundle)); + + const bundleRead = Promise.withResolvers(); + let delayedReadStarted = false; + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + const snapshot = hoisted.secureStoreValues.get(key) ?? null; + if (key === 'native-credential-bundle' && !delayedReadStarted) { + delayedReadStarted = true; + await bundleRead.promise; + } + return snapshot; + }); + + const { getCtx, unmount } = await mountProvider(); + await vi.waitFor(() => { + expect(delayedReadStarted).toBe(true); + }); + + // The delayed bootstrap owns the old bundle snapshot. Its completion comes + // after both teardown and a different account's modern credential publish. + await act(async () => { + await getCtx().signOut(); + await getCtx().signIn(replacementBundle); + }); + bundleRead.resolve(undefined); + await act(async () => { + await new Promise(resolve => { + void setTimeout(resolve, 0); + }); + }); + + const tokenOwner = await import('@/lib/auth/token-owner'); + const { getGatewayAuthTokenForRequest } = await import('@/lib/auth/credentials'); + expect(getCtx().token).toBe(replacementBundle.token); + await expect(tokenOwner.getAuthTokenForRequest()).resolves.toBe(replacementBundle.token); + await expect(getGatewayAuthTokenForRequest()).resolves.toBe( + replacementBundle.metadata.gatewayToken + ); + expect(getCtx().token).not.toBe(oldBundle.token); + + unmount(); + }); + it('regression: sign-out during bootstrap does not restore the preloaded token into React state or the owner', async () => { let releaseRead: (() => void) | undefined = undefined; const readGate = new Promise(resolve => { releaseRead = resolve; }); - // Mock queue consumed by the bootstrap load: preloadedToken, - // preloadedRefreshToken, then the expiry read (held), then the - // credential re-read (unchanged, so only the epoch fence can stop it). - hoisted.secureStore.getItemAsync - .mockResolvedValueOnce('stored-token') - .mockResolvedValueOnce('stored-refresh') - .mockImplementationOnce(async () => { - // Bootstrap expiry read: hold open so a sign-out can land mid-read. + hoisted.secureStoreValues.set('auth-token', 'stored-token'); + hoisted.secureStoreValues.set('refresh-token', 'stored-refresh'); + let expiryReadStarted = false; + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + if (key === 'token-expires-at') { + expiryReadStarted = true; await readGate; return '9999999999999'; - }) - .mockResolvedValueOnce('stored-token'); + } + return hoisted.secureStoreValues.get(key) ?? null; + }); const { getCtx, unmount } = await mountProvider(); + await vi.waitFor(() => { + expect(expiryReadStarted).toBe(true); + }); // Sign out while the bootstrap expiry read is in flight. await act(async () => { @@ -1026,20 +1225,28 @@ describe('bootstrap and foreground race fencing', () => { releaseRead = resolve; }); const storedToken = makeToken({ kiloUserId: 'user-1' }); - // Mock queue consumed by the bootstrap load: preloadedToken, - // preloadedRefreshToken, then the expiry read (held), then the - // credential re-read (unchanged, so only a fence can stop the publish). - hoisted.secureStore.getItemAsync - .mockResolvedValueOnce(storedToken) - .mockResolvedValueOnce('stored-refresh') - .mockImplementationOnce(async () => { + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + if (key === 'native-credential-bundle') { + return null; + } + if (key === 'auth-token') { + return storedToken; + } + if (key === 'refresh-token') { + return 'stored-refresh'; + } + if (key === 'token-expires-at') { // Bootstrap expiry read: hold open so a sign-out can land mid-read. await readGate; return '9999999999999'; - }) - .mockResolvedValueOnce(storedToken); + } + return null; + }); const { getCtx, unmount } = await mountProvider(); + const tokenOwner = await import('@/lib/auth/token-owner'); + const ownerBeforeSignOut = tokenOwner.getActiveToken(); + expect(ownerBeforeSignOut).toEqual({ token: storedToken, expiresAtMs: null }); // Hold the sign-out's remote cleanup open: the teardown is mid-flight and // its epoch bump (which waits for the cleanup) has not happened when the @@ -1065,10 +1272,9 @@ describe('bootstrap and foreground race fencing', () => { }); }); - // The success path must not republish what sign-out is tearing down: no - // owner token, no React token, no deep-link binding for the old account. - const tokenOwner = await import('@/lib/auth/token-owner'); - expect(tokenOwner.getActiveToken()).toBeNull(); + // The success path must not republish what sign-out is tearing down. The + // preloaded owner remains available only for the in-flight logout cleanup. + expect(tokenOwner.getActiveToken()).toEqual(ownerBeforeSignOut); expect(getCtx().token).toBeUndefined(); expect(hoisted.deepLinkLaunch.setCurrentDeepLinkUserId).not.toHaveBeenCalledWith('user-1'); @@ -1077,6 +1283,7 @@ describe('bootstrap and foreground race fencing', () => { await act(async () => { await signOutPromise; }); + expect(tokenOwner.getActiveToken()).toBeNull(); expect(getCtx().token).toBeUndefined(); expect(getCtx().sessionEnded).toBe(true); @@ -1090,15 +1297,19 @@ describe('bootstrap and foreground race fencing', () => { }); const storedToken = makeToken({ kiloUserId: 'user-1' }); // No stored refresh token: bootstrap takes the legacy-exchange branch. - // Mock queue consumed by the bootstrap load: preloadedToken, - // preloadedRefreshToken (null), then — after the fenced exchange publish - // is refused and the main restore path continues — the expiry read and - // the credential re-read. - hoisted.secureStore.getItemAsync - .mockResolvedValueOnce(storedToken) - .mockResolvedValueOnce(null) - .mockResolvedValueOnce('9999999999999') - .mockResolvedValueOnce(storedToken); + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + await Promise.resolve(); + if (key === 'native-credential-bundle') { + return null; + } + if (key === 'auth-token') { + return storedToken; + } + if (key === 'token-expires-at') { + return '9999999999999'; + } + return null; + }); hoisted.exchange.exchangeLegacyToken.mockImplementationOnce(async () => { await exchangeGate; return { token: 'exchanged-token', refreshToken: 'exchanged-refresh', expiresIn: 3600 }; @@ -1152,21 +1363,22 @@ describe('bootstrap and foreground race fencing', () => { const readGate = new Promise(resolve => { releaseRead = resolve; }); - // Mock queue consumed by the bootstrap load: preloadedToken, - // preloadedRefreshToken, then the expiry read (held). The credential - // re-read falls back to the null base mock, so it reports the preloaded - // snapshot no longer matches the stored session. - hoisted.secureStore.getItemAsync - .mockResolvedValueOnce('stored-token') - .mockResolvedValueOnce('stored-refresh') - .mockImplementationOnce(async () => { - // Bootstrap expiry read: hold open while a same-session credential - // write replaces the stored pair. + hoisted.secureStoreValues.set('auth-token', 'stored-token'); + hoisted.secureStoreValues.set('refresh-token', 'stored-refresh'); + let expiryReadStarted = false; + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + if (key === 'token-expires-at') { + expiryReadStarted = true; await readGate; return '9999999999999'; - }); + } + return hoisted.secureStoreValues.get(key) ?? null; + }); const { getCtx, unmount } = await mountProvider(); + await vi.waitFor(() => { + expect(expiryReadStarted).toBe(true); + }); // A same-session refresh replaces the stored pair and publishes the owner // while the bootstrap expiry read is in flight. @@ -1198,24 +1410,72 @@ describe('bootstrap and foreground race fencing', () => { unmount(); }); + it('forwards modern bundle metadata through sign-in credential persistence', async () => { + const { getCtx, unmount } = await mountProvider(); + const credentials = await import('@/lib/auth/credentials'); + const setCredentials = vi.spyOn(credentials, 'setCredentials'); + const bundle = { + credentialFormat: 'api-gateway-v1' as const, + gatewayToken: 'gateway-token', + expiresAt: '2026-01-01T01:00:00.000Z', + }; + + await act(async () => { + await getCtx().signIn({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: bundle, + }); + }); + + expect(setCredentials).toHaveBeenCalledWith({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: bundle, + }); + unmount(); + }); + + it('returns false without publishing React auth state when credential persistence is fenced', async () => { + const { getCtx, unmount } = await mountProvider(); + const credentials = await import('@/lib/auth/credentials'); + const setCredentials = vi.spyOn(credentials, 'setCredentials').mockResolvedValueOnce(false); + + let persisted = true; + await act(async () => { + persisted = await getCtx().signIn(tokenPair('unpublished-token')); + }); + + expect(persisted).toBe(false); + expect(getCtx().token).toBeUndefined(); + expect(hoisted.appsflyer.trackEvent).not.toHaveBeenCalled(); + setCredentials.mockRestore(); + unmount(); + }); + it('regression: sign-out during bootstrap wins over changed stored credentials', async () => { let releaseRead: (() => void) | undefined = undefined; const readGate = new Promise(resolve => { releaseRead = resolve; }); - // Mock queue consumed by the bootstrap load: preloadedToken, - // preloadedRefreshToken, then the expiry read (held). The credential - // re-read falls back to the null base mock, so the stored pair no longer - // matches the preloaded snapshot — the sign-out deleted it. - hoisted.secureStore.getItemAsync - .mockResolvedValueOnce('stored-token') - .mockResolvedValueOnce('stored-refresh') - .mockImplementationOnce(async () => { + hoisted.secureStoreValues.set('auth-token', 'stored-token'); + hoisted.secureStoreValues.set('refresh-token', 'stored-refresh'); + let expiryReadStarted = false; + hoisted.secureStore.getItemAsync.mockImplementation(async key => { + if (key === 'token-expires-at') { + expiryReadStarted = true; await readGate; return '9999999999999'; - }); + } + return hoisted.secureStoreValues.get(key) ?? null; + }); const { getCtx, unmount } = await mountProvider(); + await vi.waitFor(() => { + expect(expiryReadStarted).toBe(true); + }); // Sign out while the bootstrap expiry read is in flight. await act(async () => { @@ -1242,14 +1502,9 @@ describe('bootstrap and foreground race fencing', () => { it('binds the deep-link user id from the restored session during bootstrap', async () => { const storedToken = makeToken({ kiloUserId: 'user-1' }); - // Mock queue consumed by the bootstrap load: preloadedToken, - // preloadedRefreshToken, the bootstrap expiry read, then the bootstrap - // credential re-read (unchanged, so the main restore publishes the token). - hoisted.secureStore.getItemAsync - .mockResolvedValueOnce(storedToken) - .mockResolvedValueOnce('stored-refresh') - .mockResolvedValueOnce('9999999999999') - .mockResolvedValueOnce(storedToken); + hoisted.secureStoreValues.set('auth-token', storedToken); + hoisted.secureStoreValues.set('refresh-token', 'stored-refresh'); + hoisted.secureStoreValues.set('token-expires-at', '9999999999999'); const { getCtx, unmount } = await mountProvider(); @@ -1262,12 +1517,87 @@ describe('bootstrap and foreground race fencing', () => { unmount(); }); + it('refreshes a near-expiry modern bundle when the app enters the foreground', async () => { + const { getCtx, unmount } = await mountProvider(); + const initial = { + ...modernCredentialBundle, + metadata: { + ...modernCredentialBundle.metadata, + expiresAt: new Date(Date.now() + 60_000).toISOString(), + }, + } satisfies NativeTokenPair; + const refreshed = { + ...initial, + token: 'refreshed-api-token', + refreshToken: 'refreshed-refresh-token', + metadata: { + ...initial.metadata, + gatewayToken: 'refreshed-gateway-token', + expiresAt: new Date(Date.now() + 3_600_000).toISOString(), + }, + } satisfies NativeTokenPair; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json(refreshed)); + + await act(async () => { + await getCtx().signIn(initial); + }); + + expect(hoisted.secureStoreValues.has('token-expires-at')).toBe(false); + const eventListener = hoisted.appState.addEventListener.mock.calls.at(-1)?.[1]; + + await act(async () => { + eventListener?.('active'); + await vi.waitFor(() => { + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + }); + + expect(getCtx().token).toBe(refreshed.token); + const tokenOwner = await import('@/lib/auth/token-owner'); + expect(tokenOwner.getActiveToken()?.token).toBe(refreshed.token); + + fetchSpy.mockRestore(); + unmount(); + }); + + it('refreshes a near-expiry legacy credential pair from the persisted expiry fallback', async () => { + const { getCtx, unmount } = await mountProvider(); + const initial = { + token: 'legacy-api-token', + refreshToken: 'legacy-refresh-token', + expiresIn: 60, + } satisfies NativeTokenPair; + const refreshed = { + token: 'refreshed-api-token', + refreshToken: 'refreshed-refresh-token', + expiresIn: 3600, + } satisfies NativeTokenPair; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json(refreshed)); + + await act(async () => { + await getCtx().signIn(initial); + }); + + expect(hoisted.secureStoreValues.has('token-expires-at')).toBe(true); + const eventListener = hoisted.appState.addEventListener.mock.calls.at(-1)?.[1]; + await act(async () => { + eventListener?.('active'); + await vi.waitFor(() => { + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + }); + + expect(getCtx().token).toBe(refreshed.token); + fetchSpy.mockRestore(); + unmount(); + }); + it('regression: a foreground event from a stale epoch does not refresh or publish a token after sign-out', async () => { const { getCtx, unmount } = await mountProvider(); // Sign in so the foreground effect re-subscribes with a token in scope. await act(async () => { - await getCtx().signIn('active-token'); + await getCtx().signIn(tokenPair('active-token')); }); // Grab the listener registered by the token-bearing foreground effect. @@ -1279,7 +1609,9 @@ describe('bootstrap and foreground race fencing', () => { const readGate = new Promise(resolve => { releaseRead = resolve; }); + let expiryReadStarted = false; hoisted.secureStore.getItemAsync.mockImplementationOnce(async () => { + expiryReadStarted = true; await readGate; // An expiry inside the refresh margin: without the epoch fence the // handler would proceed to refresh. @@ -1292,6 +1624,9 @@ describe('bootstrap and foreground race fencing', () => { eventListener?.('active'); await Promise.resolve(); }); + await vi.waitFor(() => { + expect(expiryReadStarted).toBe(true); + }); // Sign out while the foreground event's expiry read is in flight. await act(async () => { @@ -1320,7 +1655,8 @@ describe('reactive auth epoch', () => { beforeEach(() => { vi.clearAllMocks(); hoisted.callOrder.length = 0; - hoisted.secureStore.getItemAsync.mockResolvedValue(null); + hoisted.secureStoreValues.clear(); + useSecureStoreMap(); }); /** Mount the provider with a consumer that re-captures the context on every @@ -1384,7 +1720,7 @@ describe('reactive auth epoch', () => { const scope: typeof ContextScopeModule = await import('../context-scope'); const tokens: typeof TokenOwnerModule = await import('./token-owner'); await act(async () => { - await getCtx().signIn('account-a-token'); + await getCtx().signIn(tokenPair('account-a-token')); }); await act(async () => { await requestOwnerTicket(); @@ -1392,7 +1728,7 @@ describe('reactive auth epoch', () => { const previous = scope.getAuthenticatedOwner(); expect(previous.userId).toBe('user-a'); // The old credentials remain readable on disk while the replacement write is held. - hoisted.secureStore.getItemAsync.mockResolvedValue('account-a-token'); + hoisted.secureStoreValues.set('auth-token', 'account-a-token'); const published: { userId: string | null; token: string | null }[] = []; const unsubscribe = scope.subscribeAuthenticatedOwner(() => { @@ -1411,7 +1747,7 @@ describe('reactive auth epoch', () => { }); const transition: { promise?: Promise } = {}; await act(async () => { - transition.promise = getCtx().signIn('account-b-token'); + transition.promise = getCtx().signIn(tokenPair('account-b-token')); await Promise.resolve(); }); @@ -1446,11 +1782,9 @@ describe('reactive auth epoch', () => { it('confirms a restored account from getMe rather than the decoded token hint', async () => { const token = makeToken({ kiloUserId: 'unconfirmed-hint' }); - hoisted.secureStore.getItemAsync - .mockResolvedValueOnce(token) - .mockResolvedValueOnce('stored-refresh') - .mockResolvedValueOnce('9999999999999') - .mockResolvedValueOnce(token); + hoisted.secureStoreValues.set('auth-token', token); + hoisted.secureStoreValues.set('refresh-token', 'stored-refresh'); + hoisted.secureStoreValues.set('token-expires-at', '9999999999999'); const { unmount } = await mountEpochTest(true); onTestFinished(() => act(unmount)); const scope: typeof ContextScopeModule = await import('../context-scope'); @@ -1468,7 +1802,7 @@ describe('reactive auth epoch', () => { const { getCtx, unmount } = await mountEpochTest(true); onTestFinished(() => act(unmount)); await act(async () => { - await getCtx().signIn('account-a-token'); + await getCtx().signIn(tokenPair('account-a-token')); }); const identity = Promise.withResolvers<{ id: string }>(); ownerProducer.getMe.mockReturnValueOnce(identity.promise); @@ -1476,7 +1810,7 @@ describe('reactive auth epoch', () => { const rejection = expect(stale).rejects.toThrow('Authenticated owner changed'); await act(async () => { - await getCtx().signIn('account-b-token'); + await getCtx().signIn(tokenPair('account-b-token')); }); ownerProducer.getMe.mockResolvedValueOnce({ id: 'user-b' }); await act(async () => { @@ -1494,7 +1828,7 @@ describe('reactive auth epoch', () => { const { getCtx, unmount } = await mountEpochTest(true); onTestFinished(() => act(unmount)); await act(async () => { - await getCtx().signIn('account-a-token'); + await getCtx().signIn(tokenPair('account-a-token')); }); await act(async () => { await requestOwnerTicket(); @@ -1529,7 +1863,7 @@ describe('reactive auth epoch', () => { const { getCtx, unmount } = await mountEpochTest(true); onTestFinished(() => act(unmount)); await act(async () => { - await getCtx().signIn('account-a-token'); + await getCtx().signIn(tokenPair('account-a-token')); }); await act(async () => { await requestOwnerTicket(); @@ -1538,12 +1872,19 @@ describe('reactive auth epoch', () => { const owner = scope.getAuthenticatedOwner(); const { performRefresh } = await import('@/lib/auth/credentials'); const tokens: typeof TokenOwnerModule = await import('./token-owner'); - hoisted.secureStore.getItemAsync.mockResolvedValueOnce('refresh-a'); - const fetch = vi - .spyOn(globalThis, 'fetch') - .mockResolvedValueOnce( - Response.json({ token: 'refreshed-token', refreshToken: 'refreshed-pair', expiresIn: 3600 }) - ); + hoisted.secureStoreValues.set('refresh-token', 'refresh-a'); + const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce( + Response.json({ + token: 'refreshed-token', + refreshToken: 'refreshed-pair', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'refreshed-gateway-token', + expiresAt: '2026-01-01T01:00:00.000Z', + }, + }) + ); onTestFinished(() => { fetch.mockRestore(); }); @@ -1571,7 +1912,7 @@ describe('reactive auth epoch', () => { const before = getCtx().authEpoch; await act(async () => { - await getCtx().signIn('new-token'); + await getCtx().signIn(tokenPair('new-token')); }); expect(getCtx().authEpoch).toBeGreaterThan(before); @@ -1600,7 +1941,8 @@ describe('auth-transition queue and sign-out failure matrix', () => { beforeEach(() => { vi.clearAllMocks(); hoisted.callOrder.length = 0; - hoisted.secureStore.getItemAsync.mockResolvedValue(null); + hoisted.secureStoreValues.clear(); + useSecureStoreMap(); }); async function mountQueueTest(): Promise<{ @@ -1663,7 +2005,7 @@ describe('auth-transition queue and sign-out failure matrix', () => { // The sign-in is queued behind the sign-out: while the cleanup is held it // must not run its credential write or any login side effect. - const signInPromise = getCtx().signIn('queued-token'); + const signInPromise = getCtx().signIn(tokenPair('queued-token')); await act(async () => { await new Promise(resolve => { void setTimeout(resolve, 0); diff --git a/apps/mobile/src/lib/auth/auth-context.tsx b/apps/mobile/src/lib/auth/auth-context.tsx index 59f92f2b2b..ff9237686a 100644 --- a/apps/mobile/src/lib/auth/auth-context.tsx +++ b/apps/mobile/src/lib/auth/auth-context.tsx @@ -1,6 +1,5 @@ -/* eslint-disable max-lines -- sign-out teardown ordering, stale sign-in fencing, and the consent-outcome clear are kept together with the provider mount */ import * as SecureStore from 'expo-secure-store'; -import { z } from 'zod'; +import { type NativeTokenPair } from '@kilocode/app-shared/native-auth'; import { createContext, type ReactNode, @@ -27,22 +26,22 @@ import { deleteAccountMetadata } from '@/lib/auth/account-metadata-write'; import { runLogoutCleanup, unregisterActivityTokensAndTombstone } from '@/lib/auth/logout-cleanup'; import { queryClient } from '@/lib/query-client'; import { setTrpcUnauthorizedHandler } from '@/lib/auth/trpc-unauthorized'; -import { exchangeLegacyToken } from '@/lib/auth/exchange-legacy-token'; import { bumpAuthEpoch, currentAuthEpoch, isCurrentAuthEpoch } from '@/lib/auth/auth-epoch'; +import { readUserIdFromToken } from '@/lib/auth/auth-user-id'; +import { useAuthBootstrap } from '@/lib/auth/use-auth-bootstrap'; +import { readStoredValueWithRetry } from '@/lib/auth/secure-store-read'; import { IOS_BEARER_SECURE_STORE_OPTIONS, performRefresh, - persistSignInCredentialsAtEpoch, REFRESH_MARGIN_MS, + setCredentials, writeCredentials, } from '@/lib/auth/credentials'; import { clearActiveToken, - getActiveToken, - setActiveToken, + getActiveTokenSnapshot, setSignOutTeardownActive, } from '@/lib/auth/token-owner'; -import { readStoredValueWithRetry } from '@/lib/auth/secure-store-read'; import { chainSave } from '@/lib/hooks/save-chain'; import { clearAgentModelPreference } from '@/lib/hooks/use-persisted-agent-model'; import { clearRunOnDestinationPreference } from '@/lib/hooks/use-persisted-run-on-destination'; @@ -68,6 +67,7 @@ import { AUTH_TOKEN_KEY, LEGACY_EXCHANGE_DONE_KEY, LIVE_SESSION_FILTERS_KEY, + NATIVE_CREDENTIAL_BUNDLE_KEY, NOTIFICATION_PROMPT_SEEN_KEY, ORGANIZATION_STORAGE_KEY, PENDING_DEEP_LINK_KEY, @@ -82,52 +82,7 @@ import { purgePostHogPersistence } from '@/lib/telemetry/posthog-storage'; import { AppState } from 'react-native'; import { beginAuthenticatedOwner } from '@/lib/context-scope'; -// Pre-load tokens at module level so they're available before React mounts -export const preloadedAuthToken = SecureStore.getItemAsync(AUTH_TOKEN_KEY); -const preloadedRefreshToken = SecureStore.getItemAsync(REFRESH_TOKEN_KEY); -// A keychain failure at process start rejects these before any consumer can -// await them, and the runtime would report that as an unhandled rejection -// before AuthProvider even mounts. Observe it here; the bootstrap read below -// still awaits the same promise as its first attempt, and it — not this -// observer — decides whether the session can be restored. -async function observePreloadRejection(preload: Promise): Promise { - try { - await preload; - } catch { - // Observed only. The bootstrap read owns the outcome. - } -} -void observePreloadRejection(preloadedAuthToken); -void observePreloadRejection(preloadedRefreshToken); - -const jwtPayloadSchema = z.object({ kiloUserId: z.string().optional() }); - -/** - * Best-effort read of the signed-in user id from a Kilo bearer token. The - * token is a JWT whose payload carries `kiloUserId` (see `generateApiToken` - * in apps/web/src/lib/tokens.ts). Decode-only: the server already accepted - * the token, so the id is read without verifying the signature (the app has - * no signing secret). Returns null for a non-JWT or malformed token so a - * decode failure can never break sign-in. - */ -function readUserIdFromToken(token: string): string | null { - try { - const segments = token.split('.'); - if (segments.length !== 3) { - return null; - } - const payloadSegment = segments[1]; - if (payloadSegment === undefined) { - return null; - } - const base64 = payloadSegment.replaceAll('-', '+').replaceAll('_', '/'); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '='); - const parsed = jwtPayloadSchema.safeParse(JSON.parse(atob(padded))); - return parsed.success && parsed.data.kiloUserId ? parsed.data.kiloUserId : null; - } catch { - return null; - } -} +export { preloadedAuthToken } from '@/lib/auth/use-auth-bootstrap'; type AuthContextValue = { token: string | undefined; @@ -141,14 +96,9 @@ type AuthContextValue = { * publication succeeds. The read-cache mount refuses to subscribe while it * is set, and the persister fence reads the same flag at write time. */ isSigningOut: boolean; - /** True when every retried startup credential read still failed. The stored - * session is NOT known to be gone, so bootstrap shows a retryable error - * surface instead of presenting the person as signed out. */ restoreFailed: boolean; - /** Re-runs the startup credential read, holding the restore-error surface - * until the fresh reads resolve. */ retryRestore: () => void; - signIn: (token: string, refreshToken?: string, expiresIn?: number) => Promise; + signIn: (pair: NativeTokenPair) => Promise; signOut: (ended?: boolean) => Promise; }; @@ -172,183 +122,67 @@ export function AuthProvider({ children }: { readonly children: ReactNode }) { const isSigningOut = useSyncExternalStore(subscribeSignOutActive, isSignOutActive); const isSignedOutReference = useRef(false); - // Declared outside the mount effect so the restore-error screen's Retry can - // re-run the exact same bootstrap. `preload` is passed only on the first - // run: a retry must never reuse the module-scope promise that already - // rejected, and re-awaiting a resolved one would answer from a stale read. - const load = useCallback( - async (preload?: { - readonly token: Promise; - readonly refresh: Promise; - }) => { - // Capture the epoch before any asynchronous read: every later check — - // including the catch below — fences against this moment, so a sign-out - // or newer sign-in during bootstrap can never be followed by the - // preloaded token being restored into React state or the token owner. - const epoch = currentAuthEpoch(); - try { - const stored = await readStoredValueWithRetry(AUTH_TOKEN_KEY, undefined, preload?.token); - const storedRefresh = await readStoredValueWithRetry( - REFRESH_TOKEN_KEY, - undefined, - preload?.refresh - ); - // The credential state is now known — a stored session restores below, - // or genuinely none exists and login is the correct destination. Clear - // a settled restore error here, not in `retryRestore`: a retry holds - // the error surface until this point (success moves past it, failure - // re-settles it in the catch), so the surface never blanks mid-retry. - setRestoreFailed(false); + const { retryRestore } = useAuthBootstrap({ setToken, setIsLoading, setRestoreFailed }); - if (stored) { - // Legacy exchange: if we have a token but no refresh token, upgrade once. - if (!storedRefresh) { - const pair = await exchangeLegacyToken(); - // The same teardown window the fence below covers: a sign-out that - // began while the exchange was in flight has not bumped the epoch - // yet, so the exchange's own epoch checks pass — the sign-out flag - // must stop this publish, exactly like the one below. - if (pair && isCurrentAuthEpoch(epoch) && !isSignedOutReference.current) { - setToken(pair.token); - setCurrentDeepLinkUserId(readUserIdFromToken(pair.token)); - setIsLoading(false); - return; - } - } - - // The session moved while the preload or legacy exchange was in - // flight: never resurrect the preloaded token. - if (!isCurrentAuthEpoch(epoch)) { - return; - } - - const expiresAtStr = await readStoredValueWithRetry(TOKEN_EXPIRES_AT_KEY); - - // Fence the asynchronous expiry read: a sign-out or newer sign-in - // during the reads owns the session, so the stale snapshot must not - // be republished and nothing may be surfaced for the torn-down - // session. - const currentStored = await readStoredValueWithRetry(AUTH_TOKEN_KEY); - // A sign-out teardown closes the epoch fence only at its bump, which - // waits for the remote cleanup — so inside the teardown window the - // epoch is still current while the sign-out flag is already set. The - // flag is the fence for that window, exactly as in the catch below: - // without it a success landing mid-teardown republishes the stored - // credentials (owner, React state, deep-link binding) that sign-out - // is tearing down. - if (!isCurrentAuthEpoch(epoch) || isSignedOutReference.current) { - return; - } - // A same-session refresh replaced the stored pair while the reads - // were in flight. The preloaded snapshot is stale, but the session - // is alive: publish the winner the refresh already put in the owner, - // or the provider ends bootstrap with no token and sends a - // signed-in user to the login screen. - if (currentStored !== stored) { - const published = getActiveToken()?.token ?? currentStored ?? undefined; - setToken(published); - setCurrentDeepLinkUserId(published ? readUserIdFromToken(published) : null); - return; - } - setActiveToken(stored, expiresAtStr ? Number(expiresAtStr) : null); - setToken(stored); - setCurrentDeepLinkUserId(readUserIdFromToken(stored)); - } - } catch { - // Every read exhausted its retries. The session is not known to be - // gone, so NEVER fall through to the signed-out path and never set a - // token here: surface a retryable error and let the person retry or - // sign out explicitly. - // But never resurrect the surface over a transition that began while - // this load was in flight. A sign-out's escape hatch already cleared - // it synchronously (and the dedupe makes a second sign-out a no-op, - // so a resurrected flag would dead-end the hatch on the login route); - // a newer sign-in moved the epoch and owns the tree. - if (!isSignedOutReference.current && isCurrentAuthEpoch(epoch)) { - setRestoreFailed(true); - } - } finally { - setIsLoading(false); + // The ENTIRE sign-in body runs inside the FIFO auth-transition queue, so a + // sign-in queued behind an in-flight sign-out lands only after the full + // teardown, and a sign-out queued behind a sign-in signs that new session + // out (documented, correct FIFO semantics). + const signIn = useCallback(async (pair: NativeTokenPair) => { + const persisted = await chainSave('auth-transition', async () => { + // Close admission before publishing the pending generation or writing credentials. + setSignOutTeardownActive(true); + setSignOutActive(true); + bumpAuthEpoch(); + beginAuthenticatedOwner(); + // Blank the prior account's glanceable surface before any credential + // persist, so a direct account switch never shows the previous account. + writeSignedOutSnapshotAndEnd(); + // Unregister the prior account's activity tokens (Live Activity / + // push-to-start) BEFORE persisting the new credentials, so the + // unregister runs under the old token owner's auth. This never revokes + // the device session or unregisters the Expo push token (logout-only). + await unregisterActivityTokensAndTombstone(); + setAuthEpoch(currentAuthEpoch()); + setToken(undefined); + clearActiveToken(); + // Bind the pending deep-link slot to the new user id at the same + // place the auth epoch advances, so a destination captured while this + // account is signed in restores only for this account. + setCurrentDeepLinkUserId(readUserIdFromToken(pair.token)); + const epoch = currentAuthEpoch(); + const published = await setCredentials(pair); + // A sign-in superseded by a newer sign-in or sign-out while its + // credential write was fenced must not clear the signed-out guard, + // update React auth state, or run login side effects. + if (!published || !isCurrentAuthEpoch(epoch)) { + return false; } - }, - [] - ); - - useEffect(() => { - void load({ token: preloadedAuthToken, refresh: preloadedRefreshToken }); - }, [load]); - - const retryRestore = useCallback(() => { - // Hold the settled error surface for the whole retry: `restoreFailed` - // stays true until `load()`'s primary reads resolve, so this surface - // stays mounted instead of blanking behind the loading gate (the native - // splash never returns once startup finished). - setIsLoading(true); - void load(); - }, [load]); - - const signIn = useCallback( - async (tokenValue: string, refreshTokenValue?: string, expiresIn?: number) => { - // The ENTIRE sign-in body runs inside the FIFO auth-transition queue, so - // a sign-in queued behind an in-flight sign-out lands only after the - // full teardown, and a sign-out queued behind a sign-in signs that new - // session out (documented, correct FIFO semantics). - await chainSave('auth-transition', async () => { - // Close admission before publishing the pending generation or writing credentials. - setSignOutTeardownActive(true); - setSignOutActive(true); - bumpAuthEpoch(); - beginAuthenticatedOwner(); - // Blank the prior account's glanceable surface before any credential - // persist, so a direct account switch never shows the previous account. - writeSignedOutSnapshotAndEnd(); - // Unregister the prior account's activity tokens (Live Activity / - // push-to-start) BEFORE persisting the new credentials, so the - // unregister runs under the old token owner's auth. This never revokes - // the device session or unregisters the Expo push token (logout-only). - await unregisterActivityTokensAndTombstone(); - setAuthEpoch(currentAuthEpoch()); - setToken(undefined); - clearActiveToken(); - // Bind the pending deep-link slot to the new user id at the same - // place the auth epoch advances, so a destination captured while this - // account is signed in restores only for this account. - setCurrentDeepLinkUserId(readUserIdFromToken(tokenValue)); - const epoch = currentAuthEpoch(); - const published = await persistSignInCredentialsAtEpoch(tokenValue, refreshTokenValue, { - expiresIn, - }); - // A sign-in superseded by a newer sign-in or sign-out while its - // credential write was fenced must not clear the signed-out guard, - // update React auth state, or run login side effects. - if (!published || !isCurrentAuthEpoch(epoch)) { - return; - } - // Clear the guard so a later refused refresh can sign out again. - isSignedOutReference.current = false; - // Credentials published on the winning epoch: the teardown window - // ends, so refresh may rotate the new session and request-token cold - // reads may warm the owner again. - setSignOutTeardownActive(false); - setSessionEnded(false); - // Credentials published on the winning epoch: the sign-out fence opens - // so the read-cache mount can subscribe for the new session, and the - // reactive `isSigningOut` follows the same flag. - setSignOutActive(false); - trackEvent('login'); - resetPurchaseErrorToastDedup(); - // A direct account switch must not keep the prior account's query - // cache: the org list is keyed account-independently, so a stale list - // would otherwise drive a false lost-org blank in the org fence. - queryClient.clear(); - setToken(tokenValue); - // A direct account switch must not keep the prior account's session - // state: trusted hosts, image confirms, media caches, temp copies. - clearSessionScopedState(); - }); - }, - [] - ); + // Clear the guard so a later refused refresh can sign out again. + isSignedOutReference.current = false; + // Credentials published on the winning epoch: the teardown window + // ends, so refresh may rotate the new session and request-token cold + // reads may warm the owner again. + setSignOutTeardownActive(false); + setSessionEnded(false); + // Credentials published on the winning epoch: the sign-out fence opens + // so the read-cache mount can subscribe for the new session, and the + // reactive `isSigningOut` follows the same flag. + setSignOutActive(false); + trackEvent('login'); + resetPurchaseErrorToastDedup(); + // A direct account switch must not keep the prior account's query + // cache: the org list is keyed account-independently, so a stale list + // would otherwise drive a false lost-org blank in the org fence. + queryClient.clear(); + setToken(pair.token); + // A direct account switch must not keep the prior account's session + // state: trusted hosts, image confirms, media caches, temp copies. + clearSessionScopedState(); + return true; + }); + return persisted; + }, []); const signOut = useCallback(async (ended = false) => { // The ENTIRE sign-out body runs inside the FIFO auth-transition queue. @@ -452,6 +286,10 @@ export function AuthProvider({ children }: { readonly children: ReactNode }) { TOKEN_EXPIRES_AT_KEY, IOS_BEARER_SECURE_STORE_OPTIONS ); + await SecureStore.deleteItemAsync( + NATIVE_CREDENTIAL_BUNDLE_KEY, + IOS_BEARER_SECURE_STORE_OPTIONS + ); await SecureStore.deleteItemAsync(LEGACY_EXCHANGE_DONE_KEY); }), deleteAccountMetadata(ACTIVE_USER_ID_KEY), @@ -532,19 +370,22 @@ export function AuthProvider({ children }: { readonly children: ReactNode }) { void (async () => { try { - const expiresAtStr = await SecureStore.getItemAsync(TOKEN_EXPIRES_AT_KEY); - if (!expiresAtStr) { - return; + let expiresAt = getActiveTokenSnapshot()?.expiresAtMs; + if (expiresAt === null || expiresAt === undefined) { + const expiresAtStr = await readStoredValueWithRetry(TOKEN_EXPIRES_AT_KEY); + if (!expiresAtStr) { + return; + } + expiresAt = Number(expiresAtStr); } - const expiresAt = Number(expiresAtStr); if (Date.now() <= expiresAt - REFRESH_MARGIN_MS) { return; } // The epoch moved while the expiry read was in flight: the event is // stale, so do not initiate a refresh for the old session. - if (!isCurrentAuthEpoch(epoch)) { + if (!isCurrentAuthEpoch(epoch) || isSignOutActive()) { return; } diff --git a/apps/mobile/src/lib/auth/auth-user-id.ts b/apps/mobile/src/lib/auth/auth-user-id.ts new file mode 100644 index 0000000000..b8f7ecb963 --- /dev/null +++ b/apps/mobile/src/lib/auth/auth-user-id.ts @@ -0,0 +1,30 @@ +import { z } from 'zod'; + +const jwtPayloadSchema = z.object({ kiloUserId: z.string().optional() }); + +/** + * Best-effort read of the signed-in user id from a Kilo bearer token. The + * token is a JWT whose payload carries `kiloUserId` (see `generateApiToken` + * in apps/web/src/lib/tokens.ts). Decode-only: the server already accepted + * the token, so the id is read without verifying the signature (the app has + * no signing secret). Returns null for a non-JWT or malformed token so a + * decode failure can never break sign-in. + */ +export function readUserIdFromToken(token: string): string | null { + try { + const segments = token.split('.'); + if (segments.length !== 3) { + return null; + } + const payloadSegment = segments[1]; + if (payloadSegment === undefined) { + return null; + } + const base64 = payloadSegment.replaceAll('-', '+').replaceAll('_', '/'); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '='); + const parsed = jwtPayloadSchema.safeParse(JSON.parse(atob(padded))); + return parsed.success && parsed.data.kiloUserId ? parsed.data.kiloUserId : null; + } catch { + return null; + } +} diff --git a/apps/mobile/src/lib/auth/credentials.ts b/apps/mobile/src/lib/auth/credentials.ts index ef6af237b8..aeae260457 100644 --- a/apps/mobile/src/lib/auth/credentials.ts +++ b/apps/mobile/src/lib/auth/credentials.ts @@ -2,11 +2,30 @@ import * as SecureStore from 'expo-secure-store'; import { API_BASE_URL } from '@/lib/config'; import { currentAuthEpoch, isCurrentAuthEpoch } from '@/lib/auth/auth-epoch'; -import { parseTokenPair } from '@/lib/auth/native-auth-contract'; -import { isSignOutTeardownActive, setActiveToken } from '@/lib/auth/token-owner'; +import { + API_GATEWAY_CREDENTIAL_FORMAT, + type NativeCredentialBundleMetadata, + type NativeTokenPair, + parseTokenPair, +} from '@/lib/auth/native-auth-contract'; +import { + clearActiveToken, + getActiveTokenSnapshot, + getAuthTokenForRequest, + isSignOutTeardownActive, + publishActiveTokenExpiry, + setActiveToken, +} from '@/lib/auth/token-owner'; import { chainSave } from '@/lib/hooks/save-chain'; -import { AUTH_TOKEN_KEY, REFRESH_TOKEN_KEY, TOKEN_EXPIRES_AT_KEY } from '@/lib/storage-keys'; +import { + AUTH_TOKEN_KEY, + NATIVE_CREDENTIAL_BUNDLE_KEY, + REFRESH_TOKEN_KEY, + TOKEN_EXPIRES_AT_KEY, +} from '@/lib/storage-keys'; import { CONTROL_PLANE_DEADLINE_MS, withDeadline } from '@kilocode/event-service'; +import { parseTimestamp } from '@/lib/utils'; +import { readStoredValueWithRetry } from '@/lib/auth/secure-store-read'; // Apple `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` is not in iCloud or // iTunes backup and does not migrate to a new device. Pin every bearer-token @@ -61,6 +80,8 @@ export async function writeCredentials(write: () => Promise): Promise { type PersistCredentialsOptions = { expiresIn?: number; expectedEpoch?: number; + bundle?: NativeCredentialBundleMetadata; + allowDuringTeardown?: boolean; }; export async function persistSignInCredentialsAtEpoch( @@ -69,8 +90,27 @@ export async function persistSignInCredentialsAtEpoch( options: PersistCredentialsOptions ): Promise { const epoch = options.expectedEpoch ?? currentAuthEpoch(); + const mayWrite = () => + isCurrentAuthEpoch(epoch) && + (options.allowDuringTeardown !== false || !isSignOutTeardownActive()); const expiresIn = options.expiresIn; - const expiresAtMs = refreshToken && expiresIn ? Date.now() + expiresIn * 1000 : null; + const hasBundle = options.bundle !== undefined; + const validBundle = hasBundle + ? parseTokenPair({ token, refreshToken, expiresIn, metadata: options.bundle }) + : null; + + if ( + hasBundle && + (!validBundle?.refreshToken || !validBundle.expiresIn || !validBundle.metadata) + ) { + return false; + } + let expiresAtMs: number | null = null; + if (validBundle?.metadata) { + expiresAtMs = parseTimestamp(validBundle.metadata.expiresAt).getTime(); + } else if (refreshToken && expiresIn) { + expiresAtMs = Date.now() + expiresIn * 1000; + } const hasPair = expiresAtMs !== null; // Wipe every credential key a fenced write may already have committed. @@ -78,21 +118,24 @@ export async function persistSignInCredentialsAtEpoch( // a newer sign-in or sign-out: their own credential write is queued // strictly behind this one. const clearPartialCredentials = async (): Promise => { - await SecureStore.deleteItemAsync(AUTH_TOKEN_KEY, IOS_BEARER_SECURE_STORE_OPTIONS); - await SecureStore.deleteItemAsync(REFRESH_TOKEN_KEY, IOS_BEARER_SECURE_STORE_OPTIONS); - await SecureStore.deleteItemAsync(TOKEN_EXPIRES_AT_KEY, IOS_BEARER_SECURE_STORE_OPTIONS); + await Promise.allSettled([ + SecureStore.deleteItemAsync(AUTH_TOKEN_KEY, IOS_BEARER_SECURE_STORE_OPTIONS), + SecureStore.deleteItemAsync(REFRESH_TOKEN_KEY, IOS_BEARER_SECURE_STORE_OPTIONS), + SecureStore.deleteItemAsync(TOKEN_EXPIRES_AT_KEY, IOS_BEARER_SECURE_STORE_OPTIONS), + SecureStore.deleteItemAsync(NATIVE_CREDENTIAL_BUNDLE_KEY, IOS_BEARER_SECURE_STORE_OPTIONS), + ]); }; // Fence one credential operation: skip it when the epoch moved before the // op, and clear the partial pair when it moved during the op. const commitWrite = async (key: string, value?: string): Promise => { - if (!isCurrentAuthEpoch(epoch)) { + if (!mayWrite()) { return false; } await (value === undefined ? SecureStore.deleteItemAsync(key, IOS_BEARER_SECURE_STORE_OPTIONS) : SecureStore.setItemAsync(key, value, IOS_BEARER_SECURE_STORE_OPTIONS)); - if (!isCurrentAuthEpoch(epoch)) { + if (!mayWrite()) { await clearPartialCredentials(); return false; } @@ -101,19 +144,60 @@ export async function persistSignInCredentialsAtEpoch( let published = false; await writeCredentials(async () => { - if (!(await commitWrite(AUTH_TOKEN_KEY, token))) { - return; - } - if (!(await commitWrite(REFRESH_TOKEN_KEY, hasPair ? refreshToken : undefined))) { - return; - } - if (!(await commitWrite(TOKEN_EXPIRES_AT_KEY, hasPair ? String(expiresAtMs) : undefined))) { - return; + try { + if (hasBundle) { + if (!Number.isFinite(expiresAtMs)) { + return; + } + if (!validBundle?.metadata) { + return; + } + const bundle = validBundle.metadata; + const value = JSON.stringify({ + token, + refreshToken, + expiresIn, + metadata: bundle, + }); + if (!(await commitWrite(NATIVE_CREDENTIAL_BUNDLE_KEY, value))) { + return; + } + if (!(await commitWrite(AUTH_TOKEN_KEY))) { + return; + } + if (!(await commitWrite(REFRESH_TOKEN_KEY))) { + return; + } + if (!(await commitWrite(TOKEN_EXPIRES_AT_KEY))) { + return; + } + setActiveToken(token, expiresAtMs, bundle); + published = true; + return; + } + if (!(await commitWrite(NATIVE_CREDENTIAL_BUNDLE_KEY))) { + return; + } + if (!(await commitWrite(AUTH_TOKEN_KEY, token))) { + return; + } + if (!(await commitWrite(REFRESH_TOKEN_KEY, hasPair ? refreshToken : undefined))) { + return; + } + if (!(await commitWrite(TOKEN_EXPIRES_AT_KEY, hasPair ? String(expiresAtMs) : undefined))) { + return; + } + // Every fenced operation passed its post-check and nothing awaited since + // the last one, so the epoch is still current: publish to the owner. + setActiveToken(token, expiresAtMs); + published = true; + } catch (error) { + await clearPartialCredentials(); + if (isCurrentAuthEpoch(epoch)) { + clearActiveToken(); + } + throw error; } - // Every fenced operation passed its post-check and nothing awaited since - // the last one, so the epoch is still current: publish to the owner. - setActiveToken(token, expiresAtMs); - published = true; }); return published; } @@ -146,7 +230,7 @@ async function doRefresh(): Promise { return { ok: false, refused: false, superseded: true }; } try { - const storedRefreshToken = await SecureStore.getItemAsync(REFRESH_TOKEN_KEY); + const storedRefreshToken = await readRefreshToken(); if (superseded()) { return { ok: false, refused: false, superseded: true }; } @@ -162,7 +246,10 @@ async function doRefresh(): Promise { const res = await fetch(`${API_BASE_URL}/api/auth/native/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ refreshToken: storedRefreshToken }), + body: JSON.stringify({ + refreshToken: storedRefreshToken, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }), signal, }); return res; @@ -196,6 +283,8 @@ async function doRefresh(): Promise { const published = await persistSignInCredentialsAtEpoch(parsed.token, parsed.refreshToken, { expiresIn: parsed.expiresIn, expectedEpoch: sessionVersion, + bundle: parsed.metadata, + allowDuringTeardown: false, }); if (!published) { return { ok: false, refused: false, superseded: true }; @@ -212,3 +301,64 @@ async function doRefresh(): Promise { return { ok: false, refused: false }; } } + +export async function getGatewayAuthTokenForRequest(): Promise { + const epoch = currentAuthEpoch(); + const token = await getAuthTokenForRequest(); + const owner = getActiveTokenSnapshot(); + if (!token || !owner || owner.epoch !== epoch || !isCurrentAuthEpoch(epoch)) { + return null; + } + let expiresAtMs = owner.expiresAtMs; + if (expiresAtMs === null && !owner.bundle) { + const expiresAt = await readStoredValueWithRetry(TOKEN_EXPIRES_AT_KEY); + if (!isCurrentAuthEpoch(epoch)) { + return null; + } + const current = getActiveTokenSnapshot(); + if (!current || current.epoch !== epoch || current.token !== owner.token) { + return getAuthTokenForRequest('gateway'); + } + const parsedExpiry = expiresAt ? Number(expiresAt) : null; + expiresAtMs = parsedExpiry !== null && Number.isFinite(parsedExpiry) ? parsedExpiry : null; + if (expiresAtMs !== null) { + publishActiveTokenExpiry(current, expiresAtMs); + } + } + if (expiresAtMs !== null && shouldRefresh(expiresAtMs)) { + const refreshed = await performRefresh(); + if (!refreshed.ok || !isCurrentAuthEpoch(epoch) || refreshed.sessionVersion !== epoch) { + return null; + } + } + if (!isCurrentAuthEpoch(epoch)) { + return null; + } + return getAuthTokenForRequest('gateway'); +} + +export async function setCredentials(pair: NativeTokenPair): Promise { + const published = await persistSignInCredentialsAtEpoch(pair.token, pair.refreshToken, { + expiresIn: pair.expiresIn, + bundle: pair.metadata, + }); + return published; +} + +function shouldRefresh(expiresAtMs: number): boolean { + return Date.now() >= expiresAtMs - REFRESH_MARGIN_MS; +} + +async function readRefreshToken(): Promise { + const rawBundle = await readStoredValueWithRetry(NATIVE_CREDENTIAL_BUNDLE_KEY); + if (rawBundle !== null) { + try { + const value: unknown = JSON.parse(rawBundle); + const pair = parseTokenPair(value); + return pair?.metadata && pair.refreshToken ? pair.refreshToken : null; + } catch { + return null; + } + } + return readStoredValueWithRetry(REFRESH_TOKEN_KEY); +} diff --git a/apps/mobile/src/lib/auth/device-auth-poll.test.ts b/apps/mobile/src/lib/auth/device-auth-poll.test.ts index 06dbd632e2..137a7d5a60 100644 --- a/apps/mobile/src/lib/auth/device-auth-poll.test.ts +++ b/apps/mobile/src/lib/auth/device-auth-poll.test.ts @@ -89,4 +89,46 @@ describe('startDeviceAuthPoll', () => { expect(cleanup).toHaveBeenCalled(); expect(setState).toHaveBeenCalled(); }); + + it('propagates modern credential metadata with an approved result', async () => { + fetchMock.mockResolvedValue( + Response.json( + { + status: 'approved', + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-01-01T01:00:00.000Z', + }, + }, + { status: 200 } + ) + ); + const { setState } = makePoll(); + + await vi.advanceTimersByTimeAsync(3000); + + const updater = setState.mock.calls[0]?.[0]; + expect( + updater?.({ + status: 'pending', + code: 'UC', + credentials: undefined, + error: undefined, + verificationUrl: 'https://example.test', + }).credentials + ).toEqual({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-01-01T01:00:00.000Z', + }, + }); + }); }); diff --git a/apps/mobile/src/lib/auth/device-auth-poll.ts b/apps/mobile/src/lib/auth/device-auth-poll.ts index 45db863e9f..95de90829f 100644 --- a/apps/mobile/src/lib/auth/device-auth-poll.ts +++ b/apps/mobile/src/lib/auth/device-auth-poll.ts @@ -7,6 +7,7 @@ import { classifyPollResponse } from '@/lib/auth/poll-response'; import { buildClientMetadataHeaders } from '@/lib/client-metadata'; import { buildDeviceAuthPollRequest, + type NativeTokenPair, parseDeviceAuthTokenResponse, } from '@/lib/auth/native-auth-contract'; import { @@ -85,6 +86,8 @@ export function startDeviceAuthPoll(params: { })(); if (parsed?.status === 'approved') { + const credentials: NativeTokenPair & { status?: 'approved' } = { ...parsed }; + delete credentials.status; cleanup(); if (Platform.OS !== 'android') { WebBrowser.dismissAuthSession(); @@ -92,9 +95,7 @@ export function startDeviceAuthPoll(params: { setState(previous => approvedDeviceAuthState({ code, - token: parsed.token, - refreshToken: parsed.refreshToken, - expiresIn: parsed.expiresIn, + credentials, previousVerificationUrl: previous.verificationUrl, }) ); diff --git a/apps/mobile/src/lib/auth/device-auth-state.ts b/apps/mobile/src/lib/auth/device-auth-state.ts index 290a664ada..de3e719529 100644 --- a/apps/mobile/src/lib/auth/device-auth-state.ts +++ b/apps/mobile/src/lib/auth/device-auth-state.ts @@ -1,11 +1,11 @@ +import { type NativeTokenPair } from '@kilocode/app-shared/native-auth'; + type DeviceAuthStatus = 'idle' | 'pending' | 'approved' | 'denied' | 'expired' | 'error'; export type DeviceAuthState = { status: DeviceAuthStatus; code: string | undefined; - token: string | undefined; - refreshToken: string | undefined; - expiresIn: number | undefined; + credentials: NativeTokenPair | undefined; error: string | undefined; verificationUrl: string | undefined; resumed?: boolean; @@ -19,9 +19,7 @@ export function errorDeviceAuthState( return { status: 'error', code, - token: undefined, - refreshToken: undefined, - expiresIn: undefined, + credentials: undefined, error, verificationUrl: previousVerificationUrl, }; @@ -31,9 +29,7 @@ export function idleDeviceAuthState(): DeviceAuthState { return { status: 'idle', code: undefined, - token: undefined, - refreshToken: undefined, - expiresIn: undefined, + credentials: undefined, error: undefined, verificationUrl: undefined, }; @@ -47,9 +43,7 @@ export function pendingDeviceAuthState( return { status: 'pending', code, - token: undefined, - refreshToken: undefined, - expiresIn: undefined, + credentials: undefined, error: undefined, verificationUrl, resumed, @@ -58,17 +52,13 @@ export function pendingDeviceAuthState( export function approvedDeviceAuthState(params: { code: string; - token: string; - refreshToken?: string; - expiresIn?: number; + credentials: NativeTokenPair; previousVerificationUrl?: string; }): DeviceAuthState { return { status: 'approved', code: params.code, - token: params.token, - refreshToken: params.refreshToken, - expiresIn: params.expiresIn, + credentials: params.credentials, error: undefined, verificationUrl: params.previousVerificationUrl, }; @@ -83,9 +73,7 @@ export function terminalDeviceAuthState(params: { return { status: params.status, code: params.code, - token: undefined, - refreshToken: undefined, - expiresIn: undefined, + credentials: undefined, error: params.error, verificationUrl: params.previousVerificationUrl, }; diff --git a/apps/mobile/src/lib/auth/exchange-legacy-token.ts b/apps/mobile/src/lib/auth/exchange-legacy-token.ts index f6c05cba0e..83c2183dfd 100644 --- a/apps/mobile/src/lib/auth/exchange-legacy-token.ts +++ b/apps/mobile/src/lib/auth/exchange-legacy-token.ts @@ -1,21 +1,22 @@ import * as SecureStore from 'expo-secure-store'; +import { type NativeSessionCredentials } from '@kilocode/app-shared/native-auth'; import { API_BASE_URL } from '@/lib/config'; import { currentAuthEpoch, isCurrentAuthEpoch } from '@/lib/auth/auth-epoch'; -import { persistSignInCredentialsAtEpoch } from '@/lib/auth/credentials'; -import { parseTokenPair } from '@/lib/auth/native-auth-contract'; +import { isSignOutTeardownActive } from '@/lib/auth/token-owner'; +import { persistSignInCredentialsAtEpoch, writeCredentials } from '@/lib/auth/credentials'; +import { API_GATEWAY_CREDENTIAL_FORMAT, parseTokenPair } from '@/lib/auth/native-auth-contract'; import { AUTH_TOKEN_KEY, LEGACY_EXCHANGE_DONE_KEY } from '@/lib/storage-keys'; -export async function exchangeLegacyToken(): Promise<{ - token: string; - refreshToken: string; - expiresIn: number; -} | null> { +export async function exchangeLegacyToken(): Promise { try { // Capture the epoch before any asynchronous read: every later epoch check // fences against this moment, so an exchange that started before a // sign-out can never send the stale token or persist its result. const epoch = currentAuthEpoch(); + if (isSignOutTeardownActive()) { + return null; + } // Guard: run at most once. If the marker is already set the exchange succeeded // (or was deliberately skipped) in a past launch. @@ -33,7 +34,7 @@ export async function exchangeLegacyToken(): Promise<{ // The session moved while the marker and legacy token were read: the token // may belong to a signed-out account. Discard before sending it. - if (!isCurrentAuthEpoch(epoch)) { + if (!isCurrentAuthEpoch(epoch) || isSignOutTeardownActive()) { return null; } @@ -43,6 +44,9 @@ export async function exchangeLegacyToken(): Promise<{ 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, + body: JSON.stringify({ + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }), }); if (!response.ok) { @@ -59,7 +63,7 @@ export async function exchangeLegacyToken(): Promise<{ return null; } - if (!isCurrentAuthEpoch(epoch)) { + if (!isCurrentAuthEpoch(epoch) || isSignOutTeardownActive()) { // The session moved while the exchange was in flight: discard the // result so it can never land after a sign-out. return null; @@ -72,24 +76,43 @@ export async function exchangeLegacyToken(): Promise<{ const published = await persistSignInCredentialsAtEpoch(parsed.token, parsed.refreshToken, { expiresIn: parsed.expiresIn, expectedEpoch: epoch, + bundle: getBundleMetadata(parsed), + allowDuringTeardown: false, }); if (!published) { // The session moved while the exchange write was fenced: stop before // the completion marker and the success result. return null; } - if (!isCurrentAuthEpoch(epoch)) { + if (!(await persistExchangeCompletionMarker(epoch))) { return null; } - // Persist the marker so we never exchange again. + + return parsed; + } catch { + return null; + } +} + +async function persistExchangeCompletionMarker(epoch: number): Promise { + let completed = false; + await writeCredentials(async () => { + if (!isCurrentAuthEpoch(epoch) || isSignOutTeardownActive()) { + return; + } await SecureStore.setItemAsync(LEGACY_EXCHANGE_DONE_KEY, '1'); - if (!isCurrentAuthEpoch(epoch)) { + if (!isCurrentAuthEpoch(epoch) || isSignOutTeardownActive()) { await SecureStore.deleteItemAsync(LEGACY_EXCHANGE_DONE_KEY); - return null; + return; } + completed = true; + }); + return completed; +} - return { token: parsed.token, refreshToken: parsed.refreshToken, expiresIn: parsed.expiresIn }; - } catch { - return null; +function getBundleMetadata(value: ReturnType) { + if (!value || !('metadata' in value) || !value.metadata) { + return undefined; } + return value.metadata; } diff --git a/apps/mobile/src/lib/auth/native-auth-contract.ts b/apps/mobile/src/lib/auth/native-auth-contract.ts index 270631e84b..4948b102b6 100644 --- a/apps/mobile/src/lib/auth/native-auth-contract.ts +++ b/apps/mobile/src/lib/auth/native-auth-contract.ts @@ -1,12 +1,13 @@ import * as z from 'zod'; +import { + API_GATEWAY_CREDENTIAL_FORMAT, + type NativeCredentialBundleMetadata, + type NativeTokenPair, + parseNativeTokenPair, +} from '@kilocode/app-shared/native-auth'; const tokenResponseSchema = z.object({ token: z.string().min(1) }); -const tokenPairSchema = z.object({ - token: z.string().min(1), - refreshToken: z.string().min(1).optional(), - expiresIn: z.number().positive().optional(), - created: z.boolean().optional(), -}); +const credentialEnvelopeSchema = z.record(z.string(), z.unknown()); const emailCodeResponseSchema = z.object({ success: z.literal(true), challengeId: z.uuid().optional(), @@ -16,30 +17,35 @@ const errorResponseSchema = z.object({ ssoOrganizationId: z.string().min(1).optional(), }); -export type TokenPair = - | { token: string; refreshToken: string; expiresIn: number; created?: boolean } - | { token: string; refreshToken?: undefined; expiresIn?: undefined; created?: boolean }; +export type TokenPair = NativeTokenPair; export function parseTokenResponse(value: unknown): { token: string } | null { + if (hasCredentialFormat(value)) { + return null; + } const result = tokenResponseSchema.safeParse(value); return result.success ? result.data : null; } export function parseTokenPair(value: unknown): TokenPair | null { - const result = tokenPairSchema.safeParse(value); - if (!result.success) { - return null; - } - const { token, refreshToken, expiresIn, created } = result.data; - if (refreshToken && expiresIn) { - return { token, refreshToken, expiresIn, created }; - } - return { token, created }; + return parseNativeTokenPair(value); +} + +export { API_GATEWAY_CREDENTIAL_FORMAT, type NativeCredentialBundleMetadata, type NativeTokenPair }; + +function hasCredentialFormat(value: unknown): boolean { + const envelope = credentialEnvelopeSchema.safeParse(value); + return ( + envelope.success && + (Object.hasOwn(envelope.data, 'credentialFormat') || + Object.hasOwn(envelope.data, 'gatewayToken') || + Object.hasOwn(envelope.data, 'metadata')) + ); } const deviceAuthTokenStatusSchema = z.enum(['pending', 'approved', 'denied', 'expired']); -const deviceAuthTokenResponseSchema = z.object({ +const deviceAuthTokenResponseSchema = z.looseObject({ status: deviceAuthTokenStatusSchema, token: z.string().min(1).optional(), refreshToken: z.string().min(1).optional(), @@ -54,8 +60,7 @@ const deviceAuthCodeResponseSchema = z.object({ }); export type DeviceAuthTokenResult = - | { status: 'approved'; token: string; refreshToken: string; expiresIn: number } - | { status: 'approved'; token: string; refreshToken?: undefined; expiresIn?: undefined } + | ({ status: 'approved' } & NativeTokenPair) | { status: 'pending' | 'denied' | 'expired' }; export type DeviceAuthCodeResult = { @@ -65,7 +70,11 @@ export type DeviceAuthCodeResult = { }; export function buildDeviceAuthPollRequest(deviceCode: string) { - return { deviceCode, supportsRefresh: true as const }; + return { + deviceCode, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + supportsRefresh: true as const, + }; } export function shouldRefreshBeforeRequest( @@ -94,21 +103,12 @@ export function parseDeviceAuthTokenResponse(value: unknown): DeviceAuthTokenRes if (!result.success) { return null; } - const { status, token, refreshToken, expiresIn } = result.data; - if (status === 'approved' && token) { - // Require a complete pair: both refreshToken AND expiresIn must be - // present. An incomplete pair (one without the other) is dropped to - // token-only so signIn never stores a refresh token with no expiry; - // proactive refresh relies on TOKEN_EXPIRES_AT_KEY to decide rotation. - if (refreshToken && expiresIn) { - return { status, token, refreshToken, expiresIn }; - } - return { status, token }; - } - if (status !== 'approved') { - return { status }; + const { status, ...pairValue } = result.data; + if (status === 'approved') { + const pair = parseNativeTokenPair(pairValue); + return pair ? { status, ...pair } : null; } - return null; + return { status }; } export function parseEmailCodeResponse(value: unknown) { diff --git a/apps/mobile/src/lib/auth/native-credential-lifecycle.test.ts b/apps/mobile/src/lib/auth/native-credential-lifecycle.test.ts new file mode 100644 index 0000000000..8fdebc4d7d --- /dev/null +++ b/apps/mobile/src/lib/auth/native-credential-lifecycle.test.ts @@ -0,0 +1,204 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + API_GATEWAY_CREDENTIAL_FORMAT, + type NativeCredentialBundleMetadata, + type NativeSessionCredentials, +} from '@kilocode/app-shared/native-auth'; +import * as SecureStore from 'expo-secure-store'; +import { bumpAuthEpoch } from './auth-epoch'; +import { + getGatewayAuthTokenForRequest, + performRefresh, + persistSignInCredentialsAtEpoch, + setCredentials, +} from './credentials'; +import { + clearActiveToken, + getActiveToken, + getAuthTokenForRequest, + setActiveToken, + setSignOutTeardownActive, +} from './token-owner'; +import { + AUTH_TOKEN_KEY, + NATIVE_CREDENTIAL_BUNDLE_KEY, + REFRESH_TOKEN_KEY, + TOKEN_EXPIRES_AT_KEY, +} from '@/lib/storage-keys'; + +const store = vi.hoisted(() => new Map()); +vi.mock('expo-secure-store', () => ({ + WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY', + getItemAsync: vi.fn(async (key: string) => { + await Promise.resolve(); + return store.get(key) ?? null; + }), + setItemAsync: vi.fn(async (key: string, value: string) => { + await Promise.resolve(); + store.set(key, value); + }), + deleteItemAsync: vi.fn(async (key: string) => { + await Promise.resolve(); + store.delete(key); + }), +})); +vi.mock('@/lib/config', () => ({ + API_BASE_URL: 'https://api.example.test', + E2E_SECURE_STORE_FAULT_MS: 0, +})); + +function bundle( + suffix: string, + expiresAt = new Date(Date.now() + 3_600_000).toISOString() +): NativeSessionCredentials & { metadata: NativeCredentialBundleMetadata } { + return { + token: `api-${suffix}`, + refreshToken: `refresh-${suffix}`, + expiresIn: 3600, + metadata: { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + gatewayToken: `gateway-${suffix}`, + expiresAt, + }, + }; +} + +beforeEach(() => { + store.clear(); + bumpAuthEpoch(); + clearActiveToken(); + setSignOutTeardownActive(false); + vi.mocked(SecureStore.getItemAsync) + .mockReset() + .mockImplementation(async key => { + await Promise.resolve(); + return store.get(key) ?? null; + }); + vi.mocked(SecureStore.setItemAsync) + .mockReset() + .mockImplementation(async (key, value) => { + await Promise.resolve(); + store.set(key, value); + }); + vi.mocked(SecureStore.deleteItemAsync) + .mockReset() + .mockImplementation(async key => { + await Promise.resolve(); + store.delete(key); + }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('native credential bundle lifecycle', () => { + it('stores the bundle atomically and removes keys an older client could misroute', async () => { + store.set(AUTH_TOKEN_KEY, 'legacy'); + store.set(REFRESH_TOKEN_KEY, 'legacy-refresh'); + store.set(TOKEN_EXPIRES_AT_KEY, '123'); + const credentials = bundle('one'); + await expect(setCredentials(credentials)).resolves.toBe(true); + expect(JSON.parse(store.get(NATIVE_CREDENTIAL_BUNDLE_KEY) ?? 'null')).toEqual(credentials); + expect(store.has(AUTH_TOKEN_KEY)).toBe(false); + expect(store.has(REFRESH_TOKEN_KEY)).toBe(false); + expect(store.has(TOKEN_EXPIRES_AT_KEY)).toBe(false); + clearActiveToken(); + await expect(getAuthTokenForRequest()).resolves.toBe('api-one'); + await expect(getGatewayAuthTokenForRequest()).resolves.toBe('gateway-one'); + expect(getActiveToken()?.expiresAtMs).toBe(Date.parse(credentials.metadata.expiresAt)); + }); + + it('rejects an incomplete tagged pair before writing or replacing the owner', async () => { + setActiveToken('prior-token', null); + await expect( + persistSignInCredentialsAtEpoch('api-one', undefined, { bundle: bundle('one').metadata }) + ).resolves.toBe(false); + expect(SecureStore.setItemAsync).not.toHaveBeenCalled(); + expect(SecureStore.deleteItemAsync).not.toHaveBeenCalled(); + expect(getActiveToken()?.token).toBe('prior-token'); + }); + + it.each([ + 'broken-json', + '{}', + JSON.stringify({ token: 'misplaced-legacy', refreshToken: 'refresh', expiresIn: 3600 }), + ])('does not fall back to legacy credentials from a corrupt versioned record: %s', async raw => { + store.set(NATIVE_CREDENTIAL_BUNDLE_KEY, raw); + store.set(AUTH_TOKEN_KEY, 'legacy'); + store.set(REFRESH_TOKEN_KEY, 'legacy-refresh'); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + await expect(getAuthTokenForRequest()).resolves.toBeNull(); + await expect(getGatewayAuthTokenForRequest()).resolves.toBeNull(); + await expect(performRefresh()).resolves.toMatchObject({ ok: false, refused: true }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refreshes both members through one rotation before a gateway request', async () => { + await setCredentials(bundle('old', new Date(Date.now() + 30_000).toISOString())); + const next = bundle('new'); + const fetchMock = vi.fn().mockResolvedValue(Response.json(next)); + vi.stubGlobal('fetch', fetchMock); + const [refresh, gatewayToken] = await Promise.all([ + performRefresh(), + getGatewayAuthTokenForRequest(), + ]); + expect(refresh.ok).toBe(true); + expect(gatewayToken).toBe('gateway-new'); + await expect(getAuthTokenForRequest()).resolves.toBe('api-new'); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0]?.[1]?.body).toBe( + JSON.stringify({ + refreshToken: 'refresh-old', + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }) + ); + expect(JSON.parse(store.get(NATIVE_CREDENTIAL_BUNDLE_KEY) ?? 'null')).toEqual(next); + }); + + it('replaces a modern bundle with a valid legacy response during rollback', async () => { + await setCredentials(bundle('old')); + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + Response.json({ token: 'legacy-new', refreshToken: 'legacy-refresh', expiresIn: 3600 }) + ) + ); + await expect(performRefresh()).resolves.toMatchObject({ ok: true, token: 'legacy-new' }); + expect(store.has(NATIVE_CREDENTIAL_BUNDLE_KEY)).toBe(false); + expect(store.get(AUTH_TOKEN_KEY)).toBe('legacy-new'); + await expect(getGatewayAuthTokenForRequest()).resolves.toBe('legacy-new'); + }); + + it('clears partial disk state and the current owner when persistence fails', async () => { + await setCredentials(bundle('old')); + vi.mocked(SecureStore.setItemAsync).mockImplementationOnce(async (key, value) => { + await Promise.resolve(); + store.set(key, value); + throw new Error('synthetic storage failure'); + }); + await expect(setCredentials(bundle('new'))).rejects.toThrow('synthetic storage failure'); + expect(store.size).toBe(0); + expect(getActiveToken()).toBeNull(); + }); + + it('never returns a different account gateway credential after a cold-read race', async () => { + const old = bundle('old'); + store.set(NATIVE_CREDENTIAL_BUNDLE_KEY, JSON.stringify(old)); + const gate = Promise.withResolvers(); + vi.mocked(SecureStore.getItemAsync).mockImplementationOnce(async () => { + await gate.promise; + return JSON.stringify(old); + }); + const pending = getGatewayAuthTokenForRequest(); + expect(SecureStore.getItemAsync).toHaveBeenCalledWith(NATIVE_CREDENTIAL_BUNDLE_KEY, undefined); + bumpAuthEpoch(); + const next = bundle('new'); + setActiveToken(next.token, Date.parse(next.metadata.expiresAt), next.metadata); + gate.resolve(undefined); + await expect(pending).resolves.toBeNull(); + await expect(getGatewayAuthTokenForRequest()).resolves.toBe('gateway-new'); + }); +}); diff --git a/apps/mobile/src/lib/auth/token-owner.test.ts b/apps/mobile/src/lib/auth/token-owner.test.ts index 314e215f63..aea4c9edf3 100644 --- a/apps/mobile/src/lib/auth/token-owner.test.ts +++ b/apps/mobile/src/lib/auth/token-owner.test.ts @@ -16,10 +16,11 @@ vi.mock('expo-secure-store', () => ({ store.delete(key); }), })); +vi.mock('@/lib/config', () => ({ E2E_SECURE_STORE_FAULT_MS: 0 })); /* eslint-disable import/first */ import * as SecureStore from 'expo-secure-store'; -import { AUTH_TOKEN_KEY } from '@/lib/storage-keys'; +import { AUTH_TOKEN_KEY, NATIVE_CREDENTIAL_BUNDLE_KEY } from '@/lib/storage-keys'; import { bumpAuthEpoch } from './auth-epoch'; import { clearActiveToken, @@ -84,7 +85,7 @@ describe('token-owner', () => { it('reads SecureStore once on the cold path and returns the stored token', async () => { store.set(AUTH_TOKEN_KEY, 'stored-token'); await expect(getAuthTokenForRequest()).resolves.toBe('stored-token'); - expect(SecureStore.getItemAsync).toHaveBeenCalledTimes(1); + expect(SecureStore.getItemAsync).toHaveBeenCalledTimes(2); }); it('warms the owner on a cold read so the next read is in-memory', async () => { @@ -93,8 +94,9 @@ describe('token-owner', () => { expect(getActiveToken()).toEqual({ token: 'stored-token', expiresAtMs: null }); await getAuthTokenForRequest(); - // One SecureStore read for the first (cold) call, none for the warm hit. - expect(SecureStore.getItemAsync).toHaveBeenCalledTimes(1); + // The first cold call checks the versioned bundle and legacy key; the + // warm hit does not access SecureStore. + expect(SecureStore.getItemAsync).toHaveBeenCalledTimes(2); }); it('does not warm the owner when the epoch changes mid-read', async () => { @@ -166,6 +168,62 @@ describe('token-owner', () => { await expect(pending).resolves.toBeNull(); expect(getActiveToken()).toBeNull(); }); + + it('uses the gateway credential from a versioned bundle', async () => { + store.set( + NATIVE_CREDENTIAL_BUNDLE_KEY, + JSON.stringify({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2030-01-01T00:00:00.000Z', + }, + }) + ); + + await expect(getAuthTokenForRequest()).resolves.toBe('api-token'); + await expect(getAuthTokenForRequest('gateway')).resolves.toBe('gateway-token'); + }); + + it('retries a transient modern bundle read before restoring it', async () => { + store.set( + NATIVE_CREDENTIAL_BUNDLE_KEY, + JSON.stringify({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2030-01-01T00:00:00.000Z', + }, + }) + ); + vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(new Error('keychain unavailable')); + + await expect(getAuthTokenForRequest()).resolves.toBe('api-token'); + expect(SecureStore.getItemAsync).toHaveBeenCalledTimes(2); + await expect(getAuthTokenForRequest('gateway')).resolves.toBe('gateway-token'); + }); + + it('uses a legacy token for gateway requests when no versioned bundle exists', async () => { + store.set(AUTH_TOKEN_KEY, 'legacy-token'); + + await expect(getAuthTokenForRequest('gateway')).resolves.toBe('legacy-token'); + }); + + it('does not fall back to legacy credentials for a corrupted tagged bundle', async () => { + store.set( + NATIVE_CREDENTIAL_BUNDLE_KEY, + JSON.stringify({ metadata: { credentialFormat: 'bad' } }) + ); + store.set(AUTH_TOKEN_KEY, 'legacy-token'); + + await expect(getAuthTokenForRequest()).resolves.toBeNull(); + }); }); describe('publishActiveTokenExpiry', () => { diff --git a/apps/mobile/src/lib/auth/token-owner.ts b/apps/mobile/src/lib/auth/token-owner.ts index 882e039b62..cb131b6907 100644 --- a/apps/mobile/src/lib/auth/token-owner.ts +++ b/apps/mobile/src/lib/auth/token-owner.ts @@ -1,14 +1,21 @@ -import * as SecureStore from 'expo-secure-store'; - import { currentAuthEpoch, isCurrentAuthEpoch } from '@/lib/auth/auth-epoch'; -import { AUTH_TOKEN_KEY } from '@/lib/storage-keys'; +import { + type NativeCredentialBundleMetadata, + parseNativeTokenPair, +} from '@kilocode/app-shared/native-auth'; +import { AUTH_TOKEN_KEY, NATIVE_CREDENTIAL_BUNDLE_KEY } from '@/lib/storage-keys'; +import { parseTimestamp } from '@/lib/utils'; +import { readStoredValueWithRetry } from '@/lib/auth/secure-store-read'; export type ActiveToken = { token: string; expiresAtMs: number | null; }; -export type ActiveTokenSnapshot = ActiveToken & { epoch: number }; +export type ActiveTokenSnapshot = ActiveToken & { + epoch: number; + bundle?: NativeCredentialBundleMetadata; +}; let activeToken: ActiveTokenSnapshot | null = null; @@ -30,8 +37,12 @@ export function isSignOutTeardownActive(): boolean { } /** Holds the token in memory, tagged with the auth epoch that was current when it was stored. */ -export function setActiveToken(token: string, expiresAtMs: number | null): void { - activeToken = { token, expiresAtMs, epoch: currentAuthEpoch() }; +export function setActiveToken( + token: string, + expiresAtMs: number | null, + bundle?: NativeCredentialBundleMetadata +): void { + activeToken = { token, expiresAtMs, epoch: currentAuthEpoch(), ...(bundle ? { bundle } : {}) }; } /** Returns the held token and expiry, or null when unset or when the epoch moved. */ @@ -86,10 +97,13 @@ export function clearActiveToken(): void { * sign-out teardown the cold path returns no token and never warms: the * stored credentials are scheduled for deletion. */ -export async function getAuthTokenForRequest(): Promise { +export async function getAuthTokenForRequest( + resource: 'api' | 'gateway' = 'api' +): Promise { const active = getActiveToken(); if (active) { - return active.token; + const snapshot = getActiveTokenSnapshot(); + return resource === 'api' ? active.token : (snapshot?.bundle?.gatewayToken ?? active.token); } const epoch = currentAuthEpoch(); // Sign-out teardown is active: the stored credentials are queued for @@ -97,12 +111,29 @@ export async function getAuthTokenForRequest(): Promise { if (isSignOutTeardownActive()) { return null; } - const token = await SecureStore.getItemAsync(AUTH_TOKEN_KEY); + const rawBundle = await readStoredValueWithRetry(NATIVE_CREDENTIAL_BUNDLE_KEY); + if (rawBundle !== null) { + const bundle = parseStoredBundle(rawBundle); + const published = getActiveToken(); + if (published) { + return resource === 'api' + ? published.token + : (getActiveTokenSnapshot()?.bundle?.gatewayToken ?? published.token); + } + if (!bundle || !isCurrentAuthEpoch(epoch) || isSignOutTeardownActive()) { + return null; + } + setActiveToken(bundle.token, bundle.expiresAtMs, bundle); + return resource === 'api' ? bundle.token : bundle.gatewayToken; + } + const token = await readStoredValueWithRetry(AUTH_TOKEN_KEY); // A sign-in or refresh may have published a newer owner while the cold read // was in flight: prefer it and never overwrite it with the stale read. const published = getActiveToken(); if (published) { - return published.token; + return resource === 'api' + ? published.token + : (getActiveTokenSnapshot()?.bundle?.gatewayToken ?? published.token); } // One read for both decisions: the flag cannot change between them. const tearingDown = isSignOutTeardownActive(); @@ -111,3 +142,27 @@ export async function getAuthTokenForRequest(): Promise { } return tearingDown ? null : token; } + +type StoredBundle = NativeCredentialBundleMetadata & { + token: string; + refreshToken: string; + expiresIn: number; + expiresAtMs: number; +}; + +function parseStoredBundle(raw: string): StoredBundle | null { + try { + const value: unknown = JSON.parse(raw); + const pair = parseNativeTokenPair(value); + if (!pair?.refreshToken || !pair.expiresIn || !pair.metadata) { + return null; + } + const expiresAtMs = parseTimestamp(pair.metadata.expiresAt).getTime(); + if (!Number.isFinite(expiresAtMs)) { + return null; + } + return { ...pair, ...pair.metadata, expiresAtMs }; + } catch { + return null; + } +} diff --git a/apps/mobile/src/lib/auth/use-auth-bootstrap.ts b/apps/mobile/src/lib/auth/use-auth-bootstrap.ts new file mode 100644 index 0000000000..7dfd6a497a --- /dev/null +++ b/apps/mobile/src/lib/auth/use-auth-bootstrap.ts @@ -0,0 +1,133 @@ +import * as SecureStore from 'expo-secure-store'; +import { type Dispatch, type SetStateAction, useCallback, useEffect } from 'react'; + +import { exchangeLegacyToken } from '@/lib/auth/exchange-legacy-token'; +import { readUserIdFromToken } from '@/lib/auth/auth-user-id'; +import { currentAuthEpoch, isCurrentAuthEpoch } from '@/lib/auth/auth-epoch'; +import { isSignOutActive } from '@/lib/auth/sign-out-state'; +import { readStoredValueWithRetry } from '@/lib/auth/secure-store-read'; +import { + getActiveToken, + getActiveTokenSnapshot, + getAuthTokenForRequest, + setActiveToken, +} from '@/lib/auth/token-owner'; +import { setCurrentDeepLinkUserId } from '@/lib/deep-link-launch'; +import { AUTH_TOKEN_KEY, REFRESH_TOKEN_KEY, TOKEN_EXPIRES_AT_KEY } from '@/lib/storage-keys'; + +// Pre-load tokens at module level so they're available before React mounts +export const preloadedAuthToken = getAuthTokenForRequest(); +const preloadedRefreshToken = SecureStore.getItemAsync(REFRESH_TOKEN_KEY); + +async function observePreloadRejection(preload: Promise): Promise { + try { + await preload; + } catch { + // Bootstrap owns the restore outcome. + } +} + +void observePreloadRejection(preloadedAuthToken); +void observePreloadRejection(preloadedRefreshToken); + +type AuthBootstrapOptions = { + setToken: Dispatch>; + setIsLoading: Dispatch>; + setRestoreFailed: Dispatch>; +}; + +export function useAuthBootstrap({ + setToken, + setIsLoading, + setRestoreFailed, +}: AuthBootstrapOptions) { + const load = useCallback( + async (preload?: { + readonly token: Promise; + readonly refresh: Promise; + }) => { + const epoch = currentAuthEpoch(); + try { + const stored = await (preload?.token ?? getAuthTokenForRequest()); + if (!isCurrentAuthEpoch(epoch) || isSignOutActive()) { + return; + } + if (stored) { + const owner = getActiveTokenSnapshot(); + if (owner?.token === stored && owner.bundle) { + setRestoreFailed(false); + setToken(stored); + setCurrentDeepLinkUserId(readUserIdFromToken(stored)); + return; + } + const storedRefresh = await readStoredValueWithRetry( + REFRESH_TOKEN_KEY, + undefined, + preload?.refresh + ); + if (!isCurrentAuthEpoch(epoch) || isSignOutActive()) { + return; + } + setRestoreFailed(false); + // Legacy exchange: if we have a token but no refresh token, upgrade once. + if (!storedRefresh) { + const pair = await exchangeLegacyToken(); + if (pair && isCurrentAuthEpoch(epoch) && !isSignOutActive()) { + setToken(pair.token); + setCurrentDeepLinkUserId(readUserIdFromToken(pair.token)); + return; + } + } + // The session moved while the preload or legacy exchange was in + // flight: never resurrect the preloaded token. + if (!isCurrentAuthEpoch(epoch) || isSignOutActive()) { + return; + } + const expiresAtStr = await readStoredValueWithRetry(TOKEN_EXPIRES_AT_KEY); + // Fence the asynchronous expiry read: a sign-out or newer sign-in + // during the reads owns the session, so the stale snapshot must not + // be republished and nothing may be surfaced for the torn-down + // session. + const currentStored = await readStoredValueWithRetry(AUTH_TOKEN_KEY); + if (!isCurrentAuthEpoch(epoch) || isSignOutActive()) { + return; + } + // A same-session refresh replaced the stored pair while the reads + // were in flight. The preloaded snapshot is stale, but the session + // is alive: publish the winner the refresh already put in the owner, + // or the provider ends bootstrap with no token and sends a + // signed-in user to the login screen. + if (currentStored !== stored) { + const published = getActiveToken()?.token ?? currentStored ?? undefined; + setToken(published); + setCurrentDeepLinkUserId(published ? readUserIdFromToken(published) : null); + return; + } + setActiveToken(stored, expiresAtStr ? Number(expiresAtStr) : null); + setToken(stored); + setCurrentDeepLinkUserId(readUserIdFromToken(stored)); + return; + } + setRestoreFailed(false); + } catch { + if (isCurrentAuthEpoch(epoch) && !isSignOutActive()) { + setRestoreFailed(true); + } + } finally { + setIsLoading(false); + } + }, + [setIsLoading, setRestoreFailed, setToken] + ); + + useEffect(() => { + void load({ token: preloadedAuthToken, refresh: preloadedRefreshToken }); + }, [load]); + + const retryRestore = useCallback(() => { + setIsLoading(true); + void load(); + }, [load, setIsLoading]); + + return { retryRestore }; +} diff --git a/apps/mobile/src/lib/auth/use-device-approval-persistence.test.ts b/apps/mobile/src/lib/auth/use-device-approval-persistence.test.ts new file mode 100644 index 0000000000..a40913d536 --- /dev/null +++ b/apps/mobile/src/lib/auth/use-device-approval-persistence.test.ts @@ -0,0 +1,192 @@ +/* oxlint-disable typescript-eslint/no-deprecated -- react-test-renderer mounts hooks in the node Vitest environment */ +import { createElement } from 'react'; +import TestRenderer, { act } from 'react-test-renderer'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { type NativeTokenPair } from '@kilocode/app-shared/native-auth'; + +import { clearLoginDrafts } from '@/lib/login-draft'; +import { useDeviceApprovalPersistence } from './use-device-approval-persistence'; + +vi.mock('@/lib/login-draft', () => ({ clearLoginDrafts: vi.fn() })); + +const credentials = { token: 'device-token' } satisfies NativeTokenPair; + +type Persistence = ReturnType; + +type HarnessProps = { + signIn: (pair: NativeTokenPair) => Promise; + resultRef: { current: Persistence | null }; + credentials: NativeTokenPair; +}; + +function Harness({ signIn, resultRef, credentials: approvedCredentials }: HarnessProps): null { + resultRef.current = useDeviceApprovalPersistence({ + status: 'approved', + credentials: approvedCredentials, + signIn, + couldNotCompleteSignIn: 'Could not complete sign-in.', + }); + return null; +} + +async function mountPersistence(signIn: (pair: NativeTokenPair) => Promise) { + const resultRef: { current: Persistence | null } = { current: null }; + let renderer: TestRenderer.ReactTestRenderer | undefined = undefined; + await act(async () => { + renderer = TestRenderer.create(createElement(Harness, { signIn, resultRef, credentials })); + await Promise.resolve(); + }); + return { + resultRef, + updateCredentials: async (nextCredentials: NativeTokenPair) => { + await act(async () => { + renderer?.update( + createElement(Harness, { signIn, resultRef, credentials: nextCredentials }) + ); + await Promise.resolve(); + }); + }, + unmount: () => renderer?.unmount(), + }; +} + +describe('useDeviceApprovalPersistence', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('does not queue a manual retry while automatic persistence is in flight', async () => { + const signInResult = Promise.withResolvers(); + const signIn = vi.fn(async () => { + const result = await signInResult.promise; + return result; + }); + const { resultRef, unmount } = await mountPersistence(signIn); + + expect(signIn).toHaveBeenCalledTimes(1); + expect(resultRef.current?.isPersisting).toBe(true); + await act(async () => { + await Promise.all([ + resultRef.current?.persistToken(credentials), + resultRef.current?.persistToken(credentials), + ]); + }); + expect(signIn).toHaveBeenCalledTimes(1); + + await act(async () => { + signInResult.resolve(true); + await signInResult.promise; + }); + expect(clearLoginDrafts).toHaveBeenCalledTimes(1); + unmount(); + }); + + it('allows retry after a rejected persistence attempt and clears drafts only on success', async () => { + const signIn = vi + .fn() + .mockRejectedValueOnce(new Error('write failed')) + .mockResolvedValueOnce(true); + const { resultRef, unmount } = await mountPersistence(signIn); + + await vi.waitFor(() => { + expect(resultRef.current?.persistError).toBe('Could not complete sign-in.'); + }); + expect(clearLoginDrafts).not.toHaveBeenCalled(); + + await act(async () => { + await resultRef.current?.persistToken(credentials); + }); + expect(signIn).toHaveBeenCalledTimes(2); + expect(clearLoginDrafts).toHaveBeenCalledTimes(1); + unmount(); + }); + + it('keeps the login draft when sign-in resolves without publishing credentials', async () => { + const signIn = vi.fn().mockResolvedValue(false); + const { resultRef, unmount } = await mountPersistence(signIn); + + await vi.waitFor(() => { + expect(resultRef.current?.persistError).toBe('Could not complete sign-in.'); + }); + expect(signIn).toHaveBeenCalledTimes(1); + expect(clearLoginDrafts).not.toHaveBeenCalled(); + unmount(); + }); + + it('persists replacement credentials after the in-flight original succeeds', async () => { + const first = Promise.withResolvers(); + const second = Promise.withResolvers(); + const replacement = { token: 'replacement-token' } satisfies NativeTokenPair; + const signIn = vi + .fn() + .mockImplementationOnce(async () => { + const result = await first.promise; + return result; + }) + .mockImplementationOnce(async () => { + const result = await second.promise; + return result; + }); + const { resultRef, updateCredentials, unmount } = await mountPersistence(signIn); + + await updateCredentials(replacement); + expect(signIn).toHaveBeenCalledTimes(1); + await act(async () => { + first.resolve(true); + await first.promise; + }); + await vi.waitFor(() => { + expect(signIn).toHaveBeenCalledTimes(2); + }); + expect(signIn).toHaveBeenLastCalledWith(replacement); + expect(clearLoginDrafts).not.toHaveBeenCalled(); + + await act(async () => { + second.resolve(true); + await second.promise; + }); + expect(resultRef.current?.isPersisting).toBe(false); + expect(clearLoginDrafts).toHaveBeenCalledTimes(1); + unmount(); + }); + + it('persists replacement credentials after the in-flight original fails', async () => { + const first = Promise.withResolvers(); + const second = Promise.withResolvers(); + const replacement = { token: 'replacement-token' } satisfies NativeTokenPair; + const signIn = vi + .fn() + .mockImplementationOnce(async () => { + const result = await first.promise; + return result; + }) + .mockImplementationOnce(async () => { + const result = await second.promise; + return result; + }); + const { resultRef, updateCredentials, unmount } = await mountPersistence(signIn); + + await updateCredentials(replacement); + await act(async () => { + first.reject(new Error('write failed')); + try { + await first.promise; + } catch { + // The hook handles the failed original attempt before continuing with the replacement. + } + }); + await vi.waitFor(() => { + expect(signIn).toHaveBeenCalledTimes(2); + }); + expect(signIn).toHaveBeenLastCalledWith(replacement); + expect(resultRef.current?.persistError).toBeUndefined(); + + await act(async () => { + second.resolve(true); + await second.promise; + }); + expect(resultRef.current?.isPersisting).toBe(false); + expect(clearLoginDrafts).toHaveBeenCalledTimes(1); + unmount(); + }); +}); diff --git a/apps/mobile/src/lib/auth/use-device-approval-persistence.ts b/apps/mobile/src/lib/auth/use-device-approval-persistence.ts new file mode 100644 index 0000000000..61c72bc24f --- /dev/null +++ b/apps/mobile/src/lib/auth/use-device-approval-persistence.ts @@ -0,0 +1,102 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { type NativeTokenPair } from '@kilocode/app-shared/native-auth'; + +import { clearLoginDrafts } from '@/lib/login-draft'; + +type DeviceApprovalPersistenceOptions = { + status: string; + credentials: NativeTokenPair | undefined; + signIn: (pair: NativeTokenPair) => Promise; + couldNotCompleteSignIn: string; +}; + +type DeviceApprovalPersistence = { + persistError: string | undefined; + isPersisting: boolean; + persistToken: (pair: NativeTokenPair) => Promise; +}; + +export function useDeviceApprovalPersistence({ + status, + credentials, + signIn, + couldNotCompleteSignIn, +}: DeviceApprovalPersistenceOptions): DeviceApprovalPersistence { + const [persistError, setPersistError] = useState(undefined); + const [isPersisting, setIsPersisting] = useState(false); + const attemptedCredentials = useRef(undefined); + const isPersistingRef = useRef(false); + const activeCredentials = useRef(undefined); + const pendingCredentials = useRef(undefined); + const isMounted = useRef(true); + + useEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + + const persistToken = useCallback( + async (pair: NativeTokenPair) => { + if (isPersistingRef.current) { + // Preserve the newest credentials received from device approval while + // the current auth transition finishes. Repeating the active pair is + // a rapid Retry and must not enqueue a duplicate transition. + if (activeCredentials.current !== pair) { + pendingCredentials.current = pair; + } + return; + } + isPersistingRef.current = true; + activeCredentials.current = pair; + attemptedCredentials.current = pair; + setIsPersisting(true); + setPersistError(undefined); + try { + const persistLatest = async (nextCredentials: NativeTokenPair): Promise => { + activeCredentials.current = nextCredentials; + attemptedCredentials.current = nextCredentials; + let didPersist = false; + try { + didPersist = await signIn(nextCredentials); + } catch { + didPersist = false; + } + + const pending = pendingCredentials.current; + pendingCredentials.current = undefined; + return pending ? persistLatest(pending) : didPersist; + }; + const didPersist = await persistLatest(pair); + + if (didPersist) { + clearLoginDrafts(); + } else if (isMounted.current) { + setPersistError(couldNotCompleteSignIn); + } + } finally { + isPersistingRef.current = false; + activeCredentials.current = undefined; + if (isMounted.current) { + setIsPersisting(false); + } + } + }, + [couldNotCompleteSignIn, signIn] + ); + + useEffect(() => { + if (status !== 'approved' || !credentials) { + attemptedCredentials.current = undefined; + return; + } + if (attemptedCredentials.current === credentials) { + return; + } + attemptedCredentials.current = credentials; + void persistToken(credentials); + }, [credentials, persistToken, status]); + + return { persistError, isPersisting, persistToken }; +} diff --git a/apps/mobile/src/lib/auth/use-device-auth.test.ts b/apps/mobile/src/lib/auth/use-device-auth.test.ts index 146800a4c4..70d25aa655 100644 --- a/apps/mobile/src/lib/auth/use-device-auth.test.ts +++ b/apps/mobile/src/lib/auth/use-device-auth.test.ts @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { getDeviceAuth429Message } from '@/lib/auth/poll-response'; import { + API_GATEWAY_CREDENTIAL_FORMAT, buildDeviceAuthPollRequest, parseDeviceAuthTokenResponse, } from '@/lib/auth/native-auth-contract'; @@ -56,6 +57,7 @@ describe('device-auth polling request', () => { expect(buildDeviceAuthPollRequest('device-secret')).toEqual({ deviceCode: 'device-secret', supportsRefresh: true, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, }); }); }); diff --git a/apps/mobile/src/lib/auth/use-native-auth.test.ts b/apps/mobile/src/lib/auth/use-native-auth.test.ts index 48903a7a70..d934f3189f 100644 --- a/apps/mobile/src/lib/auth/use-native-auth.test.ts +++ b/apps/mobile/src/lib/auth/use-native-auth.test.ts @@ -17,6 +17,7 @@ import { parseTokenResponse, selectChallengeId, } from '@/lib/auth/native-auth-contract'; +import { API_GATEWAY_CREDENTIAL_FORMAT } from '@kilocode/app-shared/native-auth'; // Mock @/lib/config to avoid pulling in react-native at module import time. vi.mock('@/lib/config', () => ({ @@ -77,7 +78,7 @@ vi.mock('expo-crypto', () => ({ })); vi.mock('@/lib/auth/auth-context', () => ({ - useAuth: vi.fn(() => ({ signIn: vi.fn() })), + useAuth: vi.fn(() => ({ signIn: vi.fn().mockResolvedValue(true) })), })); // Mock getAdmission so resolveAdmission tests can control the three paths: @@ -118,6 +119,7 @@ const mockGetAdmission = vi.mocked(getAdmission); const { useNativeAuth } = await import('@/lib/auth/use-native-auth'); const { postAuth } = await import('@/lib/auth/auth-fetch'); +const { useAuth } = await import('@/lib/auth/auth-context'); const mockPostAuth = vi.mocked(postAuth); // ── C12: Config invariant ──────────────────────────────────────────────── @@ -182,6 +184,20 @@ describe('native-auth-contract (used by use-native-auth)', () => { expect(result).toEqual({ token: 'at', refreshToken: 'rt', expiresIn: 3600 }); }); + it('retains modern gateway credential metadata', () => { + const metadata = { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + gatewayToken: 'gateway-token', + expiresAt: '2026-01-01T01:00:00.000Z', + }; + expect( + parseTokenPair({ token: 'at', refreshToken: 'rt', expiresIn: 3600, metadata }) + ).toMatchObject({ + token: 'at', + metadata, + }); + }); + it('parses a token-only response (legacy server without refresh)', () => { const result = parseTokenPair({ token: 'at' }); expect(result).toEqual({ token: 'at' }); @@ -435,6 +451,49 @@ describe('useNativeAuth created-account announcement', () => { expect(announcingToast.success).not.toHaveBeenCalled(); }); + it('negotiates gateway credentials and forwards their metadata', async () => { + const signIn = vi.fn().mockResolvedValue(true); + vi.mocked(useAuth).mockReturnValue({ + token: undefined, + isLoading: false, + sessionEnded: false, + authEpoch: 0, + isSigningOut: false, + restoreFailed: false, + retryRestore: () => undefined, + signIn, + signOut: vi.fn(), + }); + const metadata = { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + gatewayToken: 'gateway-token', + expiresAt: '2026-01-01T01:00:00.000Z', + }; + mockPostAuth.mockResolvedValue({ + ok: true, + data: { token: 'api-token', refreshToken: 'refresh-token', expiresIn: 3600, metadata }, + }); + + const resultRef = await mountNativeAuth(); + await act(async () => { + await resultRef.current?.verifyEmailCode('user@example.com', '123456'); + }); + + expect(mockPostAuth).toHaveBeenCalledWith( + '/api/auth/native/token', + expect.objectContaining({ + supportsRefresh: true, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }) + ); + expect(signIn).toHaveBeenCalledWith({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata, + }); + }); + it('stays silent when created is false', async () => { mockPostAuth.mockResolvedValue({ ok: true, @@ -451,4 +510,29 @@ describe('useNativeAuth created-account announcement', () => { expect(announcingToast.success).not.toHaveBeenCalled(); }); + + it('does not report successful email sign-in when credentials are not published', async () => { + const signIn = vi.fn().mockResolvedValue(false); + vi.mocked(useAuth).mockReturnValue({ + token: undefined, + isLoading: false, + sessionEnded: false, + authEpoch: 0, + isSigningOut: false, + restoreFailed: false, + retryRestore: () => undefined, + signIn, + signOut: vi.fn(), + }); + mockPostAuth.mockResolvedValue({ + ok: true, + data: { token: 'at', refreshToken: 'rt', expiresIn: 3600, created: true }, + }); + + const resultRef = await mountNativeAuth(); + const result = await resultRef.current?.verifyEmailCode('user@example.com', '123456'); + + expect(result).toBe(false); + expect(announcingToast.success).not.toHaveBeenCalled(); + }); }); diff --git a/apps/mobile/src/lib/auth/use-native-auth.ts b/apps/mobile/src/lib/auth/use-native-auth.ts index 49b84c64bf..1430822434 100644 --- a/apps/mobile/src/lib/auth/use-native-auth.ts +++ b/apps/mobile/src/lib/auth/use-native-auth.ts @@ -5,6 +5,10 @@ import { Platform } from 'react-native'; import { toast } from 'sonner-native'; import { GoogleSignin } from '@react-native-google-signin/google-signin'; +import { + API_GATEWAY_CREDENTIAL_FORMAT, + type NativeTokenPair, +} from '@kilocode/app-shared/native-auth'; import { i18n } from '@/i18n'; import { GOOGLE_IOS_CLIENT_ID, GOOGLE_WEB_CLIENT_ID } from '@/lib/config'; @@ -52,6 +56,32 @@ type NativeAuthResult = { handleSsoError: (email: string, ssoOrganizationId: string | undefined) => void; }; +async function getAdmissionBody() { + try { + return await resolveAdmission(); + } catch { + return null; + } +} + +async function completeNativeSignIn( + data: unknown, + signIn: (pair: NativeTokenPair) => Promise +): Promise { + const pair = parseTokenPair(data); + if (!pair) { + toast.error(defaultErrorMessage()); + return false; + } + if (!(await signIn(pair))) { + return false; + } + if (pair.created === true) { + announcingToast.success(i18n.t('login.accountCreated')); + } + return true; +} + export function useNativeAuth(): NativeAuthResult { const { signIn } = useAuth(); const [busy, setBusy] = useState(undefined); @@ -113,10 +143,8 @@ export function useNativeAuth(): NativeAuthResult { ? AppleAuthentication.formatFullName(credential.fullName) || undefined : undefined; - let admissionBody: Record = {}; - try { - admissionBody = await resolveAdmission(); - } catch { + const admissionBody = await getAdmissionBody(); + if (!admissionBody) { return; } @@ -126,23 +154,12 @@ export function useNativeAuth(): NativeAuthResult { idToken: credential.identityToken, nonce: rawNonce, supportsRefresh: true, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, ...(fullName ? { fullName } : {}), }); if (result.ok) { - const parsed = parseTokenPair(result.data); - if (!parsed) { - toast.error(defaultErrorMessage()); - return; - } - await signIn( - parsed.token, - 'refreshToken' in parsed ? parsed.refreshToken : undefined, - 'expiresIn' in parsed ? parsed.expiresIn : undefined - ); - if (parsed.created === true) { - announcingToast.success(i18n.t('login.accountCreated')); - } + await completeNativeSignIn(result.data, signIn); } else if (result.errorCode === 'SSO_ERROR') { handleSsoError(credential.email ?? '', result.ssoOrganizationId); } else { @@ -180,16 +197,15 @@ export function useNativeAuth(): NativeAuthResult { return; } - let admissionBody: Record = {}; - try { - admissionBody = await resolveAdmission(); - } catch { + const admissionBody = await getAdmissionBody(); + if (!admissionBody) { return; } const result = await postAuth('/api/auth/native/token', { provider: 'google', supportsRefresh: true, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, ...(serverAuthCode ? { serverAuthCode, googleClientId: GOOGLE_WEB_CLIENT_ID } : { idToken }), @@ -197,19 +213,7 @@ export function useNativeAuth(): NativeAuthResult { }); if (result.ok) { - const parsed = parseTokenPair(result.data); - if (!parsed) { - toast.error(defaultErrorMessage()); - return; - } - await signIn( - parsed.token, - 'refreshToken' in parsed ? parsed.refreshToken : undefined, - 'expiresIn' in parsed ? parsed.expiresIn : undefined - ); - if (parsed.created === true) { - announcingToast.success(i18n.t('login.accountCreated')); - } + await completeNativeSignIn(result.data, signIn); } else if (result.errorCode === 'SSO_ERROR') { handleSsoError(response.data.user.email, result.ssoOrganizationId); } else { @@ -272,10 +276,8 @@ export function useNativeAuth(): NativeAuthResult { // email means the challenge was generated for a different address. const challengeId = selectChallengeId(challengeRef.current, email); - let admissionBody: Record = {}; - try { - admissionBody = await resolveAdmission(); - } catch { + const admissionBody = await getAdmissionBody(); + if (!admissionBody) { return false; } @@ -285,6 +287,7 @@ export function useNativeAuth(): NativeAuthResult { email, code, supportsRefresh: true, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, ...(challengeId ? { challengeId } : {}), }); if (!result.ok) { @@ -295,19 +298,9 @@ export function useNativeAuth(): NativeAuthResult { } return false; } - const parsed = parseTokenPair(result.data); - if (!parsed) { - toast.error(defaultErrorMessage()); + if (!(await completeNativeSignIn(result.data, signIn))) { return false; } - await signIn( - parsed.token, - 'refreshToken' in parsed ? parsed.refreshToken : undefined, - 'expiresIn' in parsed ? parsed.expiresIn : undefined - ); - if (parsed.created === true) { - announcingToast.success(i18n.t('login.accountCreated')); - } return true; } catch (error) { // eslint-disable-next-line no-console -- surface swallowed auth errors to Sentry diff --git a/apps/mobile/src/lib/hooks/use-available-models.test.ts b/apps/mobile/src/lib/hooks/use-available-models.test.ts index b7cffba752..86b1776011 100644 --- a/apps/mobile/src/lib/hooks/use-available-models.test.ts +++ b/apps/mobile/src/lib/hooks/use-available-models.test.ts @@ -1,6 +1,8 @@ -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { + fetchModels, + fetchOrgDefaults, OpenRouterModelsResponseSchema, OrganizationDefaultsResponseSchema, toModelOptions, @@ -12,6 +14,22 @@ vi.mock('expo-secure-store', () => ({})); vi.mock('@tanstack/react-query', () => ({})); vi.mock('@/lib/config', () => ({ API_BASE_URL: 'https://api.example.com' })); vi.mock('@/lib/storage-keys', () => ({ AUTH_TOKEN_KEY: 'mock-token' })); +const getAuthTokenForRequest = vi.hoisted(() => vi.fn()); +const getGatewayAuthTokenForRequest = vi.hoisted(() => vi.fn()); +vi.mock('@/lib/auth/token-owner', () => ({ + getAuthTokenForRequest, +})); +vi.mock('@/lib/auth/credentials', () => ({ getGatewayAuthTokenForRequest })); + +beforeEach(() => { + getAuthTokenForRequest.mockReset().mockResolvedValue('api-token'); + getGatewayAuthTokenForRequest.mockReset().mockResolvedValue('gateway-token'); + vi.stubGlobal('fetch', vi.fn()); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); describe('toModelOptions', () => { it('passes pricing through to the ModelOption', () => { @@ -88,3 +106,33 @@ describe('OrganizationDefaultsResponseSchema', () => { }); }); }); + +describe('model request credentials', () => { + it('uses the refresh-capable gateway credential for personal models', async () => { + vi.mocked(fetch).mockResolvedValue(Response.json({ data: [] })); + + await fetchModels(undefined); + + expect(getGatewayAuthTokenForRequest).toHaveBeenCalledOnce(); + expect(getAuthTokenForRequest).not.toHaveBeenCalled(); + expect(fetch).toHaveBeenCalledWith( + 'https://api.example.com/api/openrouter/models', + expect.objectContaining({ + headers: expect.objectContaining({ Authorization: 'Bearer gateway-token' }), + }) + ); + }); + + it('uses the API credential for organization models and defaults', async () => { + vi.mocked(fetch) + .mockResolvedValueOnce(Response.json({ data: [] })) + .mockResolvedValueOnce(Response.json({ defaultModel: 'model' })); + + await fetchModels('org-1'); + await fetchOrgDefaults('org-1'); + + expect(getAuthTokenForRequest).toHaveBeenNthCalledWith(1, 'api'); + expect(getAuthTokenForRequest).toHaveBeenNthCalledWith(2, 'api'); + expect(getGatewayAuthTokenForRequest).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/mobile/src/lib/hooks/use-available-models.ts b/apps/mobile/src/lib/hooks/use-available-models.ts index 4c6d1be0f0..50e9bc2e17 100644 --- a/apps/mobile/src/lib/hooks/use-available-models.ts +++ b/apps/mobile/src/lib/hooks/use-available-models.ts @@ -4,6 +4,7 @@ import * as z from 'zod'; import { API_BASE_URL } from '@/lib/config'; import { getAuthTokenForRequest } from '@/lib/auth/token-owner'; +import { getGatewayAuthTokenForRequest } from '@/lib/auth/credentials'; import { i18n } from '@/i18n'; import { collator } from '@/lib/intl-cache'; @@ -144,8 +145,10 @@ export const OpenRouterModelsResponseSchema = z.object({ */ export const OrganizationDefaultsResponseSchema = z.object({ defaultModel: z.string() }); -async function fetchModels(organizationId: string | undefined): Promise { - const token = await getAuthTokenForRequest(); +export async function fetchModels(organizationId: string | undefined): Promise { + const token = organizationId + ? await getAuthTokenForRequest('api') + : await getGatewayAuthTokenForRequest(); const url = organizationId ? `${API_BASE_URL}/api/organizations/${organizationId}/models` : `${API_BASE_URL}/api/openrouter/models`; @@ -181,8 +184,8 @@ async function fetchModels(organizationId: string | undefined): Promise { - const token = await getAuthTokenForRequest(); +export async function fetchOrgDefaults(organizationId: string): Promise<{ defaultModel: string }> { + const token = await getAuthTokenForRequest('api'); const response = await fetch(`${API_BASE_URL}/api/organizations/${organizationId}/defaults`, { headers: { Accept: 'application/json', diff --git a/apps/mobile/src/lib/storage-keys.ts b/apps/mobile/src/lib/storage-keys.ts index 6ab3436d05..78b230f8e3 100644 --- a/apps/mobile/src/lib/storage-keys.ts +++ b/apps/mobile/src/lib/storage-keys.ts @@ -62,6 +62,7 @@ export const KILOCLAW_OWNED_KEY = 'kiloclaw-owned'; export const REFRESH_TOKEN_KEY = 'auth-refresh-token'; export const TOKEN_EXPIRES_AT_KEY = 'auth-token-expires-at'; export const LEGACY_EXCHANGE_DONE_KEY = 'auth-legacy-exchange-done'; +export const NATIVE_CREDENTIAL_BUNDLE_KEY = 'native-credential-bundle-v1'; /** iOS App Attest key identifier. The key itself lives in the Secure Enclave. */ export const ATTEST_KEY_ID_KEY = 'auth-attest-key-id'; /** diff --git a/apps/mobile/src/lib/trpc.test.ts b/apps/mobile/src/lib/trpc.test.ts index d6458dc6e4..766ae49cb0 100644 --- a/apps/mobile/src/lib/trpc.test.ts +++ b/apps/mobile/src/lib/trpc.test.ts @@ -68,11 +68,13 @@ vi.mock('@/lib/config', () => ({ API_BASE_URL: 'https://api.example.com', E2E_LATENCY_MESSAGES_MS: 0, E2E_LATENCY_SESSION_MS: 0, + E2E_SECURE_STORE_FAULT_MS: 0, })); vi.mock('@/lib/storage-keys', () => ({ AUTH_TOKEN_KEY: 'auth-token', TOKEN_EXPIRES_AT_KEY: 'token-expires-at', + NATIVE_CREDENTIAL_BUNDLE_KEY: 'native-credential-bundle', })); // auth-context pulls in react-native, Sentry and the telemetry modules. @@ -159,13 +161,12 @@ describe('getAuthHeaders', () => { const headers = await loadHeaders(); await expect(headers()).resolves.toMatchObject({ Authorization: 'Bearer stored-token' }); - // Cold path: one token read plus one expiry read. - expect(secureStoreMock.getItemAsync).toHaveBeenCalledTimes(2); + expect(secureStoreMock.getItemAsync).toHaveBeenCalledTimes(3); // The resolved expiry was published into the owner: a normal request // rereads neither key. await expect(headers()).resolves.toMatchObject({ Authorization: 'Bearer stored-token' }); - expect(secureStoreMock.getItemAsync).toHaveBeenCalledTimes(2); + expect(secureStoreMock.getItemAsync).toHaveBeenCalledTimes(3); }); it('uses the newest owner token published while the cold expiry was read', async () => { diff --git a/apps/web/src/app/api/auth/native/exchange/route.test.ts b/apps/web/src/app/api/auth/native/exchange/route.test.ts index a6a8b71a2f..e05643e0f7 100644 --- a/apps/web/src/app/api/auth/native/exchange/route.test.ts +++ b/apps/web/src/app/api/auth/native/exchange/route.test.ts @@ -24,9 +24,10 @@ const mockIssueSessionCredentials = jest.mocked(issueSessionCredentials); const fakeUser = { id: 'user-1', api_token_pepper: 'pepper' } as User; describe('POST /api/auth/native/exchange', () => { - const createRequest = (headers: Record = {}) => + const createRequest = (headers: Record = {}, body?: string) => new NextRequest('http://localhost:3000/api/auth/native/exchange', { method: 'POST', + ...(body === undefined ? {} : { body }), headers: { 'Content-Type': 'application/json', ...headers }, }); @@ -81,6 +82,50 @@ describe('POST /api/auth/native/exchange', () => { expect(mockIssueSessionCredentials).not.toHaveBeenCalled(); }); + it('rejects malformed nonempty bodies after bearer authentication without issuing', async () => { + mockGetUserFromBearer.mockResolvedValue({ user: fakeUser, authFailedResponse: null }); + + const response = await POST(createRequest(bearerHeaders, '{')); + + expect(response.status).toBe(400); + expect(mockCreateDeviceSession).not.toHaveBeenCalled(); + expect(mockIssueSessionCredentials).not.toHaveBeenCalled(); + }); + + it('propagates a negotiated credential format and tagged bundle', async () => { + mockGetUserFromBearer.mockResolvedValue({ user: fakeUser, authFailedResponse: null }); + mockCreateDeviceSession.mockResolvedValue('session-1'); + mockIssueSessionCredentials.mockResolvedValue({ + token: 'short-jwt', + refreshToken: 'refresh-abc', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }, + }); + + const response = await POST( + createRequest(bearerHeaders, JSON.stringify({ credentialFormat: 'api-gateway-v1' })) + ); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + token: 'short-jwt', + refreshToken: 'refresh-abc', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }, + }); + expect(mockIssueSessionCredentials).toHaveBeenCalledWith(fakeUser, 'session-1', { + credentialFormat: 'api-gateway-v1', + }); + }); + it('does not issue credentials when the bearer user is blocked', async () => { mockGetUserFromBearer.mockResolvedValue({ user: null, diff --git a/apps/web/src/app/api/auth/native/exchange/route.ts b/apps/web/src/app/api/auth/native/exchange/route.ts index 5d31d9fefe..48315b7a99 100644 --- a/apps/web/src/app/api/auth/native/exchange/route.ts +++ b/apps/web/src/app/api/auth/native/exchange/route.ts @@ -6,6 +6,25 @@ import { } from '@/lib/user/server'; import { createDeviceSession, issueSessionCredentials } from '@/lib/auth/device-sessions'; import { APP_URL } from '@/lib/constants'; +import * as z from 'zod'; +import { + nativeCredentialFormatSchema, + type NativeCredentialFormat, + type NativeSessionCredentials, +} from '@kilocode/app-shared/native-auth'; + +const requestSchema = z.object({ credentialFormat: nativeCredentialFormatSchema.optional() }); + +function credentialResponse(credentials: NativeSessionCredentials) { + return { + token: credentials.token, + refreshToken: credentials.refreshToken, + expiresIn: credentials.expiresIn, + ...('metadata' in credentials && credentials.metadata + ? { metadata: credentials.metadata } + : {}), + }; +} /** * Token exchange endpoint. Authenticates with the existing long-lived bearer @@ -33,18 +52,34 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } + const text = await request.text(); + let credentialFormat: NativeCredentialFormat | undefined; + if (text.length > 0) { + let body: unknown; + try { + body = JSON.parse(text); + } catch { + return NextResponse.json({ error: 'INVALID_REQUEST' }, { status: 400 }); + } + const validation = requestSchema.safeParse(body); + if (!validation.success) { + return NextResponse.json({ error: 'INVALID_REQUEST' }, { status: 400 }); + } + credentialFormat = validation.data.credentialFormat; + } + const sessionId = await createDeviceSession({ userId: auth.user.id, userAgent: request.headers.get('user-agent') ?? undefined, }); - const pair = await issueSessionCredentials(auth.user, sessionId); + const pair = credentialFormat + ? await issueSessionCredentials(auth.user, sessionId, { credentialFormat }) + : await issueSessionCredentials(auth.user, sessionId); return NextResponse.json( { - token: pair.token, - refreshToken: pair.refreshToken, - expiresIn: pair.expiresIn, + ...credentialResponse(pair), }, { status: 200, headers: { 'Cache-Control': 'no-store' } } ); diff --git a/apps/web/src/app/api/auth/native/refresh/route.test.ts b/apps/web/src/app/api/auth/native/refresh/route.test.ts index 9e79091270..78be288507 100644 --- a/apps/web/src/app/api/auth/native/refresh/route.test.ts +++ b/apps/web/src/app/api/auth/native/refresh/route.test.ts @@ -95,4 +95,41 @@ describe('POST /api/auth/native/refresh', () => { const response = await POST(createMalformedRequest()); expect(response.status).toBe(400); }); + + it('passes a negotiated credential format through and preserves metadata', async () => { + mockRotateRefreshToken.mockResolvedValue({ + ok: true, + token: 'new-access-token', + refreshToken: 'new-refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }, + }); + + const response = await POST( + createRequest({ refreshToken: 'valid-refresh', credentialFormat: 'api-gateway-v1' }) + ); + + expect(response.status).toBe(200); + expect(mockRotateRefreshToken).toHaveBeenCalledWith('valid-refresh', { + credentialFormat: 'api-gateway-v1', + }); + expect((await response.json()).metadata).toEqual({ + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }); + }); + + it('rejects an unknown credential format without rotating', async () => { + const response = await POST( + createRequest({ refreshToken: 'valid-refresh', credentialFormat: 'nope' }) + ); + + expect(response.status).toBe(400); + expect(mockRotateRefreshToken).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/app/api/auth/native/refresh/route.ts b/apps/web/src/app/api/auth/native/refresh/route.ts index 0b13872afd..55a2f7d502 100644 --- a/apps/web/src/app/api/auth/native/refresh/route.ts +++ b/apps/web/src/app/api/auth/native/refresh/route.ts @@ -2,11 +2,27 @@ import type { NextRequest } from 'next/server'; import { NextResponse } from 'next/server'; import * as z from 'zod'; import { rotateRefreshToken } from '@/lib/auth/device-sessions'; +import { + nativeCredentialFormatSchema, + type NativeSessionCredentials, +} from '@kilocode/app-shared/native-auth'; const requestSchema = z.object({ refreshToken: z.string().min(1), + credentialFormat: nativeCredentialFormatSchema.optional(), }); +function credentialResponse(credentials: NativeSessionCredentials) { + return { + token: credentials.token, + refreshToken: credentials.refreshToken, + expiresIn: credentials.expiresIn, + ...('metadata' in credentials && credentials.metadata + ? { metadata: credentials.metadata } + : {}), + }; +} + /** * Native refresh endpoint. Accepts a refresh token and returns a new * access/refresh pair. @@ -26,9 +42,11 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error: 'INVALID_REQUEST' }, { status: 400 }); } - const { refreshToken } = validation.data; + const { refreshToken, credentialFormat } = validation.data; - const result = await rotateRefreshToken(refreshToken); + const result = credentialFormat + ? await rotateRefreshToken(refreshToken, { credentialFormat }) + : await rotateRefreshToken(refreshToken); if (!result.ok) { return NextResponse.json({ error: result.error }, { status: 401 }); @@ -36,9 +54,7 @@ export async function POST(request: NextRequest) { return NextResponse.json( { - token: result.token, - refreshToken: result.refreshToken, - expiresIn: result.expiresIn, + ...credentialResponse(result), }, { status: 200 } ); diff --git a/apps/web/src/app/api/auth/native/token/route.credentials.integration.test.ts b/apps/web/src/app/api/auth/native/token/route.credentials.integration.test.ts new file mode 100644 index 0000000000..5f652dceb1 --- /dev/null +++ b/apps/web/src/app/api/auth/native/token/route.credentials.integration.test.ts @@ -0,0 +1,236 @@ +import { afterEach, beforeEach, describe, expect, test } from '@jest/globals'; +import { NextRequest } from 'next/server'; +import jwt from 'jsonwebtoken'; +import { and, eq } from 'drizzle-orm'; +import { + API_GATEWAY_CREDENTIAL_FORMAT, + parseNativeTokenPair, +} from '@kilocode/app-shared/native-auth'; +import { + KILO_API_AUDIENCE, + KILO_GATEWAY_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +import { device_refresh_tokens, device_sessions, native_attested_keys } from '@kilocode/db/schema'; + +jest.mock('@/lib/redis', () => ({ redisClient: { get: jest.fn(async () => null) } })); +jest.mock('@/lib/user', () => ({ + ...(jest.requireActual('@/lib/user') as object), + createOrUpdateUser: jest.fn(), +})); +jest.mock('@/lib/auth/magic-link-tokens', () => ({ + ...(jest.requireActual('@/lib/auth/magic-link-tokens') as object), + reserveSignInCode: jest.fn(), + commitSignInCode: jest.fn(), + releaseSignInCode: jest.fn(), +})); +jest.mock('@/lib/auth/email-signin-eligibility', () => ({ + checkDomainSignInEligibility: jest.fn(), +})); +jest.mock('@/lib/auth/native-admission', () => ({ + ...(jest.requireActual('@/lib/auth/native-admission') as object), + checkNativeAdmission: jest.fn(), + validateAdmissionPayload: jest.fn(), + verifyAdmissionAsync: jest.fn(), +})); +jest.mock('@/lib/organizations/verified-domain-membership', () => ({ + ensureVerifiedDomainOrganizationMembership: jest.fn(), +})); +jest.mock('@sentry/nextjs', () => ({ captureMessage: jest.fn() })); +jest.mock('@/lib/posthog', () => ({ + __esModule: true, + default: jest.fn(() => ({ capture: jest.fn() })), +})); + +import { POST } from './route'; +import { checkDomainSignInEligibility } from '@/lib/auth/email-signin-eligibility'; +import { + checkNativeAdmission, + validateAdmissionPayload, + verifyAdmissionAsync, +} from '@/lib/auth/native-admission'; +import { NEXTAUTH_SECRET } from '@/lib/config.server'; +import { db } from '@/lib/drizzle'; +import { createOrUpdateUser } from '@/lib/user'; +import { + commitSignInCode, + releaseSignInCode, + reserveSignInCode, +} from '@/lib/auth/magic-link-tokens'; +import { insertTestUser } from '@/tests/helpers/user.helper'; + +const nativeResourceTokensKey = 'NATIVE_RESOURCE_TOKENS_ENABLED'; +const originalNativeResourceTokens = process.env[nativeResourceTokensKey]; +const sharedResourceTokensKey = 'SHARED_RESOURCE_TOKENS_ENABLED'; +const originalSharedResourceTokens = process.env[sharedResourceTokensKey]; + +const mockCreateOrUpdateUser = jest.mocked(createOrUpdateUser); +const mockReserveSignInCode = jest.mocked(reserveSignInCode); +const mockCommitSignInCode = jest.mocked(commitSignInCode); +const mockReleaseSignInCode = jest.mocked(releaseSignInCode); +const mockCheckDomainSignInEligibility = jest.mocked(checkDomainSignInEligibility); +const mockCheckNativeAdmission = jest.mocked(checkNativeAdmission); +const mockValidateAdmissionPayload = jest.mocked(validateAdmissionPayload); +const mockVerifyAdmissionAsync = jest.mocked(verifyAdmissionAsync); + +function request(body: unknown, userAgent: string) { + return new NextRequest('http://localhost:3000/api/auth/native/token', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'User-Agent': userAgent }, + body: JSON.stringify(body), + }); +} + +function setNativeResourceTokens(enabled: boolean) { + process.env[nativeResourceTokensKey] = String(enabled); + process.env[sharedResourceTokensKey] = String(enabled); +} + +function verifyAccessToken(token: string, userId: string, sessionId: string, audience: string) { + expect(jwt.verify(token, NEXTAUTH_SECRET, { algorithms: ['HS256'] })).toMatchObject({ + kiloUserId: userId, + deviceSessionId: sessionId, + aud: audience, + tokenPurpose: 'device-access', + credentialExchange: false, + }); +} + +async function postEmailToken(userAgent: string, body: Record = {}) { + const user = await insertTestUser({ api_token_pepper: crypto.randomUUID() }); + mockCreateOrUpdateUser.mockResolvedValue({ success: true, user, isNew: false }); + const response = await POST( + request( + { + provider: 'email', + email: user.google_user_email, + code: '123456', + supportsRefresh: true, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + ...body, + }, + userAgent + ) + ); + return { user, response }; +} + +afterEach(() => { + if (originalNativeResourceTokens === undefined) { + delete process.env[nativeResourceTokensKey]; + } else { + process.env[nativeResourceTokensKey] = originalNativeResourceTokens; + } + if (originalSharedResourceTokens === undefined) { + delete process.env[sharedResourceTokensKey]; + } else { + process.env[sharedResourceTokensKey] = originalSharedResourceTokens; + } +}); + +describe('POST /api/auth/native/token credential issuance', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockReserveSignInCode.mockResolvedValue('ok'); + mockCommitSignInCode.mockResolvedValue(true); + mockReleaseSignInCode.mockResolvedValue(undefined); + mockCheckDomainSignInEligibility.mockResolvedValue({ ok: true, existingUser: false }); + mockCheckNativeAdmission.mockReturnValue({ admission: { ok: true }, verifyAsync: false }); + mockValidateAdmissionPayload.mockReturnValue(undefined); + }); + + test('returns the legacy credential shape while resource-token issuance is disabled', async () => { + setNativeResourceTokens(false); + const { response } = await postEmailToken('native-token-legacy-integration'); + const body: unknown = await response.json(); + + expect(response.status).toBe(200); + const pair = parseNativeTokenPair(body); + expect(pair).not.toBeNull(); + expect(pair?.metadata).toBeUndefined(); + expect(pair?.refreshToken).toBeDefined(); + }); + + test('issues signed API and gateway credentials and persists a device session', async () => { + setNativeResourceTokens(true); + const userAgent = 'native-token-resource-integration'; + const { user, response } = await postEmailToken(userAgent); + const body: unknown = await response.json(); + + expect(response.status).toBe(200); + const pair = parseNativeTokenPair(body); + expect(pair).not.toBeNull(); + if (!pair?.refreshToken || !pair.metadata) + throw new Error('Expected native resource credentials'); + + const [session] = await db + .select() + .from(device_sessions) + .where( + and(eq(device_sessions.kilo_user_id, user.id), eq(device_sessions.user_agent, userAgent)) + ); + expect(session).toBeDefined(); + if (!session) throw new Error('Expected device session'); + + const refreshTokens = await db + .select() + .from(device_refresh_tokens) + .where(eq(device_refresh_tokens.device_session_id, session.id)); + expect(refreshTokens).toHaveLength(1); + expect(pair.metadata.credentialFormat).toBe(API_GATEWAY_CREDENTIAL_FORMAT); + expect(pair.token).not.toBe(pair.metadata.gatewayToken); + verifyAccessToken(pair.token, user.id, session.id, KILO_API_AUDIENCE); + verifyAccessToken(pair.metadata.gatewayToken, user.id, session.id, KILO_GATEWAY_AUDIENCE); + }); + + test('atomically persists an asynchronously verified iOS key with its credential session', async () => { + setNativeResourceTokens(true); + const keyId = `native-token-attested-key-${crypto.randomUUID()}`; + const publicKey = Buffer.from('native token integration key').toString('base64'); + mockCheckNativeAdmission.mockReturnValue({ admission: { ok: true }, verifyAsync: true }); + mockValidateAdmissionPayload.mockReturnValue({ + platform: 'ios', + kind: 'attestation', + challenge: 'native-token-integration-challenge', + payload: 'native-token-integration-payload', + keyId, + }); + mockVerifyAdmissionAsync.mockResolvedValue({ ok: true, platform: 'ios', keyId, publicKey }); + + const { user, response } = await postEmailToken('native-token-attested-integration', { + admission: { + platform: 'ios', + kind: 'attestation', + challenge: 'native-token-integration-challenge', + payload: 'native-token-integration-payload', + keyId, + }, + }); + const body: unknown = await response.json(); + + expect(response.status).toBe(200); + const pair = parseNativeTokenPair(body); + expect(pair).not.toBeNull(); + if (!pair?.refreshToken || !pair.metadata) + throw new Error('Expected attested native credentials'); + + const [key] = await db + .select() + .from(native_attested_keys) + .where(eq(native_attested_keys.key_id, keyId)); + expect(key).toMatchObject({ kilo_user_id: user.id, platform: 'ios', public_key: publicKey }); + + const [session] = await db + .select() + .from(device_sessions) + .where(eq(device_sessions.kilo_user_id, user.id)); + expect(session).toBeDefined(); + if (!session) throw new Error('Expected attested device session'); + const refreshTokens = await db + .select() + .from(device_refresh_tokens) + .where(eq(device_refresh_tokens.device_session_id, session.id)); + expect(refreshTokens).toHaveLength(1); + verifyAccessToken(pair.token, user.id, session.id, KILO_API_AUDIENCE); + verifyAccessToken(pair.metadata.gatewayToken, user.id, session.id, KILO_GATEWAY_AUDIENCE); + }); +}); diff --git a/apps/web/src/app/api/auth/native/token/route.test.ts b/apps/web/src/app/api/auth/native/token/route.test.ts index 3716458fbf..3987737016 100644 --- a/apps/web/src/app/api/auth/native/token/route.test.ts +++ b/apps/web/src/app/api/auth/native/token/route.test.ts @@ -1541,6 +1541,73 @@ describe('POST /api/auth/native/token', () => { }); describe('supportsRefresh', () => { + it('rejects a requested credential format without refresh support before authentication', async () => { + const response = await POST( + createRequest({ + provider: 'google', + idToken: 'google-id-token', + credentialFormat: 'api-gateway-v1', + }) + ); + + expect(response.status).toBe(400); + expect(mockVerifyNativeGoogleIdToken).not.toHaveBeenCalled(); + expect(mockCreateOrUpdateUser).not.toHaveBeenCalled(); + expect(mockIssueSessionCredentials).not.toHaveBeenCalled(); + }); + + it('rejects an unknown credential format before authentication', async () => { + const response = await POST( + createRequest({ + provider: 'google', + idToken: 'google-id-token', + supportsRefresh: true, + credentialFormat: 'future-format', + }) + ); + + expect(response.status).toBe(400); + expect(mockVerifyNativeGoogleIdToken).not.toHaveBeenCalled(); + expect(mockCreateOrUpdateUser).not.toHaveBeenCalled(); + }); + + it('passes a requested credential format and preserves tagged metadata', async () => { + mockVerifyNativeGoogleIdToken.mockResolvedValue({ + sub: 'google-sub-1', + email: 'googleuser@example.com', + }); + mockCreateDeviceSession.mockResolvedValue('session-1'); + mockIssueSessionCredentials.mockResolvedValue({ + token: 'short-jwt', + refreshToken: 'refresh-abc', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }, + }); + + const response = await POST( + createRequest({ + provider: 'google', + idToken: 'google-id-token', + supportsRefresh: true, + credentialFormat: 'api-gateway-v1', + }) + ); + + expect(response.status).toBe(200); + expect(mockIssueSessionCredentials).toHaveBeenCalledWith(fakeUser, 'session-1', { + credentialFormat: 'api-gateway-v1', + }); + expect((await response.json()).metadata).toEqual({ + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }); + }); + it('returns short-lived pair when supportsRefresh is true', async () => { mockVerifyNativeGoogleIdToken.mockResolvedValue({ sub: 'google-sub-1', diff --git a/apps/web/src/app/api/auth/native/token/route.ts b/apps/web/src/app/api/auth/native/token/route.ts index f2d1354b23..eff4b2c7bd 100644 --- a/apps/web/src/app/api/auth/native/token/route.ts +++ b/apps/web/src/app/api/auth/native/token/route.ts @@ -39,6 +39,11 @@ import { issueSessionCredentials, createDeviceSessionWithAttestedKey, } from '@/lib/auth/device-sessions'; +import { + nativeCredentialFormatSchema, + type NativeCredentialFormat, + type NativeSessionCredentials, +} from '@kilocode/app-shared/native-auth'; import { captureMessage } from '@sentry/nextjs'; import PostHogClient from '@/lib/posthog'; import { ensureVerifiedDomainOrganizationMembership } from '@/lib/organizations/verified-domain-membership'; @@ -84,32 +89,70 @@ async function checkExistingProviderAccount( return eligibility.ok ? undefined : eligibilityResponse(eligibility); } -const requestSchema = z.discriminatedUnion('provider', [ - z.object({ - provider: z.literal('apple'), - idToken: z.string(), - fullName: z.string().optional(), - nonce: z.string().optional(), - supportsRefresh: z.boolean().optional(), - admission: z.unknown().optional(), - }), - z.object({ - provider: z.literal('google'), - idToken: z.string().optional(), - serverAuthCode: z.string().optional(), - googleClientId: z.string().optional(), - supportsRefresh: z.boolean().optional(), - admission: z.unknown().optional(), - }), - z.object({ - provider: z.literal('email'), - email: z.string().email(), - code: z.string(), - challengeId: z.string().uuid().optional(), - supportsRefresh: z.boolean().optional(), - admission: z.unknown().optional(), - }), -]); +const requestSchema = z + .discriminatedUnion('provider', [ + z.object({ + provider: z.literal('apple'), + idToken: z.string(), + fullName: z.string().optional(), + nonce: z.string().optional(), + supportsRefresh: z.boolean().optional(), + credentialFormat: nativeCredentialFormatSchema.optional(), + admission: z.unknown().optional(), + }), + z.object({ + provider: z.literal('google'), + idToken: z.string().optional(), + serverAuthCode: z.string().optional(), + googleClientId: z.string().optional(), + supportsRefresh: z.boolean().optional(), + credentialFormat: nativeCredentialFormatSchema.optional(), + admission: z.unknown().optional(), + }), + z.object({ + provider: z.literal('email'), + email: z.string().email(), + code: z.string(), + challengeId: z.string().uuid().optional(), + supportsRefresh: z.boolean().optional(), + credentialFormat: nativeCredentialFormatSchema.optional(), + admission: z.unknown().optional(), + }), + ]) + .superRefine((data, context) => { + if (data.credentialFormat && !data.supportsRefresh) { + context.addIssue({ + code: 'custom', + path: ['supportsRefresh'], + message: 'supportsRefresh is required when credentialFormat is specified', + }); + } + }); + +function credentialResponse(credentials: NativeSessionCredentials) { + return { + token: credentials.token, + refreshToken: credentials.refreshToken, + expiresIn: credentials.expiresIn, + ...('metadata' in credentials && credentials.metadata + ? { metadata: credentials.metadata } + : {}), + }; +} + +function credentialOptions(credentialFormat?: NativeCredentialFormat) { + return credentialFormat ? { credentialFormat } : undefined; +} + +function issueCredentials( + user: Parameters[0], + sessionId: string, + credentialFormat?: NativeCredentialFormat +) { + return credentialFormat + ? issueSessionCredentials(user, sessionId, { credentialFormat }) + : issueSessionCredentials(user, sessionId); +} /** * Native (mobile) sign-in token exchange. Verifies an Apple/Google ID token or an @@ -348,9 +391,7 @@ export async function POST(request: NextRequest) { // Must run BEFORE code commit so a key collision under enforce does // not burn the sign-in code without issuing a credential. let sessionId: string | undefined; - let refreshCredentials: - | { token: string; refreshToken: string; expiresIn: number } - | undefined; + let refreshCredentials: NativeSessionCredentials | undefined; if (admissionVerification && data.supportsRefresh) { // Bind key persistence and session creation in one transaction. @@ -360,13 +401,10 @@ export async function POST(request: NextRequest) { userAgent: request.headers.get('user-agent') ?? undefined, user: result.user, verification: admissionVerification, + ...credentialOptions(data.credentialFormat), }); sessionId = combined.sessionId; - refreshCredentials = { - token: combined.token, - refreshToken: combined.refreshToken, - expiresIn: combined.expiresIn, - }; + refreshCredentials = combined; } catch (err) { if (err instanceof KeyCollisionError) { captureMessage('native_attested_key_cross_user_collision'); @@ -418,9 +456,7 @@ export async function POST(request: NextRequest) { if (refreshCredentials) { return NextResponse.json( { - token: refreshCredentials.token, - refreshToken: refreshCredentials.refreshToken, - expiresIn: refreshCredentials.expiresIn, + ...credentialResponse(refreshCredentials), created: result.isNew, }, { status: 200 } @@ -434,12 +470,10 @@ export async function POST(request: NextRequest) { userId: result.user.id, userAgent: request.headers.get('user-agent') ?? undefined, })); - const pair = await issueSessionCredentials(result.user, sid); + const pair = await issueCredentials(result.user, sid, data.credentialFormat); return NextResponse.json( { - token: pair.token, - refreshToken: pair.refreshToken, - expiresIn: pair.expiresIn, + ...credentialResponse(pair), created: result.isNew, }, { status: 200 } @@ -526,7 +560,7 @@ export async function POST(request: NextRequest) { // ── Step 7: Persist attested key after settlement ──────────────────────── let sessionId: string | undefined; - let refreshCredentials: { token: string; refreshToken: string; expiresIn: number } | undefined; + let refreshCredentials: NativeSessionCredentials | undefined; if (admissionVerification) { if (data.supportsRefresh) { @@ -537,13 +571,10 @@ export async function POST(request: NextRequest) { userAgent: request.headers.get('user-agent') ?? undefined, user: result.user, verification: admissionVerification, + ...credentialOptions(data.credentialFormat), }); sessionId = combined.sessionId; - refreshCredentials = { - token: combined.token, - refreshToken: combined.refreshToken, - expiresIn: combined.expiresIn, - }; + refreshCredentials = combined; } catch (err) { if (err instanceof KeyCollisionError) { captureMessage('native_attested_key_cross_user_collision'); @@ -580,9 +611,7 @@ export async function POST(request: NextRequest) { if (refreshCredentials) { return NextResponse.json( { - token: refreshCredentials.token, - refreshToken: refreshCredentials.refreshToken, - expiresIn: refreshCredentials.expiresIn, + ...credentialResponse(refreshCredentials), created: result.isNew, }, { status: 200 } @@ -596,12 +625,10 @@ export async function POST(request: NextRequest) { userId: result.user.id, userAgent: request.headers.get('user-agent') ?? undefined, })); - const pair = await issueSessionCredentials(result.user, sid); + const pair = await issueCredentials(result.user, sid, data.credentialFormat); return NextResponse.json( { - token: pair.token, - refreshToken: pair.refreshToken, - expiresIn: pair.expiresIn, + ...credentialResponse(pair), created: result.isNew, }, { status: 200 } diff --git a/apps/web/src/app/api/auth/resource-token/route.ts b/apps/web/src/app/api/auth/resource-token/route.ts new file mode 100644 index 0000000000..fb270f2e53 --- /dev/null +++ b/apps/web/src/app/api/auth/resource-token/route.ts @@ -0,0 +1,53 @@ +import type { NextRequest } from 'next/server'; +import { NextResponse } from 'next/server'; +import { getUserFromAuth } from '@/lib/user/server'; +import { + createDelegatedResourceToken, + isDelegableResource, + TypedResourceDelegationError, +} from '@/lib/auth/resource-delegation'; + +function isSameOriginRequest(request: NextRequest): boolean { + const origin = request.headers.get('origin'); + return origin !== null && origin === request.nextUrl.origin; +} + +export async function POST(request: NextRequest) { + let body: unknown; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 }); + } + const resource = + body && typeof body === 'object' && 'resource' in body ? body.resource : undefined; + if (!isDelegableResource(resource)) { + return NextResponse.json({ error: 'Unsupported resource' }, { status: 400 }); + } + if (!request.headers.has('authorization') && !isSameOriginRequest(request)) { + return NextResponse.json({ error: 'Invalid request origin' }, { status: 403 }); + } + const { user, authFailedResponse, organizationId, tokenSource } = await getUserFromAuth({ + adminOnly: false, + }); + if (authFailedResponse) return authFailedResponse; + if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + if (organizationId) { + return NextResponse.json( + { error: 'Organization credentials are not supported' }, + { status: 403 } + ); + } + try { + const result = await createDelegatedResourceToken(user, resource, { + headers: request.headers, + tokenSource, + }); + return NextResponse.json({ token: result.token, expiresAt: result.expiresAt }); + } catch (error) { + if (error instanceof TypedResourceDelegationError) { + return NextResponse.json({ error: error.message }, { status: error.status }); + } + throw error; + } +} diff --git a/apps/web/src/app/api/device-auth/token/route.test.ts b/apps/web/src/app/api/device-auth/token/route.test.ts index dd58f1681e..292dcac6bd 100644 --- a/apps/web/src/app/api/device-auth/token/route.test.ts +++ b/apps/web/src/app/api/device-auth/token/route.test.ts @@ -52,6 +52,58 @@ describe('POST /api/device-auth/token', () => { expect(mockConsume).toHaveBeenCalledWith('secret123', { supportsRefresh: true }); }); + test('passes a negotiated credential format through and preserves metadata', async () => { + mockConsume.mockResolvedValue({ + status: 'approved', + token: 'short-jwt', + refreshToken: 'refresh-abc', + expiresIn: 3600, + metadata: { + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }, + userId: 'user-1', + userEmail: 'user@example.com', + }); + + const response = await POST( + createRequest({ + deviceCode: 'secret123', + supportsRefresh: true, + credentialFormat: 'api-gateway-v1', + }) + ); + + expect(mockConsume).toHaveBeenCalledWith('secret123', { + supportsRefresh: true, + credentialFormat: 'api-gateway-v1', + }); + expect((await response.json()).metadata).toEqual({ + credentialFormat: 'api-gateway-v1', + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }); + }); + + test('rejects requested formats without refresh support before consuming', async () => { + const response = await POST( + createRequest({ deviceCode: 'secret123', credentialFormat: 'api-gateway-v1' }) + ); + + expect(response.status).toBe(400); + expect(mockConsume).not.toHaveBeenCalled(); + }); + + test('rejects unknown formats before consuming', async () => { + const response = await POST( + createRequest({ deviceCode: 'secret123', supportsRefresh: true, credentialFormat: 'nope' }) + ); + + expect(response.status).toBe(400); + expect(mockConsume).not.toHaveBeenCalled(); + }); + test('returns refreshToken and expiresIn when consumer returns short pair', async () => { mockConsume.mockResolvedValue({ status: 'approved', diff --git a/apps/web/src/app/api/device-auth/token/route.ts b/apps/web/src/app/api/device-auth/token/route.ts index 6d42f28c39..5141f028d3 100644 --- a/apps/web/src/app/api/device-auth/token/route.ts +++ b/apps/web/src/app/api/device-auth/token/route.ts @@ -1,11 +1,23 @@ import { NextResponse } from 'next/server'; import { consumeDeviceAuthByDeviceCode } from '@/lib/device-auth/device-auth'; import * as z from 'zod'; +import { nativeCredentialFormatSchema } from '@kilocode/app-shared/native-auth'; -const TokenBodySchema = z.object({ - deviceCode: z.string().min(1), - supportsRefresh: z.boolean().optional(), -}); +const TokenBodySchema = z + .object({ + deviceCode: z.string().min(1), + supportsRefresh: z.boolean().optional(), + credentialFormat: nativeCredentialFormatSchema.optional(), + }) + .superRefine((data, context) => { + if (data.credentialFormat && !data.supportsRefresh) { + context.addIssue({ + code: 'custom', + path: ['supportsRefresh'], + message: 'supportsRefresh is required when credentialFormat is specified', + }); + } + }); export async function POST(request: Request) { let body: unknown; @@ -23,9 +35,12 @@ export async function POST(request: Request) { ); } - const { deviceCode, supportsRefresh } = validation.data; + const { deviceCode, supportsRefresh, credentialFormat } = validation.data; - const result = await consumeDeviceAuthByDeviceCode(deviceCode, { supportsRefresh }); + const result = await consumeDeviceAuthByDeviceCode(deviceCode, { + supportsRefresh, + ...(credentialFormat ? { credentialFormat } : {}), + }); switch (result.status) { case 'pending': @@ -35,9 +50,10 @@ export async function POST(request: Request) { return NextResponse.json( { status: 'approved', - token: result.token, + ...(result.token ? { token: result.token } : {}), ...(result.refreshToken ? { refreshToken: result.refreshToken } : {}), ...(result.expiresIn ? { expiresIn: result.expiresIn } : {}), + ...(result.metadata ? { metadata: result.metadata } : {}), userId: result.userId, userEmail: result.userEmail, }, diff --git a/apps/web/src/app/api/gastown/token/route.ts b/apps/web/src/app/api/gastown/token/route.ts index f8905edb31..4df3271619 100644 --- a/apps/web/src/app/api/gastown/token/route.ts +++ b/apps/web/src/app/api/gastown/token/route.ts @@ -1,9 +1,11 @@ import 'server-only'; import { NextResponse } from 'next/server'; import { getUserFromAuth } from '@/lib/user/server'; -import { generateApiToken } from '@/lib/tokens'; +import { + createControlTokenForRequest, + TypedResourceDelegationError, +} from '@/lib/auth/resource-delegation'; import { isGastownEnabled } from '@/lib/gastown/feature-flags'; -import { getUserOrgMemberships } from '@/lib/organizations/organizations'; import { recordKiloAdminElevationForRequest, serviceTarget } from '@/lib/admin/admin-access-log'; const ONE_HOUR_SECONDS = 60 * 60; @@ -24,7 +26,7 @@ const ONE_HOUR_SECONDS = 60 * 60; * membership without DB round-trips. */ export async function POST() { - const { user, authFailedResponse, tokenSource } = await getUserFromAuth({ adminOnly: false }); + const { user, authFailedResponse } = await getUserFromAuth({ adminOnly: false }); if (authFailedResponse) return authFailedResponse; if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); @@ -34,26 +36,29 @@ export async function POST() { return NextResponse.json({ error: 'Gastown access denied' }, { status: 403 }); } - if (user.is_admin) { - // The minted token carries `isAdmin`, so the elevation is exercised inside - // the Gastown worker where this app emits nothing. Correlate on - // `kiloUserId` within the token's lifetime below. - await recordKiloAdminElevationForRequest({ - user, - tokenSource, - reason: 'service_token_mint', - target: serviceTarget('gastown'), + try { + const result = await createControlTokenForRequest(user, 'gastown', { + tokenSource: 'gastown', + expiresIn: 55 * 60, + legacyExpiresIn: ONE_HOUR_SECONDS, + extra: { isAdmin: user.is_admin, gastownAccess: true }, }); + if (result.user.is_admin) { + await recordKiloAdminElevationForRequest({ + user: result.user, + tokenSource: result.tokenSource, + reason: 'service_token_mint', + target: serviceTarget('gastown'), + }); + } + return NextResponse.json({ token: result.token, expiresAt: result.expiresAt }); + } catch (error) { + if (error instanceof TypedResourceDelegationError) { + return NextResponse.json( + { error: error.message, code: error.delegationCode }, + { status: error.status } + ); + } + throw error; } - - const orgMemberships = await getUserOrgMemberships(user.id); - - const token = generateApiToken( - user, - { isAdmin: user.is_admin, gastownAccess: true, orgMemberships }, - { expiresIn: ONE_HOUR_SECONDS } - ); - const expiresAt = new Date(Date.now() + 55 * 60 * 1000).toISOString(); - - return NextResponse.json({ token, expiresAt }); } diff --git a/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.test.ts b/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.test.ts index 11ff95ea77..b63b63efc6 100644 --- a/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.test.ts +++ b/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.test.ts @@ -1,8 +1,17 @@ +import { isResourceTokenIssuanceEnabled } from '@/lib/config.server'; import { NextRequest } from 'next/server'; -import { generateApiToken } from '@/lib/tokens'; +import jwt from 'jsonwebtoken'; +import { validateAuthorizationHeader } from '@/lib/tokens'; +import { + KILO_API_AUDIENCE, + KILO_GATEWAY_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +const mockSharedResourceTokens = { enabled: false }; jest.mock('@/lib/config.server', () => ({ INTERNAL_API_SECRET: 'internal-secret', + NEXTAUTH_SECRET: 'benchmark-token-secret', + isResourceTokenIssuanceEnabled: jest.fn(() => mockSharedResourceTokens.enabled), })); const mockRows: unknown[] = []; @@ -23,14 +32,8 @@ jest.mock('@/lib/drizzle', () => ({ }, })); -jest.mock('@/lib/tokens', () => ({ - generateApiToken: jest.fn(() => 'minted-token'), -})); - import { POST } from './route'; -const mockGenerateApiToken = jest.mocked(generateApiToken); - function createRequest(body: unknown, headers: Record = {}) { return new NextRequest('http://localhost:3000/api/internal/auto-routing-benchmark/token', { method: 'POST', @@ -42,16 +45,15 @@ function createRequest(body: unknown, headers: Record = {}) { describe('POST /api/internal/auto-routing-benchmark/token', () => { beforeEach(() => { jest.clearAllMocks(); + mockSharedResourceTokens.enabled = false; mockRows.length = 0; mockMembershipRows.length = 0; mockSelectCallCount = 0; }); it('returns 401 without the bearer secret', async () => { - mockRows.push({ id: 'user-1', api_token_pepper: 'pepper' }); const res = await POST(createRequest({ userId: 'user-1' })); expect(res.status).toBe(401); - expect(mockGenerateApiToken).not.toHaveBeenCalled(); }); it('returns 401 with the wrong bearer secret', async () => { @@ -60,41 +62,51 @@ describe('POST /api/internal/auto-routing-benchmark/token', () => { }); it('returns 400 for an invalid body', async () => { + mockSharedResourceTokens.enabled = true; const res = await POST(createRequest({}, { authorization: 'Bearer internal-secret' })); expect(res.status).toBe(400); }); it('returns 404 when the user does not exist', async () => { + mockSharedResourceTokens.enabled = true; const res = await POST( createRequest({ userId: 'missing' }, { authorization: 'Bearer internal-secret' }) ); expect(res.status).toBe(404); - expect(mockGenerateApiToken).not.toHaveBeenCalled(); }); - it('mints a 6h token for an existing user', async () => { - const user = { id: 'user-1', api_token_pepper: 'pepper' }; - mockRows.push(user); + it('preserves the existing personal token while shared tokens are disabled', async () => { + mockRows.push({ + id: 'user-1', + api_token_pepper: 'pepper', + blocked_at: null, + blocked_reason: null, + }); const res = await POST( createRequest({ userId: 'user-1' }, { authorization: 'Bearer internal-secret' }) ); + expect(res.status).toBe(200); - const json = (await res.json()) as { token: string; expiresAt: string }; - expect(json.token).toBe('minted-token'); - expect(typeof json.expiresAt).toBe('string'); - expect(mockGenerateApiToken).toHaveBeenCalledWith( - user, - { tokenSource: 'auto-routing-benchmark' }, - { - expiresIn: 6 * 60 * 60, - } - ); + const { token } = (await res.json()) as { token: string }; + const claims = jwt.verify(token, 'benchmark-token-secret') as jwt.JwtPayload; + expect(claims).toMatchObject({ + apiTokenPepper: 'pepper', + tokenSource: 'auto-routing-benchmark', + }); + expect(claims).not.toHaveProperty('aud'); + expect(claims).not.toHaveProperty('tokenPurpose'); + expect(claims).not.toHaveProperty('organizationId'); + expect(isResourceTokenIssuanceEnabled).toHaveBeenCalledWith('benchmark'); }); - it('mints an organization-scoped token when organizationId is provided', async () => { - const user = { id: 'user-1', api_token_pepper: 'pepper' }; - mockRows.push(user); - mockMembershipRows.push({ role: 'owner' }); + it('preserves the existing organization token and role while shared tokens are disabled', async () => { + mockRows.push({ + id: 'user-1', + api_token_pepper: 'pepper', + blocked_at: null, + blocked_reason: null, + }); + mockMembershipRows.push({ role: 'billing_manager' }); const res = await POST( createRequest( @@ -104,10 +116,154 @@ describe('POST /api/internal/auto-routing-benchmark/token', () => { ); expect(res.status).toBe(200); - expect(mockGenerateApiToken).toHaveBeenCalledWith( - user, - { tokenSource: 'auto-routing-benchmark', organizationId: 'org-1', organizationRole: 'owner' }, - { expiresIn: 6 * 60 * 60 } + const { token } = (await res.json()) as { token: string }; + const claims = jwt.verify(token, 'benchmark-token-secret') as jwt.JwtPayload; + expect(claims).toMatchObject({ + organizationId: 'org-1', + organizationRole: 'billing_manager', + tokenSource: 'auto-routing-benchmark', + }); + expect(claims).not.toHaveProperty('aud'); + expect(claims).not.toHaveProperty('tokenPurpose'); + expect(claims).not.toHaveProperty('credentialExchange'); + }); + + it('mints one pepper-bound personal CLI token accepted by API and gateway audiences', async () => { + mockSharedResourceTokens.enabled = true; + mockRows.push({ + id: 'user-1', + api_token_pepper: 'pepper', + blocked_at: null, + blocked_reason: null, + }); + + const res = await POST( + createRequest({ userId: 'user-1' }, { authorization: 'Bearer internal-secret' }) + ); + + expect(res.status).toBe(200); + const { token } = (await res.json()) as { token: string }; + const claims = jwt.verify(token, 'benchmark-token-secret') as jwt.JwtPayload; + expect(claims).toMatchObject({ + aud: [KILO_API_AUDIENCE, KILO_GATEWAY_AUDIENCE], + apiTokenPepper: 'pepper', + tokenPurpose: 'delegated-workload', + credentialExchange: false, + tokenSource: 'auto-routing-benchmark', + }); + expect(claims.exp! - claims.iat!).toBe(6 * 60 * 60); + expect(claims).not.toHaveProperty('organizationId'); + expect(isResourceTokenIssuanceEnabled).toHaveBeenCalledWith('benchmark'); + expect(claims).not.toHaveProperty('organizationRole'); + + const headers = new Headers({ authorization: `Bearer ${token}` }); + expect( + validateAuthorizationHeader(headers, { expectedAudience: KILO_API_AUDIENCE }).error + ).toBeUndefined(); + expect( + validateAuthorizationHeader(headers, { expectedAudience: KILO_GATEWAY_AUDIENCE }).error + ).toBeUndefined(); + expect( + validateAuthorizationHeader(headers, { expectedAudience: 'unrelated-audience' }).error + ).toMatch(/^Invalid token \([a-f0-9-]+\)$/); + }); + + it.each(['owner', 'member'] as const)( + 'mints a dual-audience token with the exact eligible %s organization claims', + async role => { + mockSharedResourceTokens.enabled = true; + mockRows.push({ + id: 'user-1', + api_token_pepper: 'pepper', + blocked_at: null, + blocked_reason: null, + }); + mockMembershipRows.push({ role }); + + const res = await POST( + createRequest( + { userId: 'user-1', organizationId: 'org-1' }, + { authorization: 'Bearer internal-secret' } + ) + ); + + expect(res.status).toBe(200); + const { token } = (await res.json()) as { token: string }; + expect(jwt.verify(token, 'benchmark-token-secret')).toMatchObject({ + aud: [KILO_API_AUDIENCE, KILO_GATEWAY_AUDIENCE], + organizationId: 'org-1', + organizationRole: role, + credentialExchange: false, + }); + } + ); + + it('rejects an ineligible organization user before membership lookup', async () => { + mockSharedResourceTokens.enabled = true; + mockRows.push({ id: 'user-1', api_token_pepper: null, blocked_at: null, blocked_reason: null }); + + const res = await POST( + createRequest( + { userId: 'user-1', organizationId: 'org-1' }, + { authorization: 'Bearer internal-secret' } + ) ); + + expect(res.status).toBe(403); + expect(mockSelectCallCount).toBe(1); + }); + + it('does not mint a token for a user without an API token pepper', async () => { + mockSharedResourceTokens.enabled = true; + mockRows.push({ id: 'user-1', api_token_pepper: null, blocked_at: null, blocked_reason: null }); + + const res = await POST( + createRequest({ userId: 'user-1' }, { authorization: 'Bearer internal-secret' }) + ); + + expect(res.status).toBe(403); + await expect(res.json()).resolves.toEqual({ + error: 'User is not eligible for benchmark tokens', + }); + }); + + it.each([ + { blocked_at: '2026-09-04T00:00:00.000Z', blocked_reason: null }, + { blocked_at: null, blocked_reason: 'manual block' }, + ])('does not mint a token for a blocked user', async blocked => { + mockSharedResourceTokens.enabled = true; + mockRows.push({ id: 'user-1', api_token_pepper: 'pepper', ...blocked }); + + const res = await POST( + createRequest({ userId: 'user-1' }, { authorization: 'Bearer internal-secret' }) + ); + + expect(res.status).toBe(403); + await expect(res.json()).resolves.toEqual({ + error: 'User is not eligible for benchmark tokens', + }); + }); + + it('does not mint an organization token for an ineligible current role', async () => { + mockSharedResourceTokens.enabled = true; + mockRows.push({ + id: 'user-1', + api_token_pepper: 'pepper', + blocked_at: null, + blocked_reason: null, + }); + mockMembershipRows.push({ role: 'billing_manager' }); + + const res = await POST( + createRequest( + { userId: 'user-1', organizationId: 'org-1' }, + { authorization: 'Bearer internal-secret' } + ) + ); + + expect(res.status).toBe(403); + await expect(res.json()).resolves.toEqual({ + error: 'Organization role is not supported for benchmark tokens', + }); }); }); diff --git a/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.ts b/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.ts index 472eeda0bb..d683e3aac3 100644 --- a/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.ts +++ b/apps/web/src/app/api/internal/auto-routing-benchmark/token/route.ts @@ -1,22 +1,25 @@ /** - * Internal API: mint a short-lived user API token for the auto-routing - * decider benchmark. + * Internal API: mint a short-lived, dual-audience user token for the + * auto-routing decider benchmark. * * Called by: * - services/auto-routing-benchmark — the decider benchmark runs each case * through the real `kilo` CLI inside a Cloudflare Container. The CLI - * authenticates against the gateway with a user API token, so the worker - * fetches a fresh, short-lived token for the configured benchmark user - * once per queue message. + * authenticates with a user API token. The immutable CLI resolves its + * catalog, profile, defaults, and provider gateway requests from + * KILO_API_URL, so the worker fetches one fresh token for the configured + * benchmark user once per queue message. * * Auth: shared internal secret over `Authorization: Bearer ` — this * is the exact header the benchmark worker sends * (`Authorization: Bearer ${INTERNAL_API_SECRET_PROD}`), and * INTERNAL_API_SECRET_PROD holds the same value as INTERNAL_API_SECRET here. * - * The minted token is a full user API token (includes apiTokenPepper) so the - * gateway accepts it as a real user token; an internal-service token would be - * rejected by gateway pepper validation. It expires in 6 hours. + * While shared-resource issuance is disabled, this preserves the existing + * audience-less benchmark token. Once enabled, issuance requires an active + * benchmark user with a non-empty API-token pepper and (when supplied) a + * current owner or member organization membership. The modern token has exact + * API and gateway audiences and never falls back to the legacy shape. * * URL: POST /api/internal/auto-routing-benchmark/token */ @@ -29,8 +32,18 @@ import { z } from 'zod'; import { and, eq } from 'drizzle-orm'; import { kilocode_users, organization_memberships } from '@kilocode/db/schema'; import { db } from '@/lib/drizzle'; +import { + isResourceTokenIssuanceEnabled, + INTERNAL_API_SECRET, + NEXTAUTH_SECRET, +} from '@/lib/config.server'; import { generateApiToken } from '@/lib/tokens'; -import { INTERNAL_API_SECRET } from '@/lib/config.server'; +import { + KILO_API_AUDIENCE, + KILO_GATEWAY_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +import { buildModernKiloTokenPayload } from '@kilocode/worker-utils/kilo-token-policy'; +import jwt from 'jsonwebtoken'; const RequestSchema = z.object({ userId: z.string().min(1), @@ -44,7 +57,6 @@ export async function POST(req: NextRequest) { if (!INTERNAL_API_SECRET || !token || !timingSafeEqual(token, INTERNAL_API_SECRET)) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } - let body: unknown; try { body = await req.json(); @@ -69,33 +81,72 @@ export async function POST(req: NextRequest) { if (!user) { return NextResponse.json({ error: 'User not found' }, { status: 404 }); } - + const sharedResourceTokensEnabled = isResourceTokenIssuanceEnabled('benchmark'); + if ( + sharedResourceTokensEnabled && + (typeof user.api_token_pepper !== 'string' || + user.api_token_pepper.trim().length === 0 || + user.blocked_at !== null || + user.blocked_reason !== null) + ) { + return NextResponse.json( + { error: 'User is not eligible for benchmark tokens' }, + { status: 403 } + ); + } const extraPayload = { tokenSource: 'auto-routing-benchmark' }; const organizationId = parsed.data.organizationId; + let organizationRole: Awaited> | undefined; if (organizationId) { - const organizationRole = await getOrganizationRole(parsed.data.userId, organizationId); - if (organizationRole === null) { + const role = await getOrganizationRole(parsed.data.userId, organizationId); + if (role === null) { return NextResponse.json({ error: 'Organization membership not found' }, { status: 404 }); } + organizationRole = role; + } - const apiToken = generateApiToken( + if (!sharedResourceTokensEnabled) { + const legacyToken = generateApiToken( user, - { - ...extraPayload, - organizationId, - organizationRole, - }, + { ...extraPayload, organizationId, organizationRole }, { expiresIn: SIX_HOURS_IN_SECONDS } ); - const expiresAt = new Date(Date.now() + SIX_HOURS_IN_SECONDS * 1000).toISOString(); - - return NextResponse.json({ token: apiToken, expiresAt }); + return NextResponse.json({ + token: legacyToken, + expiresAt: new Date(Date.now() + SIX_HOURS_IN_SECONDS * 1000).toISOString(), + }); } - const apiToken = generateApiToken(user, extraPayload, { expiresIn: SIX_HOURS_IN_SECONDS }); - const expiresAt = new Date(Date.now() + SIX_HOURS_IN_SECONDS * 1000).toISOString(); + if (organizationRole !== undefined) { + if (organizationRole !== 'owner' && organizationRole !== 'member') { + return NextResponse.json( + { error: 'Organization role is not supported for benchmark tokens' }, + { status: 403 } + ); + } + } - return NextResponse.json({ token: apiToken, expiresAt }); + const issuedAt = Math.floor(Date.now() / 1000); + const expiresAt = issuedAt + SIX_HOURS_IN_SECONDS; + const signedToken = jwt.sign( + buildModernKiloTokenPayload({ + userId: user.id, + pepper: user.api_token_pepper, + env: process.env.NODE_ENV, + audience: [KILO_API_AUDIENCE, KILO_GATEWAY_AUDIENCE], + issuedAt, + expiresAt, + tokenPurpose: 'delegated-workload', + credentialExchange: false, + extra: { ...extraPayload, organizationId, organizationRole }, + }), + NEXTAUTH_SECRET, + { algorithm: 'HS256' } + ); + return NextResponse.json({ + token: signedToken, + expiresAt: new Date(expiresAt * 1000).toISOString(), + }); } async function getOrganizationRole(userId: string, organizationId: string) { diff --git a/apps/web/src/app/api/kilo-chat/token/route.ts b/apps/web/src/app/api/kilo-chat/token/route.ts index f6dd41bb3c..73cd42111e 100644 --- a/apps/web/src/app/api/kilo-chat/token/route.ts +++ b/apps/web/src/app/api/kilo-chat/token/route.ts @@ -17,10 +17,10 @@ import { getUserFromAuth } from '@/lib/user/server'; * extracting kiloUserId from the payload. Sandbox ownership is verified * server-side by the kilo-chat worker via Hyperdrive. */ -export async function POST() { +export async function POST(request: Request) { const { user, authFailedResponse } = await getUserFromAuth({ adminOnly: false }); if (authFailedResponse) return authFailedResponse; if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); - return NextResponse.json(createKiloChatTokenResponse(user)); + return NextResponse.json(await createKiloChatTokenResponse(user, request.headers)); } diff --git a/apps/web/src/app/api/organizations/[id]/user-tokens/route.test.ts b/apps/web/src/app/api/organizations/[id]/user-tokens/route.test.ts new file mode 100644 index 0000000000..cb7c75808d --- /dev/null +++ b/apps/web/src/app/api/organizations/[id]/user-tokens/route.test.ts @@ -0,0 +1,63 @@ +import { NextRequest } from 'next/server'; +import { isResourceTokenIssuanceEnabled } from '@/lib/config.server'; +import { createDelegatedResourceToken } from '@/lib/auth/resource-delegation'; +import { generateOrganizationApiToken } from '@/lib/tokens'; +import { POST } from './route'; + +jest.mock('@/lib/config.server', () => ({ isResourceTokenIssuanceEnabled: jest.fn() })); +jest.mock('@/lib/organizations/organization-auth', () => ({ + getAuthorizedOrgContext: jest.fn(async () => ({ + success: true, + data: { user: { id: 'oauth/test-user', role: 'member' }, organization: { name: 'Test' } }, + })), +})); +jest.mock('@/lib/organizations/organization-audit-logs', () => ({ createAuditLog: jest.fn() })); +jest.mock('@/lib/auth/resource-delegation', () => ({ + isDelegableResource: (value: string) => + ['api', 'gateway', 'attribution', 'html-deploy'].includes(value), + canIssueLegacyOrganizationToken: (headers: Headers) => !headers.has('authorization'), + createDelegatedResourceToken: jest.fn(async () => ({ token: 'delegated', expiresAt: 'expiry' })), +})); +jest.mock('@/lib/tokens', () => ({ + generateOrganizationApiToken: jest.fn(() => ({ token: 'legacy', expiresAt: 'expiry' })), +})); + +beforeEach(() => { + jest.clearAllMocks(); + jest.mocked(isResourceTokenIssuanceEnabled).mockReturnValue(false); +}); + +it.each(['api', 'gateway', 'attribution', 'html-deploy'])( + 'requires the delegated-resource family for explicit %s issuance', + async resource => { + const request = () => + new NextRequest('http://localhost/api/organizations/org/user-tokens', { + method: 'POST', + body: JSON.stringify({ resource }), + }); + const params = Promise.resolve({ id: 'org' }); + expect((await POST(request(), { params })).status).toBe(503); + expect(isResourceTokenIssuanceEnabled).toHaveBeenCalledWith('delegated-resource'); + expect(createDelegatedResourceToken).not.toHaveBeenCalled(); + expect(generateOrganizationApiToken).not.toHaveBeenCalled(); + jest.mocked(isResourceTokenIssuanceEnabled).mockReturnValue(true); + expect((await POST(request(), { params })).status).toBe(200); + expect(createDelegatedResourceToken).toHaveBeenCalledWith( + expect.objectContaining({ id: 'oauth/test-user' }), + resource, + expect.objectContaining({ organizationId: 'org', organizationRole: 'member' }) + ); + expect(generateOrganizationApiToken).not.toHaveBeenCalled(); + } +); + +it('retains legacy session issuance while the family gate is false', async () => { + const request = new NextRequest('http://localhost/api/organizations/org/user-tokens', { + method: 'POST', + body: '{}', + }); + const response = await POST(request, { params: Promise.resolve({ id: 'org' }) }); + expect(response.status).toBe(200); + expect(generateOrganizationApiToken).toHaveBeenCalled(); + expect(createDelegatedResourceToken).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/app/api/organizations/[id]/user-tokens/route.ts b/apps/web/src/app/api/organizations/[id]/user-tokens/route.ts index a64d1a617f..d56b6ab4e6 100644 --- a/apps/web/src/app/api/organizations/[id]/user-tokens/route.ts +++ b/apps/web/src/app/api/organizations/[id]/user-tokens/route.ts @@ -3,6 +3,13 @@ import { NextResponse } from 'next/server'; import { getAuthorizedOrgContext } from '@/lib/organizations/organization-auth'; import { generateOrganizationApiToken } from '@/lib/tokens'; import { createAuditLog } from '@/lib/organizations/organization-audit-logs'; +import { + canIssueLegacyOrganizationToken, + createDelegatedResourceToken, + isDelegableResource, + TypedResourceDelegationError, +} from '@/lib/auth/resource-delegation'; +import { isResourceTokenIssuanceEnabled } from '@/lib/config.server'; export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { const organizationId = (await params).id; @@ -16,7 +23,65 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{ const { user, organization } = result.data; - // Generate the organization-scoped JWT token (15 minute expiration) + let body: unknown; + try { + body = await request.json(); + } catch { + body = undefined; + } + const resource = + body && typeof body === 'object' ? (body as { resource?: unknown }).resource : undefined; + if (resource !== undefined && !isDelegableResource(resource)) { + return NextResponse.json({ error: 'Unsupported resource' }, { status: 400 }); + } + if (resource !== undefined) { + if (!isResourceTokenIssuanceEnabled('delegated-resource')) { + return NextResponse.json( + { error: 'Shared resource token migration is unavailable' }, + { status: 503 } + ); + } + if (user.role === 'billing_manager' || (resource === 'attribution' && user.role === 'admin')) { + return NextResponse.json( + { error: 'Organization role cannot issue this resource token' }, + { status: 403 } + ); + } + const organizationRole = user.role; + try { + const delegated = await createDelegatedResourceToken(user, resource, { + headers: request.headers, + organizationRole, + organizationId, + }); + await createAuditLog({ + organization_id: organizationId, + action: 'organization.token.generate', + actor_name: user.google_user_name, + actor_email: user.google_user_email, + actor_id: user.id, + message: `Resource token generated for organization ${organization.name}`, + }); + return NextResponse.json({ + token: delegated.token, + expiresAt: delegated.expiresAt, + organizationId, + }); + } catch (error) { + if (error instanceof TypedResourceDelegationError) { + return NextResponse.json({ error: error.message }, { status: error.status }); + } + throw error; + } + } + + if (!canIssueLegacyOrganizationToken(request.headers)) { + return NextResponse.json( + { error: 'Explicit resource negotiation is required for bearer credentials' }, + { status: 403 } + ); + } + const { token, expiresAt } = generateOrganizationApiToken(user, organizationId, user.role); // Log the token generation for audit purposes diff --git a/apps/web/src/app/api/wasteland/token/route.ts b/apps/web/src/app/api/wasteland/token/route.ts index 0bcce01985..7908c94ea9 100644 --- a/apps/web/src/app/api/wasteland/token/route.ts +++ b/apps/web/src/app/api/wasteland/token/route.ts @@ -1,8 +1,10 @@ import 'server-only'; import { NextResponse } from 'next/server'; import { getUserFromAuth } from '@/lib/user/server'; -import { generateApiToken } from '@/lib/tokens'; -import { getUserOrgMemberships } from '@/lib/organizations/organizations'; +import { + createControlTokenForRequest, + TypedResourceDelegationError, +} from '@/lib/auth/resource-delegation'; import { recordKiloAdminElevationForRequest, serviceTarget } from '@/lib/admin/admin-access-log'; const ONE_HOUR_SECONDS = 60 * 60; @@ -21,30 +23,33 @@ const ONE_HOUR_SECONDS = 60 * 60; * worker can enforce access and check org membership without DB round-trips. */ export async function POST() { - const { user, authFailedResponse, tokenSource } = await getUserFromAuth({ adminOnly: false }); + const { user, authFailedResponse } = await getUserFromAuth({ adminOnly: false }); if (authFailedResponse) return authFailedResponse; if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); - if (user.is_admin) { - // The minted token carries `isAdmin`, so the elevation is exercised inside - // the Wasteland worker where this app emits nothing. Correlate on - // `kiloUserId` within the token's lifetime below. - await recordKiloAdminElevationForRequest({ - user, - tokenSource, - reason: 'service_token_mint', - target: serviceTarget('wasteland'), + try { + const result = await createControlTokenForRequest(user, 'wasteland', { + tokenSource: 'wasteland', + expiresIn: ONE_HOUR_SECONDS, + legacyExpiresIn: ONE_HOUR_SECONDS, + extra: { isAdmin: user.is_admin }, }); + if (result.user.is_admin) { + await recordKiloAdminElevationForRequest({ + user: result.user, + tokenSource: result.tokenSource, + reason: 'service_token_mint', + target: serviceTarget('wasteland'), + }); + } + return NextResponse.json({ token: result.token, expiresAt: result.expiresAt }); + } catch (error) { + if (error instanceof TypedResourceDelegationError) { + return NextResponse.json( + { error: error.message, code: error.delegationCode }, + { status: error.status } + ); + } + throw error; } - - const orgMemberships = await getUserOrgMemberships(user.id); - - const token = generateApiToken( - user, - { isAdmin: user.is_admin, orgMemberships }, - { expiresIn: ONE_HOUR_SECONDS } - ); - const expiresAt = new Date(Date.now() + 55 * 60 * 1000).toISOString(); - - return NextResponse.json({ token, expiresAt }); } diff --git a/apps/web/src/lib/auth/device-sessions.test.ts b/apps/web/src/lib/auth/device-sessions.test.ts index 32bd4c2cf7..67e11781b8 100644 --- a/apps/web/src/lib/auth/device-sessions.test.ts +++ b/apps/web/src/lib/auth/device-sessions.test.ts @@ -9,6 +9,9 @@ import { revokeDeviceSession, } from './device-sessions'; import type { User } from '@kilocode/db/schema'; +import jwt from 'jsonwebtoken'; +import { NEXTAUTH_SECRET } from '@/lib/config.server'; +import { API_GATEWAY_CREDENTIAL_FORMAT } from '@kilocode/app-shared/native-auth'; describe('device-sessions', () => { const testUserId = 'test-user-ds-' + Date.now(); @@ -17,20 +20,18 @@ describe('device-sessions', () => { let fakeUser: User; beforeEach(async () => { - await db.insert(kilocode_users).values({ - id: testUserId, - google_user_email: testUserEmail, - google_user_name: 'Test User', - google_user_image_url: 'https://example.com/avatar.jpg', - stripe_customer_id: 'cus_test', - }); - fakeUser = { - id: testUserId, - google_user_email: testUserEmail, - google_user_name: 'Test User', - google_user_image_url: 'https://example.com/avatar.jpg', - api_token_pepper: undefined, - } as unknown as User; + const [createdUser] = await db + .insert(kilocode_users) + .values({ + id: testUserId, + google_user_email: testUserEmail, + google_user_name: 'Test User', + google_user_image_url: 'https://example.com/avatar.jpg', + stripe_customer_id: 'cus_test', + }) + .returning(); + if (!createdUser) throw new Error('Expected a test user'); + fakeUser = createdUser; }); afterEach(async () => { @@ -80,6 +81,58 @@ describe('device-sessions', () => { }); }); + test('rotates an actual negotiated bundle and supports legacy rollout rollback', async () => { + const key = 'NATIVE_RESOURCE_TOKENS_ENABLED'; + const previous = process.env[key]; + const sharedKey = 'SHARED_RESOURCE_TOKENS_ENABLED'; + const previousShared = process.env[sharedKey]; + process.env[key] = 'true'; + process.env[sharedKey] = 'true'; + try { + const sessionId = await createDeviceSession({ userId: testUserId }); + const first = await issueSessionCredentials(fakeUser, sessionId, { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }); + const next = await rotateRefreshToken(first.refreshToken, { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }); + expect(next.ok).toBe(true); + if (!next.ok) throw new Error('Expected successful rotation'); + for (const pair of [first, next]) { + expect(pair.metadata?.credentialFormat).toBe(API_GATEWAY_CREDENTIAL_FORMAT); + if (!pair.metadata) throw new Error('Expected credential bundle metadata'); + expect(jwt.verify(pair.token, NEXTAUTH_SECRET)).toMatchObject({ + kiloUserId: testUserId, + aud: 'kilo-api', + deviceSessionId: sessionId, + tokenPurpose: 'device-access', + credentialExchange: false, + }); + expect(jwt.verify(pair.metadata.gatewayToken, NEXTAUTH_SECRET)).toMatchObject({ + kiloUserId: testUserId, + aud: 'kilo-gateway', + deviceSessionId: sessionId, + tokenPurpose: 'device-access', + credentialExchange: false, + }); + } + expect(next.refreshToken).not.toBe(first.refreshToken); + process.env[key] = 'false'; + const rollback = await rotateRefreshToken(next.refreshToken, { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }); + expect(rollback.ok).toBe(true); + if (!rollback.ok) throw new Error('Expected compatible rollback rotation'); + expect(rollback).not.toHaveProperty('metadata'); + expect(jwt.verify(rollback.token, NEXTAUTH_SECRET)).not.toHaveProperty('aud'); + } finally { + if (previous === undefined) delete process.env[key]; + else process.env[key] = previous; + if (previousShared === undefined) delete process.env[sharedKey]; + else process.env[sharedKey] = previousShared; + } + }); + describe('rotateRefreshToken', () => { test('happy path: rotates and returns a new pair', async () => { const sessionId = await createDeviceSession({ userId: testUserId }); @@ -398,5 +451,27 @@ describe('device-sessions', () => { expect(retry.refreshToken).not.toBe(refreshToken); } }); + + test('native credential generation failure rolls back consumption and preserves the session', async () => { + const sessionId = await createDeviceSession({ userId: testUserId }); + const { refreshToken } = await issueSessionCredentials(fakeUser, sessionId); + await expect( + rotateRefreshToken(refreshToken, { + credentialFormat: 'unsupported-format' as never, + }) + ).rejects.toThrow('Unsupported native credential format'); + + const [oldToken] = await db + .select() + .from(device_refresh_tokens) + .where(eq(device_refresh_tokens.device_session_id, sessionId)); + const [session] = await db + .select() + .from(device_sessions) + .where(eq(device_sessions.id, sessionId)); + expect(oldToken!.consumed_at).toBeNull(); + expect(session!.revoked_at).toBeNull(); + await expect(rotateRefreshToken(refreshToken)).resolves.toMatchObject({ ok: true }); + }); }); }); diff --git a/apps/web/src/lib/auth/device-sessions.ts b/apps/web/src/lib/auth/device-sessions.ts index 8d4f9dab18..5c909a8289 100644 --- a/apps/web/src/lib/auth/device-sessions.ts +++ b/apps/web/src/lib/auth/device-sessions.ts @@ -3,9 +3,14 @@ import { db } from '@/lib/drizzle'; import { device_sessions, device_refresh_tokens, kilocode_users } from '@kilocode/db/schema'; import type { User } from '@kilocode/db/schema'; import { eq, and, isNull, gt } from 'drizzle-orm'; -import { generateApiToken, TOKEN_EXPIRY } from '@/lib/tokens'; +import { TOKEN_EXPIRY } from '@/lib/tokens'; import { createHash, randomBytes } from 'node:crypto'; import { persistAttestedKeyTx, type VerifyAdmissionOk } from './native-admission'; +import { generateNativeAccessCredentials } from './native-access-credentials'; +import type { + NativeCredentialFormat, + NativeSessionCredentials, +} from '@kilocode/app-shared/native-auth'; const REFRESH_TOKEN_BYTES = 32; @@ -48,12 +53,13 @@ export async function createDeviceSession(params: { */ export async function issueSessionCredentials( user: User, - deviceSessionId: string -): Promise<{ token: string; refreshToken: string; expiresIn: number }> { - const accessToken = generateApiToken( + deviceSessionId: string, + options?: { credentialFormat?: NativeCredentialFormat } +): Promise { + const accessCredentials = generateNativeAccessCredentials( user, - { deviceSessionId }, - { expiresIn: TOKEN_EXPIRY.oneHour } + deviceSessionId, + options?.credentialFormat ); const refreshToken = generateRefreshToken(); @@ -67,7 +73,7 @@ export async function issueSessionCredentials( }); return { - token: accessToken, + ...accessCredentials, refreshToken, expiresIn: TOKEN_EXPIRY.oneHour, }; @@ -92,9 +98,10 @@ export async function issueSessionCredentials( * usable instead of leaving the client with a permanently dead refresh path. */ export async function rotateRefreshToken( - refreshToken: string + refreshToken: string, + options?: { credentialFormat?: NativeCredentialFormat } ): Promise< - | { ok: true; token: string; refreshToken: string; expiresIn: number } + | ({ ok: true } & NativeSessionCredentials) | { ok: false; error: 'INVALID_REFRESH_TOKEN' | 'SESSION_REVOKED' | 'USER_BLOCKED' } > { const tokenHash = hashToken(refreshToken); @@ -223,10 +230,10 @@ export async function rotateRefreshToken( .where(eq(device_sessions.id, consumed.device_session_id)); // Step 8: Issue the replacement pair in the same transaction. - const accessToken = generateApiToken( + const accessCredentials = generateNativeAccessCredentials( fullUser, - { deviceSessionId: lockedSession.id }, - { expiresIn: TOKEN_EXPIRY.oneHour } + lockedSession.id, + options?.credentialFormat ); const newRefreshToken = generateRefreshToken(); @@ -240,7 +247,11 @@ export async function rotateRefreshToken( return { kind: 'ok', - pair: { token: accessToken, refreshToken: newRefreshToken, expiresIn: TOKEN_EXPIRY.oneHour }, + pair: { + ...accessCredentials, + refreshToken: newRefreshToken, + expiresIn: TOKEN_EXPIRY.oneHour, + }, } as const; }); @@ -269,7 +280,8 @@ export async function createDeviceSessionWithAttestedKey(params: { userAgent?: string; user: User; verification: VerifyAdmissionOk; -}): Promise<{ token: string; refreshToken: string; expiresIn: number; sessionId: string }> { + credentialFormat?: NativeCredentialFormat; +}): Promise { return await db.transaction(async tx => { // Persist the attested key inside the transaction await persistAttestedKeyTx(tx, params.userId, params.verification); @@ -288,10 +300,10 @@ export async function createDeviceSessionWithAttestedKey(params: { } // Issue credentials - const accessToken = generateApiToken( + const accessCredentials = generateNativeAccessCredentials( params.user, - { deviceSessionId: session.id }, - { expiresIn: TOKEN_EXPIRY.oneHour } + session.id, + params.credentialFormat ); const refreshToken = generateRefreshToken(); @@ -305,7 +317,7 @@ export async function createDeviceSessionWithAttestedKey(params: { }); return { - token: accessToken, + ...accessCredentials, refreshToken, expiresIn: TOKEN_EXPIRY.oneHour, sessionId: session.id, diff --git a/apps/web/src/lib/auth/native-access-credentials.test.ts b/apps/web/src/lib/auth/native-access-credentials.test.ts new file mode 100644 index 0000000000..91dd78fc12 --- /dev/null +++ b/apps/web/src/lib/auth/native-access-credentials.test.ts @@ -0,0 +1,108 @@ +import jwt from 'jsonwebtoken'; +import { API_GATEWAY_CREDENTIAL_FORMAT } from '@kilocode/app-shared/native-auth'; + +const config = { enabled: true, sharedReady: true }; + +jest.mock('@/lib/config.server', () => ({ + NEXTAUTH_SECRET: 'native-access-credentials-secret', + isNativeResourceCredentialIssuanceEnabled: () => config.enabled && config.sharedReady, +})); + +import { generateNativeAccessCredentials } from './native-access-credentials'; +import { + KILO_API_AUDIENCE, + KILO_GATEWAY_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +import { + isKiloCredentialExchangeEligible, + verifyKiloTokenForPolicy, +} from '@kilocode/worker-utils/kilo-token-policy'; +import type { User } from '@kilocode/db/schema'; + +const user = { + id: 'native-user', + api_token_pepper: null, +} as User; + +describe('generateNativeAccessCredentials', () => { + beforeEach(() => { + config.enabled = true; + config.sharedReady = true; + }); + + test('issues separated API and gateway credentials sharing one-hour timestamps', async () => { + const result = generateNativeAccessCredentials( + user, + 'device-session', + API_GATEWAY_CREDENTIAL_FORMAT + ); + expect(result.metadata).toBeDefined(); + if (!result.metadata) return; + + const apiClaims = jwt.verify( + result.token, + 'native-access-credentials-secret' + ) as jwt.JwtPayload; + const gatewayClaims = jwt.verify( + result.metadata.gatewayToken, + 'native-access-credentials-secret' + ) as jwt.JwtPayload; + + expect(apiClaims).toMatchObject({ + aud: KILO_API_AUDIENCE, + tokenPurpose: 'device-access', + credentialExchange: false, + deviceSessionId: 'device-session', + apiTokenPepper: null, + }); + expect(gatewayClaims).toMatchObject({ + aud: KILO_GATEWAY_AUDIENCE, + tokenPurpose: 'device-access', + credentialExchange: false, + deviceSessionId: 'device-session', + apiTokenPepper: null, + }); + expect(apiClaims.iat).toBe(gatewayClaims.iat); + expect(apiClaims.exp).toBe(gatewayClaims.exp); + expect(apiClaims.exp! - apiClaims.iat!).toBe(3600); + expect(result.metadata.expiresAt).toBe(new Date(apiClaims.exp! * 1000).toISOString()); + await expect( + verifyKiloTokenForPolicy(result.token, 'native-access-credentials-secret', { + audience: KILO_API_AUDIENCE, + mode: 'required', + }).then(auth => isKiloCredentialExchangeEligible(auth, { legacy: 'five-year-api' })) + ).resolves.toBe(false); + }); + + test('preserves the exact legacy credential shape when issuance is disabled or unnegotiated', () => { + config.enabled = false; + const disabled = generateNativeAccessCredentials( + user, + 'device-session', + API_GATEWAY_CREDENTIAL_FORMAT + ); + const unnegotiated = generateNativeAccessCredentials(user, 'device-session'); + + expect(disabled.metadata).toBeUndefined(); + expect(unnegotiated.metadata).toBeUndefined(); + expect(jwt.decode(disabled.token)).toMatchObject({ deviceSessionId: 'device-session' }); + expect(jwt.decode(unnegotiated.token)).toMatchObject({ deviceSessionId: 'device-session' }); + }); + + test('does not adopt resource credentials until the shared control issuer is ready', () => { + config.sharedReady = false; + const result = generateNativeAccessCredentials( + user, + 'device-session', + API_GATEWAY_CREDENTIAL_FORMAT + ); + + expect(result.metadata).toBeUndefined(); + }); + + test('rejects an unsupported requested format instead of silently falling back', () => { + expect(() => + generateNativeAccessCredentials(user, 'device-session', 'unknown-format' as never) + ).toThrow('Unsupported native credential format'); + }); +}); diff --git a/apps/web/src/lib/auth/native-access-credentials.ts b/apps/web/src/lib/auth/native-access-credentials.ts new file mode 100644 index 0000000000..f3b7a934d6 --- /dev/null +++ b/apps/web/src/lib/auth/native-access-credentials.ts @@ -0,0 +1,68 @@ +import 'server-only'; +import { + API_GATEWAY_CREDENTIAL_FORMAT, + nativeCredentialFormatSchema, + type NativeAccessCredentials, + type NativeCredentialFormat, +} from '@kilocode/app-shared/native-auth'; +import type { User } from '@kilocode/db/schema'; +import { + KILO_API_AUDIENCE, + KILO_GATEWAY_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +import { buildModernKiloTokenPayload } from '@kilocode/worker-utils/kilo-token-policy'; +import jwt from 'jsonwebtoken'; +import { isNativeResourceCredentialIssuanceEnabled, NEXTAUTH_SECRET } from '@/lib/config.server'; +import { generateApiToken, TOKEN_EXPIRY } from '@/lib/tokens'; + +const jwtSigningAlgorithm = 'HS256'; + +export function generateNativeAccessCredentials( + user: User, + deviceSessionId: string, + credentialFormat?: NativeCredentialFormat +): NativeAccessCredentials { + if ( + credentialFormat !== undefined && + !nativeCredentialFormatSchema.safeParse(credentialFormat).success + ) { + throw new Error('Unsupported native credential format'); + } + + if ( + credentialFormat !== API_GATEWAY_CREDENTIAL_FORMAT || + !isNativeResourceCredentialIssuanceEnabled() + ) { + return { + token: generateApiToken(user, { deviceSessionId }, { expiresIn: TOKEN_EXPIRY.oneHour }), + }; + } + + const issuedAt = Math.floor(Date.now() / 1000); + const expiresAt = issuedAt + TOKEN_EXPIRY.oneHour; + const payload = (audience: string) => + buildModernKiloTokenPayload({ + userId: user.id, + pepper: user.api_token_pepper, + env: process.env.NODE_ENV, + audience, + issuedAt, + expiresAt, + tokenPurpose: 'device-access', + credentialExchange: false, + extra: { deviceSessionId }, + }); + + return { + token: jwt.sign(payload(KILO_API_AUDIENCE), NEXTAUTH_SECRET, { + algorithm: jwtSigningAlgorithm, + }), + metadata: { + credentialFormat, + gatewayToken: jwt.sign(payload(KILO_GATEWAY_AUDIENCE), NEXTAUTH_SECRET, { + algorithm: jwtSigningAlgorithm, + }), + expiresAt: new Date(expiresAt * 1000).toISOString(), + }, + }; +} diff --git a/apps/web/src/lib/auth/native-credential-routes.integration.test.ts b/apps/web/src/lib/auth/native-credential-routes.integration.test.ts new file mode 100644 index 0000000000..45f924ce26 --- /dev/null +++ b/apps/web/src/lib/auth/native-credential-routes.integration.test.ts @@ -0,0 +1,272 @@ +import { afterEach, describe, expect, test } from '@jest/globals'; +import { NextRequest } from 'next/server'; +import jwt from 'jsonwebtoken'; +import { and, eq } from 'drizzle-orm'; +import { + API_GATEWAY_CREDENTIAL_FORMAT, + parseNativeTokenPair, +} from '@kilocode/app-shared/native-auth'; +import { + KILO_API_AUDIENCE, + KILO_GATEWAY_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +import { + device_auth_requests, + device_refresh_tokens, + device_sessions, + native_attested_keys, +} from '@kilocode/db/schema'; + +import { POST as exchange } from '@/app/api/auth/native/exchange/route'; +import { POST as refresh } from '@/app/api/auth/native/refresh/route'; +import { POST as deviceToken } from '@/app/api/device-auth/token/route'; +import { createDeviceSessionWithAttestedKey } from '@/lib/auth/device-sessions'; +import { NEXTAUTH_SECRET } from '@/lib/config.server'; +import { createDeviceAuthRequest, approveDeviceAuthRequest } from '@/lib/device-auth/device-auth'; +import { db } from '@/lib/drizzle'; +import { generateApiToken } from '@/lib/tokens'; +import { insertTestUser } from '@/tests/helpers/user.helper'; + +jest.mock('@/lib/redis', () => ({ redisClient: { get: jest.fn(async () => null) } })); + +const nativeResourceTokensKey = 'NATIVE_RESOURCE_TOKENS_ENABLED'; +const originalNativeResourceTokens = process.env[nativeResourceTokensKey]; +const sharedResourceTokensKey = 'SHARED_RESOURCE_TOKENS_ENABLED'; +const originalSharedResourceTokens = process.env[sharedResourceTokensKey]; + +function setNativeResourceTokens(enabled: boolean) { + process.env[nativeResourceTokensKey] = String(enabled); + process.env[sharedResourceTokensKey] = String(enabled); +} + +function request(url: string, body: unknown, headers: Record = {}) { + return new NextRequest(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...headers }, + body: JSON.stringify(body), + }); +} + +function verifyDeviceAccessToken( + token: string, + userId: string, + sessionId: string, + audience: string +) { + const payload = jwt.verify(token, NEXTAUTH_SECRET, { algorithms: ['HS256'] }); + expect(payload).toMatchObject({ + kiloUserId: userId, + aud: audience, + tokenPurpose: 'device-access', + credentialExchange: false, + deviceSessionId: sessionId, + }); +} + +async function refreshRows(sessionId: string) { + return db + .select() + .from(device_refresh_tokens) + .where(eq(device_refresh_tokens.device_session_id, sessionId)); +} + +afterEach(() => { + if (originalNativeResourceTokens === undefined) { + delete process.env[nativeResourceTokensKey]; + } else { + process.env[nativeResourceTokensKey] = originalNativeResourceTokens; + } + if (originalSharedResourceTokens === undefined) { + delete process.env[sharedResourceTokensKey]; + } else { + process.env[sharedResourceTokensKey] = originalSharedResourceTokens; + } +}); + +describe('native credential routes with PostgreSQL-backed sessions', () => { + test('exchanges an eligible five-year legacy bearer and rotates its native credential bundle', async () => { + setNativeResourceTokens(true); + const user = await insertTestUser({ api_token_pepper: crypto.randomUUID() }); + const legacyBearer = generateApiToken(user); + + const exchangeResponse = await exchange( + request( + 'http://localhost:3000/api/auth/native/exchange', + { credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT }, + { Authorization: `Bearer ${legacyBearer}`, 'User-Agent': 'native-integration-test' } + ) + ); + const exchangeBody: unknown = await exchangeResponse.json(); + + expect(exchangeResponse.status).toBe(200); + expect(exchangeResponse.headers.get('cache-control')).toBe('no-store'); + const pair = parseNativeTokenPair(exchangeBody); + expect(pair).not.toBeNull(); + expect(pair).toMatchObject({ + expiresIn: 3600, + metadata: { credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT }, + }); + if (!pair?.refreshToken || !pair.metadata) + throw new Error('Expected a native credential bundle'); + + const [session] = await db + .select() + .from(device_sessions) + .where( + and( + eq(device_sessions.kilo_user_id, user.id), + eq(device_sessions.user_agent, 'native-integration-test') + ) + ); + expect(session).toBeDefined(); + if (!session) throw new Error('Expected device session'); + expect(await refreshRows(session.id)).toHaveLength(1); + verifyDeviceAccessToken(pair.token, user.id, session.id, KILO_API_AUDIENCE); + verifyDeviceAccessToken(pair.metadata.gatewayToken, user.id, session.id, KILO_GATEWAY_AUDIENCE); + + const refreshResponse = await refresh( + request('http://localhost:3000/api/auth/native/refresh', { + refreshToken: pair.refreshToken, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }) + ); + const refreshBody: unknown = await refreshResponse.json(); + + expect(refreshResponse.status).toBe(200); + const rotated = parseNativeTokenPair(refreshBody); + expect(rotated).not.toBeNull(); + if (!rotated?.refreshToken || !rotated.metadata) + throw new Error('Expected rotated native credential bundle'); + expect(rotated.refreshToken).not.toBe(pair.refreshToken); + verifyDeviceAccessToken(rotated.token, user.id, session.id, KILO_API_AUDIENCE); + verifyDeviceAccessToken( + rotated.metadata.gatewayToken, + user.id, + session.id, + KILO_GATEWAY_AUDIENCE + ); + + const storedTokens = await refreshRows(session.id); + expect(storedTokens).toHaveLength(2); + expect(storedTokens.filter(token => token.consumed_at !== null)).toHaveLength(1); + expect(storedTokens.filter(token => token.consumed_at === null)).toHaveLength(1); + }); + + test('rolls a requested format back to the legacy credential response while the flag is off', async () => { + setNativeResourceTokens(false); + const user = await insertTestUser({ api_token_pepper: crypto.randomUUID() }); + + const response = await exchange( + request( + 'http://localhost:3000/api/auth/native/exchange', + { credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT }, + { Authorization: `Bearer ${generateApiToken(user)}` } + ) + ); + const body: unknown = await response.json(); + + expect(response.status).toBe(200); + const pair = parseNativeTokenPair(body); + expect(pair).not.toBeNull(); + expect(pair?.metadata).toBeUndefined(); + if (!pair?.refreshToken) throw new Error('Expected legacy refresh token'); + const payload = jwt.verify(pair.token, NEXTAUTH_SECRET, { algorithms: ['HS256'] }); + expect(payload).toMatchObject({ kiloUserId: user.id }); + }); + + test('does not issue a modern native bundle before shared issuer readiness', async () => { + process.env[nativeResourceTokensKey] = 'true'; + process.env[sharedResourceTokensKey] = 'false'; + const user = await insertTestUser({ api_token_pepper: crypto.randomUUID() }); + + const response = await exchange( + request( + 'http://localhost:3000/api/auth/native/exchange', + { credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT }, + { Authorization: `Bearer ${generateApiToken(user)}` } + ) + ); + const body: unknown = await response.json(); + + expect(response.status).toBe(200); + expect(parseNativeTokenPair(body)?.metadata).toBeUndefined(); + }); + + test('redeems an approved device code into a complete native credential envelope', async () => { + setNativeResourceTokens(true); + const user = await insertTestUser({ api_token_pepper: crypto.randomUUID() }); + const deviceAuth = await createDeviceAuthRequest({ userAgent: 'device-code-integration-test' }); + await approveDeviceAuthRequest(deviceAuth.code, user.id); + + const response = await deviceToken( + request('http://localhost:3000/api/device-auth/token', { + deviceCode: deviceAuth.deviceCode, + supportsRefresh: true, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + }) + ); + const body: unknown = await response.json(); + + expect(response.status).toBe(200); + const pair = parseNativeTokenPair(body); + expect(pair).not.toBeNull(); + if (!pair?.refreshToken || !pair.metadata) + throw new Error('Expected device-code credential bundle'); + + const [deviceAuthRow] = await db + .select({ id: device_auth_requests.id }) + .from(device_auth_requests) + .where(eq(device_auth_requests.code, deviceAuth.code)); + expect(deviceAuthRow).toBeDefined(); + if (!deviceAuthRow) throw new Error('Expected consumed device authorization request'); + + const [session] = await db + .select() + .from(device_sessions) + .where( + and( + eq(device_sessions.kilo_user_id, user.id), + eq(device_sessions.user_agent, 'device-code-integration-test') + ) + ); + expect(session).toBeDefined(); + if (!session) throw new Error('Expected device-code session'); + expect(session.kilo_user_id).toBe(user.id); + expect(session.device_auth_request_id).toBe(deviceAuthRow.id); + expect(await refreshRows(session.id)).toHaveLength(1); + verifyDeviceAccessToken(pair.token, user.id, session.id, KILO_API_AUDIENCE); + verifyDeviceAccessToken(pair.metadata.gatewayToken, user.id, session.id, KILO_GATEWAY_AUDIENCE); + }); + + test('persists an attested iOS key atomically with a native device session', async () => { + setNativeResourceTokens(true); + const user = await insertTestUser({ api_token_pepper: crypto.randomUUID() }); + const keyId = `native-integration-key-${crypto.randomUUID()}`; + const credentials = await createDeviceSessionWithAttestedKey({ + userId: user.id, + user, + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + verification: { + ok: true, + platform: 'ios', + keyId, + publicKey: Buffer.from('native integration fixture key').toString('base64'), + }, + }); + + expect( + await db.query.native_attested_keys.findFirst({ + where: eq(native_attested_keys.key_id, keyId), + }) + ).toMatchObject({ kilo_user_id: user.id, platform: 'ios' }); + expect(await refreshRows(credentials.sessionId)).toHaveLength(1); + verifyDeviceAccessToken(credentials.token, user.id, credentials.sessionId, KILO_API_AUDIENCE); + if (!credentials.metadata) throw new Error('Expected attested native credential bundle'); + verifyDeviceAccessToken( + credentials.metadata.gatewayToken, + user.id, + credentials.sessionId, + KILO_GATEWAY_AUDIENCE + ); + }); +}); diff --git a/apps/web/src/lib/device-auth/device-auth.ts b/apps/web/src/lib/device-auth/device-auth.ts index 93d6608eb8..50004e8143 100644 --- a/apps/web/src/lib/device-auth/device-auth.ts +++ b/apps/web/src/lib/device-auth/device-auth.ts @@ -5,6 +5,10 @@ import { eq, and, lt, lte, gt, isNull, isNotNull, sql } from 'drizzle-orm'; import { generateApiToken } from '@/lib/tokens'; import { randomInt, createHash, randomBytes } from 'node:crypto'; import { createDeviceSession, issueSessionCredentials } from '@/lib/auth/device-sessions'; +import type { + NativeCredentialFormat, + NativeSessionCredentials, +} from '@kilocode/app-shared/native-auth'; const CODE_LENGTH = 8; const CODE_EXPIRATION_MINUTES = 10; @@ -215,12 +219,13 @@ export async function denyDeviceAuthRequest(code: string): Promise { */ export async function consumeDeviceAuthByDeviceCode( deviceCode: string, - options?: { supportsRefresh?: boolean } + options?: { supportsRefresh?: boolean; credentialFormat?: NativeCredentialFormat } ): Promise<{ status: 'pending' | 'approved' | 'denied' | 'expired' | 'consumed'; token?: string; refreshToken?: string; expiresIn?: number; + metadata?: NativeSessionCredentials['metadata']; userId?: string; userEmail?: string; }> { @@ -296,12 +301,14 @@ export async function consumeDeviceAuthByDeviceCode( userAgent: consumed.user_agent ?? undefined, deviceAuthRequestId: consumed.id, }); - const pair = await issueSessionCredentials(user, sessionId); + const pair = options.credentialFormat + ? await issueSessionCredentials(user, sessionId, { + credentialFormat: options.credentialFormat, + }) + : await issueSessionCredentials(user, sessionId); return { status: 'approved', - token: pair.token, - refreshToken: pair.refreshToken, - expiresIn: pair.expiresIn, + ...credentialResponse(pair), userId: user.id, userEmail: user.google_user_email, }; @@ -329,6 +336,17 @@ export async function consumeDeviceAuthByDeviceCode( } } +function credentialResponse(credentials: NativeSessionCredentials) { + return { + token: credentials.token, + refreshToken: credentials.refreshToken, + expiresIn: credentials.expiresIn, + ...('metadata' in credentials && credentials.metadata + ? { metadata: credentials.metadata } + : {}), + }; +} + /** * Poll for device authorization status and return token if approved. * Legacy path — uses atomic consume to prevent double-spend. diff --git a/apps/web/src/lib/kilo-chat/token.test.ts b/apps/web/src/lib/kilo-chat/token.test.ts new file mode 100644 index 0000000000..62a650eb94 --- /dev/null +++ b/apps/web/src/lib/kilo-chat/token.test.ts @@ -0,0 +1,141 @@ +import type { User } from '@kilocode/db/schema'; +import jwt from 'jsonwebtoken'; +import type { ResourceDelegationAuthority } from '@/lib/auth/resource-delegation'; +import { getResourceDelegationAuthority } from '@/lib/auth/resource-delegation'; +import { isResourceTokenIssuanceEnabled, NEXTAUTH_SECRET } from '@/lib/config.server'; +import { generateApiToken } from '@/lib/tokens'; +import { + EVENT_SERVICE_AUDIENCE, + KILO_CHAT_AUDIENCE, + NOTIFICATIONS_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +import { createKiloChatTokenResponse } from './token'; + +jest.mock('@/lib/auth/resource-delegation', () => ({ getResourceDelegationAuthority: jest.fn() })); +jest.mock('@/lib/config.server', () => ({ + NEXTAUTH_SECRET: 'chat-token-unit-test-secret', + isResourceTokenIssuanceEnabled: jest.fn(), +})); +jest.mock('@/lib/tokens', () => ({ generateApiToken: jest.fn() })); + +const now = 1_800_000_000; +const user = { id: 'oauth/chat-user', api_token_pepper: 'test-pepper' } as User; +const mockAuthority = jest.mocked(getResourceDelegationAuthority); +const mockFlag = jest.mocked(isResourceTokenIssuanceEnabled); +const mockLegacyToken = jest.mocked(generateApiToken); + +function authority( + overrides: Partial = {} +): ResourceDelegationAuthority { + return { + user, + credentialKind: 'device-access', + isModern: true, + deviceSessionId: 'active-device-session', + expiresAt: now + 600, + runtimeAdmission: { + source: 'user', + authorizationUserId: user.id, + authorizationPepper: user.api_token_pepper, + }, + ...overrides, + }; +} + +beforeEach(() => { + jest.resetAllMocks(); + jest.useFakeTimers().setSystemTime(now * 1000); + mockFlag.mockReturnValue(false); + mockAuthority.mockResolvedValue(authority()); + mockLegacyToken.mockReturnValue('legacy-token'); +}); +afterEach(() => jest.useRealTimers()); + +it.each([ + [false, 600, 600], + [false, 7200, 3600], + [true, 600, 600], + [true, 7200, 3600], +])('signs device chat tokens (flag=%s, parent TTL=%s)', async (enabled, parentTtl, expectedTtl) => { + mockFlag.mockReturnValue(enabled); + mockAuthority.mockResolvedValue(authority({ expiresAt: now + parentTtl })); + const headers = new Headers({ authorization: 'Bearer test-device-credential' }); + const result = await createKiloChatTokenResponse(user, headers); + expect(jwt.verify(result.token, NEXTAUTH_SECRET, { algorithms: ['HS256'] })).toEqual({ + version: 3, + kiloUserId: user.id, + apiTokenPepper: user.api_token_pepper, + env: 'test', + aud: [KILO_CHAT_AUDIENCE, EVENT_SERVICE_AUDIENCE, NOTIFICATIONS_AUDIENCE], + iat: now, + exp: now + expectedTtl, + tokenPurpose: 'delegated-workload', + credentialExchange: false, + tokenSource: 'kilo-chat', + }); + expect(result.expiresAt).toBe(new Date((now + expectedTtl) * 1000).toISOString()); + expect(result.userId).toBe(user.id); + expect(mockAuthority).toHaveBeenCalledWith(user, { headers }); + expect(mockFlag).toHaveBeenCalledWith('chat'); + expect(mockLegacyToken).not.toHaveBeenCalled(); +}); + +it.each(['human-api', 'device-access'] as const)( + 'preserves flags-off legacy %s issuance and expiry cap', + async credentialKind => { + mockAuthority.mockResolvedValue( + authority({ credentialKind, isModern: false, deviceSessionId: undefined }) + ); + await expect(createKiloChatTokenResponse(user)).resolves.toEqual({ + token: 'legacy-token', + expiresAt: new Date((now + 600) * 1000).toISOString(), + userId: user.id, + }); + expect(mockLegacyToken).toHaveBeenCalledWith( + user, + { tokenSource: 'kilo-chat' }, + { expiresIn: 600 } + ); + } +); + +it.each([ + { credentialKind: 'human-api' as const }, + { deviceSessionId: undefined }, + { deviceSessionId: '' }, +])('denies unsupported modern authority after rollback: %j', async overrides => { + mockAuthority.mockResolvedValue(authority(overrides)); + await expect(createKiloChatTokenResponse(user)).rejects.toThrow( + 'Shared resource token migration is unavailable' + ); + expect(mockLegacyToken).not.toHaveBeenCalled(); +}); + +it.each([0, -1])('denies expired device authority (remaining TTL=%s)', async remaining => { + mockAuthority.mockResolvedValue(authority({ expiresAt: now + remaining })); + await expect(createKiloChatTokenResponse(user)).rejects.toThrow( + 'Kilo Chat delegation authority has expired' + ); + expect(mockLegacyToken).not.toHaveBeenCalled(); +}); + +it('propagates authority validation errors without issuing a token', async () => { + const error = new Error('Device session revoked'); + mockAuthority.mockRejectedValue(error); + await expect(createKiloChatTokenResponse(user)).rejects.toBe(error); + expect(mockFlag).not.toHaveBeenCalled(); + expect(mockLegacyToken).not.toHaveBeenCalled(); +}); + +it.each(['delegated-workload', 'internal-service'] as const)( + 'rejects modern %s without issuing legacy credentials', + async credentialKind => { + mockAuthority.mockResolvedValue( + authority({ credentialKind: credentialKind as ResourceDelegationAuthority['credentialKind'] }) + ); + await expect(createKiloChatTokenResponse(user)).rejects.toThrow( + 'Kilo Chat requires a fresh user credential' + ); + expect(mockLegacyToken).not.toHaveBeenCalled(); + } +); diff --git a/apps/web/src/lib/kilo-chat/token.ts b/apps/web/src/lib/kilo-chat/token.ts index 1c4f065b95..edc6d1c503 100644 --- a/apps/web/src/lib/kilo-chat/token.ts +++ b/apps/web/src/lib/kilo-chat/token.ts @@ -1,18 +1,74 @@ import 'server-only'; import type { User } from '@kilocode/db/schema'; +import jwt from 'jsonwebtoken'; +import { + EVENT_SERVICE_AUDIENCE, + KILO_CHAT_AUDIENCE, + NOTIFICATIONS_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; +import { buildModernKiloTokenPayload } from '@kilocode/worker-utils/kilo-token-policy'; +import { getResourceDelegationAuthority } from '@/lib/auth/resource-delegation'; +import { isResourceTokenIssuanceEnabled, NEXTAUTH_SECRET } from '@/lib/config.server'; import { generateApiToken } from '@/lib/tokens'; import type { KiloChatTokenResponse } from './token-schema'; const KILO_CHAT_TOKEN_TTL_SECONDS = 60 * 60; -export function createKiloChatTokenResponse(user: User): KiloChatTokenResponse { +export async function createKiloChatTokenResponse( + user: User, + headersList: Headers = new Headers() +): Promise { + const authority = await getResourceDelegationAuthority(user, { headers: headersList }); + if (authority.credentialKind !== 'human-api' && authority.credentialKind !== 'device-access') { + throw new Error('Kilo Chat requires a fresh user credential'); + } + // Keep validated device credentials usable after shared issuance is rolled back. + const isModernDeviceAuthority = + authority.isModern && + authority.credentialKind === 'device-access' && + !!authority.deviceSessionId; + if (isResourceTokenIssuanceEnabled('chat') || isModernDeviceAuthority) { + const now = Math.floor(Date.now() / 1000); + const expiresIn = Math.min( + KILO_CHAT_TOKEN_TTL_SECONDS, + authority.expiresAt ? authority.expiresAt - now : KILO_CHAT_TOKEN_TTL_SECONDS + ); + if (expiresIn <= 0) throw new Error('Kilo Chat delegation authority has expired'); + const singleAudiencePayload = buildModernKiloTokenPayload({ + userId: authority.user.id, + pepper: authority.user.api_token_pepper, + env: process.env.NODE_ENV, + audience: [KILO_CHAT_AUDIENCE, EVENT_SERVICE_AUDIENCE, NOTIFICATIONS_AUDIENCE], + issuedAt: now, + expiresAt: now + expiresIn, + tokenPurpose: 'delegated-workload', + credentialExchange: false, + extra: { tokenSource: 'kilo-chat' }, + }); + const token = jwt.sign(singleAudiencePayload, NEXTAUTH_SECRET, { algorithm: 'HS256' }); + return { + token, + expiresAt: new Date((now + expiresIn) * 1000).toISOString(), + userId: authority.user.id, + }; + } + if (authority.isModern) { + throw new Error('Shared resource token migration is unavailable'); + } + const legacyExpiresIn = Math.min( + KILO_CHAT_TOKEN_TTL_SECONDS, + authority.expiresAt + ? authority.expiresAt - Math.floor(Date.now() / 1000) + : KILO_CHAT_TOKEN_TTL_SECONDS + ); + if (legacyExpiresIn <= 0) throw new Error('Kilo Chat delegation authority has expired'); const token = generateApiToken( - user, + authority.user, { tokenSource: 'kilo-chat' }, - { expiresIn: KILO_CHAT_TOKEN_TTL_SECONDS } + { expiresIn: legacyExpiresIn } ); - const expiresAt = new Date(Date.now() + KILO_CHAT_TOKEN_TTL_SECONDS * 1000).toISOString(); - return { token, expiresAt, userId: user.id } satisfies KiloChatTokenResponse; + const expiresAt = new Date(Date.now() + legacyExpiresIn * 1000).toISOString(); + return { token, expiresAt, userId: authority.user.id } satisfies KiloChatTokenResponse; } diff --git a/apps/web/src/lib/wasteland/server-resolve.ts b/apps/web/src/lib/wasteland/server-resolve.ts index 5a277f1a10..95568da1be 100644 --- a/apps/web/src/lib/wasteland/server-resolve.ts +++ b/apps/web/src/lib/wasteland/server-resolve.ts @@ -3,8 +3,7 @@ import type { User } from '@kilocode/db/schema'; import { createTRPCClient, httpLink } from '@trpc/client'; import type { WrappedWastelandRouter } from '@/lib/wasteland/types/router'; import { WASTELAND_URL } from '@/lib/constants'; -import { generateApiToken } from '@/lib/tokens'; -import { getUserOrgMemberships } from '@/lib/organizations/organizations'; +import { createControlTokenForRequest } from '@/lib/auth/resource-delegation'; import { recordKiloAdminElevationForRequest, serviceTarget } from '@/lib/admin/admin-access-log'; import { parseDolthubUpstream } from '@/lib/wasteland/upstream'; @@ -28,21 +27,22 @@ export async function resolveWastelandUpstreamForUser( if (!WASTELAND_URL) return null; try { - if (user.is_admin) { + const control = await createControlTokenForRequest(user, 'wasteland', { + expiresIn: 60 * 5, + legacyExpiresIn: 60 * 5, + extra: { isAdmin: user.is_admin }, + }); + const signedUser = control.user; + if (signedUser.is_admin) { // Same elevation as POST /api/wasteland/token: the minted token carries // `isAdmin` into the worker, which emits nothing back here. await recordKiloAdminElevationForRequest({ - user, + user: signedUser, reason: 'service_token_mint', target: serviceTarget('wasteland'), }); } - const orgMemberships = await getUserOrgMemberships(user.id); - const token = generateApiToken( - user, - { isAdmin: user.is_admin, orgMemberships }, - { expiresIn: 60 * 5 } - ); + const token = control.token; const client = createTRPCClient({ links: [ diff --git a/apps/web/src/routers/kilo-chat-router.ts b/apps/web/src/routers/kilo-chat-router.ts index 752bd6d7f5..f66be0023f 100644 --- a/apps/web/src/routers/kilo-chat-router.ts +++ b/apps/web/src/routers/kilo-chat-router.ts @@ -3,5 +3,7 @@ import { createKiloChatTokenResponse } from '@/lib/kilo-chat/token'; import { baseProcedure, createTRPCRouter } from '@/lib/trpc/init'; export const kiloChatRouter = createTRPCRouter({ - getToken: baseProcedure.query(({ ctx }) => createKiloChatTokenResponse(ctx.user)), + getToken: baseProcedure.query(({ ctx }) => + createKiloChatTokenResponse(ctx.user, ctx.headersList) + ), }); diff --git a/docs/token-issuance-policy.md b/docs/token-issuance-policy.md index 50aac3eab4..a4dfadb360 100644 --- a/docs/token-issuance-policy.md +++ b/docs/token-issuance-policy.md @@ -182,3 +182,104 @@ The disconnect reader accepts its dedicated operation audience or legacy audienc Gastown/Wasteland control issuers are deferred with their delegation adapters: current paths discard bearer expiry/signed restrictions into a bare user record, and Gastown can derive and renew broader 30-day runtime credentials. A source/audience stamp alone would not close that path. Modern-builder organization roles also require a deliberate compatibility decision for web `admin` memberships; do not cast or promote them to owner. The generic organization-token issuer is not proven attribution-only and is likewise deferred. User/native credentials, Chat fan-out, Cloud Agent/App Builder/automation runtime forwarding, Gastown renewal, and other shared credentials remain PR 5.2 work. The separate Worker-local `services/security-auto-analysis/src/token.ts` snapshot assertion is not one of these 16 web callsites; migrate it with that Worker's other token paths and rollout configuration in PR 5.2. KiloClaw stays minimal for its October EOL. These reallocations keep Phase 5 at exactly two PRs, rather than claiming unsafe control-plane migrations are bounded. This PR does not retire legacy native exchange, shorten user credentials, change global pepper/session semantics, or remove ordinary legacy resource access. + +## Phase 5.2 merge, automatic deployment, and activation + +### Deployment model and implementation status + +Merging this PR automatically deploys the services within a few minutes of one another. There is no operator-managed sequence of separate service deployments. The old/new version overlap must remain compatible with all new producer and isolation-adoption flags off. After the entire automatic deployment wave is healthy, activate the flags in dependency order. This remains one Phase 5.2 PR. + +Merge readiness, feature activation, and completeness of real-environment smoke coverage are separate decisions. A missing production recovery path was a code defect; unavailable Vercel/device coverage is a separately recorded validation risk. + +1. Cloud Agent's 24-hour recovery is implemented for both session planes through the public send preflight, including legacy V2 and SDK prompt adapters. A fresh authenticated credential authorizes recovery of the same session. Recovery refuses queued/active work and live PTYs, retires the old transport before replacing authority, clears stale grants/attachment state, and lets normal dispatch attach a fresh handle. Workspace retirement is acknowledged and root-scoped; agent-plane retirement requires authoritative physical absence. Durable recovery IDs survive retries, and explicit revocation never becomes natural-expiry recovery. Real Durable Object integration tests cover successful recovery, lost acknowledgement, subsequent attach/prompt, queued-work rejection, and active-PTY rejection. +2. The real sandbox smoke matrix is not green. Local legacy execution reached Worker, DO, Docker, wrapper, Kilo 7.4.20, and the fake LLM, but the `cold-hot` scenario failed its no-preparation assertion on the first hot turn. Four LLM requests and two terminal turns were observed; they do not prove all planned hot turns completed. The legacy implementation already emits warm preparation bookkeeping. A harness correction must add positive workspace/setup reuse evidence rather than simply drop the assertion. Control-plane smoke has not demonstrated a completed Kilo/fake-provider round trip. + +### Merge and automatic deployment, producers disabled + +The automatic deployment wave includes these units. Retain all legacy readers and wire defaults throughout mixed-version overlap: + +| Deployment unit | Required compatibility | Adoption settings | +|---|---|---| +| Web API/gateway receiving deployments, including `app.kilo.ai` and `api.kilo.ai` | Legacy and modern audience readers; runtime-proof verification; native negotiation and bounded rollback bridge | Shared and native issuance off | +| Session Ingest Worker | Legacy and modern audience readers; runtime-proof verification; unchanged dedicated ticket/deletion contracts | No new runtime issuers | +| Cloud Agent Worker and its wrapper/container images | Optional isolation attachment selection and explicit wrapper hello capability; omitted selection remains directory-shared | `RUNTIME_ISOLATION_ENABLED=false` | +| Gastown and Wasteland receiving Workers | Existing supported tokens and current owner/membership checks; fail-closed modern runtime state | No new modern control issuance | +| Security Auto Analysis and Webhook Agent Ingest Workers | Legacy defaults, scoped modern issuance available but inactive, compatible callback/result readers | Their own shared-issuance settings off | +| Native application | Negotiation, bundle storage, API/gateway routing, legacy responses | Server-side native adoption off | + +Cloud Agent Worker and wrapper support is additive: an old wrapper omits the hello capability and can still receive legacy attachments; a new Worker refuses to forward an isolated attachment to a wrapper that has not advertised support. Existing modern authorization is a durable adoption marker, so its attachment stays isolated even when the admission flag is later disabled. Do not remove that support during rollback. + +Compatibility checks and validation limits: + +- Legacy unit/wrapper behavior and the additive protocol are tested. The real legacy smoke limitation above remains recorded; do not weaken assertions to conceal workspace rebuilding or missing turns, or describe partial execution as a passing full matrix. +- Old-client requests remain accepted, including native requests without `credentialFormat` and benchmark legacy six-hour tokens. +- New Worker with old-wrapper hello is tested in legacy mode; isolated dispatch is rejected before forwarding. New wrapper with old/missing attachment selection retains legacy directory sharing. +- Existing Gastown organization routes are checked with current legacy credentials and a database-unavailable case. Fresh authorization reads are an intentional availability dependency even with issuance flags off. + +Existing Gastown towns without private identity metadata adopt that metadata lazily through unattended token renewal. The stored token must be a signed, unrestricted legacy town credential; its user and the mutable configuration only locate a canonical personal/organization town-registry record. The registry must bind the exact town to that owner or organization creator, and current account, pepper, organization, and membership checks must pass before renewal. A correctly signed expired legacy token can locate this existing authority; expiration never establishes authority itself. The private identity and replacement token are installed together only if the original configuration and private state are unchanged. Missing ownership, corrupt or modern private state, revocation, and restricted tokens cannot fall back through this migration. Transient registry/database failures retry on the next alarm, without requiring a manual UI refresh. + +### Implemented runtime transport recovery + +Foreground recovery follows these invariants: + +1. Explicit authenticated demand supplies a fresh control credential. Revalidate current user, pepper, organization membership, and exact session ownership; never derive replacement authority from an expired runtime JWT. +2. Distinguish natural expiry from explicit revocation. Expiry remains unusable but does not itself persist an explicit revocation. A revoked record must not be silently resurrected. +3. Verify the target root is idle, with no active/finalizing work or live terminal. Preserve sibling roots. +4. Use an acknowledged, incarnation-fenced root transport retirement/replacement operation. A local registry update or auth-record CAS without a wrapper acknowledgment is insufficient. +5. Install the fresh sealed authority only with the expected old authorization and transport fences. Clear the stale attachment/grant only at the corresponding committed lifecycle transition. +6. Attach the replacement transport with its new session-scoped handle, then admit the original user turn exactly once. Fail closed on ambiguous retirement; do not replay completed work. + +Routine backing-JWT renewal remains transparent to active streaming: no `auth.set`, process restart, or prompt replay. Idle transport replacement after an absolute delegation deadline is a separate, explicitly authorized operation. Durable Object integration tests exercise `agent_*` and `workspace_*` recovery, and unified, legacy V2, and SDK prompt adapters share the foreground preflight. This is not a claim that a complete real-provider smoke matrix has passed. + +Additional real-environment validation matrix (not fully executed): + +| Scenario | Required evidence | +|---|---| +| Legacy/direct cold, hot, and restore | Real packaged CLI, expected output and exact terminal message IDs, workspace/setup reuse on hot turns | +| Modern direct and Cloudflare containment | Real facade request accepted by API, gateway, and Session Ingest with the correct proof and session scope | +| Vercel containment | Real provider policy behavior, no backing JWT in policy, old/new wrapper compatibility; local mocks are not equivalent | +| Streaming across ordinary renewal | Same live process and stream, renewed backing token, no prompt replay | +| Absolute expiry and user-authorized recovery | Same session ID, acknowledged replacement transport, new handle succeeds, old handle denied | +| Explicit revocation | In-flight final reread denies revoked authority; no background reactivation | +| Two same-worktree roots | Correct process mode, isolated credentials when selected, sibling-safe detach, documented behavior when one process fails | +| Rollback with an issued native bundle | Active owned device receives a bounded control token; revoked/pepper-mismatched device is denied; no five-year fallback | + +No production-only testing bypass or arbitrary token/state mutation endpoint should be added to make these tests pass. Use bounded fixture clocks for unit/Workers races and an authorized test setup for actual runtime acceptance. A local fake LLM replaces inference only, not the Worker, DO, sandbox, wrapper, or CLI. Real Vercel policy and physical-device validation require their respective environments. + +### Activate flags after the automatic deployment wave + +Web adoption requires `SHARED_RESOURCE_TOKENS_ENABLED=true` **and** the applicable producer flag below. Every flag defaults off and recognizes only the exact value `true`. The shared switch alone does not activate a producer. These are server-side deployment settings, not client-controlled request options. + +| Producer | Additional web flag | Initial shipping decision | +|---|---|---| +| Cloud Agent user controls and workflow admission | `CLOUD_AGENT_RESOURCE_TOKENS_ENABLED` | Activate only after isolation and the actual Worker/wrapper consumer chain are verified | +| Chat, events, and notification fanout | `CHAT_RESOURCE_TOKENS_ENABLED` | Independent rollout after all three readers are deployed | +| Gastown control | `GASTOWN_RESOURCE_TOKENS_ENABLED` | Keep off; modern runtime delivery remains deferred | +| Wasteland control | `WASTELAND_RESOURCE_TOKENS_ENABLED` | Keep off until its consumer chain is verified independently | +| Explicit API, gateway, attribution, and HTML delegation | `DELEGATED_RESOURCE_TOKENS_ENABLED` | Independent opt-in rollout | +| Workflow gateway credentials | `WORKFLOW_GATEWAY_RESOURCE_TOKENS_ENABLED` | Independent opt-in rollout | +| Auto-routing benchmark credentials | `BENCHMARK_RESOURCE_TOKENS_ENABLED` | Independent opt-in rollout | +| Negotiated native API/gateway bundles | `NATIVE_RESOURCE_TOKENS_ENABLED` | Keep off; mobile and CLI clients continue receiving legacy credentials | + +Unsupported CLI/native clients retain legacy issuance regardless of these adoption settings. Security Auto Analysis and Webhook Agent Ingest keep their existing Worker-local shared switches; a web setting does not activate those separately deployed producers. Bounded internal assertions retain their separate Phase 5.1 switch. + +**Gastown modern activation is blocked by known implementation gaps**, not merely missing smoke evidence. Its runtime JWT does not include Session Ingest even though the CLI uses it there, and updating the town/container configuration does not establish safe credential renewal in an already-running CLI/provider client. Keep Gastown's producer off until both the complete consumer audience contract and uninterrupted active-runtime renewal are implemented and tested. Do not add an audience without verifying the full delivery path, restart active work to rotate credentials, or disable reader checks. This PR retains the modern implementation and existing modern-state validation, but does not certify that path for activation. + +Once all receiving deployments are healthy, activate progressively while recording any accepted real-environment coverage risks: + +1. Confirm the exact deployed revisions for every receiver a producer calls, including both web receiving aliases, Session Ingest, Cloud Agent Worker, and the actual wrapper image. Verify the wrapper hello capability rather than inferring it from an image tag. +2. Enable runtime isolation admission on the selected Cloud Agent deployment/cohort. This environment boolean is deployment-scoped, not itself a per-user allowlist; use an existing cohort/staging deployment for limited exposure. +3. Enable the shared web prerequisite and one eligible producer-family flag at a time. Web and Worker-local settings are separate; record each activation independently. Leave Gastown and native adoption off for this shipping stage. Do not assume enabling web updates Security Auto Analysis or Webhook Agent Ingest. +4. Exercise the producer's real consumer chain and observe auth failures, renewal latency, sandbox restarts, child-process count, memory, and queue retries before expanding. +5. Enable native adoption last, after device and downgrade validation. Fresh bundles require both native and shared web readiness settings. + +### Rollback is producer shutdown, not receiver removal + +- Stop native adoption first. Turning the native flag off changes subsequent issuance/refresh responses, not credentials already held on a device. +- Stop new modern adoption at each web/Worker producer independently. Already-issued modern device bearers may still obtain bounded control and three-audience chat tokens while their current owned device session, pepper, and requested organization membership remain valid. This compatibility bridge intentionally operates with the master and family switches off, caps tokens at the parent's remaining lifetime and one hour, and never mints an unrestricted legacy replacement. Other modern credential kinds do not receive this device exception. +- Keep Cloud Agent isolation admission available while outstanding modern control/device credentials still need to create sessions. Turning it off immediately intentionally refuses new modern workspace creation; it is not a seamless rollback for those callers. +- After outstanding admission credentials drain, disable new isolation adoption. Existing modern sessions retain their isolated attachment selection and supported transport. +- Keep compatible readers, proof verification, wrapper capabilities, and renewal/recovery support deployed until the corresponding credential and workload populations have drained or been safely migrated. Existing Cloud Agent and Gastown delegation bounds differ; do not use one global wait interval. +- Never rotate global keys, reset all peppers, remove audience checks, or fall back to unrestricted legacy credentials to recover availability. + +Keep all new adoption flags off during the automatic deployment wave. Merge does not activate modern issuance. Record incomplete physical-device, real-provider, and full sandbox smoke coverage as validation risks rather than presenting them as missing recovery implementation or claiming unperformed tests passed. diff --git a/packages/app-shared/package.json b/packages/app-shared/package.json index 62f58c7aec..e2c0ffeabf 100644 --- a/packages/app-shared/package.json +++ b/packages/app-shared/package.json @@ -20,7 +20,8 @@ "./pr-review": "./src/pr-review/index.ts", "./commerce": "./src/commerce/index.ts", "./moderation": "./src/moderation/index.ts", - "./glanceable-agents-snapshot": "./src/glanceable-agents-snapshot.ts" + "./glanceable-agents-snapshot": "./src/glanceable-agents-snapshot.ts", + "./native-auth": "./src/native-auth.ts" }, "scripts": { "typecheck": "tsgo --noEmit", diff --git a/packages/app-shared/src/native-auth.test.ts b/packages/app-shared/src/native-auth.test.ts new file mode 100644 index 0000000000..8e18e3365b --- /dev/null +++ b/packages/app-shared/src/native-auth.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, test } from 'vitest'; +import { API_GATEWAY_CREDENTIAL_FORMAT, parseNativeTokenPair } from './native-auth'; + +describe('parseNativeTokenPair', () => { + test('accepts a complete tagged credential bundle without dropping metadata', () => { + expect( + parseNativeTokenPair({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }, + }) + ).toEqual({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + gatewayToken: 'gateway-token', + expiresAt: '2026-09-02T22:00:00.000Z', + }, + }); + }); + + test.each([ + { token: 'api-token', credentialFormat: 'future-format' }, + { token: 'api-token', metadata: { credentialFormat: 'future-format' } }, + { + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, gatewayToken: 'gateway-token' }, + }, + { + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata: { + credentialFormat: API_GATEWAY_CREDENTIAL_FORMAT, + gatewayToken: 'gateway-token', + expiresAt: 'not-an-iso-date', + }, + }, + ])('rejects tagged unknown or incomplete payloads', value => { + expect(parseNativeTokenPair(value)).toBeNull(); + }); + + test('keeps untagged legacy partial refresh responses token-only', () => { + expect(parseNativeTokenPair({ token: 'legacy-token', refreshToken: 'partial' })).toEqual({ + token: 'legacy-token', + created: undefined, + }); + }); + + test('preserves legacy response envelopes while stripping unrelated fields', () => { + expect( + parseNativeTokenPair({ + token: 'legacy-token', + userId: 'user-1', + userEmail: 'user@example.test', + status: 'approved', + }) + ).toEqual({ token: 'legacy-token', created: undefined }); + }); + + test.each([undefined, null, {}, false, { gatewayToken: 'gateway-only' }])( + 'never treats malformed metadata as a legacy credential', + metadata => { + expect( + parseNativeTokenPair({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + metadata, + }) + ).toBeNull(); + } + ); + + test('rejects misplaced bundle fields instead of dropping them', () => { + expect( + parseNativeTokenPair({ + token: 'api-token', + refreshToken: 'refresh-token', + expiresIn: 3600, + gatewayToken: 'gateway-token', + }) + ).toBeNull(); + }); +}); diff --git a/packages/app-shared/src/native-auth.ts b/packages/app-shared/src/native-auth.ts new file mode 100644 index 0000000000..c6e304a41d --- /dev/null +++ b/packages/app-shared/src/native-auth.ts @@ -0,0 +1,73 @@ +import { z } from 'zod'; + +export const API_GATEWAY_CREDENTIAL_FORMAT = 'api-gateway-v1'; + +export const nativeCredentialFormatSchema = z.literal(API_GATEWAY_CREDENTIAL_FORMAT); + +export type NativeCredentialFormat = z.infer; + +const tokenSchema = z.string().min(1); +const expiresInSchema = z.number().positive(); + +export const nativeCredentialBundleMetadataSchema = z + .object({ + credentialFormat: nativeCredentialFormatSchema, + gatewayToken: tokenSchema, + expiresAt: z.string().datetime({ offset: true }), + }) + .strict(); + +export type NativeCredentialBundleMetadata = z.infer; + +export type NativeAccessCredentials = + | { token: string; metadata: NativeCredentialBundleMetadata } + | { token: string; metadata?: undefined }; + +export type NativeSessionCredentials = NativeAccessCredentials & { + refreshToken: string; + expiresIn: number; +}; + +export type NativeTokenPair = + | (NativeSessionCredentials & { created?: boolean }) + | { + token: string; + refreshToken?: undefined; + expiresIn?: undefined; + metadata?: undefined; + created?: boolean; + }; + +const completePairSchema = z.object({ + token: tokenSchema, + refreshToken: tokenSchema, + expiresIn: expiresInSchema, + metadata: nativeCredentialBundleMetadataSchema, + created: z.boolean().optional(), +}); + +const legacyPairSchema = z.object({ + token: tokenSchema, + refreshToken: tokenSchema.optional(), + expiresIn: expiresInSchema.optional(), + created: z.boolean().optional(), +}); + +export function parseNativeTokenPair(value: unknown): NativeTokenPair | null { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return null; + + const record = value as Record; + if (Object.hasOwn(record, 'credentialFormat') || Object.hasOwn(record, 'gatewayToken')) + return null; + if (Object.hasOwn(record, 'metadata')) { + const parsed = completePairSchema.safeParse(value); + return parsed.success ? parsed.data : null; + } + + const parsed = legacyPairSchema.safeParse(value); + if (!parsed.success) return null; + + const { token, refreshToken, expiresIn, created } = parsed.data; + if (refreshToken && expiresIn) return { token, refreshToken, expiresIn, created }; + return { token, created }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f7ad664eab..56359fb1f6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3345,6 +3345,9 @@ importers: '@cloudflare/vitest-pool-workers': specifier: 'catalog:' version: 0.16.13(@cloudflare/workers-types@4.20260605.1)(@types/node@24.12.4)(@vitest/runner@4.1.6)(@vitest/snapshot@4.1.6)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(vitest@4.1.6) + '@cloudflare/workers-types': + specifier: 'catalog:' + version: 4.20260605.1 '@types/node': specifier: 'catalog:' version: 24.12.4 diff --git a/services/gastown/src/dos/Town.do.ts b/services/gastown/src/dos/Town.do.ts index 3e4dadbf00..aa79fa6327 100644 --- a/services/gastown/src/dos/Town.do.ts +++ b/services/gastown/src/dos/Town.do.ts @@ -39,6 +39,8 @@ import { import * as scm from './town/town-scm'; import * as reconciler from './town/reconciler'; import * as wasteland from './town/wasteland'; +import * as unattendedTokenRenewal from './town/unattended-token-renewal'; +import * as runtimeAuthorization from './town/runtime-authorization'; import { pickCanonicalBead, type ReporterBead } from './town/wasteland-reporter'; import { applyAction } from './town/actions'; import type { Action, ApplyActionContext } from './town/actions'; @@ -67,10 +69,6 @@ import { query } from '../util/query.util'; import { getAgentDOStub } from './Agent.do'; import { getTownContainerDoId, getTownContainerStub } from './TownContainer.do'; -import { kiloTokenPayload } from '@kilocode/worker-utils'; -import { jwtVerify } from 'jose'; -import { generateKiloApiToken } from '../util/kilo-token.util'; -import { resolveSecret } from '../util/secret.util'; import { writeEvent, type GastownEventData } from '../util/analytics.util'; import { logger, withLogTags } from '../util/log.util'; import { @@ -110,6 +108,7 @@ import type { } from '../types'; const TOWN_LOG = '[Town.do]'; +type TownIdentity = runtimeAuthorization.TownIdentity; /** Format a bead_events row into a human-readable message for the status feed. */ function formatEventMessage(row: Record): string { @@ -273,6 +272,18 @@ export class TownDO extends DurableObject { }); } + private get runtimeAuthorizationCtx(): Parameters< + typeof runtimeAuthorization.createRuntimeAuthorization + >[0] { + return { + storage: this.ctx.storage, + env: this.env, + townId: this.townId, + hasActiveWork: () => this.hasActiveWork(), + updateTownConfig: update => this.updateTownConfig(update), + }; + } + /** Build the context object used by the scheduling sub-module. */ private get schedulingCtx(): Parameters[0] { return { @@ -956,6 +967,59 @@ export class TownDO extends DurableObject { return result; } + async initializePrivateTownIdentity(identity: TownIdentity): Promise { + await runtimeAuthorization.initializePrivateTownIdentity(this.ctx.storage, identity); + } + + async initializeTownIdentityAndRuntimeAuthorization( + identity: TownIdentity, + controlToken: string + ): Promise<{ runtimeToken?: string; modernControl: boolean }> { + return runtimeAuthorization.initializeTownIdentityAndRuntimeAuthorization( + this.runtimeAuthorizationCtx, + identity, + controlToken + ); + } + + async getPrivateTownIdentity(): Promise { + return runtimeAuthorization.getPrivateTownIdentity(this.ctx.storage, this.townId); + } + + async getTownIdentityState(): Promise { + return runtimeAuthorization.getTownIdentityState(this.ctx.storage, this.townId); + } + + async createRuntimeAuthorization( + controlToken: string, + userId: string, + organizationId?: string + ): Promise { + return runtimeAuthorization.createRuntimeAuthorization( + this.runtimeAuthorizationCtx, + controlToken, + userId, + organizationId + ); + } + + async reauthorizeRuntime( + controlToken: string, + userId: string, + organizationId?: string + ): Promise { + return runtimeAuthorization.reauthorizeRuntime( + this.runtimeAuthorizationCtx, + controlToken, + userId, + organizationId + ); + } + + private async renewRuntimeAuthorization(): Promise { + return runtimeAuthorization.renewRuntimeAuthorization(this.runtimeAuthorizationCtx); + } + async getBillingStatus(): Promise { try { if (isContainerUsageMeteringEnabled(this.env)) await this.prepareContainerBilling(); @@ -1120,6 +1184,25 @@ export class TownDO extends DurableObject { await this.ctx.storage.put('container:lastTokenRefreshAt', Date.now()); } + async refreshRuntimeAuthorizationForManualRefresh(): Promise< + 'legacy' | 'renewed' | 'revoked' | 'unavailable' + > { + if (!(await runtimeAuthorization.requiresRuntimeAuthorization(this.ctx.storage, this.townId))) + return 'legacy'; + const token = await this.renewRuntimeAuthorization(); + if (token) { + await this.syncConfigToContainer(); + return 'renewed'; + } + return (await runtimeAuthorization.getRuntimeAuthorizationState(this.ctx.storage)) === 'revoked' + ? 'revoked' + : 'unavailable'; + } + + async requiresRuntimeAuthorization(): Promise { + return runtimeAuthorization.requiresRuntimeAuthorization(this.ctx.storage, this.townId); + } + /** * Push config-derived env vars to the running container. Called after * updateTownConfig so that settings changes take effect without a @@ -1319,9 +1402,24 @@ export class TownDO extends DurableObject { private async _configureRig(rigConfig: RigConfig): Promise { logger.setTags({ rigId: rigConfig.rigId, userId: rigConfig.userId }); logger.info('configureRig: start', { hasKilocodeToken: !!rigConfig.kilocodeToken }); - await this.ctx.storage.put(`rig:${rigConfig.rigId}:config`, rigConfig); - - if (rigConfig.kilocodeToken) { + const requiresRuntimeAuthorization = await runtimeAuthorization.requiresRuntimeAuthorization( + this.ctx.storage, + this.townId + ); + // A town which has ever adopted runtime authorization must not be + // downgraded by a caller carrying an old KILOCODE_TOKEN. + const storedRigConfig = requiresRuntimeAuthorization + ? { ...rigConfig, kilocodeToken: undefined } + : rigConfig; + const token = requiresRuntimeAuthorization + ? await this.renewRuntimeAuthorization() + : (rigConfig.kilocodeToken ?? (await this.resolveKilocodeToken())); + if (requiresRuntimeAuthorization && !token) { + throw new Error('Town runtime authorization is unavailable'); + } + await this.ctx.storage.put(`rig:${rigConfig.rigId}:config`, storedRigConfig); + + if (!requiresRuntimeAuthorization && rigConfig.kilocodeToken) { const townConfig = await this.getTownConfig(); if (!townConfig.kilocode_token || townConfig.kilocode_token !== rigConfig.kilocodeToken) { logger.info('configureRig: propagating kilocodeToken to town config'); @@ -1331,7 +1429,6 @@ export class TownDO extends DurableObject { } } - const token = rigConfig.kilocodeToken ?? (await this.resolveKilocodeToken()); if (token) { try { const container = getTownContainerStub(this.env, this.townId); @@ -1356,7 +1453,7 @@ export class TownDO extends DurableObject { // Proactively clone the rig's repo and create a browse worktree so // the mayor has immediate access to the codebase without waiting for // the first agent dispatch. - this.setupRigRepoInContainer(rigConfig).catch(err => + this.setupRigRepoInContainer({ ...storedRigConfig, kilocodeToken: token }).catch(err => logger.warn('configureRig: background repo setup failed', { error: err instanceof Error ? err.message : String(err), }) @@ -3416,6 +3513,14 @@ export class TownDO extends DurableObject { } private async resolveKilocodeToken(): Promise { + const runtimeToken = await this.renewRuntimeAuthorization(); + if (runtimeToken) return runtimeToken; + if ( + (await runtimeAuthorization.getTownIdentityState(this.ctx.storage, this.townId)).type !== + 'legacy' + ) { + return undefined; + } const townConfig = await this.getTownConfig(); if (townConfig.kilocode_token) return townConfig.kilocode_token; @@ -4843,70 +4948,26 @@ export class TownDO extends DurableObject { private lastKilocodeTokenCheckAt = 0; private async refreshKilocodeTokenIfExpiring(): Promise { const CHECK_INTERVAL_MS = 24 * 60 * 60_000; // once per day - const REFRESH_WINDOW_SECONDS = 7 * 24 * 60 * 60; // 7 days const now = Date.now(); if (now - this.lastKilocodeTokenCheckAt < CHECK_INTERVAL_MS) return; this.lastKilocodeTokenCheckAt = now; - - const townConfig = await this.getTownConfig(); - const token = townConfig.kilocode_token; - if (!token) return; - - if (!this.env.NEXTAUTH_SECRET) { - logger.warn('refreshKilocodeTokenIfExpiring: NEXTAUTH_SECRET not configured'); - return; - } - const secret = await resolveSecret(this.env.NEXTAUTH_SECRET); - if (!secret) { - logger.warn('refreshKilocodeTokenIfExpiring: failed to resolve NEXTAUTH_SECRET'); - return; - } - - // Verify the existing token's signature before trusting its claims. - // This prevents a forged token from being re-signed with real credentials. - // Use a very large clockTolerance so that already-expired (but validly - // signed) tokens are still accepted — this alarm is the recovery path - // for expired tokens, so rejecting them on exp would leave the town - // permanently stuck if it missed the 7-day refresh window. - let payload: { kiloUserId: string; apiTokenPepper?: string | null; exp?: number }; try { - const TEN_YEARS_SECONDS = 10 * 365 * 24 * 60 * 60; - const { payload: raw } = await jwtVerify(token, new TextEncoder().encode(secret), { - algorithms: ['HS256'], - clockTolerance: TEN_YEARS_SECONDS, - }); - const parsed = kiloTokenPayload.safeParse(raw); - if (!parsed.success) { - logger.warn('refreshKilocodeTokenIfExpiring: token payload failed schema validation'); - return; + if ( + await unattendedTokenRenewal.renewUnattendedLegacyTownToken( + this.ctx.storage, + this.env, + this.townId + ) + ) { + this._ownerUserId = (await this.getTownConfig()).owner_user_id; + await this.syncConfigToContainer(); + logger.info('refreshKilocodeTokenIfExpiring: reminted KILOCODE_TOKEN proactively'); } - payload = parsed.data; } catch { - // Signature invalid or token malformed — don't remint from untrusted claims. - logger.warn('refreshKilocodeTokenIfExpiring: existing token failed signature verification'); - return; + // Retry on the next alarm after a transient registry/database failure. + this.lastKilocodeTokenCheckAt = 0; + logger.warn('refreshKilocodeTokenIfExpiring: renewal unavailable'); } - - const exp = payload.exp; - if (!exp) return; - - const nowSeconds = Math.floor(now / 1000); - if (exp - nowSeconds > REFRESH_WINDOW_SECONDS) return; - - // Token expires within 7 days — remint it - const userId = payload.kiloUserId; - if (!userId) return; - - const newToken = await generateKiloApiToken( - { id: userId, api_token_pepper: payload.apiTokenPepper ?? null }, - secret - ); - await this.updateTownConfig({ kilocode_token: newToken }); - await this.syncConfigToContainer(); - logger.info('refreshKilocodeTokenIfExpiring: reminted KILOCODE_TOKEN proactively', { - userId, - oldExp: new Date(exp * 1000).toISOString(), - }); } private hasActiveWork(): boolean { diff --git a/services/gastown/src/dos/town/config.ts b/services/gastown/src/dos/town/config.ts index 85b3ca4715..87322922ee 100644 --- a/services/gastown/src/dos/town/config.ts +++ b/services/gastown/src/dos/town/config.ts @@ -41,7 +41,9 @@ const NEW_TOWN_CONFIG_DEFAULTS = { }, }; -export async function getTownConfig(storage: DurableObjectStorage): Promise { +export async function getTownConfig( + storage: Pick +): Promise { const raw = await storage.get(CONFIG_KEY); if (!raw) { // Fresh town: seed the new-style defaults from #2725 and persist so they @@ -57,7 +59,7 @@ export async function getTownConfig(storage: DurableObjectStorage): Promise, update: TownConfigUpdate ): Promise { const current = await getTownConfig(storage); diff --git a/services/gastown/src/dos/town/legacy-token-renewal.test.ts b/services/gastown/src/dos/town/legacy-token-renewal.test.ts new file mode 100644 index 0000000000..0b5f40bed5 --- /dev/null +++ b/services/gastown/src/dos/town/legacy-token-renewal.test.ts @@ -0,0 +1,132 @@ +import { jwtVerify } from 'jose'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { signKiloToken } from '@kilocode/worker-utils'; + +const select = vi.fn(); + +vi.mock('@kilocode/db/client', () => ({ getWorkerDb: vi.fn(() => ({ select })) })); + +import { + isLegacyTownTokenRenewalAuthorized, + resolveLegacyTownTokenOwner, +} from './legacy-token-renewal'; + +const env = { HYPERDRIVE: { connectionString: 'postgres://' } } as Env; +const personalIdentity = { ownerType: 'user' as const, ownerUserId: 'user-1' }; +const orgIdentity = { + ownerType: 'org' as const, + ownerUserId: 'user-1', + organizationId: 'org-1', +}; + +function rows(...values: unknown[]) { + let index = 0; + select.mockImplementation(() => ({ + from: () => ({ + where: () => ({ limit: () => Promise.resolve(values[index++]) }), + innerJoin: () => ({ where: () => ({ limit: () => Promise.resolve(values[index++]) }) }), + }), + })); +} + +describe('isLegacyTownTokenRenewalAuthorized', () => { + beforeEach(() => vi.resetAllMocks()); + + it('allows a current personal owner with the current pepper', async () => { + rows([{ pepper: 'current', blockedAt: null, blockedReason: null }]); + + await expect( + isLegacyTownTokenRenewalAuthorized(env, personalIdentity, 'user-1', 'current') + ).resolves.toBe(true); + }); + + it.each([ + ['rotated pepper', [{ pepper: 'new', blockedAt: null, blockedReason: null }]], + ['null pepper', [{ pepper: null, blockedAt: null, blockedReason: null }]], + ['blocked_at', [{ pepper: 'current', blockedAt: '2026-01-01', blockedReason: null }]], + ['blocked_reason', [{ pepper: 'current', blockedAt: null, blockedReason: 'abuse' }]], + ['missing user', []], + ])('rejects a %s user', async (_name, user) => { + rows(user); + + await expect( + isLegacyTownTokenRenewalAuthorized(env, personalIdentity, 'user-1', 'current') + ).resolves.toBe(false); + }); + + it('rejects a null token pepper even when the current user is unpeppered', async () => { + rows([{ pepper: null, blockedAt: null, blockedReason: null }]); + + await expect( + isLegacyTownTokenRenewalAuthorized(env, personalIdentity, 'user-1', null) + ).resolves.toBe(false); + }); + + it('rejects an org token after membership is removed and re-added for another identity', async () => { + rows([{ pepper: 'current', blockedAt: null, blockedReason: null }], [{ role: 'owner' }]); + + await expect( + isLegacyTownTokenRenewalAuthorized(env, orgIdentity, 're-added-user', 'current') + ).resolves.toBe(false); + expect(select).not.toHaveBeenCalled(); + }); + + it.each([ + ['removed membership', []], + ['billing manager membership', [{ role: 'billing_manager' }]], + ])('rejects an org token with a %s', async (_name, membership) => { + rows([{ pepper: 'current', blockedAt: null, blockedReason: null }], membership); + + await expect( + isLegacyTownTokenRenewalAuthorized(env, orgIdentity, 'user-1', 'current') + ).resolves.toBe(false); + }); + + it('allows a current eligible org member', async () => { + rows([{ pepper: 'current', blockedAt: null, blockedReason: null }], [{ role: 'owner' }]); + + await expect( + isLegacyTownTokenRenewalAuthorized(env, orgIdentity, 'user-1', 'current') + ).resolves.toBe(true); + }); + + it('returns the current owner pepper for an eligible org member', async () => { + rows( + [{ pepper: 'member-current', blockedAt: null, blockedReason: null }], + [{ role: 'member' }], + [{ pepper: 'owner-current', blockedAt: null, blockedReason: null }], + [{ role: 'owner' }] + ); + + await expect( + resolveLegacyTownTokenOwner(env, orgIdentity, { + id: 'member-1', + apiTokenPepper: 'member-current', + }) + ).resolves.toEqual({ id: 'user-1', api_token_pepper: 'owner-current' }); + }); + + it('allows an expired but validly signed token when its current owner is authorized', async () => { + const secret = 'test-secret'; + const { token } = await signKiloToken({ + userId: 'user-1', + pepper: 'current', + secret, + expiresInSeconds: -1, + }); + const { payload } = await jwtVerify(token, new TextEncoder().encode(secret), { + algorithms: ['HS256'], + clockTolerance: 10 * 365 * 24 * 60 * 60, + }); + rows([{ pepper: 'current', blockedAt: null, blockedReason: null }]); + + await expect( + isLegacyTownTokenRenewalAuthorized( + env, + personalIdentity, + payload.kiloUserId as string, + payload.apiTokenPepper as string + ) + ).resolves.toBe(true); + }); +}); diff --git a/services/gastown/src/dos/town/legacy-token-renewal.ts b/services/gastown/src/dos/town/legacy-token-renewal.ts new file mode 100644 index 0000000000..5b40c3e400 --- /dev/null +++ b/services/gastown/src/dos/town/legacy-token-renewal.ts @@ -0,0 +1,128 @@ +import { getWorkerDb } from '@kilocode/db/client'; +import { kilocode_users, organization_memberships, organizations } from '@kilocode/db/schema'; +import { and, eq, isNull } from 'drizzle-orm'; + +type PrivateTownIdentity = { + ownerType: 'user' | 'org'; + ownerUserId: string; + organizationId?: string; +}; + +type LegacyTokenActor = { + id: string; + apiTokenPepper: string | null; +}; + +export type LegacyTokenOwner = { + id: string; + api_token_pepper: string; +}; + +export class LegacyTownTokenRenewalUnavailableError extends Error {} + +function isCurrentAccount( + user: + | { + pepper: string | null; + blockedAt: Date | string | null; + blockedReason: string | null; + } + | undefined, + tokenPepper?: string | null +): user is { pepper: string; blockedAt: Date | string | null; blockedReason: string | null } { + return ( + user !== undefined && + user.blockedAt === null && + user.blockedReason === null && + user.pepper !== null && + (tokenPepper === undefined || (tokenPepper !== null && user.pepper === tokenPepper)) + ); +} + +export async function resolveLegacyTownTokenOwner( + env: Pick, + identity: PrivateTownIdentity, + actor: LegacyTokenActor +): Promise { + if (!env.HYPERDRIVE) throw new LegacyTownTokenRenewalUnavailableError(); + + try { + const db = getWorkerDb(env.HYPERDRIVE.connectionString, { statement_timeout: 5_000 }); + const [principal] = await db + .select({ + pepper: kilocode_users.api_token_pepper, + blockedAt: kilocode_users.blocked_at, + blockedReason: kilocode_users.blocked_reason, + }) + .from(kilocode_users) + .where(eq(kilocode_users.id, actor.id)) + .limit(1); + + if (!isCurrentAccount(principal, actor.apiTokenPepper)) return null; + if (identity.ownerType === 'user' && identity.ownerUserId !== actor.id) return null; + + const isEligibleMember = async (userId: string): Promise => { + if (!identity.organizationId) return false; + const [membership] = await db + .select({ role: organization_memberships.role }) + .from(organization_memberships) + .innerJoin(organizations, eq(organizations.id, organization_memberships.organization_id)) + .where( + and( + eq(organization_memberships.kilo_user_id, userId), + eq(organization_memberships.organization_id, identity.organizationId), + isNull(organizations.deleted_at) + ) + ) + .limit(1); + return membership !== undefined && membership.role !== 'billing_manager'; + }; + + if (identity.ownerType === 'org' && !(await isEligibleMember(actor.id))) return null; + + const owner = + actor.id === identity.ownerUserId + ? principal + : ( + await db + .select({ + pepper: kilocode_users.api_token_pepper, + blockedAt: kilocode_users.blocked_at, + blockedReason: kilocode_users.blocked_reason, + }) + .from(kilocode_users) + .where(eq(kilocode_users.id, identity.ownerUserId)) + .limit(1) + )[0]; + + if (!isCurrentAccount(owner)) return null; + if (identity.ownerType === 'org' && actor.id !== identity.ownerUserId) { + if (!(await isEligibleMember(identity.ownerUserId))) return null; + } + + return { id: identity.ownerUserId, api_token_pepper: owner.pepper }; + } catch (error) { + if (error instanceof LegacyTownTokenRenewalUnavailableError) throw error; + throw new LegacyTownTokenRenewalUnavailableError(); + } +} + +/** + * Checks the current database state before renewing a legacy town token. + * Legacy JWT claims and mutable town configuration are not authorization + * sources: the stored private identity and current PostgreSQL records are. + */ +export async function isLegacyTownTokenRenewalAuthorized( + env: Pick, + identity: PrivateTownIdentity, + userId: string, + tokenPepper: string | null +): Promise { + if (identity.ownerUserId !== userId) return false; + return ( + (await resolveLegacyTownTokenOwner(env, identity, { + id: userId, + apiTokenPepper: tokenPepper, + })) !== null + ); +} diff --git a/services/gastown/src/dos/town/runtime-authorization.test.ts b/services/gastown/src/dos/town/runtime-authorization.test.ts new file mode 100644 index 0000000000..13d1dd7663 --- /dev/null +++ b/services/gastown/src/dos/town/runtime-authorization.test.ts @@ -0,0 +1,333 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type * as Jose from 'jose'; +import type * as RuntimeAuthorizationModule from '@kilocode/worker-utils/runtime-authorization'; + +const mocks = vi.hoisted(() => ({ + create: vi.fn(), + renew: vi.fn(), + getState: vi.fn(), + updateConfig: vi.fn(), +})); + +vi.mock('@kilocode/worker-utils/runtime-authorization', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + createRuntimeAuthorization: mocks.create, + renewRuntimeAuthorization: mocks.renew, + }; +}); +vi.mock('jose', async importOriginal => { + const actual = await importOriginal(); + return { ...actual, decodeJwt: vi.fn(() => ({ tokenPurpose: 'human-api' })) }; +}); +vi.mock('../TownContainer.do', () => ({ + getTownContainerStub: () => ({ getState: mocks.getState }), +})); +vi.mock('./config', () => ({ updateTownConfig: mocks.updateConfig })); +vi.mock('../../util/secret.util', () => ({ resolveSecret: vi.fn(() => 'secret') })); + +import { + createRuntimeAuthorization, + getPrivateTownIdentity, + getRuntimeAuthorizationState, + getTownIdentityState, + initializePrivateTownIdentity, + RUNTIME_AUTHORIZATION_KEY, + reauthorizeRuntime, + requiresRuntimeAuthorization, + renewRuntimeAuthorization, +} from './runtime-authorization'; +import { RuntimeAuthorizationRevokedError } from '@kilocode/worker-utils/runtime-authorization'; +import { RuntimeAuthorizationExpiredError } from '@kilocode/worker-utils/runtime-authorization'; + +type TestStorage = DurableObjectStorage & { putMock: ReturnType }; + +function storage(): TestStorage { + const values = new Map(); + const put = vi.fn(async (key: string, value: unknown) => values.set(key, value)); + const store = { + transaction: async (fn: (txn: DurableObjectStorage) => Promise) => fn(store), + get: vi.fn(async (key: string) => values.get(key) as T), + put, + putMock: put, + } as unknown as TestStorage; + return store; +} + +const identity = { + ownerType: 'user' as const, + ownerUserId: 'user-1', + createdByUserId: 'user-1', + runtimeMode: 'legacy' as const, +}; + +function authorization(state: 'active' | 'revoked' = 'active') { + return { + version: 1 as const, + id: '00000000-0000-4000-8000-000000000001', + resourceKind: 'gastown' as const, + resourceId: 'town-1', + userId: 'user-1', + authorizationUserId: 'user-1', + issuedAt: '2026-01-01T00:00:00.000Z', + delegationExpiresAt: '2026-01-31T00:00:00.000Z', + state, + bindings: { + userPepperDigest: 'a'.repeat(64), + authorizationPepperDigest: 'a'.repeat(64), + }, + source: { admissionSource: 'user' as const }, + }; +} + +function context(store: DurableObjectStorage) { + return { + storage: store, + env: { + NEXTAUTH_SECRET: 'secret', + HYPERDRIVE: { connectionString: 'postgres://' }, + } as unknown as Env, + townId: 'town-1', + hasActiveWork: () => false, + updateTownConfig: mocks.updateConfig, + }; +} + +describe('runtime authorization persistence', () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.updateConfig.mockResolvedValue({}); + mocks.getState.mockResolvedValue({ status: 'stopped' }); + }); + + it('persists and reads the private town identity', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, identity); + + await expect(getPrivateTownIdentity(store, 'town-1')).resolves.toEqual(identity); + expect(mocks.updateConfig).toHaveBeenCalledWith( + store, + expect.objectContaining({ owner_user_id: 'user-1' }) + ); + }); + + it('requires runtime authorization when a persisted record lacks a valid identity', async () => { + const store = storage(); + await store.put(RUNTIME_AUTHORIZATION_KEY, { malformed: true }); + + await expect(requiresRuntimeAuthorization(store, 'town-1')).resolves.toBe(true); + }); + + it.each([ + ['a malformed identity', { malformed: true }, undefined], + ['a runtime authorization without identity', undefined, authorization()], + ['a legacy identity with a runtime authorization', identity, authorization()], + ])('classifies %s as invalid rather than legacy', async (_name, privateIdentity, runtime) => { + const store = storage(); + if (privateIdentity !== undefined) await store.put('town:private:identity', privateIdentity); + if (runtime !== undefined) await store.put(RUNTIME_AUTHORIZATION_KEY, runtime); + + await expect(getTownIdentityState(store, 'town-1')).resolves.toEqual({ type: 'invalid' }); + }); + + it('classifies a valid identity without runtime authorization as legacy', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, identity); + + await expect(getTownIdentityState(store, 'town-1')).resolves.toEqual({ + type: 'legacy', + identity, + }); + }); + + it('requires runtime authorization for a modern identity without a stored record', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + + await expect(requiresRuntimeAuthorization(store, 'town-1')).resolves.toBe(true); + }); + + it.each([ + ['resource kind', { resourceKind: 'cloud-agent-next' }], + ['resource ID', { resourceId: 'another-town' }], + ['organization', { organizationId: 'org-2' }], + ['runtime user', { userId: 'another-user' }], + ['authorization user', { authorizationUserId: 'another-user' }], + ])('rejects a modern authorization with the wrong %s binding', async (_name, update) => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, { ...authorization(), ...update }); + + await expect(getTownIdentityState(store, 'town-1')).resolves.toEqual({ type: 'invalid' }); + }); + + it('renews an active authorization and retains active state', async () => { + const store = storage(); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization()); + mocks.renew.mockResolvedValue({ token: 'runtime-token' }); + + await expect(renewRuntimeAuthorization(context(store))).resolves.toBe('runtime-token'); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('active'); + expect(mocks.updateConfig).toHaveBeenCalledWith({ kilocode_token: 'runtime-token' }); + }); + + it('persists revoked state and does not return a replacement token', async () => { + const store = storage(); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization()); + mocks.renew.mockRejectedValue(new RuntimeAuthorizationRevokedError()); + + await expect(renewRuntimeAuthorization(context(store))).resolves.toBeUndefined(); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('revoked'); + expect(mocks.updateConfig).not.toHaveBeenCalled(); + }); + + it('persists expiry as revoked without updating the town token', async () => { + const store = storage(); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization()); + mocks.renew.mockRejectedValue(new RuntimeAuthorizationExpiredError()); + + await expect(renewRuntimeAuthorization(context(store))).resolves.toBeUndefined(); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('revoked'); + expect(mocks.updateConfig).not.toHaveBeenCalled(); + }); + + it('does not revoke a newer authorization when an in-flight renewal is rejected', async () => { + const store = storage(); + const oldAuthorization = authorization(); + const replacementAuthorization = { + ...authorization(), + id: '00000000-0000-4000-8000-000000000002', + }; + await store.put(RUNTIME_AUTHORIZATION_KEY, oldAuthorization); + let rejectRenewal: (error: Error) => void = () => undefined; + mocks.renew.mockImplementation( + () => new Promise((_resolve, reject) => (rejectRenewal = reject)) + ); + + const renewal = renewRuntimeAuthorization(context(store)); + await vi.waitFor(() => expect(mocks.renew).toHaveBeenCalledOnce()); + await store.put(RUNTIME_AUTHORIZATION_KEY, replacementAuthorization); + rejectRenewal(new RuntimeAuthorizationRevokedError()); + + await expect(renewal).resolves.toBeUndefined(); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('active'); + expect(store.putMock).not.toHaveBeenCalledWith( + RUNTIME_AUTHORIZATION_KEY, + expect.objectContaining({ id: oldAuthorization.id, state: 'revoked' }) + ); + }); + + it('reauthorizes only a stopped town with a revoked authorization', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization('revoked')); + mocks.create.mockResolvedValue({ + authorization: { + ...authorization(), + id: '00000000-0000-4000-8000-000000000002', + issuedAt: '2026-02-01T00:00:00.000Z', + delegationExpiresAt: '2026-03-03T00:00:00.000Z', + }, + token: 'replacement-token', + }); + + await expect(reauthorizeRuntime(context(store), 'control-token', 'user-1')).resolves.toBe(true); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('active'); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toMatchObject({ + id: '00000000-0000-4000-8000-000000000002', + delegationExpiresAt: '2026-03-03T00:00:00.000Z', + }); + }); + + it('reauthorizes an active authorization exactly at its delegation deadline', async () => { + const store = storage(); + const expiredAuthorization = authorization(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, expiredAuthorization); + mocks.create.mockResolvedValue({ + authorization: { ...authorization(), id: '00000000-0000-4000-8000-000000000002' }, + token: 'replacement-token', + }); + + await expect( + reauthorizeRuntime( + { ...context(store), now: () => new Date(expiredAuthorization.delegationExpiresAt) }, + 'control-token', + 'user-1' + ) + ).resolves.toBe(true); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toMatchObject({ + id: '00000000-0000-4000-8000-000000000002', + state: 'active', + }); + }); + + it('does not replace a nonexpired active authorization', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization()); + + await expect( + reauthorizeRuntime( + { ...context(store), now: () => new Date('2026-01-30T23:59:59.999Z') }, + 'control-token', + 'user-1' + ) + ).resolves.toBe(false); + expect(mocks.create).not.toHaveBeenCalled(); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('active'); + }); + + it('does not revoke or replace a newer authorization during expiry reauthorization', async () => { + const store = storage(); + const expiredAuthorization = authorization(); + const replacementAuthorization = { + ...authorization(), + id: '00000000-0000-4000-8000-000000000002', + }; + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, expiredAuthorization); + let resolveState: (state: { status: string }) => void = () => undefined; + mocks.getState.mockImplementation(() => new Promise(resolve => (resolveState = resolve))); + + const reauthorization = reauthorizeRuntime( + { ...context(store), now: () => new Date(expiredAuthorization.delegationExpiresAt) }, + 'control-token', + 'user-1' + ); + await vi.waitFor(() => expect(mocks.getState).toHaveBeenCalledOnce()); + await store.put(RUNTIME_AUTHORIZATION_KEY, replacementAuthorization); + resolveState({ status: 'stopped' }); + + await expect(reauthorization).resolves.toBe(false); + expect(mocks.create).not.toHaveBeenCalled(); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('active'); + }); + + it('refuses reauthorization while the town has active work', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, identity); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization('revoked')); + + await expect( + reauthorizeRuntime( + { ...context(store), hasActiveWork: () => true }, + 'control-token', + 'user-1' + ) + ).resolves.toBe(false); + expect(mocks.create).not.toHaveBeenCalled(); + }); + + it('creates and stores a modern authorization for the private identity', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, identity); + mocks.create.mockResolvedValue({ authorization: authorization(), token: 'runtime-token' }); + + await expect( + createRuntimeAuthorization(context(store), 'control-token', 'user-1') + ).resolves.toBe('runtime-token'); + await expect(getRuntimeAuthorizationState(store)).resolves.toBe('active'); + }); +}); diff --git a/services/gastown/src/dos/town/runtime-authorization.ts b/services/gastown/src/dos/town/runtime-authorization.ts new file mode 100644 index 0000000000..5284f5ac8d --- /dev/null +++ b/services/gastown/src/dos/town/runtime-authorization.ts @@ -0,0 +1,285 @@ +import { z } from 'zod'; +import { + createRuntimeAuthorization as createAuthorization, + renewRuntimeAuthorization as renewAuthorization, + RuntimeAuthorizationExpiredError, + RuntimeAuthorizationRevokedError, + RuntimeAuthorizationSchema, + type RuntimeAuthorization, +} from '@kilocode/worker-utils/runtime-authorization'; +import { decodeJwt } from 'jose'; +import { getTownContainerStub } from '../TownContainer.do'; +import * as config from './config'; +import { resolveSecret } from '../../util/secret.util'; +import type { TownConfig, TownConfigUpdate } from '../../types'; + +export const RUNTIME_AUTHORIZATION_KEY = 'town:private:runtime-authorization'; +export const TOWN_IDENTITY_KEY = 'town:private:identity'; + +export const TownIdentitySchema = z.object({ + ownerType: z.enum(['user', 'org']), + ownerUserId: z.string().min(1), + organizationId: z.string().min(1).optional(), + createdByUserId: z.string().min(1), + runtimeMode: z.enum(['legacy', 'modern']), +}); +export type TownIdentity = z.infer; +export type TownIdentityState = + | { type: 'legacy'; identity: TownIdentity | null } + | { type: 'modern'; identity: TownIdentity } + | { type: 'invalid' }; + +type RuntimeAuthorizationContext = { + storage: DurableObjectStorage; + env: Env; + townId: string; + hasActiveWork: () => boolean; + updateTownConfig: (update: TownConfigUpdate) => Promise; + now?: () => Date; +}; + +export async function initializePrivateTownIdentity( + storage: DurableObjectStorage, + identity: TownIdentity +): Promise { + const parsed = TownIdentitySchema.parse(identity); + await storage.transaction(async txn => { + const existing = await txn.get(TOWN_IDENTITY_KEY); + if (existing !== undefined) throw new Error('Town identity already initialized'); + if ((await txn.get(RUNTIME_AUTHORIZATION_KEY)) !== undefined) { + throw new Error('Town authorization already initialized'); + } + await txn.put(TOWN_IDENTITY_KEY, parsed); + await config.updateTownConfig(txn, { + owner_type: parsed.ownerType, + owner_id: parsed.organizationId ?? parsed.ownerUserId, + owner_user_id: parsed.ownerUserId, + organization_id: parsed.organizationId, + created_by_user_id: parsed.createdByUserId, + }); + }); +} + +export function isModernControlToken(token: string): boolean { + try { + return typeof decodeJwt(token).tokenPurpose === 'string'; + } catch { + return false; + } +} + +export async function getPrivateTownIdentity( + storage: DurableObjectStorage, + townId: string +): Promise { + const state = await getTownIdentityState(storage, townId); + return state.type === 'invalid' ? null : state.identity; +} + +/** + * Classify persisted authorization metadata without treating corruption as a + * legacy town. Once either private key exists, malformed or inconsistent data + * is an authorization failure rather than permission to use stale JWT claims. + */ +export async function getTownIdentityState( + storage: Pick, + townId: string +): Promise { + const [rawIdentity, rawAuthorization] = await Promise.all([ + storage.get(TOWN_IDENTITY_KEY), + storage.get(RUNTIME_AUTHORIZATION_KEY), + ]); + const hasIdentity = rawIdentity !== undefined; + const hasAuthorization = rawAuthorization !== undefined; + const identity = TownIdentitySchema.safeParse(rawIdentity); + const authorization = RuntimeAuthorizationSchema.safeParse(rawAuthorization); + + if (!hasIdentity && !hasAuthorization) return { type: 'legacy', identity: null }; + if (!identity.success) return { type: 'invalid' }; + if (identity.data.runtimeMode === 'legacy') { + return hasAuthorization ? { type: 'invalid' } : { type: 'legacy', identity: identity.data }; + } + if (hasAuthorization && !authorization.success) return { type: 'invalid' }; + if ( + authorization.success && + (authorization.data.resourceKind !== 'gastown' || + authorization.data.resourceId !== townId || + authorization.data.organizationId !== identity.data.organizationId || + authorization.data.userId !== identity.data.ownerUserId || + authorization.data.authorizationUserId !== identity.data.ownerUserId) + ) { + return { type: 'invalid' }; + } + return { type: 'modern', identity: identity.data }; +} + +export async function requiresRuntimeAuthorization( + storage: DurableObjectStorage, + townId: string +): Promise { + return (await getTownIdentityState(storage, townId)).type !== 'legacy'; +} + +export async function createRuntimeAuthorization( + ctx: RuntimeAuthorizationContext, + controlToken: string, + userId: string, + organizationId?: string +): Promise { + const identity = await getPrivateTownIdentity(ctx.storage, ctx.townId); + if ( + !identity || + identity.organizationId !== organizationId || + (identity.ownerType === 'user' && identity.ownerUserId !== userId) || + !controlToken || + !ctx.env.NEXTAUTH_SECRET || + !ctx.env.HYPERDRIVE + ) + return undefined; + const secret = await resolveSecret(ctx.env.NEXTAUTH_SECRET); + if (!secret) return undefined; + try { + const created = await createAuthorization({ + token: controlToken, + secret, + connectionString: ctx.env.HYPERDRIVE.connectionString, + resourceKind: 'gastown', + resourceId: ctx.townId, + organizationId, + now: ctx.now?.(), + }); + if ( + created.authorization.userId !== identity.ownerUserId || + created.authorization.authorizationUserId !== identity.ownerUserId + ) { + throw new Error('Runtime authorization owner mismatch'); + } + await ctx.storage.put(RUNTIME_AUTHORIZATION_KEY, created.authorization); + await ctx.storage.put(TOWN_IDENTITY_KEY, { ...identity, runtimeMode: 'modern' }); + return created.token; + } catch { + return undefined; + } +} + +export async function initializeTownIdentityAndRuntimeAuthorization( + ctx: RuntimeAuthorizationContext, + identity: TownIdentity, + controlToken: string +): Promise<{ runtimeToken?: string; modernControl: boolean }> { + await initializePrivateTownIdentity(ctx.storage, identity); + const modernControl = isModernControlToken(controlToken); + const runtimeToken = await createRuntimeAuthorization( + ctx, + controlToken, + identity.ownerUserId, + identity.organizationId + ); + return { runtimeToken, modernControl }; +} + +export async function reauthorizeRuntime( + ctx: RuntimeAuthorizationContext, + controlToken: string, + userId: string, + organizationId?: string +): Promise { + const identity = await getPrivateTownIdentity(ctx.storage, ctx.townId); + const current = RuntimeAuthorizationSchema.safeParse( + await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY) + ); + const expired = + current.success && + current.data.state === 'active' && + Date.parse(current.data.delegationExpiresAt) <= (ctx.now?.() ?? new Date()).getTime(); + if ( + !isModernControlToken(controlToken) || + !identity || + !current.success || + (current.data.state !== 'revoked' && !expired) || + identity.organizationId !== organizationId || + (identity.ownerType === 'user' && identity.ownerUserId !== userId) || + ctx.hasActiveWork() + ) + return false; + const container = await getTownContainerStub(ctx.env, ctx.townId).getState(); + if (container.status === 'running' || container.status === 'healthy') return false; + if (expired) { + const latest = RuntimeAuthorizationSchema.safeParse( + await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY) + ); + if (!latest.success || latest.data.id !== current.data.id || latest.data.state !== 'active') { + return false; + } + await ctx.storage.put(RUNTIME_AUTHORIZATION_KEY, { + ...latest.data, + state: 'revoked', + } satisfies RuntimeAuthorization); + } + return ( + (await createRuntimeAuthorization(ctx, controlToken, userId, organizationId)) !== undefined + ); +} + +export async function renewRuntimeAuthorization( + ctx: RuntimeAuthorizationContext +): Promise { + const raw = await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY); + if (!raw || !ctx.env.NEXTAUTH_SECRET || !ctx.env.HYPERDRIVE) return undefined; + const authorization = RuntimeAuthorizationSchema.safeParse(raw); + if (!authorization.success || authorization.data.state !== 'active') return undefined; + const secret = await resolveSecret(ctx.env.NEXTAUTH_SECRET); + if (!secret) return undefined; + try { + const renewed = await renewAuthorization({ + authorization: authorization.data, + secret, + connectionString: ctx.env.HYPERDRIVE.connectionString, + now: ctx.now?.(), + }); + const current = RuntimeAuthorizationSchema.safeParse( + await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY) + ); + if ( + !current.success || + current.data.id !== authorization.data.id || + current.data.state !== 'active' + ) { + return undefined; + } + await ctx.updateTownConfig({ kilocode_token: renewed.token }); + return renewed.token; + } catch (error) { + if ( + error instanceof RuntimeAuthorizationRevokedError || + error instanceof RuntimeAuthorizationExpiredError + ) { + // A concurrent reauthorization may have replaced this record while the + // database renewal was in flight. Never let the old request revoke the + // newly-issued authorization. + const current = RuntimeAuthorizationSchema.safeParse( + await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY) + ); + if ( + current.success && + current.data.id === authorization.data.id && + current.data.state === 'active' + ) { + await ctx.storage.put(RUNTIME_AUTHORIZATION_KEY, { + ...current.data, + state: 'revoked', + } satisfies RuntimeAuthorization); + } + } + return undefined; + } +} + +export async function getRuntimeAuthorizationState( + storage: DurableObjectStorage +): Promise<'active' | 'revoked' | null> { + const authorization = RuntimeAuthorizationSchema.safeParse( + await storage.get(RUNTIME_AUTHORIZATION_KEY) + ); + return authorization.success ? authorization.data.state : null; +} diff --git a/services/gastown/src/dos/town/unattended-token-renewal.test.ts b/services/gastown/src/dos/town/unattended-token-renewal.test.ts new file mode 100644 index 0000000000..3da84f77d7 --- /dev/null +++ b/services/gastown/src/dos/town/unattended-token-renewal.test.ts @@ -0,0 +1,369 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { SignJWT, jwtVerify } from 'jose'; + +const mocks = vi.hoisted(() => ({ userTown: vi.fn(), orgTown: vi.fn(), select: vi.fn() })); +vi.mock('cloudflare:workers', () => ({ DurableObject: class {}, WorkerEntrypoint: class {} })); +vi.mock('../TownContainer.do', () => ({ + getTownContainerStub: vi.fn(), + getTownContainerDoId: vi.fn(), +})); +vi.mock('../GastownUser.do', () => ({ + getGastownUserStub: (_env: Env, id: string) => ({ + getTownAsync: (town: string) => mocks.userTown(id, town), + }), +})); +vi.mock('../GastownOrg.do', () => ({ + getGastownOrgStub: (_env: Env, id: string) => ({ + getTownAsync: (town: string) => mocks.orgTown(id, town), + }), +})); +vi.mock('@kilocode/db/client', () => ({ getWorkerDb: () => ({ select: mocks.select }) })); + +import { TownDO } from '../Town.do'; +import * as config from './config'; +import { + getTownIdentityState, + initializePrivateTownIdentity, + TOWN_IDENTITY_KEY, + RUNTIME_AUTHORIZATION_KEY, +} from './runtime-authorization'; + +const secret = 'synthetic-test-secret'; +const env = { + NEXTAUTH_SECRET: secret, + HYPERDRIVE: { connectionString: 'postgres://test' }, +} as unknown as Env; +const identity = { + ownerType: 'user' as const, + ownerUserId: 'oauth/user-1', + createdByUserId: 'oauth/user-1', + runtimeMode: 'legacy' as const, +}; +const registryRow = { + id: 'town-1', + name: 'Old town', + owner_user_id: identity.ownerUserId, + owner_org_id: 'org-1', + created_by_user_id: identity.ownerUserId, + created_at: '2025-01-01', + updated_at: '2025-01-01', +}; + +function storage() { + const values = new Map(); + let queue = Promise.resolve(); + const store = { + get: async (key: string) => structuredClone(values.get(key)), + put: async (key: string, value: unknown) => { + values.set(key, structuredClone(value)); + }, + transaction: (fn: (txn: DurableObjectTransaction) => Promise) => { + const result = queue.then(() => fn(store as unknown as DurableObjectTransaction)); + queue = result.then( + () => undefined, + () => undefined + ); + return result; + }, + } as unknown as DurableObjectStorage; + return store; +} + +async function token(extra: Record = {}, signingSecret = secret) { + const now = Math.floor(Date.now() / 1000); + return new SignJWT({ + version: 3, + kiloUserId: identity.ownerUserId, + apiTokenPepper: 'current', + iat: now - 29 * 86400, + exp: now + 86400, + ...extra, + }) + .setProtectedHeader({ alg: 'HS256' }) + .sign(new TextEncoder().encode(signingSecret)); +} + +async function town(org = false, bearer?: string) { + const store = storage(); + const oldToken = bearer ?? (await token()); + // Pre-PR state: town ID and mutable configuration, neither private key. + await store.put('town:id', 'town-1'); + await store.put('town:config', { + kilocode_token: oldToken, + ...(org + ? { + owner_type: 'org', + owner_id: 'org-1', + organization_id: 'org-1', + owner_user_id: identity.ownerUserId, + created_by_user_id: identity.ownerUserId, + } + : { owner_user_id: identity.ownerUserId }), + }); + const sync = vi.fn(); + // Invoke the actual method called by the unattended alarm, without creating + // the unrelated scheduler SQL/container runtime or using a tRPC/UI refresh. + const instance = Object.create(TownDO.prototype) as TownDO; + Object.assign(instance, { + ctx: { storage: store }, + env, + _townId: 'town-1', + lastKilocodeTokenCheckAt: 0, + syncConfigToContainer: sync, + }); + const renew = () => instance['refreshKilocodeTokenIfExpiring'](); + return { store, oldToken, sync, renew, instance }; +} + +beforeEach(() => { + vi.resetAllMocks(); + mocks.userTown.mockResolvedValue(registryRow); + mocks.orgTown.mockResolvedValue(registryRow); + mocks.select.mockImplementation(() => ({ + from: () => ({ + where: () => ({ + limit: async () => [{ pepper: 'current', blockedAt: null, blockedReason: null }], + }), + innerJoin: () => ({ where: () => ({ limit: async () => [{ role: 'owner' }] }) }), + }), + })); +}); + +describe('unattended legacy town renewal entry', () => { + it.each([false, true])( + 'adopts and renews a pre-PR town (org=%s) without UI refresh', + async org => { + const t = await town(org); + await t.renew(); + expect(await getTownIdentityState(t.store, 'town-1')).toEqual({ + type: 'legacy', + identity: org ? { ...identity, ownerType: 'org', organizationId: 'org-1' } : identity, + }); + const renewed = (await config.getTownConfig(t.store)).kilocode_token; + expect(renewed).not.toBe(t.oldToken); + const { payload } = await jwtVerify(renewed!, new TextEncoder().encode(secret)); + expect(payload.kiloUserId).toBe(identity.ownerUserId); + expect(payload.apiTokenPepper).toBe('current'); + expect(payload.exp! - payload.iat!).toBe(30 * 86400); + expect(org ? mocks.orgTown : mocks.userTown).toHaveBeenCalledWith( + org ? 'org-1' : identity.ownerUserId, + 'town-1' + ); + expect(t.sync).toHaveBeenCalledOnce(); + } + ); + + it.each([false, true])('recovers an expired registry-bound legacy token (org=%s)', async org => { + const t = await town(org, await token({ exp: Math.floor(Date.now() / 1000) - 86400 })); + await t.renew(); + expect(t.sync).toHaveBeenCalledOnce(); + }); + + it.each([ + null, + { ...registryRow, id: 'another-town' }, + { ...registryRow, owner_user_id: 'another-user' }, + ])('rejects absent or mismatched personal registry ownership: %j', async row => { + mocks.userTown.mockResolvedValue(row); + const t = await town(); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(t.sync).not.toHaveBeenCalled(); + }); + + it.each([ + null, + { ...registryRow, owner_org_id: 'another-org' }, + { ...registryRow, created_by_user_id: '' }, + { ...registryRow, created_by_user_id: 'another-member' }, + ])('rejects absent or mismatched org ownership: %j', async row => { + mocks.orgTown.mockResolvedValue(row); + const t = await town(true); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(t.sync).not.toHaveBeenCalled(); + }); + + it.each([ + { env: 'development' }, + { env: 'production' }, + { aud: 'kilo-api' }, + { tokenPurpose: 'delegated-workload', credentialExchange: false }, + { credentialExchange: false }, + { botId: 'bot' }, + { organizationId: 'org-1' }, + { runtimeAuthorization: {} }, + { deviceSessionId: 'device' }, + { gastownAccess: true }, + { nbf: Math.floor(Date.now() / 1000) + 86400 }, + { iat: Math.floor(Date.now() / 1000) + 100 }, + { apiTokenPepper: null }, + { apiTokenPepper: 'rotated' }, + ])('does not launder token claims %j', async claims => { + const t = await town(false, await token(claims)); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(t.sync).not.toHaveBeenCalled(); + }); + + it('rejects a forged expired token', async () => { + const t = await town(false, await token({ exp: 1 }, 'wrong-secret')); + await t.renew(); + expect(t.sync).not.toHaveBeenCalled(); + expect(mocks.userTown).not.toHaveBeenCalled(); + }); + + it.each([ + { rows: [] }, + { rows: [{ pepper: 'new', blockedAt: null, blockedReason: null }] }, + { rows: [{ pepper: 'current', blockedAt: '2026-01-01', blockedReason: null }] }, + { rows: [{ pepper: 'current', blockedAt: null, blockedReason: 'abuse' }] }, + ])('rejects current account revocation %j', async ({ rows }) => { + mocks.select.mockReturnValue({ from: () => ({ where: () => ({ limit: async () => rows }) }) }); + const t = await town(); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(t.sync).not.toHaveBeenCalled(); + }); + + it.each([{ rows: [] }, { rows: [{ role: 'billing_manager' }] }])( + 'rejects removed/deleted-org or ineligible membership %j', + async ({ rows }) => { + mocks.select.mockReturnValue({ + from: () => ({ + where: () => ({ + limit: async () => [{ pepper: 'current', blockedAt: null, blockedReason: null }], + }), + innerJoin: () => ({ where: () => ({ limit: async () => rows }) }), + }), + }); + const t = await town(true); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(t.sync).not.toHaveBeenCalled(); + } + ); + + it.each(['registry', 'database'])( + 'retries a transient %s failure on the next alarm', + async authority => { + if (authority === 'registry') mocks.userTown.mockRejectedValueOnce(new Error('unavailable')); + else + mocks.select.mockImplementationOnce(() => { + throw new Error('unavailable'); + }); + const t = await town(); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(t.sync).not.toHaveBeenCalled(); + await t.renew(); + expect(t.sync).toHaveBeenCalledOnce(); + } + ); + + it.each([ + null, + false, + {}, + { ...identity, runtimeMode: 'modern', ownerUserId: '' }, + { ...identity, runtimeMode: 'modern' }, + ])('never adopts over invalid or modern identity %j', async stored => { + const t = await town(); + await t.store.put(TOWN_IDENTITY_KEY, stored); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toEqual(stored); + expect(t.sync).not.toHaveBeenCalled(); + }); + + it.each(['active', 'revoked'])('does not replace modern %s authorization', async state => { + const t = await town(); + await t.store.put(TOWN_IDENTITY_KEY, { ...identity, runtimeMode: 'modern' }); + await t.store.put(RUNTIME_AUTHORIZATION_KEY, { + version: 1, + id: '00000000-0000-4000-8000-000000000001', + resourceKind: 'gastown', + resourceId: 'town-1', + userId: identity.ownerUserId, + authorizationUserId: identity.ownerUserId, + issuedAt: '2026-01-01T00:00:00.000Z', + delegationExpiresAt: '2026-01-31T00:00:00.000Z', + state, + bindings: { userPepperDigest: 'a'.repeat(64), authorizationPepperDigest: 'a'.repeat(64) }, + source: { admissionSource: 'user' }, + }); + expect((await getTownIdentityState(t.store, 'town-1')).type).toBe('modern'); + await t.renew(); + expect(t.sync).not.toHaveBeenCalled(); + expect(mocks.select).not.toHaveBeenCalled(); + }); + + it('does not overwrite a concurrent modern adoption', async () => { + const t = await town(); + mocks.userTown.mockImplementationOnce(async () => { + await initializePrivateTownIdentity(t.store, { ...identity, runtimeMode: 'modern' }); + return registryRow; + }); + await t.renew(); + expect((await getTownIdentityState(t.store, 'town-1')).type).toBe('modern'); + expect(t.sync).not.toHaveBeenCalled(); + expect((await config.getTownConfig(t.store)).kilocode_token).toBe(t.oldToken); + }); + + it('fences a concurrent token edit', async () => { + const t = await town(); + mocks.userTown.mockImplementationOnce(async () => { + await config.updateTownConfig(t.store, { kilocode_token: 'replacement' }); + return registryRow; + }); + await t.renew(); + expect(t.sync).not.toHaveBeenCalled(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + }); + + it('does not overwrite a concurrent legacy adoption', async () => { + const t = await town(); + const competingIdentity = { + ...identity, + ownerUserId: 'another-user', + createdByUserId: 'another-user', + }; + mocks.userTown.mockImplementationOnce(async () => { + await initializePrivateTownIdentity(t.store, competingIdentity); + return registryRow; + }); + await t.renew(); + expect(await t.store.get(TOWN_IDENTITY_KEY)).toEqual(competingIdentity); + expect(t.sync).not.toHaveBeenCalled(); + expect((await config.getTownConfig(t.store)).kilocode_token).toBe(t.oldToken); + }); + + it('retains the daily throttle after a completed check', async () => { + const t = await town(); + await t.renew(); + await t.renew(); + expect(t.sync).toHaveBeenCalledOnce(); + expect(mocks.select).toHaveBeenCalledOnce(); + }); + + it('rejects a stale owner token even after private identity adoption', async () => { + const t = await town(); + await initializePrivateTownIdentity(t.store, identity); + mocks.select.mockReturnValue({ + from: () => ({ + where: () => ({ + limit: async () => [{ pepper: 'rotated', blockedAt: null, blockedReason: null }], + }), + }), + }); + await t.renew(); + expect(t.sync).not.toHaveBeenCalled(); + expect((await config.getTownConfig(t.store)).kilocode_token).toBe(t.oldToken); + }); + + it('coalesces concurrent unattended calls into one adoption and renewal', async () => { + const t = await town(); + await Promise.all([t.renew(), t.renew()]); + expect(t.sync).toHaveBeenCalledOnce(); + expect(mocks.userTown).toHaveBeenCalledOnce(); + }); +}); diff --git a/services/gastown/src/dos/town/unattended-token-renewal.ts b/services/gastown/src/dos/town/unattended-token-renewal.ts new file mode 100644 index 0000000000..b9ba430912 --- /dev/null +++ b/services/gastown/src/dos/town/unattended-token-renewal.ts @@ -0,0 +1,129 @@ +import { kiloTokenPayload } from '@kilocode/worker-utils'; +import { jwtVerify, errors } from 'jose'; +import { z } from 'zod'; +import { getGastownOrgStub } from '../GastownOrg.do'; +import { getGastownUserStub } from '../GastownUser.do'; +import { OrgTownRecord } from '../../db/tables/org-towns.table'; +import { UserTownRecord } from '../../db/tables/user-towns.table'; +import { generateKiloApiToken } from '../../util/kilo-token.util'; +import { resolveSecret } from '../../util/secret.util'; +import type { TownConfig } from '../../types'; +import * as config from './config'; +import * as runtimeAuthorization from './runtime-authorization'; +import { isLegacyTownTokenRenewalAuthorized } from './legacy-token-renewal'; + +// The old town producer minted this plain token. Do not erase audience, +// purpose, device, environment, org, or workload restrictions by renewing another class. +const legacyTownPayload = kiloTokenPayload + .pick({ version: true, kiloUserId: true, apiTokenPepper: true, iat: true, exp: true }) + .extend({ apiTokenPepper: z.string().min(1), iat: z.number().int(), exp: z.number().int() }) + .strict(); + +async function resolveRegistryIdentity( + env: Env, + townId: string, + townConfig: TownConfig, + userId: string +) { + // Configuration only locates a registry. Its row must bind this exact town + // to the signed principal; an eligible org member is not the town creator. + if (townConfig.owner_type === 'org') { + const orgId = townConfig.organization_id; + if (!orgId) return null; + const row = OrgTownRecord.nullable().parse( + await getGastownOrgStub(env, orgId).getTownAsync(townId) + ); + if ( + !row || + row.id !== townId || + row.owner_org_id !== orgId || + row.created_by_user_id !== userId + ) + return null; + return runtimeAuthorization.TownIdentitySchema.parse({ + ownerType: 'org', + ownerUserId: row.created_by_user_id, + organizationId: row.owner_org_id, + createdByUserId: row.created_by_user_id, + runtimeMode: 'legacy', + }); + } + if (townConfig.organization_id) return null; + const row = UserTownRecord.nullable().parse( + await getGastownUserStub(env, userId).getTownAsync(townId) + ); + if (!row || row.id !== townId || row.owner_user_id !== userId) return null; + return runtimeAuthorization.TownIdentitySchema.parse({ + ownerType: 'user', + ownerUserId: row.owner_user_id, + createdByUserId: row.owner_user_id, + runtimeMode: 'legacy', + }); +} + +/** Only the unattended town path may recover an expired, registry-bound legacy token. */ +export async function renewUnattendedLegacyTownToken( + storage: DurableObjectStorage, + env: Env, + townId: string +): Promise { + const state = await runtimeAuthorization.getTownIdentityState(storage, townId); + if (state.type !== 'legacy') return false; + const townConfig = await config.getTownConfig(storage); + const token = townConfig.kilocode_token; + if (!token || !env.NEXTAUTH_SECRET) return false; + const secret = await resolveSecret(env.NEXTAUTH_SECRET); + if (!secret) throw new Error('Town token signing unavailable'); + let raw; + try { + raw = (await jwtVerify(token, new TextEncoder().encode(secret), { algorithms: ['HS256'] })) + .payload; + } catch (error) { + // jose checks the signature and nbf before exp. Recover only this precise + // expiry failure, with no clock tolerance that also permits future tokens. + if (!(error instanceof errors.JWTExpired) || error.claim !== 'exp') return false; + raw = error.payload; + } + const parsed = legacyTownPayload.safeParse(raw); + if (!parsed.success) return false; + const payload = parsed.data; + const now = Math.floor(Date.now() / 1000); + if (payload.iat > now || payload.exp <= payload.iat || payload.exp - now > 7 * 24 * 60 * 60) + return false; + + const identity = + state.identity ?? (await resolveRegistryIdentity(env, townId, townConfig, payload.kiloUserId)); + if ( + !identity || + !(await isLegacyTownTokenRenewalAuthorized( + env, + identity, + payload.kiloUserId, + payload.apiTokenPepper + )) + ) + return false; + const newToken = await generateKiloApiToken( + { id: payload.kiloUserId, api_token_pepper: payload.apiTokenPepper }, + secret + ); + + // External verification stays outside the transaction. Fence both private + // state and the source config so a concurrent adoption/revocation/edit wins. + return storage.transaction(async txn => { + const currentState = await runtimeAuthorization.getTownIdentityState(txn, townId); + if (JSON.stringify(currentState) !== JSON.stringify(state)) return false; + const currentConfig = await config.getTownConfig(txn); + if (JSON.stringify(currentConfig) !== JSON.stringify(townConfig)) return false; + if (!state.identity) await txn.put(runtimeAuthorization.TOWN_IDENTITY_KEY, identity); + await config.updateTownConfig(txn, { + kilocode_token: newToken, + owner_type: identity.ownerType, + owner_id: identity.organizationId ?? identity.ownerUserId, + owner_user_id: identity.ownerUserId, + organization_id: identity.organizationId, + created_by_user_id: identity.createdByUserId, + }); + return true; + }); +} diff --git a/services/gastown/src/gastown.worker.ts b/services/gastown/src/gastown.worker.ts index 545feae835..b1f4d260dd 100644 --- a/services/gastown/src/gastown.worker.ts +++ b/services/gastown/src/gastown.worker.ts @@ -142,6 +142,7 @@ import { timingMiddleware, instrumented } from './middleware/analytics.middlewar import { useWorkersLogger } from 'workers-tagged-logger'; import type { MiddlewareHandler } from 'hono'; import { handleGetTownConfig, handleUpdateTownConfig } from './handlers/town-config.handler'; +import { handleReauthorizeTownRuntime } from './handlers/town-runtime-authorization.handler'; import { handleGetMoleculeCurrentStep, handleAdvanceMoleculeStep, @@ -1039,6 +1040,11 @@ app.get('/api/towns/:townId/config', c => app.patch('/api/towns/:townId/config', c => instrumented(c, 'PATCH /api/towns/:townId/config', () => handleUpdateTownConfig(c, c.req.param())) ); +app.post('/api/towns/:townId/runtime-authorization/reauthorize', c => + instrumented(c, 'POST /api/towns/:townId/runtime-authorization/reauthorize', () => + handleReauthorizeTownRuntime(c, c.req.param()) + ) +); // ── Cloudflare Debug ──────────────────────────────────────────────── // Returns DO IDs and namespace IDs for constructing Cloudflare dashboard URLs. @@ -1366,6 +1372,8 @@ app.use( apiTokenPepper: c.get('kiloApiTokenPepper') ?? null, gastownAccess: c.get('kiloGastownAccess') ?? false, orgMemberships: c.get('kiloOrgMemberships') ?? [], + controlToken: c.get('kiloControlToken') ?? '', + usesModernToken: c.get('kiloUsesModernToken') ?? false, }), onError: ({ error, path }: { error: Error; path?: string }) => { console.error(`[gastown-trpc] error on ${path ?? 'unknown'}:`, error.message); diff --git a/services/gastown/src/handlers/org-towns.handler.test.ts b/services/gastown/src/handlers/org-towns.handler.test.ts new file mode 100644 index 0000000000..176004fdc6 --- /dev/null +++ b/services/gastown/src/handlers/org-towns.handler.test.ts @@ -0,0 +1,133 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { Hono } from 'hono'; +import type { GastownEnv } from '../gastown.worker'; + +const mocks = vi.hoisted(() => ({ + getTownAsync: vi.fn(), + createRig: vi.fn(), + getTownIdentityState: vi.fn(), + authorizeOrganization: vi.fn(), + configureRig: vi.fn(), + addRig: vi.fn(), +})); + +vi.mock('../dos/GastownOrg.do', () => ({ + getGastownOrgStub: () => ({ getTownAsync: mocks.getTownAsync, createRig: mocks.createRig }), +})); +vi.mock('../dos/Town.do', () => ({ + getTownDOStub: () => ({ + getTownIdentityState: mocks.getTownIdentityState, + configureRig: mocks.configureRig, + addRig: mocks.addRig, + }), +})); +vi.mock('../util/town-authorization.util', () => ({ + authorizeOrganization: mocks.authorizeOrganization, + TownAuthorizationUnavailableError: class extends Error {}, +})); + +import { handleCreateOrgRig, handleDeleteOrgTown } from './org-towns.handler'; + +describe('handleCreateOrgRig', () => { + beforeEach(() => vi.resetAllMocks()); + + function setup( + kiloUsesModernToken: boolean, + identity = { ownerType: 'org', organizationId: 'org-1', runtimeMode: 'modern' } + ) { + mocks.getTownAsync.mockResolvedValue({ id: 'town-1' }); + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { ownerUserId: 'owner-1', ...identity }, + }); + mocks.createRig.mockResolvedValue({ id: 'rig-1' }); + const app = new Hono(); + app.post('/api/orgs/:orgId/rigs', c => { + c.set('kiloUserId', 'user-1'); + c.set('kiloUsesModernToken', kiloUsesModernToken); + c.set('kiloApiTokenPepper', 'current'); + c.set('orgRole', 'owner'); + return handleCreateOrgRig(c, c.req.param()); + }); + + return app.request( + '/api/orgs/org-1/rigs', + { + method: 'POST', + body: JSON.stringify({ + town_id: 'town-1', + name: 'rig', + git_url: 'https://github.com/kilocode/example', + }), + }, + {} as Env + ); + } + + it.each([ + ['a legacy bearer with a fresh membership', false], + ['a modern bearer with a fresh membership', true], + ['an admin with a fresh membership', true], + ])('allows %s to mutate a modern town', async (_name, kiloUsesModernToken) => { + mocks.authorizeOrganization.mockResolvedValue({ role: 'member' }); + const response = await setup(kiloUsesModernToken); + + expect(response.status).toBe(201); + expect(mocks.createRig).toHaveBeenCalledOnce(); + expect(mocks.authorizeOrganization).toHaveBeenCalledWith( + expect.anything(), + 'org-1', + 'user-1', + 'current' + ); + }); + + it('rejects a legacy bearer whose current membership was removed', async () => { + mocks.authorizeOrganization.mockResolvedValue(null); + const response = await setup(false); + + expect(response.status).toBe(403); + expect(mocks.createRig).not.toHaveBeenCalled(); + }); + + it('rejects a modern town belonging to another organization', async () => { + const response = await setup(false, { + ownerType: 'org', + organizationId: 'org-2', + runtimeMode: 'modern', + }); + + expect(response.status).toBe(403); + expect(mocks.authorizeOrganization).not.toHaveBeenCalled(); + }); + + it('uses the fresh target-town role for deletion', async () => { + mocks.getTownAsync.mockResolvedValue({ id: 'town-1' }); + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { + ownerType: 'org', + ownerUserId: 'owner-1', + organizationId: 'org-1', + runtimeMode: 'modern', + }, + }); + mocks.authorizeOrganization.mockResolvedValue({ role: 'member' }); + const app = new Hono(); + app.delete('/api/orgs/:orgId/towns/:townId', c => { + c.set('kiloUserId', 'user-1'); + c.set('kiloApiTokenPepper', 'current'); + c.set('orgRole', 'owner'); + return handleDeleteOrgTown(c, c.req.param()); + }); + + const response = await app.request( + '/api/orgs/org-1/towns/town-1', + { method: 'DELETE' }, + {} as Env + ); + + expect(response.status).toBe(403); + expect(mocks.createRig).not.toHaveBeenCalled(); + }); +}); diff --git a/services/gastown/src/handlers/org-towns.handler.ts b/services/gastown/src/handlers/org-towns.handler.ts index a875e8375d..d4887dca50 100644 --- a/services/gastown/src/handlers/org-towns.handler.ts +++ b/services/gastown/src/handlers/org-towns.handler.ts @@ -5,6 +5,10 @@ import { getTownDOStub } from '../dos/Town.do'; import { resSuccess, resError } from '../util/res.util'; import { parseJsonBody } from '../util/parse-json-body.util'; import type { GastownEnv } from '../gastown.worker'; +import { + authorizeOrganization, + TownAuthorizationUnavailableError, +} from '../util/town-authorization.util'; const ORG_TOWNS_LOG = '[org-towns.handler]'; @@ -20,6 +24,40 @@ const CreateOrgRigBody = z.object({ platform_integration_id: z.string().min(1).optional(), }); +async function authorizeExistingTownMutation( + c: Context, + townId: string, + organizationId: string +): Promise { + const town = getTownDOStub(c.env, townId); + const identityState = await town.getTownIdentityState(); + if (identityState.type === 'invalid') { + return c.json(resError('Town authorization state is invalid'), 403); + } + if (identityState.type === 'legacy') return null; + const identity = identityState.identity; + if (identity.ownerType !== 'org' || identity.organizationId !== organizationId) + return c.json(resError('Forbidden'), 403); + const userId = c.get('kiloUserId'); + if (!userId) return c.json(resError('Authentication required'), 401); + try { + const authorization = await authorizeOrganization( + c.env, + organizationId, + userId, + c.get('kiloApiTokenPepper') + ); + if (!authorization || !('role' in authorization)) return c.json(resError('Forbidden'), 403); + c.set('orgRole', authorization.role); + return null; + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) { + return c.json(resError('Authorization unavailable'), 503); + } + throw error; + } +} + export async function handleCreateOrgTown(c: Context, params: { orgId: string }) { const parsed = CreateOrgTownBody.safeParse(await parseJsonBody(c)); if (!parsed.success) { @@ -42,7 +80,22 @@ export async function handleCreateOrgTown(c: Context, params: { orgI // Initialize the TownDO config with org ownership metadata const townDOStub = getTownDOStub(c.env, town.id); await townDOStub.setTownId(town.id); + const runtime = await townDOStub.initializeTownIdentityAndRuntimeAuthorization( + { + ownerType: 'org', + ownerUserId: userId, + organizationId: params.orgId, + createdByUserId: userId, + runtimeMode: 'legacy', + }, + c.get('kiloControlToken') + ); + if (runtime.modernControl && !runtime.runtimeToken) { + await orgDO.deleteTown(town.id); + return c.json(resError('A current Gastown control token is required'), 403); + } await townDOStub.updateTownConfig({ + ...(runtime.runtimeToken ? { kilocode_token: runtime.runtimeToken } : {}), owner_type: 'org', owner_id: params.orgId, owner_user_id: userId, @@ -90,6 +143,12 @@ export async function handleCreateOrgRig(c: Context, params: { orgId // Verify the town belongs to this org before creating the rig const town = await orgDO.getTownAsync(parsed.data.town_id); if (!town) return c.json(resError('Town not found in this org'), 404); + const authorizationError = await authorizeExistingTownMutation( + c, + parsed.data.town_id, + params.orgId + ); + if (authorizationError) return authorizationError; const rig = await orgDO.createRig(parsed.data); console.log( @@ -157,18 +216,16 @@ export async function handleDeleteOrgTown( const userId = c.get('kiloUserId'); if (!userId) return c.json(resError('Authentication required'), 401); - // Verify owner role via JWT claims (works in dev mode where orgAuthMiddleware is skipped) - const memberships = c.get('kiloOrgMemberships') ?? []; - const membership = memberships.find(m => m.orgId === params.orgId); - if (!membership || membership.role !== 'owner') { - return c.json(resError('Only org owners can delete towns'), 403); - } - const orgDO = getGastownOrgStub(c.env, params.orgId); // Verify the town belongs to this org BEFORE destroying anything const town = await orgDO.getTownAsync(params.townId); if (!town) return c.json(resError('Town not found'), 404); + const authorizationError = await authorizeExistingTownMutation(c, params.townId, params.orgId); + if (authorizationError) return authorizationError; + if (c.get('orgRole') !== 'owner') { + return c.json(resError('Only org owners can delete towns'), 403); + } // Destroy the Town DO (handles all rigs, agents, and mayor cleanup) try { @@ -193,16 +250,14 @@ export async function handleDeleteOrgRig( const userId = c.get('kiloUserId'); if (!userId) return c.json(resError('Authentication required'), 401); - // Verify owner role via JWT claims (works in dev mode where orgAuthMiddleware is skipped) - const memberships = c.get('kiloOrgMemberships') ?? []; - const membership = memberships.find(m => m.orgId === params.orgId); - if (!membership || membership.role !== 'owner') { - return c.json(resError('Only org owners can delete rigs'), 403); - } - const orgDO = getGastownOrgStub(c.env, params.orgId); const rig = await orgDO.getRigAsync(params.rigId); if (!rig) return c.json(resError('Rig not found'), 404); + const authorizationError = await authorizeExistingTownMutation(c, rig.town_id, params.orgId); + if (authorizationError) return authorizationError; + if (c.get('orgRole') !== 'owner') { + return c.json(resError('Only org owners can delete rigs'), 403); + } const deleted = await orgDO.deleteRig(params.rigId); if (!deleted) return c.json(resError('Rig not found'), 404); diff --git a/services/gastown/src/handlers/town-runtime-authorization.handler.ts b/services/gastown/src/handlers/town-runtime-authorization.handler.ts new file mode 100644 index 0000000000..1a65629e02 --- /dev/null +++ b/services/gastown/src/handlers/town-runtime-authorization.handler.ts @@ -0,0 +1,61 @@ +import type { Context } from 'hono'; +import { getTownDOStub } from '../dos/Town.do'; +import type { GastownEnv } from '../gastown.worker'; +import { resError, resSuccess } from '../util/res.util'; +import { authorizeTown, TownAuthorizationUnavailableError } from '../util/town-authorization.util'; + +export async function handleReauthorizeTownRuntime( + c: Context, + params: { townId: string } +) { + const userId = c.get('kiloUserId'); + if (!userId) return c.json(resError('Authentication required'), 401); + const town = getTownDOStub(c.env, params.townId); + const identityState = await town.getTownIdentityState(); + if (identityState.type === 'invalid') { + return c.json(resError('Town authorization state is invalid'), 403); + } + const identity = identityState.identity; + if (!identity) return c.json(resError('Town requires recreation'), 409); + let modernAuthorization; + if (identityState.type === 'modern') { + try { + modernAuthorization = await authorizeTown( + c.env, + identity, + userId, + c.get('kiloApiTokenPepper') + ); + if (!modernAuthorization) return c.json(resError('Forbidden'), 403); + if ( + identity.ownerType === 'org' && + (modernAuthorization.type !== 'org' || modernAuthorization.role !== 'owner') + ) { + return c.json(resError('Forbidden'), 403); + } + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) { + return c.json(resError('Authorization unavailable'), 503); + } + throw error; + } + } + if (identity.ownerType === 'user' && identity.ownerUserId !== userId) { + return c.json(resError('Forbidden'), 403); + } + if (identity.ownerType === 'org' && identity.runtimeMode !== 'modern') { + const membership = (c.get('kiloOrgMemberships') ?? []).find( + value => value.orgId === identity.organizationId + ); + if (!membership || membership.role !== 'owner') { + return c.json(resError('Forbidden'), 403); + } + } + const authorized = await town.reauthorizeRuntime( + c.get('kiloControlToken'), + userId, + identity.organizationId + ); + if (!authorized) return c.json(resError('Town runtime cannot be reauthorized'), 409); + return c.json(resSuccess({ reauthorized: true })); +} diff --git a/services/gastown/src/handlers/towns.handler.ts b/services/gastown/src/handlers/towns.handler.ts index 2bb6075425..4f1a63ab21 100644 --- a/services/gastown/src/handlers/towns.handler.ts +++ b/services/gastown/src/handlers/towns.handler.ts @@ -27,6 +27,7 @@ const CreateRigBody = z.object({ */ export async function handleCreateTown(c: Context, params: { userId: string }) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const parsed = CreateTownBody.safeParse(await parseJsonBody(c)); if (!parsed.success) { return c.json( @@ -37,10 +38,28 @@ export async function handleCreateTown(c: Context, params: { userId: const townDO = getGastownUserStub(c.env, params.userId); const town = await townDO.createTown({ name: parsed.data.name, owner_user_id: params.userId }); + const townStub = getTownDOStub(c.env, town.id); + await townStub.setTownId(town.id); + const runtime = await townStub.initializeTownIdentityAndRuntimeAuthorization( + { + ownerType: 'user', + ownerUserId: params.userId, + createdByUserId: params.userId, + runtimeMode: 'legacy', + }, + c.get('kiloControlToken') + ); + if (runtime.modernControl && !runtime.runtimeToken) { + await townDO.deleteTown(town.id); + return c.json(resError('A current Gastown control token is required'), 403); + } + if (runtime.runtimeToken) + await townStub.updateTownConfig({ kilocode_token: runtime.runtimeToken }); return c.json(resSuccess(town), 201); } export async function handleListTowns(c: Context, params: { userId: string }) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const townDO = getGastownUserStub(c.env, params.userId); const towns = await townDO.listTowns(); return c.json(resSuccess(towns)); @@ -50,6 +69,7 @@ export async function handleGetTown( c: Context, params: { userId: string; townId: string } ) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const townDO = getGastownUserStub(c.env, params.userId); const town = await townDO.getTownAsync(params.townId); if (!town) return c.json(resError('Town not found'), 404); @@ -57,6 +77,7 @@ export async function handleGetTown( } export async function handleCreateRig(c: Context, params: { userId: string }) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const parsed = CreateRigBody.safeParse(await parseJsonBody(c)); if (!parsed.success) { console.error(`${TOWNS_LOG} handleCreateRig: invalid body`, parsed.error.issues); @@ -70,6 +91,8 @@ export async function handleCreateRig(c: Context, params: { userId: ); const townDO = getGastownUserStub(c.env, params.userId); + const ownedTown = await townDO.getTownAsync(parsed.data.town_id); + if (!ownedTown) return c.json(resError('Town not found'), 404); const rig = await townDO.createRig(parsed.data); console.log(`${TOWNS_LOG} handleCreateRig: rig created id=${rig.id}, now configuring Rig DO`); @@ -110,6 +133,7 @@ export async function handleGetRig( c: Context, params: { userId: string; rigId: string } ) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const townDO = getGastownUserStub(c.env, params.userId); const rig = await townDO.getRigAsync(params.rigId); if (!rig) return c.json(resError('Rig not found'), 404); @@ -120,6 +144,7 @@ export async function handleListRigs( c: Context, params: { userId: string; townId: string } ) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const townDO = getGastownUserStub(c.env, params.userId); const rigs = await townDO.listRigs(params.townId); return c.json(resSuccess(rigs)); @@ -129,6 +154,7 @@ export async function handleDeleteTown( c: Context, params: { userId: string; townId: string } ) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const townDO = getGastownUserStub(c.env, params.userId); // Destroy the Town DO (handles all rigs, agents, and mayor cleanup) @@ -149,6 +175,7 @@ export async function handleDeleteRig( c: Context, params: { userId: string; rigId: string } ) { + if (c.get('kiloUserId') !== params.userId) return c.json(resError('Forbidden'), 403); const userDO = getGastownUserStub(c.env, params.userId); const rig = await userDO.getRigAsync(params.rigId); if (!rig) return c.json(resError('Rig not found'), 404); diff --git a/services/gastown/src/middleware/org-auth.middleware.test.ts b/services/gastown/src/middleware/org-auth.middleware.test.ts new file mode 100644 index 0000000000..751f1ea5f7 --- /dev/null +++ b/services/gastown/src/middleware/org-auth.middleware.test.ts @@ -0,0 +1,86 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { Hono } from 'hono'; +import type { GastownEnv } from '../gastown.worker'; + +const mocks = vi.hoisted(() => { + class UnavailableError extends Error {} + return { authorizeOrganization: vi.fn(), UnavailableError }; +}); + +vi.mock('../util/town-authorization.util', () => ({ + authorizeOrganization: mocks.authorizeOrganization, + TownAuthorizationUnavailableError: mocks.UnavailableError, +})); + +import { orgAuthMiddleware } from './org-auth.middleware'; + +function app(values: Record) { + const result = new Hono(); + result.use('*', async (c, next) => { + for (const [key, value] of Object.entries(values)) c.set(key as never, value as never); + await next(); + }); + result.use('/api/orgs/:orgId/*', orgAuthMiddleware); + result.get('/api/orgs/:orgId/towns', c => c.text(c.get('orgRole') ?? 'missing')); + return result; +} + +describe('orgAuthMiddleware', () => { + beforeEach(() => vi.resetAllMocks()); + + it.each([ + ['removed member', null], + ['demoted member', null], + ['missing pepper', null], + ['mismatched pepper', null], + ['blocked user', null], + ['deleted organization', null], + ])('rejects a modern %s', async (_name, authorization) => { + mocks.authorizeOrganization.mockResolvedValue(authorization); + const response = await app({ + kiloUserId: 'user-1', + kiloUsesModernToken: true, + kiloApiTokenPepper: 'stale', + kiloOrgMemberships: [{ orgId: 'org-1', role: 'owner' }], + }).request('/api/orgs/org-1/towns', {}, {} as Env); + + expect(response.status).toBe(403); + }); + + it('uses the fresh role for a modern request', async () => { + mocks.authorizeOrganization.mockResolvedValue({ role: 'member' }); + const response = await app({ + kiloUserId: 'user-1', + kiloUsesModernToken: true, + kiloApiTokenPepper: 'current', + kiloOrgMemberships: [{ orgId: 'org-1', role: 'owner' }], + }).request('/api/orgs/org-1/towns', {}, {} as Env); + + expect(response.status).toBe(200); + expect(await response.text()).toBe('member'); + }); + + it('fails closed when modern authorization is unavailable', async () => { + mocks.authorizeOrganization.mockRejectedValue(new mocks.UnavailableError()); + const response = await app({ + kiloUserId: 'user-1', + kiloUsesModernToken: true, + kiloApiTokenPepper: 'current', + }).request('/api/orgs/org-1/towns', {}, {} as Env); + + expect(response.status).toBe(503); + }); + + it('uses current authorization for a legacy request', async () => { + mocks.authorizeOrganization.mockResolvedValue({ role: 'owner' }); + const response = await app({ + kiloUserId: 'user-1', + kiloUsesModernToken: false, + kiloOrgMemberships: [{ orgId: 'org-1', role: 'owner' }], + }).request('/api/orgs/org-1/towns', {}, {} as Env); + + expect(response.status).toBe(200); + expect(await response.text()).toBe('owner'); + expect(mocks.authorizeOrganization).toHaveBeenCalledOnce(); + }); +}); diff --git a/services/gastown/src/middleware/org-auth.middleware.ts b/services/gastown/src/middleware/org-auth.middleware.ts index 7d49d85c61..e812120a25 100644 --- a/services/gastown/src/middleware/org-auth.middleware.ts +++ b/services/gastown/src/middleware/org-auth.middleware.ts @@ -2,11 +2,15 @@ import { createMiddleware } from 'hono/factory'; import type { GastownEnv } from '../gastown.worker'; import { resError } from '../util/res.util'; import { logger } from '../util/log.util'; +import { + authorizeOrganization, + TownAuthorizationUnavailableError, +} from '../util/town-authorization.util'; /** * Verifies the authenticated Kilo user is a member of the org identified - * by the `:orgId` route param, using org memberships from the JWT claims - * (set by kiloAuthMiddleware). Blocks `billing_manager` role. + * by the `:orgId` route param using current authorization. Collection routes + * can contain modern towns, so cached JWT organization claims are never safe. * * Sets `orgId` and `orgRole` on the Hono context for downstream handlers. * Must run after `kiloAuthMiddleware` (which sets `kiloUserId` and `kiloOrgMemberships`). @@ -17,14 +21,27 @@ export const orgAuthMiddleware = createMiddleware(async (c, next) => const userId = c.get('kiloUserId'); if (!userId) return c.json(resError('Authentication required'), 401); - const memberships = c.get('kiloOrgMemberships') ?? []; - const membership = memberships.find(m => m.orgId === orgId); - if (!membership) return c.json(resError('Not an org member'), 403); - if (membership.role === 'billing_manager') - return c.json(resError('Insufficient permissions'), 403); + let role: string; + try { + const authorization = await authorizeOrganization( + c.env, + orgId, + userId, + c.get('kiloApiTokenPepper') + ); + if (!authorization || !('role' in authorization)) { + return c.json(resError('Not an org member'), 403); + } + role = authorization.role; + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) { + return c.json(resError('Authorization unavailable'), 503); + } + throw error; + } c.set('orgId', orgId); - c.set('orgRole', membership.role); + c.set('orgRole', role); logger.setTags({ orgId }); await next(); }); diff --git a/services/gastown/src/middleware/town-auth.middleware.test.ts b/services/gastown/src/middleware/town-auth.middleware.test.ts new file mode 100644 index 0000000000..4f2175a6ff --- /dev/null +++ b/services/gastown/src/middleware/town-auth.middleware.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from 'vitest'; +import { Hono } from 'hono'; +import type { GastownEnv } from '../gastown.worker'; + +const mocks = vi.hoisted(() => ({ getTownIdentityState: vi.fn(), authorizeTown: vi.fn() })); + +vi.mock('../dos/Town.do', () => ({ + getTownDOStub: () => ({ getTownIdentityState: mocks.getTownIdentityState }), +})); +vi.mock('../util/town-authorization.util', () => ({ + authorizeTown: mocks.authorizeTown, + TownAuthorizationUnavailableError: class extends Error {}, +})); + +import { townAuthMiddleware } from './town-auth.middleware'; + +describe('townAuthMiddleware', () => { + it('uses fresh modern authorization instead of the cached admin claim', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { ownerType: 'user', ownerUserId: 'owner', runtimeMode: 'modern' }, + }); + mocks.authorizeTown.mockResolvedValue(null); + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('kiloUserId', 'stale-admin'); + c.set('kiloIsAdmin', true); + c.set('kiloApiTokenPepper', 'pepper'); + await next(); + }); + app.use('/api/towns/:townId/*', townAuthMiddleware); + app.get('/api/towns/:townId/config', c => c.text('allowed')); + + expect((await app.request('/api/towns/town-1/config', {}, {} as Env)).status).toBe(403); + }); + + it('preserves the cached admin bypass for legacy towns', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'legacy', + identity: { ownerType: 'user', ownerUserId: 'owner', runtimeMode: 'legacy' }, + }); + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('kiloUserId', 'admin'); + c.set('kiloIsAdmin', true); + await next(); + }); + app.use('/api/towns/:townId/*', townAuthMiddleware); + app.get('/api/towns/:townId/config', c => c.text('allowed')); + + expect((await app.request('/api/towns/town-1/config', {}, {} as Env)).status).toBe(200); + }); + + it('fails closed for an invalid persisted authorization state', async () => { + mocks.getTownIdentityState.mockResolvedValue({ type: 'invalid' }); + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('kiloUserId', 'user-1'); + c.set('kiloIsAdmin', true); + await next(); + }); + app.use('/api/towns/:townId/*', townAuthMiddleware); + app.get('/api/towns/:townId/config', c => c.text('allowed')); + + expect((await app.request('/api/towns/town-1/config', {}, {} as Env)).status).toBe(403); + }); +}); diff --git a/services/gastown/src/middleware/town-auth.middleware.ts b/services/gastown/src/middleware/town-auth.middleware.ts index 9d1f19657d..74df293ffc 100644 --- a/services/gastown/src/middleware/town-auth.middleware.ts +++ b/services/gastown/src/middleware/town-auth.middleware.ts @@ -2,6 +2,7 @@ import { createMiddleware } from 'hono/factory'; import type { GastownEnv } from '../gastown.worker'; import { getTownDOStub } from '../dos/Town.do'; import { resError } from '../util/res.util'; +import { authorizeTown, TownAuthorizationUnavailableError } from '../util/town-authorization.util'; /** * For user-facing /api/towns/:townId/* routes, verifies the caller is @@ -17,10 +18,41 @@ export const townAuthMiddleware = createMiddleware(async (c, next) = const userId = c.get('kiloUserId'); if (!userId) return c.json(resError('Authentication required'), 401); - // Admins bypass ownership checks - if (c.get('kiloIsAdmin')) return next(); - const townStub = getTownDOStub(c.env, townId); + const identityState = await townStub.getTownIdentityState(); + if (identityState.type === 'invalid') { + return c.json(resError('Town authorization state is invalid'), 403); + } + const identity = identityState.identity; + if (identityState.type === 'modern') { + try { + const authorization = await authorizeTown( + c.env, + identityState.identity, + userId, + c.get('kiloApiTokenPepper') + ); + if (!authorization) return c.json(resError('Forbidden'), 403); + return next(); + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) { + return c.json(resError('Authorization unavailable'), 503); + } + throw error; + } + } + if (identity) { + if (c.get('kiloIsAdmin')) return next(); + if (identity.ownerType === 'user') { + if (identity.ownerUserId !== userId) return c.json(resError('Forbidden'), 403); + return next(); + } + const memberships = c.get('kiloOrgMemberships') ?? []; + const membership = memberships.find(value => value.orgId === identity.organizationId); + if (!membership || membership.role === 'billing_manager') + return c.json(resError('Forbidden'), 403); + return next(); + } let config; try { config = await townStub.getTownConfig(); diff --git a/services/gastown/src/trpc/init.ts b/services/gastown/src/trpc/init.ts index bea8bb9b6d..715d9c5142 100644 --- a/services/gastown/src/trpc/init.ts +++ b/services/gastown/src/trpc/init.ts @@ -11,6 +11,8 @@ export type TRPCContext = { apiTokenPepper: string | null; gastownAccess: boolean; orgMemberships: JwtOrgMembership[]; + controlToken: string; + usesModernToken: boolean; }; const t = initTRPC.context().create(); diff --git a/services/gastown/src/trpc/router.ts b/services/gastown/src/trpc/router.ts index 2936ae72f0..44c1b92787 100644 --- a/services/gastown/src/trpc/router.ts +++ b/services/gastown/src/trpc/router.ts @@ -16,6 +16,10 @@ import { getGastownOrgStub } from '../dos/GastownOrg.do'; import type { JwtOrgMembership } from '../middleware/auth.middleware'; import { generateKiloApiToken } from '../util/kilo-token.util'; import { resolveSecret } from '../util/secret.util'; +import { + LegacyTownTokenRenewalUnavailableError, + resolveLegacyTownTokenOwner, +} from '../dos/town/legacy-token-renewal'; import { TownConfigSchema, TownConfigUpdateSchema, RigOverrideConfigSchema } from '../types'; import { resolveModel } from '../dos/town/config'; import type { UserRigRecord } from '../db/tables/user-rigs.table'; @@ -39,6 +43,11 @@ import { } from './schemas'; import type { TRPCContext } from './init'; import { ContainerBillingError } from '../billing/ContainerBilling.error'; +import { + authorizeOrganization, + authorizeTown, + TownAuthorizationUnavailableError, +} from '../util/town-authorization.util'; // rpcSafe wrapper for TownConfigSchema (imported from ../types, not ./schemas) const RpcTownConfigSchema = z.any().pipe(TownConfigSchema); @@ -122,6 +131,11 @@ function listAccessibleOrgIds(memberships: JwtOrgMembership[]): string[] { * personal vs org ownership in tRPC procedures. */ type RigOwnerStub = { + getTownAsync(townId: string): Promise<{ + owner_user_id?: string; + owner_org_id?: string; + created_by_user_id?: string; + } | null>; listRigs(townId: string): Promise; createRig(input: { town_id: string; @@ -147,7 +161,7 @@ type TownOwnershipResult = updated_at: string; }; } - | { type: 'org'; stub: RigOwnerStub; orgId: string } + | { type: 'org'; stub: RigOwnerStub; orgId: string; role: string } | { type: 'admin' }; /** @@ -158,12 +172,43 @@ type TownOwnershipResult = * support/debugging purposes. The caller is responsible for restricting * destructive mutations (delete, billing config) when the result type is 'admin'. */ -async function resolveTownOwnership( +export async function resolveTownOwnership( env: Env, ctx: TRPCContext, townId: string ): Promise { const { userId, isAdmin, orgMemberships: memberships } = ctx; + const townStub = getTownDOStub(env, townId); + const identityState = await townStub.getTownIdentityState(); + if (identityState.type === 'invalid') { + throw new TRPCError({ code: 'FORBIDDEN', message: 'Town authorization state is invalid' }); + } + if (identityState.type === 'modern') { + const identity = identityState.identity; + let authorization; + try { + authorization = await authorizeTown(env, identity, userId, ctx.apiTokenPepper); + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) { + throw new TRPCError({ code: 'SERVICE_UNAVAILABLE', message: 'Authorization unavailable' }); + } + throw error; + } + if (!authorization) throw new TRPCError({ code: 'FORBIDDEN', message: 'Forbidden' }); + if (authorization.type === 'admin') return { type: 'admin' }; + if (authorization.type === 'org') { + return { + type: 'org', + stub: getGastownOrgStub(env, authorization.organizationId), + orgId: authorization.organizationId, + role: authorization.role, + }; + } + const ownerStub = getGastownUserStub(env, identity.ownerUserId); + const town = await ownerStub.getTownAsync(townId); + if (!town) throw new TRPCError({ code: 'NOT_FOUND', message: 'Town not found' }); + return { type: 'user', stub: ownerStub, town }; + } // Fast path: personal town lookup const userStub = getGastownUserStub(env, userId); @@ -178,7 +223,6 @@ async function resolveTownOwnership( } // Check TownDO config for org ownership, verify via JWT claims - const townStub = getTownDOStub(env, townId); let config; try { config = await townStub.getTownConfig(); @@ -199,6 +243,7 @@ async function resolveTownOwnership( type: 'org', stub: getGastownOrgStub(env, config.organization_id), orgId: config.organization_id, + role: membership.role, }; } @@ -207,6 +252,41 @@ async function resolveTownOwnership( throw new TRPCError({ code: 'NOT_FOUND', message: 'Town not found' }); } +/** Authorize organization collection routes with current authority. */ +async function authorizeOrgCollection(ctx: TRPCContext, organizationId: string): Promise { + try { + const authorization = await authorizeOrganization( + ctx.env, + organizationId, + ctx.userId, + ctx.apiTokenPepper + ); + if (!authorization || !('role' in authorization)) throw new TRPCError({ code: 'FORBIDDEN' }); + return authorization.role; + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) { + throw new TRPCError({ code: 'SERVICE_UNAVAILABLE', message: 'Authorization unavailable' }); + } + throw error; + } +} + +/** A modern town always uses its freshly-resolved role, even for a legacy bearer. */ +async function authorizeExistingOrgTown( + ctx: TRPCContext, + organizationId: string, + townId: string +): Promise { + const ownership = await resolveTownOwnership(ctx.env, ctx, townId); + if (ownership.type === 'org') { + if (ownership.orgId !== organizationId) throw new TRPCError({ code: 'FORBIDDEN' }); + return ownership.role; + } + // Preserve the existing collection-level platform-admin policy. This also + // handles legacy towns, whose authorization remains claim-based. + return authorizeOrgCollection(ctx, organizationId); +} + /** Resolve the DO stub that owns rigs/towns. Verifies access via JWT claims. */ async function resolveRigOwnerStub( env: Env, @@ -290,7 +370,10 @@ async function verifyRigOwnership(env: Env, ctx: TRPCContext, rigId: string, tow // Fast path: personal rig lookup const userStub = getGastownUserStub(env, userId); const personalRig = await userStub.getRigAsync(rigId); - if (personalRig) return personalRig; + if (personalRig) { + await resolveTownOwnership(env, ctx, personalRig.town_id); + return personalRig; + } // Check org DOs in parallel (billing_manager excluded) const orgIds = listAccessibleOrgIds(memberships); @@ -299,7 +382,10 @@ async function verifyRigOwnership(env: Env, ctx: TRPCContext, rigId: string, tow orgIds.map(orgId => getGastownOrgStub(env, orgId).getRigAsync(rigId)) ); const orgRig = results.find(r => r !== null); - if (orgRig) return orgRig; + if (orgRig) { + await resolveTownOwnership(env, ctx, orgRig.town_id); + return orgRig; + } } // Admin bypass: resolve the real owner from TownDO config so we can @@ -359,10 +445,25 @@ export const gastownRouter = router({ const userStub = getGastownUserStub(ctx.env, user.id); const town = await userStub.createTown({ name: input.name, owner_user_id: user.id }); - // Store kilocode token so agents can auth with the Kilo LLM gateway - const kilocodeToken = await mintKilocodeToken(ctx.env, user); const townStub = getTownDOStub(ctx.env, town.id); await townStub.setTownId(town.id); + const runtime = await townStub.initializeTownIdentityAndRuntimeAuthorization( + { + ownerType: 'user', + ownerUserId: user.id, + createdByUserId: user.id, + runtimeMode: 'legacy', + }, + ctx.controlToken + ); + if (runtime.modernControl && !runtime.runtimeToken) { + await userStub.deleteTown(town.id); + throw new TRPCError({ + code: 'FORBIDDEN', + message: 'A current Gastown control token is required', + }); + } + const kilocodeToken = runtime.runtimeToken ?? (await mintKilocodeToken(ctx.env, user)); await townStub.updateTownConfig({ kilocode_token: kilocodeToken, owner_user_id: user.id, @@ -443,8 +544,7 @@ export const gastownRouter = router({ } const ownership = await resolveTownOwnership(ctx.env, ctx, input.townId); if (ownership.type === 'org') { - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); - if (!membership || membership.role !== 'owner') { + if (ownership.role !== 'owner') { throw new TRPCError({ code: 'FORBIDDEN', message: 'Only org owners can delete towns' }); } } @@ -491,6 +591,7 @@ export const gastownRouter = router({ const ownerStub = ownership.stub; const townStub = getTownDOStub(ctx.env, input.townId); + const requiresRuntimeAuthorization = await townStub.requiresRuntimeAuthorization(); // For org towns, use the town owner's identity for credentials; // for personal towns the caller is always the owner. @@ -501,7 +602,7 @@ export const gastownRouter = router({ // have their own api_token_pepper in ctx). For org towns where // a non-owner member adds a rig, keep the existing town token. let kilocodeToken: string | undefined; - if (credentialUserId === user.id) { + if (!requiresRuntimeAuthorization && credentialUserId === user.id) { kilocodeToken = await mintKilocodeToken(ctx.env, user); await townStub.updateTownConfig({ kilocode_token: kilocodeToken }); } @@ -536,7 +637,7 @@ export const gastownRouter = router({ gitUrl: input.gitUrl, defaultBranch: input.defaultBranch, userId: credentialUserId, - kilocodeToken, + kilocodeToken: requiresRuntimeAuthorization ? undefined : kilocodeToken, platformIntegrationId: input.platformIntegrationId, }); await townStub.addRig({ @@ -594,8 +695,7 @@ export const gastownRouter = router({ }); } if (ownership.type === 'org') { - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); - if (!membership || membership.role !== 'owner') { + if (ownership.role !== 'owner') { throw new TRPCError({ code: 'FORBIDDEN', message: 'Only org owners can delete rigs' }); } } @@ -632,8 +732,7 @@ export const gastownRouter = router({ if (ownership.type === 'org') { const townStubForCheck = getTownDOStub(ctx.env, rig.town_id); const townConfig = await townStubForCheck.getTownConfig(); - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); - const isOrgOwner = membership?.role === 'owner'; + const isOrgOwner = ownership.role === 'owner'; const isTownCreator = ctx.userId === townConfig.created_by_user_id; if (!isOrgOwner && !isTownCreator) { throw new TRPCError({ @@ -1051,9 +1150,8 @@ export const gastownRouter = router({ const town = getTownDOStub(ctx.env, input.townId); if (ownership.type === 'org') { - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); const townConfig = await town.getTownConfig(); - const isOrgOwner = membership?.role === 'owner'; + const isOrgOwner = ownership.role === 'owner'; const isTownCreator = ctx.userId === townConfig.created_by_user_id; if (!isOrgOwner && !isTownCreator) { throw new TRPCError({ @@ -1222,8 +1320,7 @@ export const gastownRouter = router({ // Mask secrets for non-owner, non-creator org members if (ownership.type === 'org') { - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); - const isOrgOwner = membership?.role === 'owner'; + const isOrgOwner = ownership.role === 'owner'; const isTownCreator = ctx.userId === config.created_by_user_id; if (!isOrgOwner && !isTownCreator) { const mask = (s?: string) => (s ? '****' + s.slice(-4) : undefined); @@ -1265,23 +1362,12 @@ export const gastownRouter = router({ }); } - // Strip ownership fields — only the system (createTown flows) should set these - const { - owner_user_id: _a, - owner_type: _b, - owner_id: _c, - organization_id: _d, - created_by_user_id: _e, - ...safeConfig - } = input.config; - const townStub = getTownDOStub(ctx.env, input.townId); const existingConfig = await townStub.getTownConfig(); // For org towns, only owners or the town creator can update config if (ownership.type === 'org') { - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); - const isOrgOwner = membership?.role === 'owner'; + const isOrgOwner = ownership.role === 'owner'; const isTownCreator = ctx.userId === existingConfig.created_by_user_id; if (!isOrgOwner && !isTownCreator) { throw new TRPCError({ @@ -1290,7 +1376,7 @@ export const gastownRouter = router({ }); } } - const result = await townStub.updateTownConfig(safeConfig); + const result = await townStub.updateTownConfig(input.config); // Push updated env vars to the running container so changes // take effect without a container restart @@ -1347,48 +1433,165 @@ export const gastownRouter = router({ }); } const townStub = getTownDOStub(ctx.env, input.townId); + const runtimeRefresh = await townStub.refreshRuntimeAuthorizationForManualRefresh(); + if (runtimeRefresh === 'revoked') { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'Town runtime requires reauthorization', + }); + } + if (runtimeRefresh === 'unavailable') { + throw new TRPCError({ + code: 'SERVICE_UNAVAILABLE', + message: 'Runtime authorization unavailable', + }); + } + + if (runtimeRefresh === 'renewed') { + await townStub.forceRefreshContainerToken(); + return; + } + + let identityState = await townStub.getTownIdentityState(); + if (identityState.type !== 'legacy') { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'Town legacy authorization is unavailable', + }); + } + if (!identityState.identity) { + const identity = + ownership.type === 'user' + ? { + ownerType: 'user' as const, + ownerUserId: ownership.town.owner_user_id, + createdByUserId: ownership.town.owner_user_id, + runtimeMode: 'legacy' as const, + } + : ownership.type === 'org' + ? await (async () => { + const town = await ownership.stub.getTownAsync(input.townId); + if (!town || town.owner_org_id !== ownership.orgId || !town.created_by_user_id) { + return null; + } + return { + ownerType: 'org' as const, + ownerUserId: town.created_by_user_id, + organizationId: ownership.orgId, + createdByUserId: town.created_by_user_id, + runtimeMode: 'legacy' as const, + }; + })() + : null; + if (!identity) { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'Town legacy authorization is unavailable', + }); + } + await Promise.resolve(townStub.initializePrivateTownIdentity(identity)).catch( + () => undefined + ); + identityState = await townStub.getTownIdentityState(); + const organizationId = 'organizationId' in identity ? identity.organizationId : undefined; + if ( + identityState.type !== 'legacy' || + !identityState.identity || + identityState.identity.ownerType !== identity.ownerType || + identityState.identity.ownerUserId !== identity.ownerUserId || + identityState.identity.organizationId !== organizationId || + identityState.identity.createdByUserId !== identity.createdByUserId || + identityState.identity.runtimeMode !== 'legacy' + ) { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'Town legacy authorization is unavailable', + }); + } + } + let tokenUser; + try { + tokenUser = await resolveLegacyTownTokenOwner(ctx.env, identityState.identity, { + id: ctx.userId, + apiTokenPepper: ctx.apiTokenPepper, + }); + } catch (error) { + if (error instanceof LegacyTownTokenRenewalUnavailableError) { + throw new TRPCError({ + code: 'SERVICE_UNAVAILABLE', + message: 'Legacy token authorization unavailable', + }); + } + throw error; + } + if (!tokenUser) { + throw new TRPCError({ code: 'FORBIDDEN', message: 'Legacy token authorization revoked' }); + } await townStub.forceRefreshContainerToken(); + const newKilocodeToken = await mintKilocodeToken(ctx.env, tokenUser); + await townStub.updateTownConfig({ kilocode_token: newKilocodeToken }); + await townStub.syncConfigToContainer(); + }), - // Also remint and push KILOCODE_TOKEN — this is what actually - // authenticates GT tool calls and is the main reason users hit 401s. - // For personal towns the caller IS the owner; for org towns we must - // use the town owner's identity (not the caller's) so that - // git-credentials and other owner-scoped APIs continue to work. - let tokenUser: { id: string; api_token_pepper: string | null }; - if (ownership.type === 'user') { - tokenUser = userFromCtx(ctx); - } else { - // Org town: resolve the owner from the town config - const config = await townStub.getTownConfig(); - const ownerId = config.owner_user_id ?? config.created_by_user_id; - if (ownerId && ownerId === ctx.userId) { - // Caller happens to be the owner — use their live context - tokenUser = userFromCtx(ctx); - } else if (ownerId) { - // Different org member — look up the owner's pepper from the DB - if (!ctx.env.HYPERDRIVE) { - throw new TRPCError({ - code: 'INTERNAL_SERVER_ERROR', - message: 'HYPERDRIVE binding not configured — cannot resolve town owner', - }); - } - const { findUserById } = await import('../util/user-db.util'); - const ownerUser = await findUserById(ctx.env.HYPERDRIVE.connectionString, ownerId); - if (!ownerUser) { + reauthorizeRuntime: gastownProcedure + .input(z.object({ townId: z.string().uuid() })) + .mutation(async ({ ctx, input }) => { + const town = getTownDOStub(ctx.env, input.townId); + const identityState = await town.getTownIdentityState(); + if (identityState.type === 'invalid') { + throw new TRPCError({ code: 'FORBIDDEN', message: 'Town authorization state is invalid' }); + } + const identity = identityState.identity; + if (!identity) { + throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Town requires recreation' }); + } + let modernAuthorization; + if (identityState.type === 'modern') { + try { + modernAuthorization = await authorizeTown( + ctx.env, + identity, + ctx.userId, + ctx.apiTokenPepper + ); + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) { throw new TRPCError({ - code: 'INTERNAL_SERVER_ERROR', - message: 'Town owner not found — cannot refresh KILOCODE_TOKEN', + code: 'SERVICE_UNAVAILABLE', + message: 'Authorization unavailable', }); } - tokenUser = { id: ownerUser.id, api_token_pepper: ownerUser.api_token_pepper }; - } else { - // No owner recorded — fall back to caller - tokenUser = userFromCtx(ctx); + throw error; + } + if (!modernAuthorization) throw new TRPCError({ code: 'FORBIDDEN' }); + if ( + identity.ownerType === 'org' && + (modernAuthorization.type !== 'org' || modernAuthorization.role !== 'owner') + ) { + throw new TRPCError({ code: 'FORBIDDEN' }); } } - const newKilocodeToken = await mintKilocodeToken(ctx.env, tokenUser); - await townStub.updateTownConfig({ kilocode_token: newKilocodeToken }); - await townStub.syncConfigToContainer(); + if (identity.ownerType === 'user' && identity.ownerUserId !== ctx.userId) { + throw new TRPCError({ code: 'FORBIDDEN' }); + } + if (identity.ownerType === 'org' && identity.runtimeMode !== 'modern') { + const membership = getOrgMembership(ctx.orgMemberships, identity.organizationId ?? ''); + if (!membership || membership.role !== 'owner') { + throw new TRPCError({ code: 'FORBIDDEN' }); + } + } + const authorized = await town.reauthorizeRuntime( + ctx.controlToken, + ctx.userId, + identity.organizationId + ); + if (!authorized) { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'Town runtime cannot be reauthorized', + }); + } + return { reauthorized: true }; }), forceRestartContainer: gastownProcedure @@ -1404,8 +1607,7 @@ export const gastownRouter = router({ if (ownership.type === 'org') { const townStub = getTownDOStub(ctx.env, input.townId); const config = await townStub.getTownConfig(); - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); - const isOrgOwner = membership?.role === 'owner'; + const isOrgOwner = ownership.role === 'owner'; const isTownCreator = ctx.userId === config.created_by_user_id; if (!isOrgOwner && !isTownCreator) { throw new TRPCError({ @@ -1433,8 +1635,7 @@ export const gastownRouter = router({ if (ownership.type === 'org') { const townStub = getTownDOStub(ctx.env, input.townId); const config = await townStub.getTownConfig(); - const membership = getOrgMembership(ctx.orgMemberships, ownership.orgId); - const isOrgOwner = membership?.role === 'owner'; + const isOrgOwner = ownership.role === 'owner'; const isTownCreator = ctx.userId === config.created_by_user_id; if (!isOrgOwner && !isTownCreator) { throw new TRPCError({ @@ -1576,9 +1777,7 @@ export const gastownRouter = router({ .input(z.object({ organizationId: z.string().uuid() })) .output(z.array(RpcOrgTownOutput)) .query(async ({ input, ctx }) => { - const membership = getOrgMembership(ctx.orgMemberships, input.organizationId); - if (!membership || membership.role === 'billing_manager') - throw new TRPCError({ code: 'FORBIDDEN' }); + await authorizeOrgCollection(ctx, input.organizationId); const stub = getGastownOrgStub(ctx.env, input.organizationId); return stub.listTowns(); }), @@ -1587,9 +1786,7 @@ export const gastownRouter = router({ .input(z.object({ organizationId: z.string().uuid(), name: z.string().min(1).max(64) })) .output(RpcOrgTownOutput) .mutation(async ({ input, ctx }) => { - const membership = getOrgMembership(ctx.orgMemberships, input.organizationId); - if (!membership || membership.role === 'billing_manager') - throw new TRPCError({ code: 'FORBIDDEN' }); + await authorizeOrgCollection(ctx, input.organizationId); const stub = getGastownOrgStub(ctx.env, input.organizationId); const town = await stub.createTown({ name: input.name, @@ -1597,12 +1794,27 @@ export const gastownRouter = router({ created_by_user_id: ctx.userId, }); - // Mint kilocode token so the mayor can start without waiting for rig creation - const user = userFromCtx(ctx); - const kilocodeToken = await mintKilocodeToken(ctx.env, user); - const townStub = getTownDOStub(ctx.env, town.id); await townStub.setTownId(town.id); + const runtime = await townStub.initializeTownIdentityAndRuntimeAuthorization( + { + ownerType: 'org', + ownerUserId: ctx.userId, + organizationId: input.organizationId, + createdByUserId: ctx.userId, + runtimeMode: 'legacy', + }, + ctx.controlToken + ); + if (runtime.modernControl && !runtime.runtimeToken) { + await stub.deleteTown(town.id); + throw new TRPCError({ + code: 'FORBIDDEN', + message: 'A current Gastown control token is required', + }); + } + const kilocodeToken = + runtime.runtimeToken ?? (await mintKilocodeToken(ctx.env, userFromCtx(ctx))); await townStub.updateTownConfig({ kilocode_token: kilocodeToken, owner_type: 'org', @@ -1618,11 +1830,13 @@ export const gastownRouter = router({ deleteOrgTown: gastownProcedure .input(z.object({ organizationId: z.string().uuid(), townId: z.string().uuid() })) .mutation(async ({ input, ctx }) => { - const membership = getOrgMembership(ctx.orgMemberships, input.organizationId); - if (!membership || membership.role !== 'owner') throw new TRPCError({ code: 'FORBIDDEN' }); + const role = await authorizeOrgCollection(ctx, input.organizationId); + if (role !== 'owner') throw new TRPCError({ code: 'FORBIDDEN' }); const stub = getGastownOrgStub(ctx.env, input.organizationId); const town = await stub.getTownAsync(input.townId); if (!town) throw new TRPCError({ code: 'NOT_FOUND', message: 'Town not found' }); + const townRole = await authorizeExistingOrgTown(ctx, input.organizationId, input.townId); + if (townRole !== 'owner') throw new TRPCError({ code: 'FORBIDDEN' }); // Destroy the Town DO (handles all rigs, agents, and mayor cleanup) try { @@ -1642,12 +1856,11 @@ export const gastownRouter = router({ .input(z.object({ organizationId: z.string().uuid(), townId: z.string().uuid() })) .output(z.array(RpcRigOutput)) .query(async ({ input, ctx }) => { - const membership = getOrgMembership(ctx.orgMemberships, input.organizationId); - if (!membership || membership.role === 'billing_manager') - throw new TRPCError({ code: 'FORBIDDEN' }); + await authorizeOrgCollection(ctx, input.organizationId); const stub = getGastownOrgStub(ctx.env, input.organizationId); const town = await stub.getTownAsync(input.townId); if (!town) throw new TRPCError({ code: 'NOT_FOUND', message: 'Town not found' }); + await authorizeExistingOrgTown(ctx, input.organizationId, input.townId); return stub.listRigs(input.townId); }), @@ -1664,22 +1877,22 @@ export const gastownRouter = router({ ) .output(RpcRigOutput) .mutation(async ({ input, ctx }) => { - const membership = getOrgMembership(ctx.orgMemberships, input.organizationId); - if (!membership || membership.role === 'billing_manager') - throw new TRPCError({ code: 'FORBIDDEN' }); + await authorizeOrgCollection(ctx, input.organizationId); const orgStub = getGastownOrgStub(ctx.env, input.organizationId); const town = await orgStub.getTownAsync(input.townId); if (!town) throw new TRPCError({ code: 'NOT_FOUND', message: 'Town not found' }); + await authorizeExistingOrgTown(ctx, input.organizationId, input.townId); const townStub = getTownDOStub(ctx.env, input.townId); + const requiresRuntimeAuthorization = await townStub.requiresRuntimeAuthorization(); // Use the town owner's identity for credentials. Only re-mint the // kilocode token if the caller is the owner (they have their pepper // in ctx). For non-owner members, keep the existing town token. const townConfig = await townStub.getTownConfig(); const credentialUserId = townConfig.owner_user_id ?? ctx.userId; let kilocodeToken: string | undefined; - if (credentialUserId === ctx.userId) { + if (!requiresRuntimeAuthorization && credentialUserId === ctx.userId) { kilocodeToken = await mintKilocodeToken(ctx.env, userFromCtx(ctx)); await townStub.updateTownConfig({ kilocode_token: kilocodeToken }); } @@ -1712,7 +1925,7 @@ export const gastownRouter = router({ gitUrl: input.gitUrl, defaultBranch: input.defaultBranch, userId: credentialUserId, - kilocodeToken, + kilocodeToken: requiresRuntimeAuthorization ? undefined : kilocodeToken, platformIntegrationId: input.platformIntegrationId, }); await townStub.addRig({ diff --git a/services/gastown/src/trpc/town-authorization.router.test.ts b/services/gastown/src/trpc/town-authorization.router.test.ts new file mode 100644 index 0000000000..63ef0a7a7e --- /dev/null +++ b/services/gastown/src/trpc/town-authorization.router.test.ts @@ -0,0 +1,409 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { TRPCContext } from './init'; + +const mocks = vi.hoisted(() => ({ + getTownIdentityState: vi.fn(), + getTownAsync: vi.fn(), + authorizeOrganization: vi.fn(), + listTowns: vi.fn(), + authorizeTown: vi.fn(), + refreshRuntimeAuthorizationForManualRefresh: vi.fn(), + forceRefreshContainerToken: vi.fn(), + updateTownConfig: vi.fn(), + syncConfigToContainer: vi.fn(), + getTownConfig: vi.fn(), + initializePrivateTownIdentity: vi.fn(), + resolveLegacyTownTokenOwner: vi.fn(), + generateKiloApiToken: vi.fn(), +})); + +vi.mock('cloudflare:workers', () => ({})); +vi.mock('../dos/Town.do', () => ({ + getTownDOStub: () => ({ + getTownIdentityState: mocks.getTownIdentityState, + requiresRuntimeAuthorization: vi.fn(), + refreshRuntimeAuthorizationForManualRefresh: mocks.refreshRuntimeAuthorizationForManualRefresh, + forceRefreshContainerToken: mocks.forceRefreshContainerToken, + updateTownConfig: mocks.updateTownConfig, + syncConfigToContainer: mocks.syncConfigToContainer, + getTownConfig: mocks.getTownConfig, + initializePrivateTownIdentity: mocks.initializePrivateTownIdentity, + }), +})); +vi.mock('../dos/TownContainer.do', () => ({ getTownContainerStub: vi.fn() })); +vi.mock('../dos/GastownUser.do', () => ({ + getGastownUserStub: () => ({ getTownAsync: mocks.getTownAsync }), +})); +vi.mock('../dos/GastownOrg.do', () => ({ + getGastownOrgStub: () => ({ getTownAsync: mocks.getTownAsync, listTowns: mocks.listTowns }), +})); +vi.mock('../util/town-authorization.util', () => ({ + authorizeTown: mocks.authorizeTown, + authorizeOrganization: mocks.authorizeOrganization, + TownAuthorizationUnavailableError: class extends Error {}, +})); +vi.mock('../dos/town/legacy-token-renewal', () => ({ + LegacyTownTokenRenewalUnavailableError: class extends Error {}, + resolveLegacyTownTokenOwner: mocks.resolveLegacyTownTokenOwner, +})); +vi.mock('../util/kilo-token.util', () => ({ generateKiloApiToken: mocks.generateKiloApiToken })); +vi.mock('../util/secret.util', () => ({ resolveSecret: vi.fn(() => 'secret') })); + +import { gastownRouter, resolveTownOwnership } from './router'; +import { LegacyTownTokenRenewalUnavailableError } from '../dos/town/legacy-token-renewal'; + +const env = {} as Env; +env.NEXTAUTH_SECRET = {} as Env['NEXTAUTH_SECRET']; + +const ctx = { + env, + executionCtx: {}, + userId: 'cached-admin', + isAdmin: true, + apiTokenPepper: 'pepper', + gastownAccess: true, + orgMemberships: [{ orgId: 'org-1', role: 'owner' }], + controlToken: 'token', + usesModernToken: true, +} as TRPCContext; + +describe('resolveTownOwnership', () => { + beforeEach(() => vi.resetAllMocks()); + + it('rejects a stale cached admin for another modern town', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { ownerType: 'user', ownerUserId: 'owner', runtimeMode: 'modern' }, + }); + mocks.authorizeTown.mockResolvedValue(null); + + await expect(resolveTownOwnership(ctx.env, ctx, 'town-1')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + }); + + it('allows a fresh active admin for a modern town', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { ownerType: 'user', ownerUserId: 'owner', runtimeMode: 'modern' }, + }); + mocks.authorizeTown.mockResolvedValue({ type: 'admin' }); + + await expect(resolveTownOwnership(ctx.env, ctx, 'town-1')).resolves.toEqual({ type: 'admin' }); + }); + + it('rejects a removed org member despite cached membership', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { + ownerType: 'org', + ownerUserId: 'owner', + organizationId: 'org-1', + runtimeMode: 'modern', + }, + }); + mocks.authorizeTown.mockResolvedValue(null); + + await expect(resolveTownOwnership(ctx.env, ctx, 'town-1')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + }); + + it('fails closed when persisted town authorization metadata is invalid', async () => { + mocks.getTownIdentityState.mockResolvedValue({ type: 'invalid' }); + + await expect(resolveTownOwnership(ctx.env, ctx, 'town-1')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + }); + + it('uses current organization authorization for a legacy bearer collection read', async () => { + mocks.authorizeOrganization.mockResolvedValue(null); + const legacyCtx = { ...ctx, usesModernToken: false }; + + await expect( + gastownRouter.createCaller(legacyCtx).listOrgTowns({ + organizationId: '00000000-0000-4000-8000-000000000001', + }) + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(mocks.authorizeOrganization).toHaveBeenCalledOnce(); + expect(mocks.listTowns).not.toHaveBeenCalled(); + }); + + it('renews a modern runtime without legacy reminting', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { ownerType: 'user', ownerUserId: 'cached-admin', runtimeMode: 'modern' }, + }); + mocks.authorizeTown.mockResolvedValue({ type: 'user' }); + mocks.getTownAsync.mockResolvedValue({ id: 'town-1', owner_user_id: 'cached-admin' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('renewed'); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).resolves.toBeUndefined(); + expect(mocks.forceRefreshContainerToken).toHaveBeenCalledOnce(); + expect(mocks.updateTownConfig).not.toHaveBeenCalled(); + expect(mocks.syncConfigToContainer).not.toHaveBeenCalled(); + }); + + it('rejects a revoked modern runtime before refreshing the container token', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'modern', + identity: { ownerType: 'user', ownerUserId: 'cached-admin', runtimeMode: 'modern' }, + }); + mocks.authorizeTown.mockResolvedValue({ type: 'user' }); + mocks.getTownAsync.mockResolvedValue({ id: 'town-1', owner_user_id: 'cached-admin' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('revoked'); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' }); + expect(mocks.forceRefreshContainerToken).not.toHaveBeenCalled(); + expect(mocks.updateTownConfig).not.toHaveBeenCalled(); + expect(mocks.syncConfigToContainer).not.toHaveBeenCalled(); + }); + + it('does not mint or sync a legacy token when current authorization is revoked', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'legacy', + identity: { + ownerType: 'org', + ownerUserId: 'owner-1', + organizationId: 'org-1', + runtimeMode: 'legacy', + }, + }); + mocks.getTownAsync.mockResolvedValue(null); + mocks.getTownConfig.mockResolvedValue({ owner_type: 'org', organization_id: 'org-1' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + mocks.resolveLegacyTownTokenOwner.mockResolvedValue(null); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(mocks.forceRefreshContainerToken).not.toHaveBeenCalled(); + expect(mocks.generateKiloApiToken).not.toHaveBeenCalled(); + expect(mocks.updateTownConfig).not.toHaveBeenCalled(); + expect(mocks.syncConfigToContainer).not.toHaveBeenCalled(); + }); + + it('does not mint or sync a legacy token when authorization is unavailable', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'legacy', + identity: { + ownerType: 'org', + ownerUserId: 'owner-1', + organizationId: 'org-1', + runtimeMode: 'legacy', + }, + }); + mocks.getTownAsync.mockResolvedValue(null); + mocks.getTownConfig.mockResolvedValue({ owner_type: 'org', organization_id: 'org-1' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + mocks.resolveLegacyTownTokenOwner.mockRejectedValue( + new LegacyTownTokenRenewalUnavailableError() + ); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE' }); + expect(mocks.forceRefreshContainerToken).not.toHaveBeenCalled(); + expect(mocks.generateKiloApiToken).not.toHaveBeenCalled(); + expect(mocks.updateTownConfig).not.toHaveBeenCalled(); + expect(mocks.syncConfigToContainer).not.toHaveBeenCalled(); + }); + + it('mints a legacy org town token with the current owner pepper', async () => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'legacy', + identity: { + ownerType: 'org', + ownerUserId: 'owner-1', + organizationId: 'org-1', + runtimeMode: 'legacy', + }, + }); + mocks.getTownAsync.mockResolvedValue(null); + mocks.getTownConfig.mockResolvedValue({ owner_type: 'org', organization_id: 'org-1' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + mocks.resolveLegacyTownTokenOwner.mockResolvedValue({ + id: 'owner-1', + api_token_pepper: 'owner-current', + }); + mocks.generateKiloApiToken.mockResolvedValue('new-token'); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).resolves.toBeUndefined(); + expect(mocks.forceRefreshContainerToken).toHaveBeenCalledOnce(); + expect(mocks.generateKiloApiToken).toHaveBeenCalledWith( + { id: 'owner-1', api_token_pepper: 'owner-current' }, + 'secret' + ); + expect(mocks.updateTownConfig).toHaveBeenCalledWith({ kilocode_token: 'new-token' }); + expect(mocks.syncConfigToContainer).toHaveBeenCalledOnce(); + }); + + it('migrates a personal legacy town before minting with its current owner pepper', async () => { + const identity = { + ownerType: 'user' as const, + ownerUserId: 'cached-admin', + createdByUserId: 'cached-admin', + runtimeMode: 'legacy' as const, + }; + mocks.getTownIdentityState + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity }); + mocks.getTownAsync.mockResolvedValue({ id: 'town-1', owner_user_id: 'cached-admin' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + mocks.resolveLegacyTownTokenOwner.mockResolvedValue({ + id: 'cached-admin', + api_token_pepper: 'owner-current', + }); + mocks.generateKiloApiToken.mockResolvedValue('new-token'); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).resolves.toBeUndefined(); + expect(mocks.initializePrivateTownIdentity).toHaveBeenCalledWith(identity); + expect(mocks.resolveLegacyTownTokenOwner).toHaveBeenCalledWith(env, identity, { + id: 'cached-admin', + apiTokenPepper: 'pepper', + }); + expect(mocks.generateKiloApiToken).toHaveBeenCalledWith( + { id: 'cached-admin', api_token_pepper: 'owner-current' }, + 'secret' + ); + }); + + it('migrates an org legacy town from its owner registry record', async () => { + const identity = { + ownerType: 'org' as const, + ownerUserId: 'creator-1', + organizationId: 'org-1', + createdByUserId: 'creator-1', + runtimeMode: 'legacy' as const, + }; + mocks.getTownIdentityState + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity }); + mocks.getTownAsync.mockResolvedValueOnce(null).mockResolvedValueOnce({ + id: 'town-1', + owner_org_id: 'org-1', + created_by_user_id: 'creator-1', + }); + mocks.getTownConfig.mockResolvedValue({ owner_type: 'org', organization_id: 'org-1' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + mocks.resolveLegacyTownTokenOwner.mockResolvedValue({ + id: 'creator-1', + api_token_pepper: 'owner-current', + }); + mocks.generateKiloApiToken.mockResolvedValue('new-token'); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).resolves.toBeUndefined(); + expect(mocks.initializePrivateTownIdentity).toHaveBeenCalledWith(identity); + expect(mocks.generateKiloApiToken).toHaveBeenCalledWith( + { id: 'creator-1', api_token_pepper: 'owner-current' }, + 'secret' + ); + }); + + it.each([ + ['missing', null], + ['mismatched', { id: 'town-1', owner_org_id: 'other-org', created_by_user_id: 'creator-1' }], + ])('rejects a %s org owner registry record without minting', async (_kind, registryTown) => { + mocks.getTownIdentityState + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity: null }); + mocks.getTownAsync.mockResolvedValueOnce(null).mockResolvedValueOnce(registryTown); + mocks.getTownConfig.mockResolvedValue({ owner_type: 'org', organization_id: 'org-1' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' }); + expect(mocks.initializePrivateTownIdentity).not.toHaveBeenCalled(); + expect(mocks.forceRefreshContainerToken).not.toHaveBeenCalled(); + expect(mocks.generateKiloApiToken).not.toHaveBeenCalled(); + expect(mocks.updateTownConfig).not.toHaveBeenCalled(); + expect(mocks.syncConfigToContainer).not.toHaveBeenCalled(); + }); + + it('accepts an exact identity initialized concurrently', async () => { + const identity = { + ownerType: 'user' as const, + ownerUserId: 'cached-admin', + createdByUserId: 'cached-admin', + runtimeMode: 'legacy' as const, + }; + mocks.getTownIdentityState + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity }); + mocks.getTownAsync.mockResolvedValue({ id: 'town-1', owner_user_id: 'cached-admin' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + mocks.initializePrivateTownIdentity.mockRejectedValue(new Error('already initialized')); + mocks.resolveLegacyTownTokenOwner.mockResolvedValue({ + id: 'cached-admin', + api_token_pepper: 'owner-current', + }); + mocks.generateKiloApiToken.mockResolvedValue('new-token'); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).resolves.toBeUndefined(); + expect(mocks.generateKiloApiToken).toHaveBeenCalledOnce(); + }); + + it('rejects a concurrent mismatched identity without minting', async () => { + mocks.getTownIdentityState + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ type: 'legacy', identity: null }) + .mockResolvedValueOnce({ + type: 'legacy', + identity: { + ownerType: 'user', + ownerUserId: 'other-user', + createdByUserId: 'other-user', + runtimeMode: 'legacy', + }, + }); + mocks.getTownAsync.mockResolvedValue({ id: 'town-1', owner_user_id: 'cached-admin' }); + mocks.refreshRuntimeAuthorizationForManualRefresh.mockResolvedValue('legacy'); + mocks.initializePrivateTownIdentity.mockRejectedValue(new Error('already initialized')); + + await expect( + gastownRouter.createCaller(ctx).refreshContainerToken({ + townId: '00000000-0000-4000-8000-000000000001', + }) + ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' }); + expect(mocks.resolveLegacyTownTokenOwner).not.toHaveBeenCalled(); + expect(mocks.forceRefreshContainerToken).not.toHaveBeenCalled(); + expect(mocks.generateKiloApiToken).not.toHaveBeenCalled(); + expect(mocks.updateTownConfig).not.toHaveBeenCalled(); + expect(mocks.syncConfigToContainer).not.toHaveBeenCalled(); + }); +}); diff --git a/services/gastown/src/types.runtime-authorization.test.ts b/services/gastown/src/types.runtime-authorization.test.ts new file mode 100644 index 0000000000..bb03491f09 --- /dev/null +++ b/services/gastown/src/types.runtime-authorization.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { TownConfigUpdateSchema } from './types'; + +describe('TownConfigUpdateSchema', () => { + it.each(['owner_user_id', 'owner_type', 'owner_id', 'organization_id', 'created_by_user_id'])( + 'rejects public mutation of %s', + field => { + expect(TownConfigUpdateSchema.safeParse({ [field]: 'attacker' }).success).toBe(false); + } + ); + + it('accepts ordinary public configuration', () => { + expect(TownConfigUpdateSchema.safeParse({ default_model: 'openai/gpt-5' }).success).toBe(true); + }); +}); diff --git a/services/gastown/src/types.ts b/services/gastown/src/types.ts index 01635ddcfa..fe63abb06c 100644 --- a/services/gastown/src/types.ts +++ b/services/gastown/src/types.ts @@ -395,67 +395,70 @@ export type RigOverrideConfig = z.infer; * .default() during parsing, injecting phantom values (e.g. merge_strategy: * 'direct') that overwrite existing config on partial updates. */ -export const TownConfigUpdateSchema = z.object({ - env_vars: z.record(z.string(), z.string()).optional(), - git_auth: z - .object({ - github_token: z.string().optional(), - gitlab_token: z.string().optional(), - gitlab_instance_url: z.string().optional(), - platform_integration_id: z.string().optional(), - }) - .optional(), - owner_user_id: z.string().optional(), - owner_type: z.enum(['user', 'org']).optional(), - owner_id: z.string().optional(), - created_by_user_id: z.string().optional(), - organization_id: z.string().optional(), - kilocode_token: z.string().optional(), - default_model: z.string().optional(), - role_models: z - .object({ - mayor: z.string().optional(), - refinery: z.string().optional(), - polecat: z.string().optional(), - }) - .optional(), - small_model: z.string().optional(), - max_polecats_per_rig: z.number().int().min(1).max(50).optional(), - merge_strategy: MergeStrategy.optional(), - refinery: z - .object({ - gates: z.array(z.string()).optional(), - auto_merge: z.boolean().optional(), - require_clean_merge: z.boolean().optional(), - code_review: z.boolean().optional(), - review_mode: z.enum(['rework', 'comments']).optional(), - auto_resolve_pr_feedback: z.boolean().optional(), - auto_resolve_merge_conflicts: z.boolean().optional(), - auto_merge_delay_minutes: z.number().int().min(0).nullable().optional(), - }) - .optional(), - alarm_interval_active: z.number().int().min(5).max(600).optional(), - alarm_interval_idle: z.number().int().min(30).max(3600).optional(), - container: z - .object({ - sleep_after_minutes: z.number().int().min(5).max(120).optional(), - }) - .optional(), - staged_convoys_default: z.boolean().optional(), - convoy_merge_mode: z.enum(['review-then-land', 'review-and-merge']).optional(), - github_cli_pat: z.string().optional(), - git_author_name: z.string().optional(), - git_author_email: z.string().optional(), - disable_ai_coauthor: z.boolean().optional(), - custom_instructions: z - .object({ - polecat: z.string().max(2000).optional(), - refinery: z.string().max(2000).optional(), - mayor: z.string().max(2000).optional(), - }) - .optional(), -}); -export type TownConfigUpdate = z.infer; +export const TownConfigUpdateSchema = z + .object({ + env_vars: z.record(z.string(), z.string()).optional(), + git_auth: z + .object({ + github_token: z.string().optional(), + gitlab_token: z.string().optional(), + gitlab_instance_url: z.string().optional(), + platform_integration_id: z.string().optional(), + }) + .optional(), + kilocode_token: z.string().optional(), + default_model: z.string().optional(), + role_models: z + .object({ + mayor: z.string().optional(), + refinery: z.string().optional(), + polecat: z.string().optional(), + }) + .optional(), + small_model: z.string().optional(), + max_polecats_per_rig: z.number().int().min(1).max(50).optional(), + merge_strategy: MergeStrategy.optional(), + refinery: z + .object({ + gates: z.array(z.string()).optional(), + auto_merge: z.boolean().optional(), + require_clean_merge: z.boolean().optional(), + code_review: z.boolean().optional(), + review_mode: z.enum(['rework', 'comments']).optional(), + auto_resolve_pr_feedback: z.boolean().optional(), + auto_resolve_merge_conflicts: z.boolean().optional(), + auto_merge_delay_minutes: z.number().int().min(0).nullable().optional(), + }) + .optional(), + alarm_interval_active: z.number().int().min(5).max(600).optional(), + alarm_interval_idle: z.number().int().min(30).max(3600).optional(), + container: z + .object({ + sleep_after_minutes: z.number().int().min(5).max(120).optional(), + }) + .optional(), + staged_convoys_default: z.boolean().optional(), + convoy_merge_mode: z.enum(['review-then-land', 'review-and-merge']).optional(), + github_cli_pat: z.string().optional(), + git_author_name: z.string().optional(), + git_author_email: z.string().optional(), + disable_ai_coauthor: z.boolean().optional(), + custom_instructions: z + .object({ + polecat: z.string().max(2000).optional(), + refinery: z.string().max(2000).optional(), + mayor: z.string().max(2000).optional(), + }) + .optional(), + }) + .strict(); +export type TownConfigUpdate = z.infer & + Partial< + Pick< + TownConfig, + 'owner_user_id' | 'owner_type' | 'owner_id' | 'created_by_user_id' | 'organization_id' + > + >; /** Agent-level config overrides (merged on top of town config) */ export const AgentConfigOverridesSchema = z.object({ diff --git a/services/gastown/src/util/town-authorization.util.test.ts b/services/gastown/src/util/town-authorization.util.test.ts new file mode 100644 index 0000000000..697b3c1fc3 --- /dev/null +++ b/services/gastown/src/util/town-authorization.util.test.ts @@ -0,0 +1,165 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const select = vi.fn(); + +vi.mock('@kilocode/db/client', () => ({ getWorkerDb: vi.fn(() => ({ select })) })); + +import { + authorizeOrganization, + authorizeTown, + TownAuthorizationUnavailableError, +} from './town-authorization.util'; + +const identity = { + ownerType: 'org' as const, + ownerUserId: 'owner', + organizationId: 'org-1', + runtimeMode: 'modern' as const, +}; + +function rows(...values: unknown[]) { + let index = 0; + select.mockImplementation(() => ({ + from: () => ({ + where: () => ({ limit: () => Promise.resolve(values[index++]) }), + innerJoin: () => ({ where: () => ({ limit: () => Promise.resolve(values[index++]) }) }), + }), + })); +} + +describe('authorizeTown', () => { + beforeEach(() => vi.resetAllMocks()); + + it.each([ + [ + 'stale admin', + [[{ pepper: 'pepper', blockedAt: null, blockedReason: null, isAdmin: false }], []], + ], + ['missing pepper', [[{ pepper: null, blockedAt: null, blockedReason: null, isAdmin: true }]]], + [ + 'blocked principal', + [[{ pepper: 'pepper', blockedAt: '2026-01-01', blockedReason: null, isAdmin: true }]], + ], + [ + 'null token pepper', + [[{ pepper: 'pepper', blockedAt: null, blockedReason: null, isAdmin: true }]], + ], + ])('rejects %s', async (_name, values) => { + rows(...values); + const result = await authorizeTown( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + identity, + 'user', + _name === 'null token pepper' ? null : 'pepper' + ); + expect(result).toBeNull(); + }); + + it('allows a current active admin', async () => { + rows([{ pepper: 'pepper', blockedAt: null, blockedReason: null, isAdmin: true }]); + await expect( + authorizeTown( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + identity, + 'user', + 'pepper' + ) + ).resolves.toEqual({ type: 'admin' }); + }); + + it('reports a personal-town authority database failure as unavailable', async () => { + select.mockImplementation(() => { + throw new Error('database unavailable'); + }); + await expect( + authorizeTown( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + { ...identity, ownerType: 'user', organizationId: undefined }, + 'user', + 'pepper' + ) + ).rejects.toBeInstanceOf(TownAuthorizationUnavailableError); + }); + + it('uses one principal query and one membership query for a non-admin org member', async () => { + rows( + [{ pepper: 'pepper', blockedAt: null, blockedReason: null, isAdmin: false }], + [{ role: 'member' }] + ); + await expect( + authorizeTown( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + identity, + 'user', + 'pepper' + ) + ).resolves.toEqual({ type: 'org', organizationId: 'org-1', role: 'member' }); + expect(select).toHaveBeenCalledTimes(2); + }); + + it.each([ + ['removed member', []], + ['cached billing manager role', [{ role: 'billing_manager' }]], + ])('rejects %s', async (_name, membership) => { + rows([{ pepper: 'pepper', blockedAt: null, blockedReason: null, isAdmin: false }], membership); + await expect( + authorizeTown( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + identity, + 'user', + 'pepper' + ) + ).resolves.toBeNull(); + }); +}); + +describe('authorizeOrganization', () => { + it.each([ + ['removed member', [{ pepper: 'pepper', blockedAt: null, blockedReason: null }], []], + [ + 'demoted member', + [{ pepper: 'pepper', blockedAt: null, blockedReason: null }], + [{ role: 'billing_manager' }], + ], + ['missing pepper', [{ pepper: null, blockedAt: null, blockedReason: null }], []], + ['mismatched pepper', [{ pepper: 'other', blockedAt: null, blockedReason: null }], []], + ['blocked user', [{ pepper: 'pepper', blockedAt: '2026-01-01', blockedReason: null }], []], + ['deleted organization', [{ pepper: 'pepper', blockedAt: null, blockedReason: null }], []], + ])('rejects a %s', async (_name, principal, membership) => { + rows(principal, membership); + await expect( + authorizeOrganization( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + 'org-1', + 'user', + 'pepper' + ) + ).resolves.toBeNull(); + }); + + it('returns the current membership role', async () => { + rows([{ pepper: 'pepper', blockedAt: null, blockedReason: null }], [{ role: 'member' }]); + await expect( + authorizeOrganization( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + 'org-1', + 'user', + 'pepper' + ) + ).resolves.toEqual({ role: 'member' }); + }); + + it('reports an authority database failure as unavailable', async () => { + select.mockImplementation(() => { + throw new Error('database unavailable'); + }); + await expect( + authorizeOrganization( + { HYPERDRIVE: { connectionString: 'postgres://' } } as Env, + 'org-1', + 'user', + 'pepper' + ) + ).rejects.toBeInstanceOf(TownAuthorizationUnavailableError); + }); +}); diff --git a/services/gastown/src/util/town-authorization.util.ts b/services/gastown/src/util/town-authorization.util.ts new file mode 100644 index 0000000000..9c88857ec9 --- /dev/null +++ b/services/gastown/src/util/town-authorization.util.ts @@ -0,0 +1,140 @@ +import { getWorkerDb } from '@kilocode/db/client'; +import { kilocode_users, organization_memberships, organizations } from '@kilocode/db/schema'; +import { and, eq, isNull } from 'drizzle-orm'; + +type PrivateTownIdentity = { + ownerType: 'user' | 'org'; + ownerUserId: string; + organizationId?: string; + runtimeMode: 'legacy' | 'modern'; +}; + +export type TownAuthorization = + | { type: 'user' } + | { type: 'org'; organizationId: string; role: string } + | { type: 'admin' }; + +export class TownAuthorizationUnavailableError extends Error {} + +type OrganizationAuthorization = { role: string } | { isAdmin: true }; + +export async function authorizeOrganization( + env: Pick, + organizationId: string, + userId: string, + apiTokenPepper: string | null, + options?: { allowAdmin: boolean } +): Promise { + if (!env.HYPERDRIVE) throw new TownAuthorizationUnavailableError(); + + try { + const db = getWorkerDb(env.HYPERDRIVE.connectionString, { statement_timeout: 5_000 }); + const [principal] = await db + .select({ + pepper: kilocode_users.api_token_pepper, + blockedAt: kilocode_users.blocked_at, + blockedReason: kilocode_users.blocked_reason, + isAdmin: kilocode_users.is_admin, + }) + .from(kilocode_users) + .where(eq(kilocode_users.id, userId)) + .limit(1); + + if ( + !principal || + principal.blockedAt !== null || + principal.blockedReason !== null || + !apiTokenPepper || + !principal.pepper || + principal.pepper !== apiTokenPepper + ) { + return null; + } + if (options?.allowAdmin && principal.isAdmin) return { isAdmin: true }; + + const [membership] = await db + .select({ role: organization_memberships.role }) + .from(organization_memberships) + .innerJoin(organizations, eq(organizations.id, organization_memberships.organization_id)) + .where( + and( + eq(organization_memberships.kilo_user_id, userId), + eq(organization_memberships.organization_id, organizationId), + isNull(organizations.deleted_at) + ) + ) + .limit(1); + + if (!membership || membership.role === 'billing_manager') return null; + return membership; + } catch (error) { + if (error instanceof TownAuthorizationUnavailableError) throw error; + throw new TownAuthorizationUnavailableError(); + } +} + +export async function authorizeTown( + env: Pick, + identity: PrivateTownIdentity, + userId: string, + apiTokenPepper: string | null +): Promise { + if (identity.runtimeMode !== 'modern') return null; + if (!env.HYPERDRIVE) throw new TownAuthorizationUnavailableError(); + + if (identity.ownerType === 'org') { + if (!identity.organizationId) return null; + const organizationAuthorization = await authorizeOrganization( + env, + identity.organizationId, + userId, + apiTokenPepper, + { allowAdmin: true } + ); + if (!organizationAuthorization) return null; + if ('isAdmin' in organizationAuthorization) return { type: 'admin' }; + return { + type: 'org', + organizationId: identity.organizationId, + role: organizationAuthorization.role, + }; + } + + let principal: + | { + pepper: string | null; + blockedAt: Date | string | null; + blockedReason: string | null; + isAdmin: boolean; + } + | undefined; + try { + const db = getWorkerDb(env.HYPERDRIVE.connectionString, { statement_timeout: 5_000 }); + [principal] = await db + .select({ + pepper: kilocode_users.api_token_pepper, + blockedAt: kilocode_users.blocked_at, + blockedReason: kilocode_users.blocked_reason, + isAdmin: kilocode_users.is_admin, + }) + .from(kilocode_users) + .where(eq(kilocode_users.id, userId)) + .limit(1); + } catch { + throw new TownAuthorizationUnavailableError(); + } + + if ( + !principal || + principal.blockedAt !== null || + principal.blockedReason !== null || + !apiTokenPepper || + !principal.pepper || + principal.pepper !== apiTokenPepper + ) { + return null; + } + + if (principal.isAdmin) return { type: 'admin' }; + return identity.ownerUserId === userId ? { type: 'user' } : null; +} diff --git a/services/gastown/test/integration/town-private-identity.test.ts b/services/gastown/test/integration/town-private-identity.test.ts new file mode 100644 index 0000000000..b59a14886a --- /dev/null +++ b/services/gastown/test/integration/town-private-identity.test.ts @@ -0,0 +1,79 @@ +import { env, runInDurableObject } from 'cloudflare:test'; +import { describe, expect, it } from 'vitest'; +import { getTownDOStub } from '../../src/dos/Town.do'; +import { + initializePrivateTownIdentity, + TOWN_IDENTITY_KEY, + RUNTIME_AUTHORIZATION_KEY, +} from '../../src/dos/town/runtime-authorization'; + +const identity = { + ownerType: 'user' as const, + ownerUserId: 'oauth/legacy-owner', + createdByUserId: 'oauth/legacy-owner', + runtimeMode: 'legacy' as const, +}; + +function town() { + return getTownDOStub(env, `identity-${crypto.randomUUID()}`); +} + +describe('private town identity on real Durable Object storage', () => { + it('initializes identity and owner configuration together', async () => { + await runInDurableObject(town(), async (_instance, state) => { + await state.storage.put('town:config', { kilocode_token: 'retained-token' }); + await initializePrivateTownIdentity(state.storage, identity); + expect(await state.storage.get(TOWN_IDENTITY_KEY)).toEqual(identity); + expect(await state.storage.get('town:config')).toMatchObject({ + kilocode_token: 'retained-token', + owner_user_id: identity.ownerUserId, + owner_type: 'user', + }); + }); + }); + + it('rolls back the identity write when persisted config validation fails', async () => { + await runInDurableObject(town(), async (_instance, state) => { + const malformedConfig = { kilocode_token: 123 }; + await state.storage.put('town:config', malformedConfig); + await expect(initializePrivateTownIdentity(state.storage, identity)).rejects.toThrow(); + expect(await state.storage.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(await state.storage.get('town:config')).toEqual(malformedConfig); + }); + }); + + it.each([null, false, {}, { ...identity, runtimeMode: 'modern' }])( + 'does not overwrite existing invalid/modern identity %j', + async existing => { + await runInDurableObject(town(), async (_instance, state) => { + await state.storage.put(TOWN_IDENTITY_KEY, existing); + await expect(initializePrivateTownIdentity(state.storage, identity)).rejects.toThrow(); + expect(await state.storage.get(TOWN_IDENTITY_KEY)).toEqual(existing); + }); + } + ); + + it('does not adopt a legacy identity over an orphaned authorization', async () => { + await runInDurableObject(town(), async (_instance, state) => { + await state.storage.put(RUNTIME_AUTHORIZATION_KEY, { state: 'revoked' }); + await expect(initializePrivateTownIdentity(state.storage, identity)).rejects.toThrow(); + expect(await state.storage.get(TOWN_IDENTITY_KEY)).toBeUndefined(); + expect(await state.storage.get(RUNTIME_AUTHORIZATION_KEY)).toEqual({ state: 'revoked' }); + }); + }); + + it('allows only one concurrent identity initialization', async () => { + await runInDurableObject(town(), async (_instance, state) => { + await state.storage.put('town:config', {}); + const attempts = await Promise.allSettled([ + initializePrivateTownIdentity(state.storage, identity), + initializePrivateTownIdentity(state.storage, { ...identity, ownerUserId: 'other-owner' }), + ]); + expect(attempts.filter(result => result.status === 'fulfilled')).toHaveLength(1); + const stored = await state.storage.get<{ ownerUserId: string }>(TOWN_IDENTITY_KEY); + expect(await state.storage.get('town:config')).toMatchObject({ + owner_user_id: stored?.ownerUserId, + }); + }); + }); +}); diff --git a/services/gastown/vitest.workers.config.ts b/services/gastown/vitest.workers.config.ts index 928619e974..aa4a13b6f5 100644 --- a/services/gastown/vitest.workers.config.ts +++ b/services/gastown/vitest.workers.config.ts @@ -1,6 +1,7 @@ import { cloudflareTest } from '@cloudflare/vitest-pool-workers'; import { defineConfig } from 'vitest/config'; import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; // Integration tests - run in Cloudflare Workers runtime via Miniflare export default defineConfig({ @@ -12,6 +13,20 @@ export default defineConfig({ }, }, plugins: [ + { + // Match Cloud Agent's Workers harness: pg's CommonJS require must + // resolve its dependencies to CommonJS rather than their ESM exports. + name: 'fix-pg-cjs-dependencies', + enforce: 'pre', + resolveId(source: string, importer?: string) { + if (importer === undefined) return undefined; + if (source === 'pg-protocol') { + return createRequire(importer).resolve('pg-protocol/dist/index.js'); + } + if (source === 'pg-pool') return createRequire(importer).resolve(source); + return undefined; + }, + }, cloudflareTest({ wrangler: { configPath: './wrangler.test.jsonc', diff --git a/services/security-auto-analysis/src/callbacks.lifecycle.test.ts b/services/security-auto-analysis/src/callbacks.lifecycle.test.ts index 58b1128505..cce12cfb40 100644 --- a/services/security-auto-analysis/src/callbacks.lifecycle.test.ts +++ b/services/security-auto-analysis/src/callbacks.lifecycle.test.ts @@ -6,7 +6,7 @@ import { getAnalysisActorById, getSecurityFindingById, } from './db/queries.js'; -import { generateApiToken } from './token.js'; +import { generateTriageToken } from './token.js'; import { extractSandboxAnalysis } from './extraction.js'; import { maybeAutoDismissCompletedAnalysis } from './auto-dismiss.js'; import { trackSecurityAnalysisCompleted } from './posthog.js'; @@ -30,7 +30,7 @@ vi.mock('./db/queries.js', () => ({ })); vi.mock('./token.js', () => ({ - generateApiToken: vi.fn(), + generateTriageToken: vi.fn(), })); vi.mock('./extraction.js', () => ({ @@ -84,6 +84,7 @@ describe('analysis lifecycle push emit wiring', () => { ignored_reason: null, analysis_status: 'running', analysis: { triggeredByUserId: 'user-1' }, + owned_by_organization_id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', } as never); vi.mocked(getActiveAnalysisAttemptToken).mockResolvedValue(ATTEMPT_TOKEN); vi.mocked(getAnalysisActorById).mockResolvedValue({ @@ -92,7 +93,7 @@ describe('analysis lifecycle push emit wiring', () => { name: 'User', is_admin: false, } as never); - vi.mocked(generateApiToken).mockResolvedValue('api-token'); + vi.mocked(generateTriageToken).mockResolvedValue('api-token'); vi.mocked(extractSandboxAnalysis).mockResolvedValue({ isExploitable: false, extractionStatus: 'succeeded', @@ -126,6 +127,17 @@ describe('analysis lifecycle push emit wiring', () => { }) ).resolves.toEqual({ status: 'completed-finalized' }); + expect(generateTriageToken).toHaveBeenCalledWith( + expect.objectContaining({ id: 'user-1' }), + 'nextauth-secret', + 'development', + undefined, + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + ); + expect(extractSandboxAnalysis).toHaveBeenCalledWith( + expect.objectContaining({ organizationId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' }) + ); + expect(dispatchSecurityLifecycleEventForFinding).toHaveBeenCalledWith({ env, db, @@ -243,7 +255,7 @@ describe('analysis lifecycle push emit wiring', () => { name: 'User', is_admin: false, } as never); - vi.mocked(generateApiToken).mockResolvedValue('api-token'); + vi.mocked(generateTriageToken).mockResolvedValue('api-token'); vi.mocked(extractSandboxAnalysis).mockResolvedValue({ isExploitable: false, extractionStatus: 'succeeded', diff --git a/services/security-auto-analysis/src/callbacks.ts b/services/security-auto-analysis/src/callbacks.ts index 49a21a4388..711343c487 100644 --- a/services/security-auto-analysis/src/callbacks.ts +++ b/services/security-auto-analysis/src/callbacks.ts @@ -10,7 +10,7 @@ import { getSecurityFindingById, } from './db/queries.js'; import { transitionAnalysisCallbackLifecycle } from './analysis-start-lifecycle.js'; -import { generateApiToken } from './token.js'; +import { generateTriageToken } from './token.js'; import { extractSandboxAnalysis as runSandboxExtraction } from './extraction.js'; import { fetchLatestAssistantText as fetchSessionAssistantText } from './session-result.js'; import { maybeAutoDismissCompletedAnalysis } from './auto-dismiss.js'; @@ -466,6 +466,7 @@ export async function finalizeCompletedAnalysisCallbackFromEnv(params: { userId, sessionIngestWorkerUrl: params.env.SESSION_INGEST_WORKER_URL, nextAuthSecret, + sharedResourceTokensEnabled: params.env.SHARED_RESOURCE_TOKENS_ENABLED, }); }, extractSandboxAnalysis: async ({ finding, rawMarkdown }) => { @@ -478,7 +479,13 @@ export async function finalizeCompletedAnalysisCallbackFromEnv(params: { throw new Error(`Analysis actor ${triggeredByUserId} is unavailable`); } const [nextAuthSecret] = await Promise.all([params.env.NEXTAUTH_SECRET.get()]); - const authToken = await generateApiToken(actor, nextAuthSecret, params.env.ENVIRONMENT); + const authToken = await generateTriageToken( + actor, + nextAuthSecret, + params.env.ENVIRONMENT, + params.env.SHARED_RESOURCE_TOKENS_ENABLED, + finding.owned_by_organization_id ?? undefined + ); return runSandboxExtraction({ finding, rawMarkdown, diff --git a/services/security-auto-analysis/src/db/queries.ts b/services/security-auto-analysis/src/db/queries.ts index 990b9f624e..302b2f0cd3 100644 --- a/services/security-auto-analysis/src/db/queries.ts +++ b/services/security-auto-analysis/src/db/queries.ts @@ -567,7 +567,13 @@ export async function getAnalysisActorById( is_admin: kilocode_users.is_admin, }) .from(kilocode_users) - .where(and(eq(kilocode_users.id, userId), isNull(kilocode_users.blocked_reason))) + .where( + and( + eq(kilocode_users.id, userId), + isNull(kilocode_users.blocked_at), + isNull(kilocode_users.blocked_reason) + ) + ) .limit(1); return rows[0] ?? null; } @@ -585,7 +591,13 @@ export async function resolveAutoAnalysisActor( api_token_pepper: kilocode_users.api_token_pepper, }) .from(kilocode_users) - .where(and(eq(kilocode_users.id, owner.id), isNull(kilocode_users.blocked_reason))) + .where( + and( + eq(kilocode_users.id, owner.id), + isNull(kilocode_users.blocked_at), + isNull(kilocode_users.blocked_reason) + ) + ) .limit(1); const user = rows[0]; @@ -604,6 +616,7 @@ export async function resolveAutoAnalysisActor( and( eq(organization_memberships.organization_id, owner.id), eq(organization_memberships.role, 'owner'), + isNull(kilocode_users.blocked_at), isNull(kilocode_users.blocked_reason) ) ) @@ -627,6 +640,7 @@ export async function resolveAutoAnalysisActor( and( eq(organization_memberships.organization_id, owner.id), eq(organization_memberships.role, 'member'), + isNull(kilocode_users.blocked_at), isNull(kilocode_users.blocked_reason) ) ) diff --git a/services/security-auto-analysis/src/launch.test.ts b/services/security-auto-analysis/src/launch.test.ts index 0b404f9211..d3dcf84e83 100644 --- a/services/security-auto-analysis/src/launch.test.ts +++ b/services/security-auto-analysis/src/launch.test.ts @@ -10,7 +10,7 @@ import { } from './db/queries.js'; import { transitionAnalysisStartLifecycle } from './analysis-start-lifecycle.js'; import { buildSecurityAnalysisCallbackTarget, startSecurityAnalysis } from './launch.js'; -import { generateApiToken } from './token.js'; +import { generateControlToken, generateTriageToken } from './token.js'; import { triageSecurityFinding } from './triage.js'; vi.mock('./db/queries.js', () => ({ @@ -21,7 +21,7 @@ vi.mock('./db/queries.js', () => ({ tryAcquireAnalysisStartLease: vi.fn(), })); vi.mock('./analysis-start-lifecycle.js', () => ({ transitionAnalysisStartLifecycle: vi.fn() })); -vi.mock('./token.js', () => ({ generateApiToken: vi.fn() })); +vi.mock('./token.js', () => ({ generateControlToken: vi.fn(), generateTriageToken: vi.fn() })); vi.mock('./triage.js', () => ({ triageSecurityFinding: vi.fn() })); const CALLBACK_SECRET = 'test-callback-token-secret'; @@ -225,7 +225,8 @@ describe('startSecurityAnalysis retrySandboxOnly', () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(tryAcquireAnalysisStartLease).mockResolvedValue(true); - vi.mocked(generateApiToken).mockResolvedValue('auth-token'); + vi.mocked(generateControlToken).mockResolvedValue('control-token'); + vi.mocked(generateTriageToken).mockResolvedValue('triage-token'); vi.mocked(getSecurityAgentConfigForOwner).mockResolvedValue({ auto_dismiss_enabled: true, auto_dismiss_confidence_threshold: 'high', @@ -272,6 +273,45 @@ describe('startSecurityAnalysis retrySandboxOnly', () => { }); }); + it('passes the prepareSession organization to the modern control token', async () => { + vi.mocked(getSecurityFindingById).mockResolvedValue(finding as never); + vi.mocked(triageSecurityFinding).mockResolvedValue(existingTriage); + const organizationId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + + const params = createParams( + false, + vi + .fn() + .mockResolvedValueOnce( + Response.json({ + result: { data: { cloudAgentSessionId: 'agent-session', kiloSessionId: 'ses-123' } }, + }) + ) + .mockResolvedValueOnce( + Response.json({ result: { data: { executionId: 'exec-123' } } }) + ) as never + ); + params.organizationId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'; + + await startSecurityAnalysis(params); + + expect(generateControlToken).toHaveBeenCalledWith( + expect.objectContaining({ id: 'user-123' }), + 'next-auth-secret', + 'development', + undefined, + organizationId + ); + expect(generateTriageToken).toHaveBeenCalledWith( + expect.objectContaining({ id: 'user-123' }), + 'next-auth-secret', + 'development', + undefined, + organizationId + ); + expect(triageSecurityFinding).toHaveBeenCalledWith(expect.objectContaining({ organizationId })); + }); + it('reuses existing triage and launches sandbox without retriaging', async () => { const previousAnalysis = { triage: existingTriage, diff --git a/services/security-auto-analysis/src/launch.ts b/services/security-auto-analysis/src/launch.ts index 5e11cf8721..f3abd5bc2e 100644 --- a/services/security-auto-analysis/src/launch.ts +++ b/services/security-auto-analysis/src/launch.ts @@ -15,7 +15,7 @@ import { type AnalysisStartLifecycleClaim, } from './analysis-start-lifecycle.js'; import { logger } from './logger.js'; -import { generateApiToken } from './token.js'; +import { generateControlToken, generateTriageToken } from './token.js'; import { triageSecurityFinding } from './triage.js'; import { maybeAutoDismissCompletedAnalysis } from './auto-dismiss.js'; import type { AnalysisMode, SecurityFindingAnalysis } from './types.js'; @@ -196,15 +196,30 @@ export async function startSecurityAnalysis( try { const environment = params.env.ENVIRONMENT === 'production' ? 'production' : 'development'; - const authToken = await generateApiToken(params.actorUser, params.nextAuthSecret, environment); + const [controlToken, triageToken] = await Promise.all([ + generateControlToken( + params.actorUser, + params.nextAuthSecret, + environment, + params.env.SHARED_RESOURCE_TOKENS_ENABLED, + finding.owned_by_organization_id ?? undefined + ), + generateTriageToken( + params.actorUser, + params.nextAuthSecret, + environment, + params.env.SHARED_RESOURCE_TOKENS_ENABLED, + finding.owned_by_organization_id ?? undefined + ), + ]); const triage = skipTriage ? existingTriage : await triageSecurityFinding({ finding, - authToken, + authToken: triageToken, model: params.triageModel, backendBaseUrl: params.env.KILOCODE_BACKEND_BASE_URL, - organizationId: params.organizationId, + organizationId: finding.owned_by_organization_id ?? undefined, }); const runSandbox = @@ -273,7 +288,7 @@ export async function startSecurityAnalysis( model: params.analysisModel, githubRepo: finding.repo_full_name, githubToken: params.githubToken, - kilocodeOrganizationId: params.organizationId, + kilocodeOrganizationId: finding.owned_by_organization_id ?? undefined, createdOnPlatform: 'security-agent', callbackTarget, }; @@ -283,7 +298,7 @@ export async function startSecurityAnalysis( method: 'POST', headers: { 'Content-Type': 'application/json', - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${controlToken}`, 'x-internal-api-key': params.internalApiSecret, }, body: JSON.stringify(prepareInput), @@ -323,7 +338,7 @@ export async function startSecurityAnalysis( method: 'POST', headers: { 'Content-Type': 'application/json', - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${controlToken}`, }, body: JSON.stringify({ cloudAgentSessionId }), }) diff --git a/services/security-auto-analysis/src/manual-analysis.ts b/services/security-auto-analysis/src/manual-analysis.ts index 81e0e150b0..fd56d25b0c 100644 --- a/services/security-auto-analysis/src/manual-analysis.ts +++ b/services/security-auto-analysis/src/manual-analysis.ts @@ -22,7 +22,7 @@ import { } from './db/queries.js'; import { transitionAnalysisStartLifecycle } from './analysis-start-lifecycle.js'; import { InsufficientCreditsError, startSecurityAnalysis } from './launch.js'; -import { generateApiToken } from './token.js'; +import { generateControlToken } from './token.js'; import { resolveSecurityAgentModels, SECURITY_ANALYSIS_OWNER_CAP, @@ -163,10 +163,12 @@ export async function processManualAnalysisStart(params: { ]); if (!tokenResult.success) return { status: 'token-missing' }; - const authToken = await generateApiToken( + const authToken = await generateControlToken( actor, nextAuthSecret, - params.env.ENVIRONMENT === 'production' ? 'production' : 'development' + params.env.ENVIRONMENT === 'production' ? 'production' : 'development', + params.env.SHARED_RESOURCE_TOKENS_ENABLED, + owner.type === 'org' ? owner.id : undefined ); const restart = await prepareActiveAnalysisRestart(params.db, { findingId: finding.id, diff --git a/services/security-auto-analysis/src/remediation.ts b/services/security-auto-analysis/src/remediation.ts index 844994886e..e115ffe88b 100644 --- a/services/security-auto-analysis/src/remediation.ts +++ b/services/security-auto-analysis/src/remediation.ts @@ -55,7 +55,7 @@ import { } from './db/queries.js'; import { InsufficientCreditsError } from './launch.js'; import { logger } from './logger.js'; -import { generateApiToken } from './token.js'; +import { generateControlToken } from './token.js'; import { type QueueOwner, type SecurityAgentConfig } from './types.js'; const REMEDIATION_LAUNCH_MAX_ATTEMPTS = 3; @@ -1170,10 +1170,12 @@ async function launchAttempt(params: { params.env.INTERNAL_API_SECRET.get(), params.env.CALLBACK_TOKEN_SECRET.get(), ]); - const authToken = await generateApiToken( + const authToken = await generateControlToken( params.actor, nextAuthSecret, - params.env.ENVIRONMENT === 'production' ? 'production' : 'development' + params.env.ENVIRONMENT === 'production' ? 'production' : 'development', + params.env.SHARED_RESOURCE_TOKENS_ENABLED, + params.owner.type === 'org' ? params.owner.id : undefined ); const attemptToken = randomUUID(); const callbackToken = await deriveCallbackToken({ @@ -2495,7 +2497,13 @@ export async function cancelRemediation(params: { .where(eq(security_remediation_attempts.id, attempt.id)); if (attempt.cloud_agent_session_id) { const nextAuthSecret = await params.env.NEXTAUTH_SECRET.get(); - const authToken = await generateApiToken(actor, nextAuthSecret, params.env.ENVIRONMENT); + const authToken = await generateControlToken( + actor, + nextAuthSecret, + params.env.ENVIRONMENT, + params.env.SHARED_RESOURCE_TOKENS_ENABLED, + owner.type === 'org' ? owner.id : undefined + ); await interruptCloudAgentSession({ env: params.env, authToken, diff --git a/services/security-auto-analysis/src/session-result.ts b/services/security-auto-analysis/src/session-result.ts index 1fad8c8096..fc490c23bd 100644 --- a/services/security-auto-analysis/src/session-result.ts +++ b/services/security-auto-analysis/src/session-result.ts @@ -40,9 +40,14 @@ export async function fetchLatestAssistantText(params: { userId: string; sessionIngestWorkerUrl: string; nextAuthSecret: string; + sharedResourceTokensEnabled?: string | boolean; }): Promise { if (!params.sessionIngestWorkerUrl) return null; - const token = await generateInternalServiceToken(params.userId, params.nextAuthSecret); + const token = await generateInternalServiceToken( + params.userId, + params.nextAuthSecret, + params.sharedResourceTokensEnabled + ); const response = await fetch( `${params.sessionIngestWorkerUrl}/api/session/${encodeURIComponent(params.sessionId)}/export`, { headers: { Authorization: `Bearer ${token}` } } diff --git a/services/security-auto-analysis/src/token.test.ts b/services/security-auto-analysis/src/token.test.ts new file mode 100644 index 0000000000..9358d1c990 --- /dev/null +++ b/services/security-auto-analysis/src/token.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest'; +import { + generateControlToken, + generateInternalServiceToken, + generateTriageToken, +} from './token.js'; + +const secret = 'test-secret-at-least-thirty-two-characters'; +const user = { id: 'user-1', api_token_pepper: 'current-pepper' }; + +function decodeJwt(token: string): Record { + const payload = token.split('.')[1]; + if (!payload) throw new Error('JWT payload missing'); + return JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/'))) as Record; +} + +describe('security analysis token issuance', () => { + it('preserves legacy tokens while shared resource tokens are disabled', async () => { + const [control, triage, session] = await Promise.all([ + generateControlToken(user, secret, 'production', false), + generateTriageToken(user, secret, 'production', undefined, 'organization-1'), + generateInternalServiceToken(user.id, secret, 'false'), + ]); + + expect(decodeJwt(control)).toMatchObject({ + kiloUserId: user.id, + apiTokenPepper: user.api_token_pepper, + env: 'production', + internalApiUse: true, + createdOnPlatform: 'security-agent', + }); + expect(decodeJwt(control)).not.toHaveProperty('aud'); + expect(decodeJwt(control)).not.toHaveProperty('organizationId'); + expect(decodeJwt(triage)).not.toHaveProperty('aud'); + expect(decodeJwt(triage)).not.toHaveProperty('organizationId'); + expect(decodeJwt(session)).not.toHaveProperty('aud'); + expect(decodeJwt(session)).not.toHaveProperty('apiTokenPepper'); + }); + + it('mints isolated modern control, triage, and session assertions', async () => { + const [control, triage, session] = await Promise.all([ + generateControlToken(user, secret, 'production', true), + generateTriageToken(user, secret, 'production', true), + generateInternalServiceToken(user.id, secret, true), + ]); + + expect(decodeJwt(control)).toMatchObject({ + aud: 'cloud-agent-next', + tokenPurpose: 'internal-service', + credentialExchange: false, + env: 'production', + apiTokenPepper: user.api_token_pepper, + runtimeAdmission: { + source: 'automation', + authorizationUserId: user.id, + authorizationPepper: user.api_token_pepper, + }, + }); + expect(decodeJwt(control)).not.toHaveProperty('organizationId'); + expect(decodeJwt(triage)).toMatchObject({ + aud: 'kilo-gateway', + tokenPurpose: 'internal-service', + credentialExchange: false, + env: 'production', + apiTokenPepper: user.api_token_pepper, + }); + expect(decodeJwt(triage)).not.toHaveProperty('runtimeAdmission'); + expect(decodeJwt(session)).toMatchObject({ + aud: 'session-ingest', + tokenPurpose: 'internal-service', + credentialExchange: false, + }); + expect(decodeJwt(session)).not.toHaveProperty('env'); + expect(decodeJwt(session)).not.toHaveProperty('apiTokenPepper'); + }); + + it('includes only the requested organization in modern control assertions', async () => { + const organizationId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const control = await generateControlToken(user, secret, 'production', true, organizationId); + + expect(decodeJwt(control)).toMatchObject({ organizationId }); + expect(decodeJwt(control)).not.toMatchObject({ + organizationId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + }); + }); + + it('includes only the requested organization in modern triage assertions', async () => { + const organizationId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const triage = await generateTriageToken(user, secret, 'production', true, organizationId); + + expect(decodeJwt(triage)).toMatchObject({ + aud: 'kilo-gateway', + organizationId, + }); + expect(decodeJwt(triage)).not.toMatchObject({ + organizationId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + }); + }); +}); diff --git a/services/security-auto-analysis/src/token.ts b/services/security-auto-analysis/src/token.ts index f4a4792459..07b5c7a96e 100644 --- a/services/security-auto-analysis/src/token.ts +++ b/services/security-auto-analysis/src/token.ts @@ -1,4 +1,10 @@ import { signKiloToken } from '@kilocode/worker-utils'; +import { signModernKiloToken } from '@kilocode/worker-utils/kilo-token-policy'; +import { + CLOUD_AGENT_NEXT_AUDIENCE, + KILO_GATEWAY_AUDIENCE, + SESSION_INGEST_AUDIENCE, +} from '@kilocode/worker-utils/internal-service-token-audiences'; type TokenUser = { id: string; @@ -7,10 +13,27 @@ type TokenUser = { const ONE_HOUR_SECONDS = 60 * 60; +export function isSharedResourceTokensEnabled(value: string | boolean | undefined): boolean { + return value === true || value === 'true'; +} + export async function generateInternalServiceToken( userId: string, - secret: string + secret: string, + sharedResourceTokensEnabled: string | boolean | undefined ): Promise { + if (isSharedResourceTokensEnabled(sharedResourceTokensEnabled)) { + const { token } = await signModernKiloToken({ + userId, + secret, + expiresInSeconds: ONE_HOUR_SECONDS, + audience: SESSION_INGEST_AUDIENCE, + tokenPurpose: 'internal-service', + credentialExchange: false, + }); + return token; + } + // No `pepper` field: verifiers treat an absent apiTokenPepper claim as // "skip pepper comparison" for internal-service tokens (see // verifyKiloBearerAgainstCurrentPepper in @kilocode/worker-utils). @@ -22,11 +45,37 @@ export async function generateInternalServiceToken( return token; } -export async function generateApiToken( +export async function generateControlToken( user: TokenUser, secret: string, - environment: string + environment: string, + sharedResourceTokensEnabled: string | boolean | undefined, + organizationId?: string ): Promise { + if (isSharedResourceTokensEnabled(sharedResourceTokensEnabled)) { + const { token } = await signModernKiloToken({ + userId: user.id, + pepper: user.api_token_pepper, + secret, + expiresInSeconds: ONE_HOUR_SECONDS, + env: environment, + audience: CLOUD_AGENT_NEXT_AUDIENCE, + tokenPurpose: 'internal-service', + credentialExchange: false, + extra: { + internalApiUse: true, + createdOnPlatform: 'security-agent', + organizationId, + runtimeAdmission: { + source: 'automation', + authorizationUserId: user.id, + authorizationPepper: user.api_token_pepper, + }, + }, + }); + return token; + } + const { token } = await signKiloToken({ userId: user.id, pepper: user.api_token_pepper, @@ -40,3 +89,32 @@ export async function generateApiToken( }); return token; } + +export async function generateTriageToken( + user: TokenUser, + secret: string, + environment: string, + sharedResourceTokensEnabled: string | boolean | undefined, + organizationId?: string +): Promise { + if (!isSharedResourceTokensEnabled(sharedResourceTokensEnabled)) { + return generateControlToken(user, secret, environment, false); + } + + const { token } = await signModernKiloToken({ + userId: user.id, + pepper: user.api_token_pepper, + secret, + expiresInSeconds: ONE_HOUR_SECONDS, + env: environment, + audience: KILO_GATEWAY_AUDIENCE, + tokenPurpose: 'internal-service', + credentialExchange: false, + extra: { + internalApiUse: true, + createdOnPlatform: 'security-agent', + organizationId, + }, + }); + return token; +} diff --git a/services/security-auto-analysis/worker-configuration.d.ts b/services/security-auto-analysis/worker-configuration.d.ts index 5b0843d09d..cb7dccea8c 100644 --- a/services/security-auto-analysis/worker-configuration.d.ts +++ b/services/security-auto-analysis/worker-configuration.d.ts @@ -91,6 +91,7 @@ declare type CloudflareEnv = { SECURITY_ANALYSIS_CALLBACK_WORKER_BASE_URL: string; SECURITY_ANALYSIS_CALLBACK_WORKER_INGRESS_ENABLED: string | undefined; MANUAL_ANALYSIS_COMMAND_ROUTING_ENABLED: string | undefined; + SHARED_RESOURCE_TOKENS_ENABLED: string | boolean | undefined; NEXT_PUBLIC_POSTHOG_KEY: string | undefined; }; diff --git a/services/security-auto-analysis/wrangler.jsonc b/services/security-auto-analysis/wrangler.jsonc index ccd248da4b..45d2470b8a 100644 --- a/services/security-auto-analysis/wrangler.jsonc +++ b/services/security-auto-analysis/wrangler.jsonc @@ -41,6 +41,7 @@ "SECURITY_ANALYSIS_CALLBACK_WORKER_BASE_URL": "https://security-auto-analysis.kilosessions.ai", "SECURITY_ANALYSIS_CALLBACK_WORKER_INGRESS_ENABLED": "true", "MANUAL_ANALYSIS_COMMAND_ROUTING_ENABLED": "true", + "SHARED_RESOURCE_TOKENS_ENABLED": "false", "SECURITY_AGENT_COMMAND_ACCEPTED_TIMEOUT_MS": "300000", "SECURITY_AGENT_COMMAND_RUNNING_TIMEOUT_MS": "1800000", "SECURITY_AGENT_COMMAND_RETENTION_DAYS": "30", @@ -169,6 +170,7 @@ "SECURITY_ANALYSIS_CALLBACK_WORKER_BASE_URL": "http://localhost:8797", "SECURITY_ANALYSIS_CALLBACK_WORKER_INGRESS_ENABLED": "true", "MANUAL_ANALYSIS_COMMAND_ROUTING_ENABLED": "true", + "SHARED_RESOURCE_TOKENS_ENABLED": "false", "SECURITY_AGENT_COMMAND_ACCEPTED_TIMEOUT_MS": "300000", "SECURITY_AGENT_COMMAND_RUNNING_TIMEOUT_MS": "1800000", "SECURITY_AGENT_COMMAND_RETENTION_DAYS": "30", diff --git a/services/webhook-agent-ingest/package.json b/services/webhook-agent-ingest/package.json index 70c29a060a..807089ed43 100644 --- a/services/webhook-agent-ingest/package.json +++ b/services/webhook-agent-ingest/package.json @@ -10,7 +10,7 @@ "deploy:dev": "wrangler deploy --env dev", "dev": "wrangler dev --env dev", "start": "wrangler dev --env dev", - "types": "wrangler types", + "types": "wrangler types --include-runtime false", "lint": "pnpm -w exec oxlint --config .oxlintrc.json services/webhook-agent-ingest/src", "format": "oxfmt src", "format:check": "oxfmt --list-different src", @@ -32,6 +32,7 @@ "zod": "catalog:" }, "devDependencies": { + "@cloudflare/workers-types": "catalog:", "@cloudflare/vitest-pool-workers": "catalog:", "@types/node": "catalog:", "@typescript/native-preview": "catalog:", diff --git a/services/webhook-agent-ingest/src/db/queries.ts b/services/webhook-agent-ingest/src/db/queries.ts index 45b9f93abb..2ef489df2b 100644 --- a/services/webhook-agent-ingest/src/db/queries.ts +++ b/services/webhook-agent-ingest/src/db/queries.ts @@ -11,12 +11,14 @@ export { getWorkerDb, type WorkerDb }; export type UserForToken = Pick< typeof kilocode_users.$inferSelect, - 'id' | 'blocked_reason' | 'api_token_pepper' + 'id' | 'blocked_at' | 'blocked_reason' | 'api_token_pepper' >; export type BotUserForToken = { id: string; api_token_pepper: string; + blocked_at: string | null; + blocked_reason: string | null; }; // Bot user constants — must match kilocode-backend's src/lib/bot-users/types.ts @@ -85,6 +87,7 @@ export async function findUserForToken(db: WorkerDb, userId: string): Promise { expect(retry).not.toHaveBeenCalled(); }); + it('uses the organization from the queue configuration in prepareSession', async () => { + const organizationId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const prepareRequests: Request[] = []; + const stub = { + getRequest: vi.fn(async () => makeRequest()), + getConfig: vi.fn(async () => + makeTriggerConfig({ + userId: null, + orgId: organizationId, + targetType: 'cloud_agent', + mode: 'code', + model: 'model-1', + githubRepo: 'owner/repo', + profileId: 'profile-1', + }) + ), + updateRequest: vi.fn(async () => ({ success: true })), + }; + const env = { + WEBHOOK_AGENT_URL: 'https://hooks.test', + WEBHOOK_TOKEN_CACHE: { get: vi.fn(async () => 'api-token'), put: vi.fn() }, + INTERNAL_API_SECRET: { get: vi.fn(async () => 'test-internal-secret') }, + CALLBACK_TOKEN_SECRET: { get: vi.fn(async () => 'test-callback-token-secret') }, + TRIGGER_DO: { idFromName: vi.fn((name: string) => name), get: vi.fn(() => stub) }, + CLOUD_AGENT: { + fetch: vi.fn(async (request: Request) => { + prepareRequests.push(request); + return request.url.includes('/trpc/prepareSession') + ? Response.json({ result: { data: { cloudAgentSessionId: 'cloud-session-1' } } }) + : Response.json({ + result: { data: { executionId: 'execution-1', status: 'running' } }, + }); + }), + }, + } as unknown as Env; + const ack = vi.fn(); + const retry = vi.fn(); + const batch = { + queue: 'webhook-delivery', + messages: [{ body: makeWebhook(), attempts: 1, ack, retry }], + } as unknown as MessageBatch>; + + await handleWebhookDeliveryBatch(batch, env); + + expect(await prepareRequests[0]?.json()).toMatchObject({ + kilocodeOrganizationId: organizationId, + }); + expect(ack).toHaveBeenCalledTimes(1); + expect(retry).not.toHaveBeenCalled(); + }); + it.each([ ['webhook', undefined, undefined], ['webhook', 'high', undefined], diff --git a/services/webhook-agent-ingest/src/queue-consumer.ts b/services/webhook-agent-ingest/src/queue-consumer.ts index 4f8e64d2cf..4af83572e0 100644 --- a/services/webhook-agent-ingest/src/queue-consumer.ts +++ b/services/webhook-agent-ingest/src/queue-consumer.ts @@ -10,6 +10,7 @@ import { getKiloChat } from './kilo-chat-binding'; import type { PostMessageAsUserResult } from '@kilocode/kilo-chat'; import { deriveCallbackToken } from '@kilocode/worker-utils'; import { z } from 'zod'; +import { getSecretValue } from './util/secret'; // Token cache TTL: 30 minutes. Token validity is 1 hour, so 30 min gives safety margin. const TOKEN_CACHE_TTL_SECONDS = 30 * 60; @@ -17,11 +18,18 @@ const TOKEN_CACHE_TTL_SECONDS = 30 * 60; // Maximum number of retry attempts for failed webhook processing const MAX_RETRY_ATTEMPTS = 3; -function tokenCacheKey(triggerConfig: TriggerConfig): string { +function tokenCacheKey( + triggerConfig: TriggerConfig, + sharedResourceTokensEnabled: string | boolean | undefined +): string { // Cache key is based on userId or orgId, not namespace // This ensures token caching is per-user or per-org const principal = triggerConfig.userId ?? triggerConfig.orgId; - return `webhook-token:${principal}`; + const format = + sharedResourceTokensEnabled === true || sharedResourceTokensEnabled === 'true' + ? 'modern' + : 'legacy'; + return `webhook-token:${format}:${principal}`; } const PrepareSessionResponseSchema = z.object({ @@ -57,7 +65,7 @@ async function getOrMintToken( env: Env, triggerConfig: TriggerConfig ): Promise<{ token: string; cached: boolean }> { - const cacheKey = tokenCacheKey(triggerConfig); + const cacheKey = tokenCacheKey(triggerConfig, env.SHARED_RESOURCE_TOKENS_ENABLED); // Check KV cache first const cachedToken = await env.WEBHOOK_TOKEN_CACHE.get(cacheKey); @@ -356,8 +364,8 @@ async function processWebhookMessage( // Fetch callback signing and internal API credentials once for Cloud Agent calls. const [internalApiSecret, callbackTokenSecret] = await Promise.all([ - env.INTERNAL_API_SECRET.get(), - env.CALLBACK_TOKEN_SECRET.get(), + getSecretValue(env.INTERNAL_API_SECRET), + getSecretValue(env.CALLBACK_TOKEN_SECRET), ]); if (!cloudAgentSessionId) { diff --git a/services/webhook-agent-ingest/src/routes/callbacks.ts b/services/webhook-agent-ingest/src/routes/callbacks.ts index efb8a044d3..600074cae2 100644 --- a/services/webhook-agent-ingest/src/routes/callbacks.ts +++ b/services/webhook-agent-ingest/src/routes/callbacks.ts @@ -5,6 +5,7 @@ import { logger } from '../util/logger'; import { resError, resSuccess, verifyCallbackToken } from '@kilocode/worker-utils'; import { CloudAgentCallbackFailureSchema } from '@kilocode/worker-utils/cloud-agent-failure'; import { withDORetry } from '../util/do-retry'; +import { getSecretValue } from '../util/secret'; const callbacks = new Hono(); @@ -33,7 +34,7 @@ callbacks.post('/execution', async c => { return c.json(resError('Missing webhook identification headers'), 400); } - const callbackTokenSecret = await c.env.CALLBACK_TOKEN_SECRET.get(); + const callbackTokenSecret = await getSecretValue(c.env.CALLBACK_TOKEN_SECRET); if (!callbackTokenSecret) { logger.error('Callback authentication secret not configured'); return c.json(resError('Internal server error'), 500); diff --git a/services/webhook-agent-ingest/src/services/token-minting-service.test.ts b/services/webhook-agent-ingest/src/services/token-minting-service.test.ts new file mode 100644 index 0000000000..680358b241 --- /dev/null +++ b/services/webhook-agent-ingest/src/services/token-minting-service.test.ts @@ -0,0 +1,137 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { TokenMintingService } from './token-minting-service.js'; + +const { findUserForToken, organizationExists, ensureBotUserForOrg } = vi.hoisted(() => ({ + findUserForToken: vi.fn(), + organizationExists: vi.fn(), + ensureBotUserForOrg: vi.fn(), +})); + +vi.mock('../db/queries.js', () => ({ + getWorkerDb: vi.fn(() => ({})), + findUserForToken, + organizationExists, + ensureBotUserForOrg, +})); + +const secret = 'test-secret-at-least-thirty-two-characters'; + +function decodeJwt(token: string): Record { + const payload = token.split('.')[1]; + if (!payload) throw new Error('JWT payload missing'); + return JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/'))) as Record; +} + +function service(sharedResourceTokensEnabled?: string | boolean) { + return new TokenMintingService({ + HYPERDRIVE: { connectionString: 'postgres://test' }, + NEXTAUTH_SECRET: { get: async () => secret }, + ENVIRONMENT: 'production', + SHARED_RESOURCE_TOKENS_ENABLED: sharedResourceTokensEnabled, + }); +} + +describe('webhook token minting', () => { + beforeEach(() => { + findUserForToken.mockReset(); + organizationExists.mockReset(); + ensureBotUserForOrg.mockReset(); + findUserForToken.mockResolvedValue({ + id: 'user-1', + api_token_pepper: 'current-pepper', + blocked_at: null, + blocked_reason: null, + }); + organizationExists.mockResolvedValue(true); + ensureBotUserForOrg.mockResolvedValue({ + id: 'webhook-bot-org-1', + api_token_pepper: 'bot-pepper', + blocked_at: null, + blocked_reason: null, + }); + }); + + it('uses the legacy format by default', async () => { + const result = await service().mintToken({ userId: 'user-1', triggerId: 'trigger-1' }); + const claims = decodeJwt(result.token); + + expect(claims).toMatchObject({ + kiloUserId: 'user-1', + apiTokenPepper: 'current-pepper', + env: 'production', + internalApiUse: true, + createdOnPlatform: 'webhook', + }); + expect(claims).not.toHaveProperty('aud'); + }); + + it('uses a current-user modern cloud-agent control assertion when enabled', async () => { + const result = await service(true).mintToken({ userId: 'user-1', triggerId: 'trigger-1' }); + const claims = decodeJwt(result.token); + + expect(claims).toMatchObject({ + aud: 'cloud-agent-next', + tokenPurpose: 'internal-service', + credentialExchange: false, + apiTokenPepper: 'current-pepper', + runtimeAdmission: { + source: 'automation', + authorizationUserId: 'user-1', + authorizationPepper: 'current-pepper', + }, + }); + expect(claims).not.toHaveProperty('organizationId'); + }); + + it('includes the triggering organization in modern bot control assertions', async () => { + const organizationId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const result = await service(true).mintToken({ orgId: organizationId, triggerId: 'trigger-1' }); + const claims = decodeJwt(result.token); + + expect(claims).toMatchObject({ + kiloUserId: 'webhook-bot-org-1', + organizationId, + }); + expect(claims).not.toMatchObject({ + organizationId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + }); + }); + + it('preserves the legacy bot token shape when modern assertions are disabled', async () => { + const result = await service(false).mintToken({ orgId: 'org-1', triggerId: 'trigger-1' }); + const claims = decodeJwt(result.token); + + expect(claims).not.toHaveProperty('aud'); + expect(claims).not.toHaveProperty('organizationId'); + }); + + it.each([ + { blocked_at: new Date(), blocked_reason: null }, + { blocked_at: null, blocked_reason: 'disabled' }, + ])('rejects disabled personal users', async disabled => { + findUserForToken.mockResolvedValue({ + id: 'user-1', + api_token_pepper: 'current-pepper', + ...disabled, + }); + + await expect( + service(true).mintToken({ userId: 'user-1', triggerId: 'trigger-1' }) + ).rejects.toThrow('User is blocked'); + }); + + it.each([ + { blocked_at: new Date(), blocked_reason: null }, + { blocked_at: null, blocked_reason: 'disabled' }, + ])('rejects disabled organization bot users', async disabled => { + ensureBotUserForOrg.mockResolvedValue({ + id: 'webhook-bot-org-1', + api_token_pepper: 'bot-pepper', + ...disabled, + }); + + await expect( + service(true).mintToken({ orgId: 'org-1', triggerId: 'trigger-1' }) + ).rejects.toThrow('Webhook bot user is blocked'); + }); +}); diff --git a/services/webhook-agent-ingest/src/services/token-minting-service.ts b/services/webhook-agent-ingest/src/services/token-minting-service.ts index 359c4fe808..6fb2a7387e 100644 --- a/services/webhook-agent-ingest/src/services/token-minting-service.ts +++ b/services/webhook-agent-ingest/src/services/token-minting-service.ts @@ -1,4 +1,6 @@ import { signKiloToken } from '@kilocode/worker-utils'; +import { signModernKiloToken } from '@kilocode/worker-utils/kilo-token-policy'; +import { CLOUD_AGENT_NEXT_AUDIENCE } from '@kilocode/worker-utils/internal-service-token-audiences'; import { getWorkerDb, findUserForToken, @@ -7,14 +9,16 @@ import { type WorkerDb, } from '../db/queries.js'; import { logger } from '../util/logger.js'; +import { getSecretValue } from '../util/secret.js'; /** * Environment bindings required for token minting. */ export type TokenMintingEnv = { HYPERDRIVE: { connectionString: string }; - NEXTAUTH_SECRET: { get(): Promise }; // Same secret used by kilocode-backend + NEXTAUTH_SECRET: SecretsStoreSecret | string; // Same secret used by kilocode-backend ENVIRONMENT: string; + SHARED_RESOURCE_TOKENS_ENABLED?: string | boolean; }; type MintTokenParams = { @@ -57,7 +61,7 @@ export class TokenMintingService { private async getJwtSecret(): Promise { if (!this.jwtSecret) { - this.jwtSecret = await this.env.NEXTAUTH_SECRET.get(); + this.jwtSecret = await getSecretValue(this.env.NEXTAUTH_SECRET); } return this.jwtSecret; } @@ -80,8 +84,8 @@ export class TokenMintingService { throw new Error(`User not found: ${params.userId}`); } - if (user.blocked_reason) { - throw new Error(`User is blocked: ${user.blocked_reason}`); + if (user.blocked_at || user.blocked_reason) { + throw new Error('User is blocked'); } const token = await this.signToken({ @@ -111,11 +115,15 @@ export class TokenMintingService { logger.info('Token minting: ensuring bot user', { orgId: params.orgId }); const botUser = await ensureBotUserForOrg(db, params.orgId); + if (botUser.blocked_at || botUser.blocked_reason) { + throw new Error('Webhook bot user is blocked'); + } const token = await this.signToken({ kiloUserId: botUser.id, apiTokenPepper: botUser.api_token_pepper, botId: WEBHOOK_BOT_ID, + organizationId: params.orgId, internalApiUse: true, createdOnPlatform: 'webhook', }); @@ -143,11 +151,40 @@ export class TokenMintingService { kiloUserId: string; apiTokenPepper: string | null; botId?: string; + organizationId?: string; internalApiUse: boolean; createdOnPlatform: string; }): Promise { const jwtSecret = await this.getJwtSecret(); + if ( + this.env.SHARED_RESOURCE_TOKENS_ENABLED === true || + this.env.SHARED_RESOURCE_TOKENS_ENABLED === 'true' + ) { + const { token } = await signModernKiloToken({ + userId: payload.kiloUserId, + pepper: payload.apiTokenPepper, + secret: jwtSecret, + expiresInSeconds: 60 * 60, + env: this.env.ENVIRONMENT === 'production' ? 'production' : 'development', + audience: CLOUD_AGENT_NEXT_AUDIENCE, + tokenPurpose: 'internal-service', + credentialExchange: false, + extra: { + botId: payload.botId, + organizationId: payload.organizationId, + internalApiUse: payload.internalApiUse, + createdOnPlatform: payload.createdOnPlatform, + runtimeAdmission: { + source: 'automation', + authorizationUserId: payload.kiloUserId, + authorizationPepper: payload.apiTokenPepper, + }, + }, + }); + return token; + } + const { token } = await signKiloToken({ userId: payload.kiloUserId, pepper: payload.apiTokenPepper, diff --git a/services/webhook-agent-ingest/src/util/auth.ts b/services/webhook-agent-ingest/src/util/auth.ts index ba91ad60ed..d2c6cf7020 100644 --- a/services/webhook-agent-ingest/src/util/auth.ts +++ b/services/webhook-agent-ingest/src/util/auth.ts @@ -10,6 +10,7 @@ import { createMiddleware } from 'hono/factory'; import type { HonoContext } from '../index'; import { logger } from './logger'; import { resError } from '@kilocode/worker-utils'; +import { getSecretValue } from './secret'; /** Header name for internal API key */ export const INTERNAL_API_KEY_HEADER = 'X-Internal-API-Key'; @@ -51,7 +52,7 @@ export const internalApiMiddleware = createMiddleware(async (c, nex } const apiKeyHeader = c.req.header(INTERNAL_API_KEY_HEADER); - const secret = await c.env.INTERNAL_API_SECRET.get(); + const secret = await getSecretValue(c.env.INTERNAL_API_SECRET); if (!secret) { logger.error('INTERNAL_API_SECRET not configured'); diff --git a/services/webhook-agent-ingest/src/util/secret.ts b/services/webhook-agent-ingest/src/util/secret.ts new file mode 100644 index 0000000000..cb73e1d173 --- /dev/null +++ b/services/webhook-agent-ingest/src/util/secret.ts @@ -0,0 +1,3 @@ +export function getSecretValue(secret: SecretsStoreSecret | string): Promise { + return typeof secret === 'string' ? Promise.resolve(secret) : secret.get(); +} diff --git a/services/webhook-agent-ingest/tsconfig.json b/services/webhook-agent-ingest/tsconfig.json index 09d17e27df..3c73948b59 100644 --- a/services/webhook-agent-ingest/tsconfig.json +++ b/services/webhook-agent-ingest/tsconfig.json @@ -6,6 +6,7 @@ "moduleResolution": "bundler", "types": [ "@types/node", + "@cloudflare/workers-types", "./worker-configuration.d.ts", "@cloudflare/vitest-pool-workers/types" ], diff --git a/services/webhook-agent-ingest/worker-configuration.d.ts b/services/webhook-agent-ingest/worker-configuration.d.ts index 53937bff94..8642e540ea 100644 --- a/services/webhook-agent-ingest/worker-configuration.d.ts +++ b/services/webhook-agent-ingest/worker-configuration.d.ts @@ -1,11984 +1,57 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: 587dd1eac396d8c2bdb105dcaf48ea3b) -// Runtime types generated with workerd@1.20251217.0 2025-09-27 nodejs_compat -declare namespace Cloudflare { - interface GlobalProps { - mainModule: typeof import('./src/index'); - durableNamespaces: 'TriggerDO'; - } - interface Env { - WEBHOOK_TOKEN_CACHE: KVNamespace; - ENVIRONMENT: 'production' | 'development'; - KILOCODE_BACKEND_BASE_URL: 'https://api.kilo.ai' | 'http://localhost:3000'; - WEBHOOK_AGENT_URL: string; - KILOCLAW_API_URL: string; - TRIGGER_DO: DurableObjectNamespace; - INTERNAL_API_SECRET: SecretsStoreSecret; - CALLBACK_TOKEN_SECRET: SecretsStoreSecret; - NEXTAUTH_SECRET: SecretsStoreSecret; - CLOUD_AGENT: Fetcher /* cloud-agent */; - KILO_CHAT: Service /* entrypoint KiloChatService from kilo-chat */; - WEBHOOK_DELIVERY_QUEUE: Queue; - HYPERDRIVE: Hyperdrive; - CF_VERSION_METADATA: WorkerVersionMetadata; - } +// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 5a54445493a1c6efa93aadfac11e9410) +interface __BaseEnv_Env { + WEBHOOK_TOKEN_CACHE: KVNamespace; + HYPERDRIVE: Hyperdrive; + WEBHOOK_DELIVERY_QUEUE: Queue; + INTERNAL_API_SECRET: SecretsStoreSecret | string; + CALLBACK_TOKEN_SECRET: SecretsStoreSecret | string; + NEXTAUTH_SECRET: SecretsStoreSecret | string; + CF_VERSION_METADATA: WorkerVersionMetadata; + ENVIRONMENT: "development" | "production"; + KILOCODE_BACKEND_BASE_URL: "http://localhost:3000" | "https://api.kilo.ai"; + KILOCLAW_API_URL: "http://localhost:8795" | "https://claw.kilosessions.ai"; + SHARED_RESOURCE_TOKENS_ENABLED: "false"; + WEBHOOK_AGENT_URL: string; + TRIGGER_DO: DurableObjectNamespace; + CLOUD_AGENT: Fetcher /* cloud-agent-next-dev */ | Fetcher /* cloud-agent-next */; + KILO_CHAT: Service /* entrypoint KiloChatService from kilo-chat */; } -interface Env extends Cloudflare.Env {} +declare namespace Cloudflare { + interface GlobalProps { + mainModule: typeof import("./src/index"); + durableNamespaces: "TriggerDO"; + } + interface DevEnv { + WEBHOOK_TOKEN_CACHE: KVNamespace; + HYPERDRIVE: Hyperdrive; + WEBHOOK_DELIVERY_QUEUE: Queue; + INTERNAL_API_SECRET: SecretsStoreSecret; + CALLBACK_TOKEN_SECRET: SecretsStoreSecret; + NEXTAUTH_SECRET: SecretsStoreSecret; + CF_VERSION_METADATA: WorkerVersionMetadata; + ENVIRONMENT: "development"; + KILOCODE_BACKEND_BASE_URL: "http://localhost:3000"; + KILOCLAW_API_URL: "http://localhost:8795"; + SHARED_RESOURCE_TOKENS_ENABLED: "false"; + NEXTAUTH_SECRET: string; + INTERNAL_API_SECRET: string; + CALLBACK_TOKEN_SECRET: string; + WEBHOOK_AGENT_URL: string; + TRIGGER_DO: DurableObjectNamespace; + CLOUD_AGENT: Fetcher /* cloud-agent-next-dev */; + KILO_CHAT: Service /* entrypoint KiloChatService from kilo-chat */; + } + interface Env extends __BaseEnv_Env {} +} +interface Env extends __BaseEnv_Env {} type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; + [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; declare namespace NodeJS { - interface ProcessEnv - extends StringifyValues< - Pick - > {} -} - -// Begin runtime types -/*! ***************************************************************************** -Copyright (c) Cloudflare. All rights reserved. -Copyright (c) Microsoft Corporation. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* eslint-disable */ -// noinspection JSUnusedGlobalSymbols -declare var onmessage: never; -/** - * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) - */ -declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * The **`message`** read-only property of the a message or description associated with the given error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) - */ - readonly message: string; - /** - * The **`name`** read-only property of the one of the strings associated with an error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) - */ - readonly name: string; - /** - * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); -} -type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; -}; -declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; -} -/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * - * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) - */ -interface Console { - 'assert'(condition?: boolean, ...data: any[]): void; - /** - * The **`console.clear()`** static method clears the console if possible. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) - */ - clear(): void; - /** - * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) - */ - count(label?: string): void; - /** - * The **`console.countReset()`** static method resets counter used with console/count_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) - */ - countReset(label?: string): void; - /** - * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) - */ - debug(...data: any[]): void; - /** - * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) - */ - dir(item?: any, options?: any): void; - /** - * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) - */ - dirxml(...data: any[]): void; - /** - * The **`console.error()`** static method outputs a message to the console at the 'error' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) - */ - error(...data: any[]): void; - /** - * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) - */ - group(...data: any[]): void; - /** - * The **`console.groupCollapsed()`** static method creates a new inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) - */ - groupCollapsed(...data: any[]): void; - /** - * The **`console.groupEnd()`** static method exits the current inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) - */ - groupEnd(): void; - /** - * The **`console.info()`** static method outputs a message to the console at the 'info' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) - */ - info(...data: any[]): void; - /** - * The **`console.log()`** static method outputs a message to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) - */ - log(...data: any[]): void; - /** - * The **`console.table()`** static method displays tabular data as a table. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) - */ - table(tabularData?: any, properties?: string[]): void; - /** - * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) - */ - time(label?: string): void; - /** - * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) - */ - timeEnd(label?: string): void; - /** - * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) - */ - timeLog(label?: string, ...data: any[]): void; - timeStamp(label?: string): void; - /** - * The **`console.trace()`** static method outputs a stack trace to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) - */ - trace(...data: any[]): void; - /** - * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) - */ - warn(...data: any[]): void; -} -declare const console: Console; -type BufferSource = ArrayBufferView | ArrayBuffer; -type TypedArray = - | Int8Array - | Uint8Array - | Uint8ClampedArray - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array; -declare namespace WebAssembly { - class CompileError extends Error { - constructor(message?: string); - } - class RuntimeError extends Error { - constructor(message?: string); - } - type ValueType = 'anyfunc' | 'externref' | 'f32' | 'f64' | 'i32' | 'i64' | 'v128'; - interface GlobalDescriptor { - value: ValueType; - mutable?: boolean; - } - class Global { - constructor(descriptor: GlobalDescriptor, value?: any); - value: any; - valueOf(): any; - } - type ImportValue = ExportValue | number; - type ModuleImports = Record; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = 'function' | 'global' | 'memory' | 'table'; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = 'anyfunc' | 'externref'; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; -} -/** - * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) - */ -interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args - ): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args - ): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; -} -declare function addEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetAddEventListenerOptions | boolean -): void; -declare function removeEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetEventListenerOptions | boolean -): void; -/** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ -declare function dispatchEvent( - event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] -): boolean; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ -declare function btoa(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ -declare function atob(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args -): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ -declare function clearTimeout(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args -): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ -declare function clearInterval(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ -declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ -declare function reportError(error: any): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch( - input: RequestInfo | URL, - init?: RequestInit -): Promise; -declare const self: ServiceWorkerGlobalScope; -/** - * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. - * The Workers runtime implements the full surface of this API, but with some differences in - * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) - * compared to those implemented in most browsers. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) - */ -declare const crypto: Crypto; -/** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ -declare const caches: CacheStorage; -declare const scheduler: Scheduler; -/** - * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, - * as well as timing of subrequests and other operations. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) - */ -declare const performance: Performance; -declare const Cloudflare: Cloudflare; -declare const origin: string; -declare const navigator: Navigator; -interface TestController {} -interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly props: Props; -} -type ExportedHandlerFetchHandler = ( - request: Request>, - env: Env, - ctx: ExecutionContext -) => Response | Promise; -type ExportedHandlerTailHandler = ( - events: TraceItem[], - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerTraceHandler = ( - traces: TraceItem[], - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerTailStreamHandler = ( - event: TailStream.TailEvent, - env: Env, - ctx: ExecutionContext -) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = ( - controller: ScheduledController, - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerQueueHandler = ( - batch: MessageBatch, - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerTestHandler = ( - controller: TestController, - env: Env, - ctx: ExecutionContext -) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; -} -interface StructuredSerializeOptions { - transfer?: any[]; -} -declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly language: string; - readonly languages: string[]; -} -interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; -} -interface Cloudflare { - readonly compatibilityFlags: Record; -} -interface DurableObject { - fetch(request: Request): Response | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?( - ws: WebSocket, - code: number, - reason: string, - wasClean: boolean - ): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher< - T, - 'alarm' | 'webSocketMessage' | 'webSocketClose' | 'webSocketError' -> & { - readonly id: DurableObjectId; - readonly name?: string; -}; -interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; -} -declare abstract class DurableObjectNamespace< - T extends Rpc.DurableObjectBranded | undefined = undefined, -> { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get( - id: DurableObjectId, - options?: DurableObjectNamespaceGetDurableObjectOptions - ): DurableObjectStub; - getByName( - name: string, - options?: DurableObjectNamespaceGetDurableObjectOptions - ): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; -} -type DurableObjectJurisdiction = 'eu' | 'fedramp' | 'fedramp-high'; -interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = - | 'wnam' - | 'enam' - | 'sam' - | 'weur' - | 'eeur' - | 'apac' - | 'oc' - | 'afr' - | 'me'; -interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {} -interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - blockConcurrencyWhile(callback: () => Promise): Promise; - acceptWebSocket(ws: WebSocket, tags?: string[]): void; - getWebSockets(tag?: string): WebSocket[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; -} -interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; -} -interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; -} -interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; -} -interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; -} -interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; -} -declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; -} -interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; -} -interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; -} -/** - * The **`Event`** interface represents an event which takes place on an `EventTarget`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) - */ -declare class Event { - constructor(type: string, init?: EventInit); - /** - * The **`type`** read-only property of the Event interface returns a string containing the event's type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) - */ - get composed(): boolean; - /** - * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) - */ - get bubbles(): boolean; - /** - * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) - */ - get cancelable(): boolean; - /** - * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) - */ - get defaultPrevented(): boolean; - /** - * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) - */ - get returnValue(): boolean; - /** - * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) - */ - get currentTarget(): EventTarget | undefined; - /** - * The read-only **`target`** property of the dispatched. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) - */ - get target(): EventTarget | undefined; - /** - * The deprecated **`Event.srcElement`** is an alias for the Event.target property. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) - */ - get srcElement(): EventTarget | undefined; - /** - * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) - */ - get timeStamp(): number; - /** - * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) - */ - get isTrusted(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) - */ - stopImmediatePropagation(): void; - /** - * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) - */ - preventDefault(): void; - /** - * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) - */ - stopPropagation(): void; - /** - * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; -} -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} -type EventListener = (event: EventType) => void; -interface EventListenerObject { - handleEvent(event: EventType): void; -} -type EventListenerOrEventListenerObject = - | EventListener - | EventListenerObject; -/** - * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) - */ -declare class EventTarget = Record> { - constructor(); - /** - * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) - */ - addEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetAddEventListenerOptions | boolean - ): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetEventListenerOptions | boolean - ): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; -} -interface EventTargetEventListenerOptions { - capture?: boolean; -} -interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; -} -interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; -} -/** - * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) - */ -declare class AbortController { - constructor(); - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - get signal(): AbortSignal; - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void; -} -/** - * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) - */ -declare abstract class AbortSignal extends EventTarget { - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - static abort(reason?: any): AbortSignal; - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - static timeout(delay: number): AbortSignal; - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - static any(signals: AbortSignal[]): AbortSignal; - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - get aborted(): boolean; - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - get reason(): any; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - get onabort(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - set onabort(value: any | null); - /** - * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; -} -interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; -} -interface SchedulerWaitOptions { - signal?: AbortSignal; -} -/** - * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) - */ -declare abstract class ExtendableEvent extends Event { - /** - * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; -} -/** - * The **`CustomEvent`** interface represents events initialized by an application for any purpose. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) - */ -declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) - */ - get detail(): T; -} -interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; -} -/** - * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) - */ -declare class Blob { - constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); - /** - * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) - */ - get size(): number; - /** - * The **`type`** read-only property of the Blob interface returns the MIME type of the file. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) - */ - get type(): string; - /** - * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) - */ - slice(start?: number, end?: number, type?: string): Blob; - /** - * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) - */ - arrayBuffer(): Promise; - /** - * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) - */ - bytes(): Promise; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) - */ - stream(): ReadableStream; -} -interface BlobOptions { - type?: string; -} -/** - * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) - */ -declare class File extends Blob { - constructor( - bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, - name: string, - options?: FileOptions - ); - /** - * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) - */ - get name(): string; - /** - * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) - */ - get lastModified(): number; -} -interface FileOptions { - type?: string; - lastModified?: number; -} -/** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ -declare abstract class CacheStorage { - /** - * The **`open()`** method of the the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - readonly default: Cache; -} -/** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ -declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; -} -interface CacheQueryOptions { - ignoreMethod?: boolean; -} -/** - * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. - * The Workers runtime implements the full surface of this API, but with some differences in - * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) - * compared to those implemented in most browsers. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) - */ -declare abstract class Crypto { - /** - * The **`Crypto.subtle`** read-only property returns a cryptographic operations. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) - */ - get subtle(): SubtleCrypto; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues< - T extends - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | BigInt64Array - | BigUint64Array, - >(buffer: T): T; - /** - * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; -} -/** - * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) - */ -declare abstract class SubtleCrypto { - /** - * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) - */ - encrypt( - algorithm: string | SubtleCryptoEncryptAlgorithm, - key: CryptoKey, - plainText: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt( - algorithm: string | SubtleCryptoEncryptAlgorithm, - key: CryptoKey, - cipherText: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) - */ - sign( - algorithm: string | SubtleCryptoSignAlgorithm, - key: CryptoKey, - data: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) - */ - verify( - algorithm: string | SubtleCryptoSignAlgorithm, - key: CryptoKey, - signature: ArrayBuffer | ArrayBufferView, - data: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest( - algorithm: string | SubtleCryptoHashAlgorithm, - data: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) - */ - generateKey( - algorithm: string | SubtleCryptoGenerateKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - /** - * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) - */ - deriveKey( - algorithm: string | SubtleCryptoDeriveKeyAlgorithm, - baseKey: CryptoKey, - derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits( - algorithm: string | SubtleCryptoDeriveKeyAlgorithm, - baseKey: CryptoKey, - length?: number | null - ): Promise; - /** - * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) - */ - importKey( - format: string, - keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, - algorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - /** - * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) - */ - exportKey(format: string, key: CryptoKey): Promise; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey( - format: string, - key: CryptoKey, - wrappingKey: CryptoKey, - wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm - ): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) - */ - unwrapKey( - format: string, - wrappedKey: ArrayBuffer | ArrayBufferView, - unwrappingKey: CryptoKey, - unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, - unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; -} -/** - * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) - */ -declare abstract class CryptoKey { - /** - * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) - */ - readonly type: string; - /** - * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) - */ - readonly extractable: boolean; - /** - * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) - */ - readonly algorithm: - | CryptoKeyKeyAlgorithm - | CryptoKeyAesKeyAlgorithm - | CryptoKeyHmacKeyAlgorithm - | CryptoKeyRsaKeyAlgorithm - | CryptoKeyEllipticKeyAlgorithm - | CryptoKeyArbitraryKeyAlgorithm; - /** - * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) - */ - readonly usages: string[]; -} -interface CryptoKeyPair { - publicKey: CryptoKey; - privateKey: CryptoKey; -} -interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; -} -interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; -} -interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: ArrayBuffer | ArrayBufferView; - iterations?: number; - hash?: string | SubtleCryptoHashAlgorithm; - $public?: CryptoKey; - info?: ArrayBuffer | ArrayBufferView; -} -interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: ArrayBuffer | ArrayBufferView; - additionalData?: ArrayBuffer | ArrayBufferView; - tagLength?: number; - counter?: ArrayBuffer | ArrayBufferView; - length?: number; - label?: ArrayBuffer | ArrayBufferView; -} -interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: string | SubtleCryptoHashAlgorithm; - modulusLength?: number; - publicExponent?: ArrayBuffer | ArrayBufferView; - length?: number; - namedCurve?: string; -} -interface SubtleCryptoHashAlgorithm { - name: string; -} -interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: string | SubtleCryptoHashAlgorithm; - length?: number; - namedCurve?: string; - compressed?: boolean; -} -interface SubtleCryptoSignAlgorithm { - name: string; - hash?: string | SubtleCryptoHashAlgorithm; - dataLength?: number; - saltLength?: number; -} -interface CryptoKeyKeyAlgorithm { - name: string; -} -interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; -} -interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; -} -interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; -} -interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; -} -interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; -} -declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; -} -/** - * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) - */ -declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) - */ - decode(input?: ArrayBuffer | ArrayBufferView, options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -/** - * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) - */ -declare class TextEncoder { - constructor(); - /** - * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) - */ - encode(input?: string): Uint8Array; - /** - * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) - */ - encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; -} -interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; -} -interface TextDecoderDecodeOptions { - stream: boolean; -} -interface TextEncoderEncodeIntoResult { - read: number; - written: number; -} -/** - * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) - */ -declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) - */ - get filename(): string; - /** - * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) - */ - get message(): string; - /** - * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) - */ - get lineno(): number; - /** - * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) - */ - get colno(): number; - /** - * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) - */ - get error(): any; -} -interface ErrorEventErrorEventInit { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; -} -/** - * The **`MessageEvent`** interface represents a message received by a target object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) - */ -declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of the origin of the message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null; - /** - * The **`lastEventId`** read-only property of the unique ID for the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string; - /** - * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[]; -} -interface MessageEventInit { - data: ArrayBuffer | string; -} -/** - * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) - */ -declare abstract class PromiseRejectionEvent extends Event { - /** - * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) - */ - readonly reason: any; -} -/** - * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) - */ -declare class FormData { - constructor(); - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: Blob, filename?: string): void; - /** - * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) - */ - delete(name: string): void; - /** - * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) - */ - get(name: string): (File | string) | null; - /** - * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) - */ - getAll(name: string): (File | string)[]; - /** - * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: Blob, filename?: string): void; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[key: string, value: File | string]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator; - forEach( - callback: (this: This, value: File | string, key: string, parent: FormData) => void, - thisArg?: This - ): void; - [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; -} -interface ContentOptions { - html?: boolean; -} -declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; -} -interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; -} -interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; -} -interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; -} -interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; -} -interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; -} -interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; -} -interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; -} -interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; -} -/** - * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) - */ -declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) - */ - respondWith(promise: Response | Promise): void; - passThroughOnException(): void; -} -type HeadersInit = Headers | Iterable> | Record; -/** - * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) - */ -declare class Headers { - constructor(init?: HeadersInit); - /** - * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) - */ - get(name: string): string | null; - getAll(name: string): string[]; - /** - * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) - */ - getSetCookie(): string[]; - /** - * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) - */ - set(name: string, value: string): void; - /** - * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) - */ - delete(name: string): void; - forEach( - callback: (this: This, value: string, key: string, parent: Headers) => void, - thisArg?: This - ): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[key: string, value: string]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[key: string, value: string]>; -} -type BodyInit = - | ReadableStream - | string - | ArrayBuffer - | ArrayBufferView - | Blob - | URLSearchParams - | FormData; -declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; -} -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: ResponseInit | Response): Response; -}; -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -interface Response extends Body { - /** - * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) - */ - clone(): Response; - /** - * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) - */ - status: number; - /** - * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) - */ - statusText: string; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) - */ - ok: boolean; - /** - * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) - */ - redirected: boolean; - /** - * The **`url`** read-only property of the Response interface contains the URL of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) - */ - url: string; - webSocket: WebSocket | null; - cf: any | undefined; - /** - * The **`type`** read-only property of the Response interface contains the type of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) - */ - type: 'default' | 'error'; -} -interface ResponseInit { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: WebSocket | null; - encodeBody?: 'automatic' | 'manual'; -} -type RequestInfo> = - | Request - | string; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -declare var Request: { - prototype: Request; - new >( - input: RequestInfo | URL, - init?: RequestInit - ): Request; -}; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -interface Request> extends Body { - /** - * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) - */ - clone(): Request; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) - */ - method: string; - /** - * The **`url`** read-only property of the Request interface contains the URL of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) - */ - url: string; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) - */ - redirect: string; - fetcher: Fetcher | null; - /** - * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) - */ - signal: AbortSignal; - cf: Cf | undefined; - /** - * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) - */ - integrity: string; - /** - * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) - */ - keepalive: boolean; - /** - * The **`cache`** read-only property of the Request interface contains the cache mode of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: 'no-store' | 'no-cache'; -} -interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: Fetcher | null; - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: 'no-store' | 'no-cache'; - /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string; - /* An AbortSignal to set request's signal. */ - signal?: AbortSignal | null; - encodeResponseBody?: 'automatic' | 'manual'; -} -type Service< - T extends - | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) - | Rpc.WorkerEntrypointBranded - | ExportedHandler - | undefined = undefined, -> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded - ? Fetcher> - : T extends Rpc.WorkerEntrypointBranded - ? Fetcher - : T extends Exclude - ? never - : Fetcher; -type Fetcher< - T extends Rpc.EntrypointBranded | undefined = undefined, - Reserved extends string = never, -> = (T extends Rpc.EntrypointBranded - ? Rpc.Provider - : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; -}; -interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = - | { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; - } - | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; - }; -interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: 'text'): Promise; - get(key: Key, type: 'json'): Promise; - get(key: Key, type: 'arrayBuffer'): Promise; - get(key: Key, type: 'stream'): Promise; - get(key: Key, options?: KVNamespaceGetOptions<'text'>): Promise; - get( - key: Key, - options?: KVNamespaceGetOptions<'json'> - ): Promise; - get(key: Key, options?: KVNamespaceGetOptions<'arrayBuffer'>): Promise; - get(key: Key, options?: KVNamespaceGetOptions<'stream'>): Promise; - get(key: Array, type: 'text'): Promise>; - get( - key: Array, - type: 'json' - ): Promise>; - get( - key: Array, - options?: Partial> - ): Promise>; - get( - key: Array, - options?: KVNamespaceGetOptions<'text'> - ): Promise>; - get( - key: Array, - options?: KVNamespaceGetOptions<'json'> - ): Promise>; - list( - options?: KVNamespaceListOptions - ): Promise>; - put( - key: Key, - value: string | ArrayBuffer | ArrayBufferView | ReadableStream, - options?: KVNamespacePutOptions - ): Promise; - getWithMetadata( - key: Key, - options?: Partial> - ): Promise>; - getWithMetadata( - key: Key, - type: 'text' - ): Promise>; - getWithMetadata( - key: Key, - type: 'json' - ): Promise>; - getWithMetadata( - key: Key, - type: 'arrayBuffer' - ): Promise>; - getWithMetadata( - key: Key, - type: 'stream' - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'text'> - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'json'> - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'arrayBuffer'> - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'stream'> - ): Promise>; - getWithMetadata( - key: Array, - type: 'text' - ): Promise>>; - getWithMetadata( - key: Array, - type: 'json' - ): Promise>>; - getWithMetadata( - key: Array, - options?: Partial> - ): Promise>>; - getWithMetadata( - key: Array, - options?: KVNamespaceGetOptions<'text'> - ): Promise>>; - getWithMetadata( - key: Array, - options?: KVNamespaceGetOptions<'json'> - ): Promise>>; - delete(key: Key): Promise; -} -interface KVNamespaceListOptions { - limit?: number; - prefix?: string | null; - cursor?: string | null; -} -interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; -} -interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: any | null; -} -interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; -} -type QueueContentType = 'text' | 'bytes' | 'json' | 'v8'; -interface Queue { - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch( - messages: Iterable>, - options?: QueueSendBatchOptions - ): Promise; -} -interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueSendBatchOptions { - delaySeconds?: number; -} -interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueRetryOptions { - delaySeconds?: number; -} -interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; -} -interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface MessageBatch { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; -} -interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ('httpMetadata' | 'customMetadata')[]; -} -declare abstract class R2Bucket { - head(key: string): Promise; - get( - key: string, - options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - } - ): Promise; - get(key: string, options?: R2GetOptions): Promise; - put( - key: string, - value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, - options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - } - ): Promise; - put( - key: string, - value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, - options?: R2PutOptions - ): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; -} -interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart( - partNumber: number, - value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, - options?: R2UploadPartOptions - ): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; -} -interface R2UploadedPart { - partNumber: number; - etag: string; -} -declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; -} -interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -type R2Range = - | { - offset: number; - length?: number; - } - | { - offset?: number; - length: number; - } - | { - suffix: number; - }; -interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; -} -interface R2GetOptions { - onlyIf?: R2Conditional | Headers; - range?: R2Range | Headers; - ssecKey?: ArrayBuffer | string; -} -interface R2PutOptions { - onlyIf?: R2Conditional | Headers; - httpMetadata?: R2HTTPMetadata | Headers; - customMetadata?: Record; - md5?: (ArrayBuffer | ArrayBufferView) | string; - sha1?: (ArrayBuffer | ArrayBufferView) | string; - sha256?: (ArrayBuffer | ArrayBufferView) | string; - sha384?: (ArrayBuffer | ArrayBufferView) | string; - sha512?: (ArrayBuffer | ArrayBufferView) | string; - storageClass?: string; - ssecKey?: ArrayBuffer | string; -} -interface R2MultipartOptions { - httpMetadata?: R2HTTPMetadata | Headers; - customMetadata?: Record; - storageClass?: string; - ssecKey?: ArrayBuffer | string; -} -interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; -} -interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; -} -interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; -} -type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ( - | { - truncated: true; - cursor: string; - } - | { - truncated: false; - } -); -interface R2UploadPartOptions { - ssecKey?: ArrayBuffer | string; -} -declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface QueuingStrategy { - highWaterMark?: number | bigint; - size?: (chunk: T) => number | bigint; -} -interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; -} -interface UnderlyingByteSource { - type: 'bytes'; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; -} -interface UnderlyingSource { - type?: '' | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number | bigint; -} -interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; -} -interface StreamPipeOptions { - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - preventAbort?: boolean; - preventCancel?: boolean; - signal?: AbortSignal; -} -type ReadableStreamReadResult = - | { - done: false; - value: R; - } - | { - done: true; - value?: undefined; - }; -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -interface ReadableStream { - /** - * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) - */ - get locked(): boolean; - /** - * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) - */ - cancel(reason?: any): Promise; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /** - * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) - */ - pipeThrough( - transform: ReadableWritablePair, - options?: StreamPipeOptions - ): ReadableStream; - /** - * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) - */ - pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) - */ - tee(): [ReadableStream, ReadableStream]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; -} -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -declare const ReadableStream: { - prototype: ReadableStream; - new ( - underlyingSource: UnderlyingByteSource, - strategy?: QueuingStrategy - ): ReadableStream; - new ( - underlyingSource?: UnderlyingSource, - strategy?: QueuingStrategy - ): ReadableStream; -}; -/** - * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) - */ -declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) - */ - read(): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) - */ - releaseLock(): void; -} -/** - * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) - */ -declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast( - minElements: number, - view: T - ): Promise>; -} -interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; -} -interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: 'byob'; -} -/** - * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) - */ -declare abstract class ReadableStreamBYOBRequest { - /** - * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) - */ - get view(): Uint8Array | null; - /** - * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) - */ - respond(bytesWritten: number): void; - /** - * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) - */ - respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; - get atLeast(): number | null; -} -/** - * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) - */ -declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) - */ - error(reason: any): void; -} -/** - * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) - */ -declare abstract class ReadableByteStreamController { - /** - * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) - */ - get byobRequest(): ReadableStreamBYOBRequest | null; - /** - * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) - */ - enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /** - * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) - */ - error(reason: any): void; -} -/** - * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) - */ -declare abstract class WritableStreamDefaultController { - /** - * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) - */ - get signal(): AbortSignal; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) - */ - error(reason?: any): void; -} -/** - * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) - */ -declare abstract class TransformStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) - */ - enqueue(chunk?: O): void; - /** - * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) - */ - error(reason: any): void; - /** - * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) - */ - terminate(): void; -} -interface ReadableWritablePair { - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream; - readable: ReadableStream; -} -/** - * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) - */ -declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) - */ - get locked(): boolean; - /** - * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; -} -/** - * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) - */ -declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) - */ - get ready(): Promise; - /** - * The **`desiredSize`** read-only property of the to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; -} -/** - * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) - */ -declare class TransformStream { - constructor( - transformer?: Transformer, - writableStrategy?: QueuingStrategy, - readableStrategy?: QueuingStrategy - ); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; -} -declare class FixedLengthStream extends IdentityTransformStream { - constructor( - expectedLength: number | bigint, - queuingStrategy?: IdentityTransformStreamQueuingStrategy - ); -} -declare class IdentityTransformStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - Uint8Array -> { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: number | bigint; -} -interface ReadableStreamValuesOptions { - preventCancel?: boolean; -} -/** - * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) - */ -declare class CompressionStream extends TransformStream { - constructor(format: 'gzip' | 'deflate' | 'deflate-raw'); -} -/** - * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) - */ -declare class DecompressionStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - Uint8Array -> { - constructor(format: 'gzip' | 'deflate' | 'deflate-raw'); -} -/** - * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) - */ -declare class TextEncoderStream extends TransformStream { - constructor(); - get encoding(): string; -} -/** - * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) - */ -declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; -} -/** - * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) - */ -declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -/** - * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) - */ -declare class CountQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; -} -interface ScriptVersion { - id?: string; - tag?: string; - message?: string; -} -declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; -} -interface TraceItem { - readonly event: - | ( - | TraceItemFetchEventInfo - | TraceItemJsRpcEventInfo - | TraceItemScheduledEventInfo - | TraceItemAlarmEventInfo - | TraceItemQueueEventInfo - | TraceItemEmailEventInfo - | TraceItemTailEventInfo - | TraceItemCustomEventInfo - | TraceItemHibernatableWebSocketEventInfo - ) - | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - readonly scriptVersion?: ScriptVersion; - readonly dispatchNamespace?: string; - readonly scriptTags?: string[]; - readonly durableObjectId?: string; - readonly outcome: string; - readonly executionModel: string; - readonly truncated: boolean; - readonly cpuTime: number; - readonly wallTime: number; -} -interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; -} -interface TraceItemCustomEventInfo {} -interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; -} -interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; -} -interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; -} -interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; -} -interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; -} -interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoResponse { - readonly status: number; -} -interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; -} -interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: - | TraceItemHibernatableWebSocketEventInfoMessage - | TraceItemHibernatableWebSocketEventInfoClose - | TraceItemHibernatableWebSocketEventInfoError; -} -interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; -} -interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; -} -interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; -} -interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; -} -interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; -} -interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; -} -interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; -} -interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; -} -/** - * The **`URL`** interface is used to parse, construct, normalize, and encode URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) - */ -declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) - */ - get origin(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - get href(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - set href(value: string); - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - get protocol(): string; - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - set protocol(value: string); - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - get username(): string; - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - set username(value: string); - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - get password(): string; - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - set password(value: string); - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - get host(): string; - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - set host(value: string); - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - get hostname(): string; - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - set hostname(value: string); - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - get port(): string; - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - set port(value: string); - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - get pathname(): string; - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - set pathname(value: string); - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - get search(): string; - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - set search(value: string); - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - get hash(): string; - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) - */ - get searchParams(): URLSearchParams; - /** - * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) - */ - toJSON(): string; - /*function toString() { [native code] }*/ - toString(): string; - /** - * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) - */ - static canParse(url: string, base?: string): boolean; - /** - * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) - */ - static parse(url: string, base?: string): URL | null; - /** - * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) - */ - static createObjectURL(object: File | Blob): string; - /** - * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) - */ - static revokeObjectURL(object_url: string): void; -} -/** - * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) - */ -declare class URLSearchParams { - constructor(init?: Iterable> | Record | string); - /** - * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) - */ - get size(): number; - /** - * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) - */ - delete(name: string, value?: string): void; - /** - * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) - */ - get(name: string): string | null; - /** - * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) - */ - getAll(name: string): string[]; - /** - * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) - */ - has(name: string, value?: string): boolean; - /** - * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) - */ - set(name: string, value: string): void; - /** - * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[key: string, value: string]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach( - callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, - thisArg?: This - ): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[key: string, value: string]>; -} -declare class URLPattern { - constructor( - input?: string | URLPatternInit, - baseURL?: string | URLPatternOptions, - patternOptions?: URLPatternOptions - ); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: string | URLPatternInit, baseURL?: string): boolean; - exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; -} -interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; -} -interface URLPatternComponentResult { - input: string; - groups: Record; -} -interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; -} -interface URLPatternOptions { - ignoreCase?: boolean; -} -/** - * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) - */ -declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) - */ - readonly code: number; - /** - * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) - */ - readonly reason: string; - /** - * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) - */ - readonly wasClean: boolean; -} -interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; -} -type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: string[] | string): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -interface WebSocket extends EventTarget { - accept(): void; - /** - * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) - */ - readyState: number; - /** - * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) - */ - url: string | null; - /** - * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) - */ - protocol: string | null; - /** - * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) - */ - extensions: string | null; -} -declare const WebSocketPair: { - new (): { - 0: WebSocket; - 1: WebSocket; - }; -}; -interface SqlStorage { - exec>( - query: string, - ...bindings: any[] - ): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement {} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): - | { - done?: false; - value: T; - } - | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; -} -interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): 'on' | 'off' | 'starttls'; - close(): Promise; - startTls(options?: TlsOptions): Socket; -} -interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: number | bigint; -} -interface SocketAddress { - hostname: string; - port: number; -} -interface TlsOptions { - expectedServerHostname?: string; -} -interface SocketInfo { - remoteAddress?: string; - localAddress?: string; -} -/** - * The **`EventSource`** interface is web content's interface to server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) - */ -declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} -interface Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; -} -interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - hardTimeout?: number | bigint; -} -/** - * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) - */ -declare abstract class MessagePort extends EventTarget { - /** - * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void; - /** - * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void; - /** - * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); -} -/** - * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) - */ -declare class MessageChannel { - constructor(); - /** - * The **`port1`** read-only property of the the port attached to the context that originated the channel. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) - */ - readonly port1: MessagePort; - /** - * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) - */ - readonly port2: MessagePort; -} -interface MessagePortPostMessageOptions { - transfer?: any[]; -} -type LoopbackForExport< - T extends - | (new (...args: any[]) => Rpc.EntrypointBranded) - | ExportedHandler - | undefined = undefined, -> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded - ? LoopbackServiceStub> - : T extends new (...args: any[]) => Rpc.DurableObjectBranded - ? LoopbackDurableObjectClass> - : T extends ExportedHandler - ? LoopbackServiceStub - : undefined; -type LoopbackServiceStub = - Fetcher & - (T extends CloudflareWorkersModule.WorkerEntrypoint - ? (opts: { props?: Props }) => Fetcher - : (opts: { props?: any }) => Fetcher); -type LoopbackDurableObjectClass = - DurableObjectClass & - (T extends CloudflareWorkersModule.DurableObject - ? (opts: { props?: Props }) => DurableObjectClass - : (opts: { props?: any }) => DurableObjectClass); -interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[string, T]>; - put(key: string, value: T): void; - delete(key: string): boolean; -} -interface SyncKvListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; -} -interface WorkerStub { - getEntrypoint( - name?: string, - options?: WorkerStubEntrypointOptions - ): Fetcher; -} -interface WorkerStubEntrypointOptions { - props?: any; -} -interface WorkerLoader { - get( - name: string | null, - getCode: () => WorkerLoaderWorkerCode | Promise - ): WorkerStub; -} -interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; -} -interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - mainModule: string; - modules: Record; - env?: any; - globalOutbound?: Fetcher | null; - tails?: Fetcher[]; - streamingTails?: Fetcher[]; -} -/** - * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, - * as well as timing of subrequests and other operations. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) - */ -declare abstract class Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - get timeOrigin(): number; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number; -} -type AiImageClassificationInput = { - image: number[]; -}; -type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; -} -type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; -} -type AiImageTextToTextInput = { - image: string; - prompt?: string; - max_tokens?: number; - temperature?: number; - ignore_eos?: boolean; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageTextToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; -}; -type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; -}; -declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiObjectDetectionInput = { - image: number[]; -}; -type AiObjectDetectionOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; -} -type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; -}; -type AiSentenceSimilarityOutput = number[]; -declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; -} -type AiAutomaticSpeechRecognitionInput = { - audio: number[]; -}; -type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; -}; -declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; -} -type AiSummarizationInput = { - input_text: string; - max_length?: number; -}; -type AiSummarizationOutput = { - summary: string; -}; -declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; -} -type AiTextClassificationInput = { - text: string; -}; -type AiTextClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; -} -type AiTextEmbeddingsInput = { - text: string | string[]; -}; -type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; -}; -declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; -} -type RoleScopedChatInput = { - role: 'user' | 'assistant' | 'system' | 'tool' | (string & NonNullable); - content: string; - name?: string; -}; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: 'object' | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; -type AiTextGenerationToolInput = { - type: 'function' | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: 'object' | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; - }; -}; -type AiTextGenerationFunctionsInput = { - name: string; - code: string; -}; -type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; -}; -type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: - | AiTextGenerationToolInput[] - | AiTextGenerationToolLegacyInput[] - | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; -}; -type AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; -}; -type AiTextGenerationToolOutput = { - id: string; - type: 'function'; - function: { - name: string; - arguments: string; - }; -}; -type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; -}; -type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; -}; -declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; -} -type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = - | Uint8Array - | { - audio: string; - }; -declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; -} -type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; -}; -type AiTextToImageOutput = ReadableStream; -declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; -} -type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; -}; -type AiTranslationOutput = { - translated_text?: string; -}; -declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; -} -/** - * Workers AI support for OpenAI's Responses API - * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts - * - * It's a stripped down version from its source. - * It currently supports basic function calling, json mode and accepts images as input. - * - * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. - * We plan to add those incrementally as model + platform capabilities evolve. - */ -type ResponsesInput = { - background?: boolean | null; - conversation?: string | ResponseConversationParam | null; - include?: Array | null; - input?: string | ResponseInput; - instructions?: string | null; - max_output_tokens?: number | null; - parallel_tool_calls?: boolean | null; - previous_response_id?: string | null; - prompt_cache_key?: string; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; - stream?: boolean | null; - stream_options?: StreamOptions | null; - temperature?: number | null; - text?: ResponseTextConfig; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - truncation?: 'auto' | 'disabled' | null; -}; -type ResponsesOutput = { - id?: string; - created_at?: number; - output_text?: string; - error?: ResponseError | null; - incomplete_details?: ResponseIncompleteDetails | null; - instructions?: string | Array | null; - object?: 'response'; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - max_output_tokens?: number | null; - previous_response_id?: string | null; - prompt?: ResponsePrompt | null; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; - status?: ResponseStatus; - text?: ResponseTextConfig; - truncation?: 'auto' | 'disabled' | null; - usage?: ResponseUsage; -}; -type EasyInputMessage = { - content: string | ResponseInputMessageContentList; - role: 'user' | 'assistant' | 'system' | 'developer'; - type?: 'message'; -}; -type ResponsesFunctionTool = { - name: string; - parameters: { - [key: string]: unknown; - } | null; - strict: boolean | null; - type: 'function'; - description?: string | null; -}; -type ResponseIncompleteDetails = { - reason?: 'max_output_tokens' | 'content_filter'; -}; -type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; -}; -type Reasoning = { - effort?: ReasoningEffort | null; - generate_summary?: 'auto' | 'concise' | 'detailed' | null; - summary?: 'auto' | 'concise' | 'detailed' | null; -}; -type ResponseContent = - | ResponseInputText - | ResponseInputImage - | ResponseOutputText - | ResponseOutputRefusal - | ResponseContentReasoningText; -type ResponseContentReasoningText = { - text: string; - type: 'reasoning_text'; -}; -type ResponseConversationParam = { - id: string; -}; -type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: 'response.created'; -}; -type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: 'custom_tool_call_output'; - id?: string; -}; -type ResponseError = { - code: - | 'server_error' - | 'rate_limit_exceeded' - | 'invalid_prompt' - | 'vector_store_timeout' - | 'invalid_image' - | 'invalid_image_format' - | 'invalid_base64_image' - | 'invalid_image_url' - | 'image_too_large' - | 'image_too_small' - | 'image_parse_error' - | 'image_content_policy_violation' - | 'invalid_image_mode' - | 'image_file_too_large' - | 'unsupported_image_media_type' - | 'empty_image_file' - | 'failed_to_download_image' - | 'image_file_not_found'; - message: string; -}; -type ResponseErrorEvent = { - code: string | null; - message: string; - param: string | null; - sequence_number: number; - type: 'error'; -}; -type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: 'response.failed'; -}; -type ResponseFormatText = { - type: 'text'; -}; -type ResponseFormatJSONObject = { - type: 'json_object'; -}; -type ResponseFormatTextConfig = - | ResponseFormatText - | ResponseFormatTextJSONSchemaConfig - | ResponseFormatJSONObject; -type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: 'json_schema'; - description?: string; - strict?: boolean | null; -}; -type ResponseFunctionCallArgumentsDeltaEvent = { - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: 'response.function_call_arguments.delta'; -}; -type ResponseFunctionCallArgumentsDoneEvent = { - arguments: string; - item_id: string; - name: string; - output_index: number; - sequence_number: number; - type: 'response.function_call_arguments.done'; -}; -type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; -type ResponseFunctionCallOutputItemList = Array; -type ResponseFunctionToolCall = { - arguments: string; - call_id: string; - name: string; - type: 'function_call'; - id?: string; - status?: 'in_progress' | 'completed' | 'incomplete'; -}; -interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; -} -type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: 'function_call_output'; - status?: 'in_progress' | 'completed' | 'incomplete'; -}; -type ResponseIncludable = 'message.input_image.image_url' | 'message.output_text.logprobs'; -type ResponseIncompleteEvent = { - response: Response; - sequence_number: number; - type: 'response.incomplete'; -}; -type ResponseInput = Array; -type ResponseInputContent = ResponseInputText | ResponseInputImage; -type ResponseInputImage = { - detail: 'low' | 'high' | 'auto'; - type: 'input_image'; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputImageContent = { - type: 'input_image'; - detail?: 'low' | 'high' | 'auto' | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = - | EasyInputMessage - | ResponseInputItemMessage - | ResponseOutputMessage - | ResponseFunctionToolCall - | ResponseInputItemFunctionCallOutput - | ResponseReasoningItem; -type ResponseInputItemFunctionCallOutput = { - call_id: string; - output: string | ResponseFunctionCallOutputItemList; - type: 'function_call_output'; - id?: string | null; - status?: 'in_progress' | 'completed' | 'incomplete' | null; -}; -type ResponseInputItemMessage = { - content: ResponseInputMessageContentList; - role: 'user' | 'system' | 'developer'; - status?: 'in_progress' | 'completed' | 'incomplete'; - type?: 'message'; -}; -type ResponseInputMessageContentList = Array; -type ResponseInputMessageItem = { - id: string; - content: ResponseInputMessageContentList; - role: 'user' | 'system' | 'developer'; - status?: 'in_progress' | 'completed' | 'incomplete'; - type?: 'message'; -}; -type ResponseInputText = { - text: string; - type: 'input_text'; -}; -type ResponseInputTextContent = { - text: string; - type: 'input_text'; -}; -type ResponseItem = - | ResponseInputMessageItem - | ResponseOutputMessage - | ResponseFunctionToolCallItem - | ResponseFunctionToolCallOutputItem; -type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; -type ResponseOutputItemAddedEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: 'response.output_item.added'; -}; -type ResponseOutputItemDoneEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: 'response.output_item.done'; -}; -type ResponseOutputMessage = { - id: string; - content: Array; - role: 'assistant'; - status: 'in_progress' | 'completed' | 'incomplete'; - type: 'message'; -}; -type ResponseOutputRefusal = { - refusal: string; - type: 'refusal'; -}; -type ResponseOutputText = { - text: string; - type: 'output_text'; - logprobs?: Array; -}; -type ResponseReasoningItem = { - id: string; - summary: Array; - type: 'reasoning'; - content?: Array; - encrypted_content?: string | null; - status?: 'in_progress' | 'completed' | 'incomplete'; -}; -type ResponseReasoningSummaryItem = { - text: string; - type: 'summary_text'; -}; -type ResponseReasoningContentItem = { - text: string; - type: 'reasoning_text'; -}; -type ResponseReasoningTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: 'response.reasoning_text.delta'; -}; -type ResponseReasoningTextDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - sequence_number: number; - text: string; - type: 'response.reasoning_text.done'; -}; -type ResponseRefusalDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: 'response.refusal.delta'; -}; -type ResponseRefusalDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - refusal: string; - sequence_number: number; - type: 'response.refusal.done'; -}; -type ResponseStatus = - | 'completed' - | 'failed' - | 'in_progress' - | 'cancelled' - | 'queued' - | 'incomplete'; -type ResponseStreamEvent = - | ResponseCompletedEvent - | ResponseCreatedEvent - | ResponseErrorEvent - | ResponseFunctionCallArgumentsDeltaEvent - | ResponseFunctionCallArgumentsDoneEvent - | ResponseFailedEvent - | ResponseIncompleteEvent - | ResponseOutputItemAddedEvent - | ResponseOutputItemDoneEvent - | ResponseReasoningTextDeltaEvent - | ResponseReasoningTextDoneEvent - | ResponseRefusalDeltaEvent - | ResponseRefusalDoneEvent - | ResponseTextDeltaEvent - | ResponseTextDoneEvent; -type ResponseCompletedEvent = { - response: Response; - sequence_number: number; - type: 'response.completed'; -}; -type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: 'low' | 'medium' | 'high' | null; -}; -type ResponseTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - type: 'response.output_text.delta'; -}; -type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: 'response.output_text.done'; -}; -type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; -}; -type TopLogprob = { - token?: string; - logprob?: number; -}; -type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; -}; -type Tool = ResponsesFunctionTool; -type ToolChoiceFunction = { - name: string; - type: 'function'; -}; -type ToolChoiceOptions = 'none'; -type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | null; -type StreamOptions = { - include_obfuscation?: boolean; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - }[]; - }; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; - } - | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; -} -type Ai_Cf_Openai_Whisper_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; - }; -interface Ai_Cf_Openai_Whisper_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; -} -type Ai_Cf_Meta_M2M100_1_2B_Input = - | { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - }[]; - }; -type Ai_Cf_Meta_M2M100_1_2B_Output = - | { - /** - * The translated text in the target language - */ - translated_text?: string; - } - | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; -interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; -} -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - }[]; - }; -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; - } - | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; -} -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - }[]; - }; -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; - } - | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; -} -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = - | string - | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - image: number[] | (string & NonNullable); - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - }; -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; -} -declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; -} -type Ai_Cf_Openai_Whisper_Tiny_En_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; - }; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean; - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string; - /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. - */ - language_probability?: number; - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number; - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number; - }; - /** - * The complete transcription of the audio. - */ - text: string; - /** - * The total number of words in the transcription. - */ - word_count?: number; - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number; - /** - * The transcription of the segment. - */ - text?: string; - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number; - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number; - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number; - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; -} -type Ai_Cf_Baai_Bge_M3_Input = - | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts - | Ai_Cf_Baai_Bge_M3_Input_Embedding - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: ( - | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 - | Ai_Cf_Baai_Bge_M3_Input_Embedding_1 - )[]; - }; -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_Embedding { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -type Ai_Cf_Baai_Bge_M3_Output = - | Ai_Cf_Baai_Bge_M3_Ouput_Query - | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts - | Ai_Cf_Baai_Bge_M3_Ouput_Embedding - | Ai_Cf_Baai_Bge_M3_AsyncResponse; -interface Ai_Cf_Baai_Bge_M3_Ouput_Query { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { - response?: number[][]; - shape?: number[]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; -} -interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; -} -interface Ai_Cf_Baai_Bge_M3_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = - | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt - | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - image?: number[] | (string & NonNullable); - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; -} -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { - /** - * The generated text response from the model - */ - response?: string; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; - }[]; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = - | { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; - } - | string - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender must alternate between 'user' and 'assistant'. - */ - role: 'user' | 'assistant'; - /** - * The content of the message as a string. - */ - content: string; - }[]; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Dictate the output format of the generated response. - */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: - | string - | { - /** - * Whether the conversation is safe or not. - */ - safe?: boolean; - /** - * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. - */ - categories?: string[]; - }; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = - | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt - | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; -} -type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; -interface Ai_Cf_Qwen_Qwq_32B_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwq_32B_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = - | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt - | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; -} -type Ai_Cf_Google_Gemma_3_12B_It_Input = - | Ai_Cf_Google_Gemma_3_12B_It_Prompt - | Ai_Cf_Google_Gemma_3_12B_It_Messages; -interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Google_Gemma_3_12B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Google_Gemma_3_12B_It_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { - requests: ( - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner - )[]; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The tool call id. - */ - id?: string; - /** - * Specifies the type of tool (e.g., 'function'). - */ - type?: string; - /** - * Details of the function tool. - */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - }; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { - requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response - | string - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'chat.completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: 'function'; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'text_completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { - inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; -} -interface Ai_Cf_Deepgram_Nova_3_Input { - audio: { - body: object; - contentType: string; - }; - /** - * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. - */ - custom_topic_mode?: 'extended' | 'strict'; - /** - * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 - */ - custom_topic?: string; - /** - * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param - */ - custom_intent_mode?: 'extended' | 'strict'; - /** - * Custom intents you want the model to detect within your input audio if present - */ - custom_intent?: string; - /** - * Identifies and extracts key entities from content in submitted audio - */ - detect_entities?: boolean; - /** - * Identifies the dominant language spoken in submitted audio - */ - detect_language?: boolean; - /** - * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 - */ - diarize?: boolean; - /** - * Identify and extract key entities from content in submitted audio - */ - dictation?: boolean; - /** - * Specify the expected encoding of your submitted audio - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'amr-nb' | 'amr-wb' | 'opus' | 'speex' | 'g729'; - /** - * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing - */ - extra?: string; - /** - * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' - */ - filler_words?: boolean; - /** - * Key term prompting can boost or suppress specialized terminology and brands. - */ - keyterm?: string; - /** - * Keywords can boost or suppress specialized terminology and brands. - */ - keywords?: string; - /** - * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. - */ - language?: string; - /** - * Spoken measurements will be converted to their corresponding abbreviations. - */ - measurements?: boolean; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. - */ - mip_opt_out?: boolean; - /** - * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio - */ - mode?: 'general' | 'medical' | 'finance'; - /** - * Transcribe each audio channel independently. - */ - multichannel?: boolean; - /** - * Numerals converts numbers from written format to numerical format. - */ - numerals?: boolean; - /** - * Splits audio into paragraphs to improve transcript readability. - */ - paragraphs?: boolean; - /** - * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. - */ - profanity_filter?: boolean; - /** - * Add punctuation and capitalization to the transcript. - */ - punctuate?: boolean; - /** - * Redaction removes sensitive information from your transcripts. - */ - redact?: string; - /** - * Search for terms or phrases in submitted audio and replaces them. - */ - replace?: string; - /** - * Search for terms or phrases in submitted audio. - */ - search?: string; - /** - * Recognizes the sentiment throughout a transcript or text. - */ - sentiment?: boolean; - /** - * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. - */ - smart_format?: boolean; - /** - * Detect topics throughout a transcript or text. - */ - topics?: boolean; - /** - * Segments speech into meaningful semantic units. - */ - utterances?: boolean; - /** - * Seconds to wait before detecting a pause between words in submitted audio. - */ - utt_split?: number; - /** - * The number of channels in the submitted audio - */ - channels?: number; - /** - * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. - */ - interim_results?: boolean; - /** - * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing - */ - endpointing?: string; - /** - * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. - */ - vad_events?: boolean; - /** - * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. - */ - utterance_end_ms?: boolean; -} -interface Ai_Cf_Deepgram_Nova_3_Output { - results?: { - channels?: { - alternatives?: { - confidence?: number; - transcript?: string; - words?: { - confidence?: number; - end?: number; - start?: number; - word?: string; - }[]; - }[]; - }[]; - summary?: { - result?: string; - short?: string; - }; - sentiments?: { - segments?: { - text?: string; - start_word?: number; - end_word?: number; - sentiment?: string; - sentiment_score?: number; - }[]; - average?: { - sentiment?: string; - sentiment_score?: number; - }; - }; - }; -} -declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { - inputs: Ai_Cf_Deepgram_Nova_3_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { - queries?: string | string[]; - /** - * Optional instruction for the task - */ - instruction?: string; - documents?: string | string[]; - text?: string | string[]; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { - data?: number[][]; - shape?: number[]; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { - inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; -} -type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = - | { - /** - * readable stream with audio data and content-type specified for that data - */ - audio: { - body: object; - contentType: string; - }; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: 'uint8' | 'float32' | 'float64'; - } - | { - /** - * base64 encoded audio data - */ - audio: string; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: 'uint8' | 'float32' | 'float64'; - }; -interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { - /** - * if true, end-of-turn was detected - */ - is_complete?: boolean; - /** - * probability of the end-of-turn detection - */ - probability?: number; -} -declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { - inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; - postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; -} -interface Ai_Cf_Leonardo_Phoenix_1_0_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * Specify what to exclude from the generated images - */ - negative_prompt?: string; -} -/** - * The generated image in JPEG format - */ -type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; -declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { - inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - steps?: number; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { - inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; -} -interface Ai_Cf_Deepgram_Aura_1_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: - | 'angus' - | 'asteria' - | 'arcas' - | 'orion' - | 'orpheus' - | 'athena' - | 'luna' - | 'zeus' - | 'perseus' - | 'helios' - | 'hera' - | 'stella'; - /** - * Encoding of the output audio. - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: 'none' | 'wav' | 'ogg'; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_1_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { - inputs: Ai_Cf_Deepgram_Aura_1_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { - /** - * Input text to translate. Can be a single string or a list of strings. - */ - text: string | string[]; - /** - * Target langauge to translate to - */ - target_language: - | 'asm_Beng' - | 'awa_Deva' - | 'ben_Beng' - | 'bho_Deva' - | 'brx_Deva' - | 'doi_Deva' - | 'eng_Latn' - | 'gom_Deva' - | 'gon_Deva' - | 'guj_Gujr' - | 'hin_Deva' - | 'hne_Deva' - | 'kan_Knda' - | 'kas_Arab' - | 'kas_Deva' - | 'kha_Latn' - | 'lus_Latn' - | 'mag_Deva' - | 'mai_Deva' - | 'mal_Mlym' - | 'mar_Deva' - | 'mni_Beng' - | 'mni_Mtei' - | 'npi_Deva' - | 'ory_Orya' - | 'pan_Guru' - | 'san_Deva' - | 'sat_Olck' - | 'snd_Arab' - | 'snd_Deva' - | 'tam_Taml' - | 'tel_Telu' - | 'urd_Arab' - | 'unr_Deva'; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { - /** - * Translated texts - */ - translations: string[]; -} -declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { - inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; - postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { - requests: ( - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 - )[]; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response - | string - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'chat.completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: 'function'; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'text_completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { - inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; - postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { - /** - * Input text to embed. Can be a single string or a list of strings. - */ - text: string | string[]; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { - /** - * Embedding vectors, where each vector is a list of floats. - */ - data: number[][]; - /** - * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. - * - * @minItems 2 - * @maxItems 2 - */ - shape: [number, number]; -} -declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { - inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; - postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; -} -interface Ai_Cf_Deepgram_Flux_Input { - /** - * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. - */ - encoding: 'linear16'; - /** - * Sample rate of the audio stream in Hz. - */ - sample_rate: string; - /** - * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. - */ - eager_eot_threshold?: string; - /** - * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. - */ - eot_threshold?: string; - /** - * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. - */ - eot_timeout_ms?: string; - /** - * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. - */ - keyterm?: string; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip - */ - mip_opt_out?: 'true' | 'false'; - /** - * Label your requests for the purpose of identification during usage reporting - */ - tag?: string; -} -/** - * Output will be returned as websocket messages. - */ -interface Ai_Cf_Deepgram_Flux_Output { - /** - * The unique identifier of the request (uuid) - */ - request_id?: string; - /** - * Starts at 0 and increments for each message the server sends to the client. - */ - sequence_id?: number; - /** - * The type of event being reported. - */ - event?: 'Update' | 'StartOfTurn' | 'EagerEndOfTurn' | 'TurnResumed' | 'EndOfTurn'; - /** - * The index of the current turn - */ - turn_index?: number; - /** - * Start time in seconds of the audio range that was transcribed - */ - audio_window_start?: number; - /** - * End time in seconds of the audio range that was transcribed - */ - audio_window_end?: number; - /** - * Text that was said over the course of the current turn - */ - transcript?: string; - /** - * The words in the transcript - */ - words?: { - /** - * The individual punctuated, properly-cased word from the transcript - */ - word: string; - /** - * Confidence that this word was transcribed correctly - */ - confidence: number; - }[]; - /** - * Confidence that no more speech is coming in this turn - */ - end_of_turn_confidence?: number; -} -declare abstract class Base_Ai_Cf_Deepgram_Flux { - inputs: Ai_Cf_Deepgram_Flux_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; -} -interface Ai_Cf_Deepgram_Aura_2_En_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: - | 'amalthea' - | 'andromeda' - | 'apollo' - | 'arcas' - | 'aries' - | 'asteria' - | 'athena' - | 'atlas' - | 'aurora' - | 'callista' - | 'cora' - | 'cordelia' - | 'delia' - | 'draco' - | 'electra' - | 'harmonia' - | 'helena' - | 'hera' - | 'hermes' - | 'hyperion' - | 'iris' - | 'janus' - | 'juno' - | 'jupiter' - | 'luna' - | 'mars' - | 'minerva' - | 'neptune' - | 'odysseus' - | 'ophelia' - | 'orion' - | 'orpheus' - | 'pandora' - | 'phoebe' - | 'pluto' - | 'saturn' - | 'thalia' - | 'theia' - | 'vesta' - | 'zeus'; - /** - * Encoding of the output audio. - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: 'none' | 'wav' | 'ogg'; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_En_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { - inputs: Ai_Cf_Deepgram_Aura_2_En_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; -} -interface Ai_Cf_Deepgram_Aura_2_Es_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: - | 'sirio' - | 'nestor' - | 'carina' - | 'celeste' - | 'alvaro' - | 'diana' - | 'aquila' - | 'selena' - | 'estrella' - | 'javier'; - /** - * Encoding of the output audio. - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: 'none' | 'wav' | 'ogg'; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_Es_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { - inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; -} -interface AiModels { - '@cf/huggingface/distilbert-sst-2-int8': BaseAiTextClassification; - '@cf/stabilityai/stable-diffusion-xl-base-1.0': BaseAiTextToImage; - '@cf/runwayml/stable-diffusion-v1-5-inpainting': BaseAiTextToImage; - '@cf/runwayml/stable-diffusion-v1-5-img2img': BaseAiTextToImage; - '@cf/lykon/dreamshaper-8-lcm': BaseAiTextToImage; - '@cf/bytedance/stable-diffusion-xl-lightning': BaseAiTextToImage; - '@cf/myshell-ai/melotts': BaseAiTextToSpeech; - '@cf/google/embeddinggemma-300m': BaseAiTextEmbeddings; - '@cf/microsoft/resnet-50': BaseAiImageClassification; - '@cf/meta/llama-2-7b-chat-int8': BaseAiTextGeneration; - '@cf/mistral/mistral-7b-instruct-v0.1': BaseAiTextGeneration; - '@cf/meta/llama-2-7b-chat-fp16': BaseAiTextGeneration; - '@hf/thebloke/llama-2-13b-chat-awq': BaseAiTextGeneration; - '@hf/thebloke/mistral-7b-instruct-v0.1-awq': BaseAiTextGeneration; - '@hf/thebloke/zephyr-7b-beta-awq': BaseAiTextGeneration; - '@hf/thebloke/openhermes-2.5-mistral-7b-awq': BaseAiTextGeneration; - '@hf/thebloke/neural-chat-7b-v3-1-awq': BaseAiTextGeneration; - '@hf/thebloke/llamaguard-7b-awq': BaseAiTextGeneration; - '@hf/thebloke/deepseek-coder-6.7b-base-awq': BaseAiTextGeneration; - '@hf/thebloke/deepseek-coder-6.7b-instruct-awq': BaseAiTextGeneration; - '@cf/deepseek-ai/deepseek-math-7b-instruct': BaseAiTextGeneration; - '@cf/defog/sqlcoder-7b-2': BaseAiTextGeneration; - '@cf/openchat/openchat-3.5-0106': BaseAiTextGeneration; - '@cf/tiiuae/falcon-7b-instruct': BaseAiTextGeneration; - '@cf/thebloke/discolm-german-7b-v1-awq': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-0.5b-chat': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-7b-chat-awq': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-14b-chat-awq': BaseAiTextGeneration; - '@cf/tinyllama/tinyllama-1.1b-chat-v1.0': BaseAiTextGeneration; - '@cf/microsoft/phi-2': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-1.8b-chat': BaseAiTextGeneration; - '@cf/mistral/mistral-7b-instruct-v0.2-lora': BaseAiTextGeneration; - '@hf/nousresearch/hermes-2-pro-mistral-7b': BaseAiTextGeneration; - '@hf/nexusflow/starling-lm-7b-beta': BaseAiTextGeneration; - '@hf/google/gemma-7b-it': BaseAiTextGeneration; - '@cf/meta-llama/llama-2-7b-chat-hf-lora': BaseAiTextGeneration; - '@cf/google/gemma-2b-it-lora': BaseAiTextGeneration; - '@cf/google/gemma-7b-it-lora': BaseAiTextGeneration; - '@hf/mistral/mistral-7b-instruct-v0.2': BaseAiTextGeneration; - '@cf/meta/llama-3-8b-instruct': BaseAiTextGeneration; - '@cf/fblgit/una-cybertron-7b-v2-bf16': BaseAiTextGeneration; - '@cf/meta/llama-3-8b-instruct-awq': BaseAiTextGeneration; - '@cf/meta/llama-3.1-8b-instruct-fp8': BaseAiTextGeneration; - '@cf/meta/llama-3.1-8b-instruct-awq': BaseAiTextGeneration; - '@cf/meta/llama-3.2-3b-instruct': BaseAiTextGeneration; - '@cf/meta/llama-3.2-1b-instruct': BaseAiTextGeneration; - '@cf/deepseek-ai/deepseek-r1-distill-qwen-32b': BaseAiTextGeneration; - '@cf/ibm-granite/granite-4.0-h-micro': BaseAiTextGeneration; - '@cf/facebook/bart-large-cnn': BaseAiSummarization; - '@cf/llava-hf/llava-1.5-7b-hf': BaseAiImageToText; - '@cf/baai/bge-base-en-v1.5': Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - '@cf/openai/whisper': Base_Ai_Cf_Openai_Whisper; - '@cf/meta/m2m100-1.2b': Base_Ai_Cf_Meta_M2M100_1_2B; - '@cf/baai/bge-small-en-v1.5': Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - '@cf/baai/bge-large-en-v1.5': Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - '@cf/unum/uform-gen2-qwen-500m': Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - '@cf/openai/whisper-tiny-en': Base_Ai_Cf_Openai_Whisper_Tiny_En; - '@cf/openai/whisper-large-v3-turbo': Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - '@cf/baai/bge-m3': Base_Ai_Cf_Baai_Bge_M3; - '@cf/black-forest-labs/flux-1-schnell': Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - '@cf/meta/llama-3.2-11b-vision-instruct': Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - '@cf/meta/llama-3.3-70b-instruct-fp8-fast': Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - '@cf/meta/llama-guard-3-8b': Base_Ai_Cf_Meta_Llama_Guard_3_8B; - '@cf/baai/bge-reranker-base': Base_Ai_Cf_Baai_Bge_Reranker_Base; - '@cf/qwen/qwen2.5-coder-32b-instruct': Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - '@cf/qwen/qwq-32b': Base_Ai_Cf_Qwen_Qwq_32B; - '@cf/mistralai/mistral-small-3.1-24b-instruct': Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - '@cf/google/gemma-3-12b-it': Base_Ai_Cf_Google_Gemma_3_12B_It; - '@cf/meta/llama-4-scout-17b-16e-instruct': Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; - '@cf/qwen/qwen3-30b-a3b-fp8': Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; - '@cf/deepgram/nova-3': Base_Ai_Cf_Deepgram_Nova_3; - '@cf/qwen/qwen3-embedding-0.6b': Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; - '@cf/pipecat-ai/smart-turn-v2': Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; - '@cf/openai/gpt-oss-120b': Base_Ai_Cf_Openai_Gpt_Oss_120B; - '@cf/openai/gpt-oss-20b': Base_Ai_Cf_Openai_Gpt_Oss_20B; - '@cf/leonardo/phoenix-1.0': Base_Ai_Cf_Leonardo_Phoenix_1_0; - '@cf/leonardo/lucid-origin': Base_Ai_Cf_Leonardo_Lucid_Origin; - '@cf/deepgram/aura-1': Base_Ai_Cf_Deepgram_Aura_1; - '@cf/ai4bharat/indictrans2-en-indic-1B': Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; - '@cf/aisingapore/gemma-sea-lion-v4-27b-it': Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; - '@cf/pfnet/plamo-embedding-1b': Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; - '@cf/deepgram/flux': Base_Ai_Cf_Deepgram_Flux; - '@cf/deepgram/aura-2-en': Base_Ai_Cf_Deepgram_Aura_2_En; - '@cf/deepgram/aura-2-es': Base_Ai_Cf_Deepgram_Aura_2_Es; -} -type AiOptions = { - /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api - */ - queueRequest?: boolean; - /** - * Establish websocket connections, only works for supported models - */ - websocket?: boolean; - /** - * Tag your requests to group and view them in Cloudflare dashboard. - * - * Rules: - * Tags must only contain letters, numbers, and the symbols: : - . / @ - * Each tag can have maximum 50 characters. - * Maximum 5 tags are allowed each request. - * Duplicate tags will removed. - */ - tags?: string[]; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; -}; -type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; -}; -type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { - id: string; - name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; -}; -interface InferenceUpstreamError extends Error {} -interface AiInternalError extends Error {} -type AiModelListType = Record; -declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - autorag(autoragId: string): AutoRAG; - run< - Name extends keyof AiModelList, - Options extends AiOptions, - InputOptions extends AiModelList[Name]['inputs'], - >( - model: Name, - inputs: InputOptions, - options?: Options - ): Promise< - Options extends - | { - returnRawResponse: true; - } - | { - websocket: true; - } - ? Response - : InputOptions extends { - stream: true; - } - ? ReadableStream - : AiModelList[Name]['postProcessedOutputs'] - >; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown( - files: MarkdownDocument[], - options?: ConversionRequestOptions - ): Promise; - toMarkdown( - files: MarkdownDocument, - options?: ConversionRequestOptions - ): Promise; -} -type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: 'constant' | 'linear' | 'exponential'; -}; -type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; -}; -type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = - | 'workers-ai' - | 'anthropic' - | 'aws-bedrock' - | 'azure-openai' - | 'google-vertex-ai' - | 'huggingface' - | 'openai' - | 'perplexity-ai' - | 'replicate' - | 'groq' - | 'cohere' - | 'google-ai-studio' - | 'mistral' - | 'grok' - | 'openrouter' - | 'deepseek' - | 'cerebras' - | 'cartesia' - | 'elevenlabs' - | 'adobe-firefly'; -type AIGatewayHeaders = { - 'cf-aig-metadata': Record | string; - 'cf-aig-custom-cost': - | { - per_token_in?: number; - per_token_out?: number; - } - | { - total_cost?: number; - } - | string; - 'cf-aig-cache-ttl': number | string; - 'cf-aig-skip-cache': boolean | string; - 'cf-aig-cache-key': string; - 'cf-aig-event-id': string; - 'cf-aig-request-timeout': number | string; - 'cf-aig-max-attempts': number | string; - 'cf-aig-retry-delay': number | string; - 'cf-aig-backoff': string; - 'cf-aig-collect-log': boolean | string; - Authorization: string; - 'Content-Type': string; - [key: string]: string | number | boolean | object; -}; -type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; -}; -interface AiGatewayInternalError extends Error {} -interface AiGatewayLogNotFound extends Error {} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run( - data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], - options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - } - ): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line -} -interface AutoRAGInternalError extends Error {} -interface AutoRAGNotFoundError extends Error {} -interface AutoRAGUnauthorizedError extends Error {} -interface AutoRAGNameNotSetError extends Error {} -type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; -}; -type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; -}; -type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - reranking?: { - enabled?: boolean; - model?: string; - }; - rewrite_query?: boolean; -}; -type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; - system_prompt?: string; -}; -type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; -}; -type AutoRagSearchResponse = { - object: 'vector_store.search_results.page'; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: 'text'; - text: string; - }[]; - }[]; - has_more: boolean; - next_page: string | null; -}; -type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; -}[]; -type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; -}; -declare abstract class AutoRAG { - list(): Promise; - search(params: AutoRagSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -interface BasicImageTransformations { - /** - * Maximum width in image pixels. The value must be an integer. - */ - width?: number; - /** - * Maximum height in image pixels. The value must be an integer. - */ - height?: number; - /** - * Resizing mode as a string. It affects interpretation of width and height - * options: - * - scale-down: Similar to contain, but the image is never enlarged. If - * the image is larger than given width or height, it will be resized. - * Otherwise its original size will be kept. - * - contain: Resizes to maximum size that fits within the given width and - * height. If only a single dimension is given (e.g. only width), the - * image will be shrunk or enlarged to exactly match that dimension. - * Aspect ratio is always preserved. - * - cover: Resizes (shrinks or enlarges) to fill the entire area of width - * and height. If the image has an aspect ratio different from the ratio - * of width and height, it will be cropped to fit. - * - crop: The image will be shrunk and cropped to fit within the area - * specified by width and height. The image will not be enlarged. For images - * smaller than the given dimensions it's the same as scale-down. For - * images larger than the given dimensions, it's the same as cover. - * See also trim. - * - pad: Resizes to the maximum size that fits within the given width and - * height, and then fills the remaining area with a background color - * (white by default). Use of this mode is not recommended, as the same - * effect can be more efficiently achieved with the contain mode and the - * CSS object-fit: contain property. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio - */ - fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad' | 'squeeze'; - /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. - */ - segment?: 'foreground'; - /** - * When cropping with fit: "cover", this defines the side or point that should - * be left uncropped. The value is either a string - * "left", "right", "top", "bottom", "auto", or "center" (the default), - * or an object {x, y} containing focal point coordinates in the original - * image expressed as fractions ranging from 0.0 (top or left) to 1.0 - * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will - * crop bottom or left and right sides as necessary, but won’t crop anything - * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to - * preserve as much as possible around a point at 20% of the height of the - * source image. - */ - gravity?: - | 'face' - | 'left' - | 'right' - | 'top' - | 'bottom' - | 'center' - | 'auto' - | 'entropy' - | BasicImageTransformationsGravityCoordinates; - /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) - */ - background?: string; - /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. - */ - rotate?: 0 | 90 | 180 | 270 | 360; -} -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; -} -/** - * In addition to the properties you can set in the RequestInit dict - * that you pass as an argument to the Request constructor, you can - * set certain properties of a `cf` object to control how Cloudflare - * features are applied to that new Request. - * - * Note: Currently, these properties cannot be tested in the - * playground. - */ -interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; - /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. - */ - cacheKey?: string; - /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. - */ - cacheTags?: string[]; - /** - * Force response to be cached for a given number of seconds. (e.g. 300) - */ - cacheTtl?: number; - /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) - */ - cacheTtlByStatus?: Record; - scrapeShield?: boolean; - apps?: boolean; - image?: RequestInitCfPropertiesImage; - minify?: RequestInitCfPropertiesImageMinify; - mirage?: boolean; - polish?: 'lossy' | 'lossless' | 'off'; - r2?: RequestInitCfPropertiesR2; - /** - * Redirects the request to an alternate origin server. You can use this, - * for example, to implement load balancing across several origins. - * (e.g.us-east.example.com) - * - * Note - For security reasons, the hostname set in resolveOverride must - * be proxied on the same Cloudflare zone of the incoming request. - * Otherwise, the setting is ignored. CNAME hosts are allowed, so to - * resolve to a host under a different domain or a DNS only domain first - * declare a CNAME record within your own zone’s DNS mapping to the - * external hostname, set proxy on Cloudflare, then set resolveOverride - * to point to that CNAME record. - */ - resolveOverride?: string; -} -interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { - /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. - */ - url: string; - /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. - */ - opacity?: number; - /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). - */ - repeat?: true | 'x' | 'y'; - /** - * Position of the overlay image relative to a given edge. Each property is - * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. - */ - top?: number; - left?: number; - bottom?: number; - right?: number; -} -interface RequestInitCfPropertiesImage extends BasicImageTransformations { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number; - /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep - */ - trim?: - | 'border' - | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: - | boolean - | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; - /** - * Quality setting from 1-100 (useful values are in 60-90 range). Lower values - * make images look worse, but load faster. The default is 85. It applies only - * to JPEG and WebP images. It doesn’t have any effect on PNG. - */ - quality?: number | 'low' | 'medium-low' | 'medium-high' | 'high'; - /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. - */ - format?: 'avif' | 'webp' | 'json' | 'jpeg' | 'png' | 'baseline-jpeg' | 'png-force' | 'svg'; - /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. - */ - anim?: boolean; - /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * output formats always discard metadata. - */ - metadata?: 'keep' | 'copyright' | 'none'; - /** - * Strength of sharpening filter to apply to the image. Floating-point - * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a - * recommended value for downscaled images. - */ - sharpen?: number; - /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. - */ - blur?: number; - /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). - */ - draw?: RequestInitCfPropertiesImageDraw[]; - /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. - */ - 'origin-auth'?: 'share-publicly'; - /** - * Adds a border around the image. The border is added after resizing. Border - * width takes dpr into account, and can be specified either using a single - * width property, or individually for each side. - */ - border?: - | { - color: string; - width: number; - } - | { - color: string; - top: number; - right: number; - bottom: number; - left: number; - }; - /** - * Increase brightness by a factor. A value of 1.0 equals no change, a value - * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. - * 0 is ignored. - */ - brightness?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - contrast?: number; - /** - * Increase exposure by a factor. A value of 1.0 equals no change, a value of - * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. - */ - gamma?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - saturation?: number; - /** - * Flips the images horizontally, vertically, or both. Flipping is applied before - * rotation, so if you apply flip=h,rotate=90 then the image will be flipped - * horizontally, then rotated by 90 degrees. - */ - flip?: 'h' | 'v' | 'hv'; - /** - * Slightly reduces latency on a cache miss by selecting a - * quickest-to-compress file format, at a cost of increased file size and - * lower image quality. It will usually override the format option and choose - * JPEG over WebP or AVIF. We do not recommend using this option, except in - * unusual circumstances like resizing uncacheable dynamically-generated - * images. - */ - compression?: 'fast'; -} -interface RequestInitCfPropertiesImageMinify { - javascript?: boolean; - css?: boolean; - html?: boolean; -} -interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; -} -/** - * Request metadata provided by Cloudflare's edge. - */ -type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & - IncomingRequestCfPropertiesBotManagementEnterprise & - IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & - IncomingRequestCfPropertiesGeographicInformation & - IncomingRequestCfPropertiesCloudflareAccessOrApiShield; -interface IncomingRequestCfPropertiesBase extends Record { - /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 - */ - asn?: number; - /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" - */ - asOrganization?: string; - /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" - */ - clientAcceptEncoding?: string; - /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 - */ - clientTcpRtt?: number; - /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" - */ - colo: string; - /** - * Represents the upstream's response to a - * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) - * from cloudflare. - * - * For workers with no upstream, this will always be `1`. - * - * @example 3 - */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; - /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" - */ - httpProtocol: string; - /** - * The browser-requested prioritization information in the request object. - * - * If no information was set, defaults to the empty string `""` - * - * @example "weight=192;exclusive=0;group=3;group-weight=127" - * @default "" - */ - requestPriority: string; - /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" - */ - tlsVersion: string; - /** - * The cipher for the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "AEAD-AES128-GCM-SHA256" - */ - tlsCipher: string; - /** - * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. - * - * If the incoming request was served over plaintext (without TLS) this field is undefined. - */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; -} -interface IncomingRequestCfPropertiesBotManagementBase { - /** - * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, - * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). - * - * @example 54 - */ - score: number; - /** - * A boolean value that is true if the request comes from a good bot, like Google or Bing. - * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). - */ - verifiedBot: boolean; - /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. - */ - corporateProxy: boolean; - /** - * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. - */ - staticResource: boolean; - /** - * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). - */ - detectionIds: number[]; -} -interface IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase; - /** - * Duplicate of `botManagement.score`. - * - * @deprecated - */ - clientTrustScore: number; -} -interface IncomingRequestCfPropertiesBotManagementEnterprise - extends IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase & { - /** - * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients - * across different destination IPs, Ports, and X509 certificates. - */ - ja3Hash: string; - }; -} -interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { - /** - * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). - * - * This field is only present if you have Cloudflare for SaaS enabled on your account - * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). - */ - hostMetadata?: HostMetadata; -} -interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { - /** - * Information about the client certificate presented to Cloudflare. - * - * This is populated when the incoming request is served over TLS using - * either Cloudflare Access or API Shield (mTLS) - * and the presented SSL certificate has a valid - * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) - * (i.e., not `null` or `""`). - * - * Otherwise, a set of placeholder values are used. - * - * The property `certPresented` will be set to `"1"` when - * the object is populated (i.e. the above conditions were met). - */ - tlsClientAuth: - | IncomingRequestCfPropertiesTLSClientAuth - | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; -} -/** - * Metadata about the request's TLS handshake - */ -interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { - /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - clientHandshake: string; - /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - serverHandshake: string; - /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - clientFinished: string; - /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - serverFinished: string; -} -/** - * Geographic data about the request's origin. - */ -interface IncomingRequestCfPropertiesGeographicInformation { - /** - * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. - * - * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. - * - * If Cloudflare is unable to determine where the request originated this property is omitted. - * - * The country code `"T1"` is used for requests originating on TOR. - * - * @example "GB" - */ - country?: Iso3166Alpha2Code | 'T1'; - /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" - */ - isEUCountry?: '1'; - /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" - */ - continent?: ContinentCode; - /** - * The city the request originated from - * - * @example "Austin" - */ - city?: string; - /** - * Postal code of the incoming request - * - * @example "78701" - */ - postalCode?: string; - /** - * Latitude of the incoming request - * - * @example "30.27130" - */ - latitude?: string; - /** - * Longitude of the incoming request - * - * @example "-97.74260" - */ - longitude?: string; - /** - * Timezone of the incoming request - * - * @example "America/Chicago" - */ - timezone?: string; - /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" - */ - region?: string; - /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" - */ - regionCode?: string; - /** - * Metro code (DMA) of the incoming request - * - * @example "635" - */ - metroCode?: string; -} -/** Data about the incoming request's TLS certificate */ -interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: '1'; - /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude; - /** The presented certificate's revokation status. - * - * - A value of `"1"` indicates the certificate has been revoked - * - A value of `"0"` indicates the certificate has not been revoked - */ - certRevoked: '1' | '0'; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDN: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDN: string; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDNRFC2253: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDNRFC2253: string; - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string; - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string; - /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" - */ - certSerial: string; - /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" - */ - certIssuerSerial: string; - /** - * The certificate's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certSKI: string; - /** - * The certificate issuer's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certIssuerSKI: string; - /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" - */ - certFingerprintSHA1: string; - /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" - */ - certFingerprintSHA256: string; - /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotBefore: string; - /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotAfter: string; -} -/** Placeholder values for TLS Client Authorization */ -interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: '0'; - certVerified: 'NONE'; - certRevoked: '0'; - certIssuerDN: ''; - certSubjectDN: ''; - certIssuerDNRFC2253: ''; - certSubjectDNRFC2253: ''; - certIssuerDNLegacy: ''; - certSubjectDNLegacy: ''; - certSerial: ''; - certIssuerSerial: ''; - certSKI: ''; - certIssuerSKI: ''; - certFingerprintSHA1: ''; - certFingerprintSHA256: ''; - certNotBefore: ''; - certNotAfter: ''; -} -/** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = - /** Authentication succeeded */ - | 'SUCCESS' - /** No certificate was presented */ - | 'NONE' - /** Failed because the certificate was self-signed */ - | 'FAILED:self signed certificate' - /** Failed because the certificate failed a trust chain check */ - | 'FAILED:unable to verify the first certificate' - /** Failed because the certificate not yet valid */ - | 'FAILED:certificate is not yet valid' - /** Failed because the certificate is expired */ - | 'FAILED:certificate has expired' - /** Failed for another unspecified reason */ - | 'FAILED'; -/** - * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. - */ -declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = - | 0 /** Unknown */ - | 1 /** no keepalives (not found) */ - | 2 /** no connection re-use, opening keepalive connection failed */ - | 3 /** no connection re-use, keepalive accepted and saved */ - | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ - | 5; /** connection re-use, accepted by the origin server */ -/** ISO 3166-1 Alpha-2 codes */ -declare type Iso3166Alpha2Code = - | 'AD' - | 'AE' - | 'AF' - | 'AG' - | 'AI' - | 'AL' - | 'AM' - | 'AO' - | 'AQ' - | 'AR' - | 'AS' - | 'AT' - | 'AU' - | 'AW' - | 'AX' - | 'AZ' - | 'BA' - | 'BB' - | 'BD' - | 'BE' - | 'BF' - | 'BG' - | 'BH' - | 'BI' - | 'BJ' - | 'BL' - | 'BM' - | 'BN' - | 'BO' - | 'BQ' - | 'BR' - | 'BS' - | 'BT' - | 'BV' - | 'BW' - | 'BY' - | 'BZ' - | 'CA' - | 'CC' - | 'CD' - | 'CF' - | 'CG' - | 'CH' - | 'CI' - | 'CK' - | 'CL' - | 'CM' - | 'CN' - | 'CO' - | 'CR' - | 'CU' - | 'CV' - | 'CW' - | 'CX' - | 'CY' - | 'CZ' - | 'DE' - | 'DJ' - | 'DK' - | 'DM' - | 'DO' - | 'DZ' - | 'EC' - | 'EE' - | 'EG' - | 'EH' - | 'ER' - | 'ES' - | 'ET' - | 'FI' - | 'FJ' - | 'FK' - | 'FM' - | 'FO' - | 'FR' - | 'GA' - | 'GB' - | 'GD' - | 'GE' - | 'GF' - | 'GG' - | 'GH' - | 'GI' - | 'GL' - | 'GM' - | 'GN' - | 'GP' - | 'GQ' - | 'GR' - | 'GS' - | 'GT' - | 'GU' - | 'GW' - | 'GY' - | 'HK' - | 'HM' - | 'HN' - | 'HR' - | 'HT' - | 'HU' - | 'ID' - | 'IE' - | 'IL' - | 'IM' - | 'IN' - | 'IO' - | 'IQ' - | 'IR' - | 'IS' - | 'IT' - | 'JE' - | 'JM' - | 'JO' - | 'JP' - | 'KE' - | 'KG' - | 'KH' - | 'KI' - | 'KM' - | 'KN' - | 'KP' - | 'KR' - | 'KW' - | 'KY' - | 'KZ' - | 'LA' - | 'LB' - | 'LC' - | 'LI' - | 'LK' - | 'LR' - | 'LS' - | 'LT' - | 'LU' - | 'LV' - | 'LY' - | 'MA' - | 'MC' - | 'MD' - | 'ME' - | 'MF' - | 'MG' - | 'MH' - | 'MK' - | 'ML' - | 'MM' - | 'MN' - | 'MO' - | 'MP' - | 'MQ' - | 'MR' - | 'MS' - | 'MT' - | 'MU' - | 'MV' - | 'MW' - | 'MX' - | 'MY' - | 'MZ' - | 'NA' - | 'NC' - | 'NE' - | 'NF' - | 'NG' - | 'NI' - | 'NL' - | 'NO' - | 'NP' - | 'NR' - | 'NU' - | 'NZ' - | 'OM' - | 'PA' - | 'PE' - | 'PF' - | 'PG' - | 'PH' - | 'PK' - | 'PL' - | 'PM' - | 'PN' - | 'PR' - | 'PS' - | 'PT' - | 'PW' - | 'PY' - | 'QA' - | 'RE' - | 'RO' - | 'RS' - | 'RU' - | 'RW' - | 'SA' - | 'SB' - | 'SC' - | 'SD' - | 'SE' - | 'SG' - | 'SH' - | 'SI' - | 'SJ' - | 'SK' - | 'SL' - | 'SM' - | 'SN' - | 'SO' - | 'SR' - | 'SS' - | 'ST' - | 'SV' - | 'SX' - | 'SY' - | 'SZ' - | 'TC' - | 'TD' - | 'TF' - | 'TG' - | 'TH' - | 'TJ' - | 'TK' - | 'TL' - | 'TM' - | 'TN' - | 'TO' - | 'TR' - | 'TT' - | 'TV' - | 'TW' - | 'TZ' - | 'UA' - | 'UG' - | 'UM' - | 'US' - | 'UY' - | 'UZ' - | 'VA' - | 'VC' - | 'VE' - | 'VG' - | 'VI' - | 'VN' - | 'VU' - | 'WF' - | 'WS' - | 'YE' - | 'YT' - | 'ZA' - | 'ZM' - | 'ZW'; -/** The 2-letter continent codes Cloudflare uses */ -declare type ContinentCode = 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA'; -type CfProperties = - | IncomingRequestCfProperties - | RequestInitCfProperties; -interface D1Meta { - duration: number; - size_after: number; - rows_read: number; - rows_written: number; - last_row_id: number; - changed_db: boolean; - changes: number; - /** - * The region of the database instance that executed the query. - */ - served_by_region?: string; - /** - * True if-and-only-if the database instance that executed the query was the primary. - */ - served_by_primary?: boolean; - timings?: { - /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. - */ - sql_duration_ms: number; - }; - /** - * Number of total attempts to execute the query, due to automatic retries. - * Note: All other fields in the response like `timings` only apply to the last attempt. - */ - total_attempts?: number; -} -interface D1Response { - success: true; - meta: D1Meta & Record; - error?: never; -} -type D1Result = D1Response & { - results: T[]; -}; -interface D1ExecResult { - count: number; - duration: number; -} -type D1SessionConstraint = - // Indicates that the first query should go to the primary, and the rest queries - // using the same D1DatabaseSession will go to any replica that is consistent with - // the bookmark maintained by the session (returned by the first query). - | 'first-primary' - // Indicates that the first query can go anywhere (primary or replica), and the rest queries - // using the same D1DatabaseSession will go to any replica that is consistent with - // the bookmark maintained by the session (returned by the first query). - | 'first-unconstrained'; -type D1SessionBookmark = string; -declare abstract class D1Database { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. - */ - withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; - /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. - */ - dump(): Promise; -} -declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. - */ - getBookmark(): D1SessionBookmark | null; -} -declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement; - first(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { columnNames: true }): Promise<[string[], ...T[]]>; - raw(options?: { columnNames?: false }): Promise; -} -// `Disposable` was added to TypeScript's standard lib types in version 5.2. -// To support older TypeScript versions, define an empty `Disposable` interface. -// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, -// but this will ensure type checking on older versions still passes. -// TypeScript's interface merging will ensure our empty interface is effectively -// ignored when `Disposable` is included in the standard lib. -interface Disposable {} -/** - * An email message that can be sent from a Worker. - */ -interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string; - /** - * Envelope To attribute of the email message. - */ - readonly to: string; -} -/** - * An email message that is sent to a consumer Worker and can be rejected/forwarded. - */ -interface ForwardableEmailMessage extends EmailMessage { - /** - * Stream of the email message content. - */ - readonly raw: ReadableStream; - /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - */ - readonly headers: Headers; - /** - * Size of the email message content. - */ - readonly rawSize: number; - /** - * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. - * @param reason The reject reason. - * @returns void - */ - setReject(reason: string): void; - /** - * Forward this email message to a verified destination address of the account. - * @param rcptTo Verified destination address. - * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - * @returns A promise that resolves when the email message is forwarded. - */ - forward(rcptTo: string, headers?: Headers): Promise; - /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. - */ - reply(message: EmailMessage): Promise; -} -/** - * A binding that allows a Worker to send email messages. - */ -interface SendEmail { - send(message: EmailMessage): Promise; -} -declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; -} -declare type EmailExportedHandler = ( - message: ForwardableEmailMessage, - env: Env, - ctx: ExecutionContext -) => void | Promise; -declare module 'cloudflare:email' { - let _EmailMessage: { - prototype: EmailMessage; - new (from: string, to: string, raw: ReadableStream | string): EmailMessage; - }; - export { _EmailMessage as EmailMessage }; -} -/** - * Hello World binding to serve as an explanatory example. DO NOT USE - */ -interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string; - ms?: number; - }>; - /** - * Set a new stored value - */ - set(value: string): Promise; -} -interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an idential socket to if you call - * `connect("host:port")` using the `host` and `port` fields from this object. - * Pick whichever approach works better with your preferred DB client library. - * - * Note that this socket is not yet authenticated -- it's expected that your - * code (or preferably, the client library of your choice) will authenticate - * using the information in this class's readonly fields. - */ - connect(): Socket; - /** - * A valid DB connection string that can be passed straight into the typical - * client library/driver/ORM. This will typically be the easiest way to use - * Hyperdrive. - */ - readonly connectionString: string; - /* - * A randomly generated hostname that is only valid within the context of the - * currently running Worker which, when passed into `connect()` function from - * the "cloudflare:sockets" module, will connect to the Hyperdrive instance - * for your database. - */ - readonly host: string; - /* - * The port that must be paired the the host field when connecting. - */ - readonly port: number; - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time - */ - readonly user: string; - /* - * The randomly generated password to use when authenticating to your - * database via Hyperdrive. Like the host field, this password is only valid - * within the context of the currently running Worker instance from which - * it's read. - */ - readonly password: string; - /* - * The name of the database to connect to. - */ - readonly database: string; -} -// Copyright (c) 2024 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = - | { - format: 'image/svg+xml'; - } - | { - format: string; - fileSize: number; - width: number; - height: number; - }; -type ImageTransform = { - width?: number; - height?: number; - background?: string; - blur?: number; - border?: - | { - color?: string; - width?: number; - } - | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - brightness?: number; - contrast?: number; - fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; - flip?: 'h' | 'v' | 'hv'; - gamma?: number; - segment?: 'foreground'; - gravity?: - | 'face' - | 'left' - | 'right' - | 'top' - | 'bottom' - | 'center' - | 'auto' - | 'entropy' - | { - x?: number; - y?: number; - mode: 'remainder' | 'box-center'; - }; - rotate?: 0 | 90 | 180 | 270; - saturation?: number; - sharpen?: number; - trim?: - | 'border' - | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: - | boolean - | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; -}; -type ImageDrawOptions = { - opacity?: number; - repeat?: boolean | string; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; -type ImageInputOptions = { - encoding?: 'base64'; -}; -type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; - anim?: boolean; -}; -interface ImagesBinding { - /** - * Get image metadata (type, width and height) - * @throws {@link ImagesError} with code 9412 if input is not an image - * @param stream The image bytes - */ - info(stream: ReadableStream, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; -} -interface ImageTransformer { - /** - * Apply transform next, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param transform - */ - transform(transform: ImageTransform): ImageTransformer; - /** - * Draw an image on this transformer, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param image The image (or transformer that will give the image) to draw - * @param options The options configuring how to draw the image - */ - draw( - image: ReadableStream | ImageTransformer, - options?: ImageDrawOptions - ): ImageTransformer; - /** - * Retrieve the image that results from applying the transforms to the - * provided input - * @param options Options that apply to the output e.g. output format - */ - output(options: ImageOutputOptions): Promise; -} -type ImageTransformationOutputOptions = { - encoding?: 'base64'; -}; -interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; -} -interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -/** - * Media binding for transforming media streams. - * Provides the entry point for media transformation operations. - */ -interface MediaBinding { - /** - * Creates a media transformer from an input stream. - * @param media - The input media bytes - * @returns A MediaTransformer instance for applying transformations - */ - input(media: ReadableStream): MediaTransformer; -} -/** - * Media transformer for applying transformation operations to media content. - * Handles sizing, fitting, and other input transformation parameters. - */ -interface MediaTransformer { - /** - * Applies transformation options to the media content. - * @param transform - Configuration for how the media should be transformed - * @returns A generator for producing the transformed media output - */ - transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; -} -/** - * Generator for producing media transformation results. - * Configures the output format and parameters for the transformed media. - */ -interface MediaTransformationGenerator { - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output: MediaTransformationOutputOptions): MediaTransformationResult; -} -/** - * Result of a media transformation operation. - * Provides multiple ways to access the transformed media content. - */ -interface MediaTransformationResult { - /** - * Returns the transformed media as a readable stream of bytes. - * @returns A stream containing the transformed media data - */ - media(): ReadableStream; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Response, ready to store in cache or return to users - */ - response(): Response; - /** - * Returns the MIME type of the transformed media. - * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): string; -} -/** - * Configuration options for transforming media input. - * Controls how the media should be resized and fitted. - */ -type MediaTransformationInputOptions = { - /** How the media should be resized to fit the specified dimensions */ - fit?: 'contain' | 'cover' | 'scale-down'; - /** Target width in pixels */ - width?: number; - /** Target height in pixels */ - height?: number; -}; -/** - * Configuration options for Media Transformations output. - * Controls the format, timing, and type of the generated output. - */ -type MediaTransformationOutputOptions = { - /** - * Output mode determining the type of media to generate - */ - mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; - /** Whether to include audio in the output */ - audio?: boolean; - /** - * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). - */ - time?: string; - /** - * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). - */ - duration?: string; - /** - * Number of frames in the spritesheet. - */ - imageCount?: number; - /** - * Output format for the generated media. - */ - format?: 'jpg' | 'png' | 'm4a'; -}; -/** - * Error object for media transformation operations. - * Extends the standard Error interface with additional media-specific information. - */ -interface MediaError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -declare module 'cloudflare:node' { - interface NodeStyleServer { - listen(...args: unknown[]): this; - address(): { - port?: number | null | undefined; - }; - } - export function httpServerHandler(port: number): ExportedHandler; - export function httpServerHandler(options: { port: number }): ExportedHandler; - export function httpServerHandler(server: NodeStyleServer): ExportedHandler; -} -type Params

= Record; -type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; -}; -type PagesFunction< - Env = unknown, - Params extends string = any, - Data extends Record = Record, -> = (context: EventContext) => Response | Promise; -type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction< - Env = unknown, - Params extends string = any, - Data extends Record = Record, - PluginArgs = unknown, -> = (context: EventPluginContext) => Response | Promise; -declare module 'assets:*' { - export const onRequest: PagesFunction; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -declare module 'cloudflare:pipelines' { - export abstract class PipelineTransformationEntrypoint< - Env = unknown, - I extends PipelineRecord = PipelineRecord, - O extends PipelineRecord = PipelineRecord, - > { - protected env: Env; - protected ctx: ExecutionContext; - constructor(ctx: ExecutionContext, env: Env); - /** - * run recieves an array of PipelineRecord which can be - * transformed and returned to the pipeline - * @param records Incoming records from the pipeline to be transformed - * @param metadata Information about the specific pipeline calling the transformation entrypoint - * @returns A promise containing the transformed PipelineRecord array - */ - public run(records: I[], metadata: PipelineBatchMetadata): Promise; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * The Pipeline interface represents the type of a binding to a Pipeline - * - * @param records The records to send to the pipeline - */ - send(records: T[]): Promise; - } -} -// PubSubMessage represents an incoming PubSub message. -// The message includes metadata about the broker, the client, and the payload -// itself. -// https://developers.cloudflare.com/pub-sub/ -interface PubSubMessage { - // Message ID - readonly mid: number; - // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT - readonly broker: string; - // The MQTT topic the message was sent on. - readonly topic: string; - // The client ID of the client that published this message. - readonly clientId: string; - // The unique identifier (JWT ID) used by the client to authenticate, if token - // auth was used. - readonly jti?: string; - // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker - // received the message from the client. - readonly receivedAt: number; - // An (optional) string with the MIME type of the payload, if set by the - // client. - readonly contentType: string; - // Set to 1 when the payload is a UTF-8 string - // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 - readonly payloadFormatIndicator: number; - // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. - // You can use payloadFormatIndicator to inspect this before decoding. - payload: string | Uint8Array; -} -// JsonWebKey extended by kid parameter -interface JsonWebKeyWithKid extends JsonWebKey { - // Key Identifier of the JWK - readonly kid: string; -} -interface RateLimitOptions { - key: string; -} -interface RateLimitOutcome { - success: boolean; -} -interface RateLimit { - /** - * Rate limit a request based on the provided options. - * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ - * @returns A promise that resolves with the outcome of the rate limit. - */ - limit(options: RateLimitOptions): Promise; -} -// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need -// to referenced by `Fetcher`. This is included in the "importable" version of the types which -// strips all `module` blocks. -declare namespace Rpc { - // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. - // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. - // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to - // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) - export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; - export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; - export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; - export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; - export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; - export interface RpcTargetBranded { - [__RPC_TARGET_BRAND]: never; - } - export interface WorkerEntrypointBranded { - [__WORKER_ENTRYPOINT_BRAND]: never; - } - export interface DurableObjectBranded { - [__DURABLE_OBJECT_BRAND]: never; - } - export interface WorkflowEntrypointBranded { - [__WORKFLOW_ENTRYPOINT_BRAND]: never; - } - export type EntrypointBranded = - | WorkerEntrypointBranded - | DurableObjectBranded - | WorkflowEntrypointBranded; - // Types that can be used through `Stub`s - export type Stubable = RpcTargetBranded | ((...args: any[]) => any); - // Types that can be passed over RPC - // The reason for using a generic type here is to build a serializable subset of structured - // cloneable composite types. This allows types defined with the "interface" keyword to pass the - // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. - type Serializable = - // Structured cloneables - | BaseType - // Structured cloneable composites - | Map< - T extends Map ? Serializable : never, - T extends Map ? Serializable : never - > - | Set ? Serializable : never> - | ReadonlyArray ? Serializable : never> - | { - [K in keyof T]: K extends number | string ? Serializable : never; - } - // Special types - | Stub - // Serialized as stubs, see `Stubify` - | Stubable; - // Base type for all RPC stubs, including common memory management methods. - // `T` is used as a marker type for unwrapping `Stub`s later. - interface StubBase extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // This represents all the types that can be sent as-is over an RPC boundary - type BaseType = - | void - | undefined - | null - | boolean - | number - | bigint - | string - | TypedArray - | ArrayBuffer - | DataView - | Date - | Error - | RegExp - | ReadableStream - | WritableStream - | Request - | Response - | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: any; - } ? { - [K in keyof T]: Stubify; - } : T; - // Recursively rewrite all `Stub`s with the corresponding `T`s. - // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: - // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. - // prettier-ignore - type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: unknown; - } ? { - [K in keyof T]: Unstubify; - } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = T extends object ? Disposable : unknown; - // Type for method return or property on an RPC interface. - // - Stubable types are replaced by stubs. - // - Serializable types are passed by value, with stubable types replaced by stubs - // and a top-level `Disposer`. - // Everything else can't be passed over PRC. - // Technically, we use custom thenables here, but they quack like `Promise`s. - // Intersecting with `(Maybe)Provider` allows pipelining. - // prettier-ignore - type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; - // Type for method or property on an RPC interface. - // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. - // Unwrapping `Stub`s allows calling with `Stubable` arguments. - // For properties, rewrite types to be `Result`s. - // In each case, unwrap `Promise`s. - type MethodOrProperty = V extends (...args: infer P) => infer R - ? (...args: UnstubifyAll

) => Result> - : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; - // Base type for all other types providing RPC-like interfaces. - // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. - // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider< - T extends object, - Reserved extends string = never, - > = MaybeCallableProvider & - Pick< - { - [K in keyof T]: MethodOrProperty; - }, - Exclude> - >; -} -declare namespace Cloudflare { - // Type of `env`. - // - // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript - // will merge all declarations. - // - // You can use `wrangler types` to generate the `Env` type automatically. - interface Env {} - // Project-specific parameters used to inform types. - // - // This interface is, again, intended to be declared in project-specific files, and then that - // declaration will be merged with this one. - // - // A project should have a declaration like this: - // - // interface GlobalProps { - // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type - // // of `ctx.exports`. - // mainModule: typeof import("my-main-module"); - // - // // Declares which of the main module's exports are configured with durable storage, and - // // thus should behave as Durable Object namsepace bindings. - // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; - // } - // - // You can use `wrangler types` to generate `GlobalProps` automatically. - interface GlobalProps {} - // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not - // present. - type GlobalProp = K extends keyof GlobalProps - ? GlobalProps[K] - : Default; - // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the - // `mainModule` property. - type MainModule = GlobalProp<'mainModule', {}>; - // The type of ctx.exports, which contains loopback bindings for all top-level exports. - type Exports = { - [K in keyof MainModule]: LoopbackForExport & - // If the export is listed in `durableNamespaces`, then it is also a - // DurableObjectNamespace. - (K extends GlobalProp<'durableNamespaces', never> - ? MainModule[K] extends new (...args: any[]) => infer DoInstance - ? DoInstance extends Rpc.DurableObjectBranded - ? DurableObjectNamespace - : DurableObjectNamespace - : DurableObjectNamespace - : {}); - }; -} -declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - export abstract class RpcTarget implements Rpc.RpcTargetBranded { - [Rpc.__RPC_TARGET_BRAND]: never; - } - // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC - export abstract class WorkerEntrypoint - implements Rpc.WorkerEntrypointBranded - { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?( - event: TailStream.TailEvent - ): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject - implements Rpc.DurableObjectBranded - { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?( - ws: WebSocket, - code: number, - reason: string, - wasClean: boolean - ): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - export type WorkflowDurationLabel = - | 'second' - | 'minute' - | 'hour' - | 'day' - | 'week' - | 'month' - | 'year'; - export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; - export type WorkflowDelayDuration = WorkflowSleepDuration; - export type WorkflowTimeoutDuration = WorkflowSleepDuration; - export type WorkflowRetentionDuration = WorkflowSleepDuration; - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; - export type WorkflowStepConfig = { - retries?: { - limit: number; - delay: WorkflowDelayDuration | number; - backoff?: WorkflowBackoff; - }; - timeout?: WorkflowTimeoutDuration | number; - }; - export type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export abstract class WorkflowStep { - do>(name: string, callback: () => Promise): Promise; - do>( - name: string, - config: WorkflowStepConfig, - callback: () => Promise - ): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>( - name: string, - options: { - type: string; - timeout?: WorkflowTimeoutDuration | number; - } - ): Promise>; - } - export abstract class WorkflowEntrypoint< - Env = unknown, - T extends Rpc.Serializable | unknown = unknown, - > implements Rpc.WorkflowEntrypointBranded - { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): void; - export function withEnv(newEnv: unknown, fn: () => unknown): unknown; - export function withExports(newExports: unknown, fn: () => unknown): unknown; - export function withEnvAndExports( - newEnv: unknown, - newExports: unknown, - fn: () => unknown - ): unknown; - export const env: Cloudflare.Env; - export const exports: Cloudflare.Exports; -} -declare module 'cloudflare:workers' { - export = CloudflareWorkersModule; -} -interface SecretsStoreSecret { - /** - * Get a secret from the Secrets Store, returning a string of the secret value - * if it exists, or throws an error if it does not exist - */ - get(): Promise; -} -declare module 'cloudflare:sockets' { - function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; - export { _connect as connect }; -} -type MarkdownDocument = { - name: string; - blob: Blob; -}; -type ConversionResponse = - | { - name: string; - mimeType: string; - format: 'markdown'; - tokens: number; - data: string; - } - | { - name: string; - mimeType: string; - format: 'error'; - error: string; - }; -type ImageConversionOptions = { - descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; -}; -type EmbeddedImageConversionOptions = ImageConversionOptions & { - convert?: boolean; - maxConvertedImages?: number; -}; -type ConversionOptions = { - html?: { - images?: EmbeddedImageConversionOptions & { - convertOGImage?: boolean; - }; - }; - docx?: { - images?: EmbeddedImageConversionOptions; - }; - image?: ImageConversionOptions; - pdf?: { - images?: EmbeddedImageConversionOptions; - metadata?: boolean; - }; -}; -type ConversionRequestOptions = { - gateway?: GatewayOptions; - extraHeaders?: object; - conversionOptions?: ConversionOptions; -}; -type SupportedFileFormat = { - mimeType: string; - extension: string; -}; -declare abstract class ToMarkdownService { - transform( - files: MarkdownDocument[], - options?: ConversionRequestOptions - ): Promise; - transform( - files: MarkdownDocument, - options?: ConversionRequestOptions - ): Promise; - supported(): Promise; -} -declare namespace TailStream { - interface Header { - readonly name: string; - readonly value: string; - } - interface FetchEventInfo { - readonly type: 'fetch'; - readonly method: string; - readonly url: string; - readonly cfJson?: object; - readonly headers: Header[]; - } - interface JsRpcEventInfo { - readonly type: 'jsrpc'; - } - interface ScheduledEventInfo { - readonly type: 'scheduled'; - readonly scheduledTime: Date; - readonly cron: string; - } - interface AlarmEventInfo { - readonly type: 'alarm'; - readonly scheduledTime: Date; - } - interface QueueEventInfo { - readonly type: 'queue'; - readonly queueName: string; - readonly batchSize: number; - } - interface EmailEventInfo { - readonly type: 'email'; - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; - } - interface TraceEventInfo { - readonly type: 'trace'; - readonly traces: (string | null)[]; - } - interface HibernatableWebSocketEventInfoMessage { - readonly type: 'message'; - } - interface HibernatableWebSocketEventInfoError { - readonly type: 'error'; - } - interface HibernatableWebSocketEventInfoClose { - readonly type: 'close'; - readonly code: number; - readonly wasClean: boolean; - } - interface HibernatableWebSocketEventInfo { - readonly type: 'hibernatableWebSocket'; - readonly info: - | HibernatableWebSocketEventInfoClose - | HibernatableWebSocketEventInfoError - | HibernatableWebSocketEventInfoMessage; - } - interface CustomEventInfo { - readonly type: 'custom'; - } - interface FetchResponseInfo { - readonly type: 'fetch'; - readonly statusCode: number; - } - type EventOutcome = - | 'ok' - | 'canceled' - | 'exception' - | 'unknown' - | 'killSwitch' - | 'daemonDown' - | 'exceededCpu' - | 'exceededMemory' - | 'loadShed' - | 'responseStreamDisconnected' - | 'scriptNotFound'; - interface ScriptVersion { - readonly id: string; - readonly tag?: string; - readonly message?: string; - } - interface Onset { - readonly type: 'onset'; - readonly attributes: Attribute[]; - // id for the span being opened by this Onset event. - readonly spanId: string; - readonly dispatchNamespace?: string; - readonly entrypoint?: string; - readonly executionModel: string; - readonly scriptName?: string; - readonly scriptTags?: string[]; - readonly scriptVersion?: ScriptVersion; - readonly info: - | FetchEventInfo - | JsRpcEventInfo - | ScheduledEventInfo - | AlarmEventInfo - | QueueEventInfo - | EmailEventInfo - | TraceEventInfo - | HibernatableWebSocketEventInfo - | CustomEventInfo; - } - interface Outcome { - readonly type: 'outcome'; - readonly outcome: EventOutcome; - readonly cpuTime: number; - readonly wallTime: number; - } - interface SpanOpen { - readonly type: 'spanOpen'; - readonly name: string; - // id for the span being opened by this SpanOpen event. - readonly spanId: string; - readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; - } - interface SpanClose { - readonly type: 'spanClose'; - readonly outcome: EventOutcome; - } - interface DiagnosticChannelEvent { - readonly type: 'diagnosticChannel'; - readonly channel: string; - readonly message: any; - } - interface Exception { - readonly type: 'exception'; - readonly name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: 'log'; - readonly level: 'debug' | 'error' | 'info' | 'log' | 'warn'; - readonly message: object; - } - // This marks the worker handler return information. - // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue - // streaming information or SSE http connections. - interface Return { - readonly type: 'return'; - readonly info?: FetchResponseInfo; - } - interface Attribute { - readonly name: string; - readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; - } - interface Attributes { - readonly type: 'attributes'; - readonly info: Attribute[]; - } - type EventType = - | Onset - | Outcome - | SpanOpen - | SpanClose - | DiagnosticChannelEvent - | Exception - | Log - | Return - | Attributes; - // Context in which this trace event lives. - interface SpanContext { - // Single id for the entire top-level invocation - // This should be a new traceId for the first worker stage invoked in the eyeball request and then - // same-account service-bindings should reuse the same traceId but cross-account service-bindings - // should use a new traceId. - readonly traceId: string; - // spanId in which this event is handled - // for Onset and SpanOpen events this would be the parent span id - // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events - // For Hibernate and Mark this would be the span under which they were emitted. - // spanId is not set ONLY if: - // 1. This is an Onset event - // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) - readonly spanId?: string; - } - interface TailEvent { - // invocation id of the currently invoked worker stage. - // invocation id will always be unique to every Onset event and will be the same until the Outcome event. - readonly invocationId: string; - // Inherited spanContext for this event. - readonly spanContext: SpanContext; - readonly timestamp: Date; - readonly sequence: number; - readonly event: Event; - } - type TailEventHandler = ( - event: TailEvent - ) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -/** - * Data types supported for holding vector metadata. - */ -type VectorizeVectorMetadataValue = string | number | boolean | string[]; -/** - * Additional information to associate with a vector. - */ -type VectorizeVectorMetadata = - | VectorizeVectorMetadataValue - | Record; -type VectorFloatArray = Float32Array | Float64Array; -interface VectorizeError { - code?: number; - error: string; -} -/** - * Comparison logic/operation to use for metadata filtering. - * - * This list is expected to grow as support for more operations are released. - */ -type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; -type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; -/** - * Filter criteria for vector metadata used to limit the retrieved query result set. - */ -type VectorizeVectorMetadataFilter = { - [field: string]: - | Exclude - | null - | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude< - VectorizeVectorMetadataValue, - string[] - > | null; - } - | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude< - VectorizeVectorMetadataValue, - string[] - >[]; - }; -}; -/** - * Supported distance metrics for an index. - * Distance metrics determine how other "similar" vectors are determined. - */ -type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product'; -/** - * Metadata return levels for a Vectorize query. - * - * Default to "none". - * - * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. - * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). - * @property none No indexed metadata will be returned. - */ -type VectorizeMetadataRetrievalLevel = 'all' | 'indexed' | 'none'; -interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; -} -/** - * Information about the configuration of an index. - */ -type VectorizeIndexConfig = - | { - dimensions: number; - metric: VectorizeDistanceMetric; - } - | { - preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity - }; -/** - * Metadata about an existing index. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeIndexInfo} for its post-beta equivalent. - */ -interface VectorizeIndexDetails { - /** The unique ID of the index */ - readonly id: string; - /** The name of the index. */ - name: string; - /** (optional) A human readable description for the index. */ - description?: string; - /** The index configuration, including the dimension size and distance metric. */ - config: VectorizeIndexConfig; - /** The number of records containing vectors within the index. */ - vectorsCount: number; -} -/** - * Metadata about an existing index. - */ -interface VectorizeIndexInfo { - /** The number of records containing vectors within the index. */ - vectorCount: number; - /** Number of dimensions the index has been configured for. */ - dimensions: number; - /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ - processedUpToDatetime: number; - /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ - processedUpToMutation: number; -} -/** - * Represents a single vector value set along with its associated metadata. - */ -interface VectorizeVector { - /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ - id: string; - /** The vector values */ - values: VectorFloatArray | number[]; - /** The namespace this vector belongs to. */ - namespace?: string; - /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ - metadata?: Record; -} -/** - * Represents a matched vector for a query along with its score and (if specified) the matching vector information. - */ -type VectorizeMatch = Pick, 'values'> & - Omit & { - /** The score or rank for similarity, when returned as a result */ - score: number; - }; -/** - * A set of matching {@link VectorizeMatch} for a particular query. - */ -interface VectorizeMatches { - matches: VectorizeMatch[]; - count: number; -} -/** - * Results of an operation that performed a mutation on a set of vectors. - * Here, `ids` is a list of vectors that were successfully processed. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeAsyncMutation} for its post-beta equivalent. - */ -interface VectorizeVectorMutation { - /* List of ids of vectors that were successfully processed. */ - ids: string[]; - /* Total count of the number of processed vectors. */ - count: number; -} -/** - * Result type indicating a mutation on the Vectorize Index. - * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. - */ -interface VectorizeAsyncMutation { - /** The unique identifier for the async mutation operation containing the changeset. */ - mutationId: string; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link Vectorize} for its new implementation. - */ -declare abstract class VectorizeIndex { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query( - vector: VectorFloatArray | number[], - options?: VectorizeQueryOptions - ): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * Mutations in this version are async, returning a mutation id. - */ -declare abstract class Vectorize { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query( - vector: VectorFloatArray | number[], - options?: VectorizeQueryOptions - ): Promise; - /** - * Use the provided vector-id to perform a similarity search across the index. - * @param vectorId Id for a vector in the index against which the index should be queried. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * The interface for "version_metadata" binding - * providing metadata about the Worker Version using this binding. - */ -type WorkerVersionMetadata = { - /** The ID of the Worker Version using this binding */ - id: string; - /** The tag of the Worker Version using this binding */ - tag: string; - /** The timestamp of when the Worker Version was uploaded */ - timestamp: string; -}; -interface DynamicDispatchLimits { - /** - * Limit CPU time in milliseconds. - */ - cpuMs?: number; - /** - * Limit number of subrequests. - */ - subRequests?: number; -} -interface DynamicDispatchOptions { - /** - * Limit resources of invoked Worker script. - */ - limits?: DynamicDispatchLimits; - /** - * Arguments for outbound Worker script, if configured. - */ - outbound?: { - [key: string]: any; - }; -} -interface DispatchNamespace { - /** - * @param name Name of the Worker script. - * @param args Arguments to Worker script. - * @param options Options for Dynamic Dispatch invocation. - * @returns A Fetcher object that allows you to send requests to the Worker script. - * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. - */ - get( - name: string, - args?: { - [key: string]: any; - }, - options?: DynamicDispatchOptions - ): Fetcher; -} -declare module 'cloudflare:workflows' { - /** - * NonRetryableError allows for a user to throw a fatal error - * that makes a Workflow instance fail immediately without triggering a retry - */ - export class NonRetryableError extends Error { - public constructor(message: string, name?: string); - } -} -declare abstract class Workflow { - /** - * Get a handle to an existing instance of the Workflow. - * @param id Id for the instance of this Workflow - * @returns A promise that resolves with a handle for the Instance - */ - public get(id: string): Promise; - /** - * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. - * @param options Options when creating an instance including id and params - * @returns A promise that resolves with a handle for the Instance - */ - public create(options?: WorkflowInstanceCreateOptions): Promise; - /** - * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. - * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. - * @param batch List of Options when creating an instance including name and params - * @returns A promise that resolves with a list of handles for the created instances. - */ - public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; -} -type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; -type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; -type WorkflowRetentionDuration = WorkflowSleepDuration; -interface WorkflowInstanceCreateOptions { - /** - * An id for your Workflow instance. Must be unique within the Workflow. - */ - id?: string; - /** - * The event payload the Workflow instance is triggered with - */ - params?: PARAMS; - /** - * The retention policy for Workflow instance. - * Defaults to the maximum retention period available for the owner's account. - */ - retention?: { - successRetention?: WorkflowRetentionDuration; - errorRetention?: WorkflowRetentionDuration; - }; -} -type InstanceStatus = { - status: - | 'queued' // means that instance is waiting to be started (see concurrency limits) - | 'running' - | 'paused' - | 'errored' - | 'terminated' // user terminated the instance while it was running - | 'complete' - | 'waiting' // instance is hibernating and waiting for sleep or event to finish - | 'waitingForPause' // instance is finishing the current work to pause - | 'unknown'; - error?: { - name: string; - message: string; - }; - output?: unknown; -}; -interface WorkflowError { - code?: number; - message: string; -} -declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. - */ - public restart(): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload }: { type: string; payload: unknown }): Promise; + interface ProcessEnv extends StringifyValues> {} } +declare module "*.sql" { + const value: string; + export default value; + } \ No newline at end of file diff --git a/services/webhook-agent-ingest/wrangler.jsonc b/services/webhook-agent-ingest/wrangler.jsonc index 86f8574a12..68b8c57a47 100644 --- a/services/webhook-agent-ingest/wrangler.jsonc +++ b/services/webhook-agent-ingest/wrangler.jsonc @@ -34,6 +34,7 @@ "KILOCODE_BACKEND_BASE_URL": "https://api.kilo.ai", "WEBHOOK_AGENT_URL": "https://hooks.kilosessions.ai", "KILOCLAW_API_URL": "https://claw.kilosessions.ai", + "SHARED_RESOURCE_TOKENS_ENABLED": "false", }, // PRODUCTION service binding to Cloud Agent Next "services": [ @@ -137,6 +138,7 @@ "KILOCODE_BACKEND_BASE_URL": "http://localhost:3000", "KILOCLAW_API_URL": "http://localhost:8795", "WEBHOOK_AGENT_URL": "http://localhost:8793", + "SHARED_RESOURCE_TOKENS_ENABLED": "false", }, // DEV service binding to Cloud Agent Next "services": [ @@ -173,7 +175,6 @@ { "name": "TRIGGER_DO", "class_name": "TriggerDO", - "script_name": "cloudflare-webhook-agent-ingest-dev", }, ], }, From e4535104f380a3ff0700fb0463288a3ffa3c8f7a Mon Sep 17 00:00:00 2001 From: Florian Hines Date: Tue, 8 Sep 2026 12:23:33 -0500 Subject: [PATCH 2/5] docs(auth): clarify stacked rollout and issuance defaults --- docs/token-issuance-policy.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/token-issuance-policy.md b/docs/token-issuance-policy.md index a4dfadb360..9e313f0881 100644 --- a/docs/token-issuance-policy.md +++ b/docs/token-issuance-policy.md @@ -187,12 +187,16 @@ This PR does not retire legacy native exchange, shorten user credentials, change ### Deployment model and implementation status -Merging this PR automatically deploys the services within a few minutes of one another. There is no operator-managed sequence of separate service deployments. The old/new version overlap must remain compatible with all new producer and isolation-adoption flags off. After the entire automatic deployment wave is healthy, activate the flags in dependency order. This remains one Phase 5.2 PR. +Phase 5.2 is available as an ordered stack: foundation (#5974), Cloud Agent (#5975), then remaining families (#5976). The original combined PR #5857 remains unchanged. Wait for each preceding PR's deployments to become healthy before merging the next; components within one PR still deploy independently. + +The Cloud Agent PR configures `RUNTIME_ISOLATION_ENABLED=true` in production and development. This permits modern workspace admission; it does not issue modern tokens or migrate legacy sessions. Missing or non-`true` values still reject new modern workspace admission. The wrapper must advertise isolation support. **Resolve the outstanding Cloud Agent smoke failures before merging that PR.** Readiness for review is not deployment approval. + +Keep web issuance off through the Cloud Agent deployment. Once the actual Worker/wrapper chain is healthy and verified, enable web `SHARED_RESOURCE_TOKENS_ENABLED` and `CLOUD_AGENT_RESOURCE_TOKENS_ENABLED`. This activation does not need to wait for the remaining-family PR. That PR keeps every additional producer flag off, even if the shared web master is already on. Merge readiness, feature activation, and completeness of real-environment smoke coverage are separate decisions. A missing production recovery path was a code defect; unavailable Vercel/device coverage is a separately recorded validation risk. 1. Cloud Agent's 24-hour recovery is implemented for both session planes through the public send preflight, including legacy V2 and SDK prompt adapters. A fresh authenticated credential authorizes recovery of the same session. Recovery refuses queued/active work and live PTYs, retires the old transport before replacing authority, clears stale grants/attachment state, and lets normal dispatch attach a fresh handle. Workspace retirement is acknowledged and root-scoped; agent-plane retirement requires authoritative physical absence. Durable recovery IDs survive retries, and explicit revocation never becomes natural-expiry recovery. Real Durable Object integration tests cover successful recovery, lost acknowledgement, subsequent attach/prompt, queued-work rejection, and active-PTY rejection. -2. The real sandbox smoke matrix is not green. Local legacy execution reached Worker, DO, Docker, wrapper, Kilo 7.4.20, and the fake LLM, but the `cold-hot` scenario failed its no-preparation assertion on the first hot turn. Four LLM requests and two terminal turns were observed; they do not prove all planned hot turns completed. The legacy implementation already emits warm preparation bookkeeping. A harness correction must add positive workspace/setup reuse evidence rather than simply drop the assertion. Control-plane smoke has not demonstrated a completed Kilo/fake-provider round trip. +2. The latest recorded original-branch sandbox smoke matrix passed 9/13 scenarios after the harness corrections. CLI/container startup and recovery failures remain; SDK cold-wake also failed during replacement startup. The stack extraction and readiness-default change do not resolve those failures or establish complete real-provider coverage. Rerun the affected end-to-end paths before merging the Cloud Agent PR. ### Merge and automatic deployment, producers disabled @@ -202,7 +206,7 @@ The automatic deployment wave includes these units. Retain all legacy readers an |---|---|---| | Web API/gateway receiving deployments, including `app.kilo.ai` and `api.kilo.ai` | Legacy and modern audience readers; runtime-proof verification; native negotiation and bounded rollback bridge | Shared and native issuance off | | Session Ingest Worker | Legacy and modern audience readers; runtime-proof verification; unchanged dedicated ticket/deletion contracts | No new runtime issuers | -| Cloud Agent Worker and its wrapper/container images | Optional isolation attachment selection and explicit wrapper hello capability; omitted selection remains directory-shared | `RUNTIME_ISOLATION_ENABLED=false` | +| Cloud Agent Worker and its wrapper/container images | Optional isolation attachment selection and explicit wrapper hello capability; omitted selection remains directory-shared | `RUNTIME_ISOLATION_ENABLED=true` in the Cloud Agent PR; issuance remains off | | Gastown and Wasteland receiving Workers | Existing supported tokens and current owner/membership checks; fail-closed modern runtime state | No new modern control issuance | | Security Auto Analysis and Webhook Agent Ingest Workers | Legacy defaults, scoped modern issuance available but inactive, compatible callback/result readers | Their own shared-issuance settings off | | Native application | Negotiation, bundle storage, API/gateway routing, legacy responses | Server-side native adoption off | @@ -248,7 +252,7 @@ No production-only testing bypass or arbitrary token/state mutation endpoint sho ### Activate flags after the automatic deployment wave -Web adoption requires `SHARED_RESOURCE_TOKENS_ENABLED=true` **and** the applicable producer flag below. Every flag defaults off and recognizes only the exact value `true`. The shared switch alone does not activate a producer. These are server-side deployment settings, not client-controlled request options. +Web adoption requires `SHARED_RESOURCE_TOKENS_ENABLED=true` **and** the applicable producer flag below. Every web issuance flag defaults off and recognizes only the exact value `true`. The shared switch alone does not activate a producer. These are server-side deployment settings, not client-controlled request options. | Producer | Additional web flag | Initial shipping decision | |---|---|---| @@ -261,6 +265,8 @@ Web adoption requires `SHARED_RESOURCE_TOKENS_ENABLED=true` **and** the applicab | Auto-routing benchmark credentials | `BENCHMARK_RESOURCE_TOKENS_ENABLED` | Independent opt-in rollout | | Negotiated native API/gateway bundles | `NATIVE_RESOURCE_TOKENS_ENABLED` | Keep off; mobile and CLI clients continue receiving legacy credentials | +No additional producer in the remaining-family PR defaults on. Chat changes an existing token shared by Chat, Events, and Notifications; verify all three consumers together. Workflow gateway and the two Worker-local switches alter automation credentials and require a real job/callback round trip. Benchmark issuance changes the CLI credential contract and account/organization eligibility checks; verify a real benchmark container run. Explicit delegation is opt-in and leaves non-negotiating callers on their existing path, making it a good early rollout candidate, but enabling it still creates usable API/gateway/attribution/HTML credentials and should follow consumer-path verification. Native, Gastown, and Wasteland retain the blockers listed above and below. + Unsupported CLI/native clients retain legacy issuance regardless of these adoption settings. Security Auto Analysis and Webhook Agent Ingest keep their existing Worker-local shared switches; a web setting does not activate those separately deployed producers. Bounded internal assertions retain their separate Phase 5.1 switch. **Gastown modern activation is blocked by known implementation gaps**, not merely missing smoke evidence. Its runtime JWT does not include Session Ingest even though the CLI uses it there, and updating the town/container configuration does not establish safe credential renewal in an already-running CLI/provider client. Keep Gastown's producer off until both the complete consumer audience contract and uninterrupted active-runtime renewal are implemented and tested. Do not add an audience without verifying the full delivery path, restart active work to rotate credentials, or disable reader checks. This PR retains the modern implementation and existing modern-state validation, but does not certify that path for activation. @@ -268,7 +274,7 @@ Unsupported CLI/native clients retain legacy issuance regardless of these adopti Once all receiving deployments are healthy, activate progressively while recording any accepted real-environment coverage risks: 1. Confirm the exact deployed revisions for every receiver a producer calls, including both web receiving aliases, Session Ingest, Cloud Agent Worker, and the actual wrapper image. Verify the wrapper hello capability rather than inferring it from an image tag. -2. Enable runtime isolation admission on the selected Cloud Agent deployment/cohort. This environment boolean is deployment-scoped, not itself a per-user allowlist; use an existing cohort/staging deployment for limited exposure. +2. Verify runtime isolation admission is enabled by the Cloud Agent deployment configuration and the connected wrapper advertises support. This environment boolean is deployment-scoped, not itself a per-user allowlist; use an existing cohort/staging deployment for limited exposure. 3. Enable the shared web prerequisite and one eligible producer-family flag at a time. Web and Worker-local settings are separate; record each activation independently. Leave Gastown and native adoption off for this shipping stage. Do not assume enabling web updates Security Auto Analysis or Webhook Agent Ingest. 4. Exercise the producer's real consumer chain and observe auth failures, renewal latency, sandbox restarts, child-process count, memory, and queue retries before expanding. 5. Enable native adoption last, after device and downgrade validation. Fresh bundles require both native and shared web readiness settings. @@ -282,4 +288,4 @@ Once all receiving deployments are healthy, activate progressively while recordi - Keep compatible readers, proof verification, wrapper capabilities, and renewal/recovery support deployed until the corresponding credential and workload populations have drained or been safely migrated. Existing Cloud Agent and Gastown delegation bounds differ; do not use one global wait interval. - Never rotate global keys, reset all peppers, remove audience checks, or fall back to unrestricted legacy credentials to recover availability. -Keep all new adoption flags off during the automatic deployment wave. Merge does not activate modern issuance. Record incomplete physical-device, real-provider, and full sandbox smoke coverage as validation risks rather than presenting them as missing recovery implementation or claiming unperformed tests passed. +Keep new producer issuance off during each automatic deployment wave. The Cloud Agent PR enables runtime isolation admission, but merge does not activate modern issuance. Record incomplete physical-device, real-provider, and full sandbox smoke coverage as validation risks rather than presenting them as missing recovery implementation or claiming unperformed tests passed. From d20fb1dd7448eebf17276407ac134e69e235a9ad Mon Sep 17 00:00:00 2001 From: Florian Hines Date: Tue, 8 Sep 2026 17:11:34 -0500 Subject: [PATCH 3/5] refactor(auth): remove unused additions from token rollout --- apps/mobile/src/lib/auth/native-auth-contract.ts | 14 -------------- .../gastown/src/dos/town/runtime-authorization.ts | 2 +- services/security-auto-analysis/src/token.ts | 2 +- 3 files changed, 2 insertions(+), 16 deletions(-) diff --git a/apps/mobile/src/lib/auth/native-auth-contract.ts b/apps/mobile/src/lib/auth/native-auth-contract.ts index 4948b102b6..0c16729125 100644 --- a/apps/mobile/src/lib/auth/native-auth-contract.ts +++ b/apps/mobile/src/lib/auth/native-auth-contract.ts @@ -7,7 +7,6 @@ import { } from '@kilocode/app-shared/native-auth'; const tokenResponseSchema = z.object({ token: z.string().min(1) }); -const credentialEnvelopeSchema = z.record(z.string(), z.unknown()); const emailCodeResponseSchema = z.object({ success: z.literal(true), challengeId: z.uuid().optional(), @@ -20,9 +19,6 @@ const errorResponseSchema = z.object({ export type TokenPair = NativeTokenPair; export function parseTokenResponse(value: unknown): { token: string } | null { - if (hasCredentialFormat(value)) { - return null; - } const result = tokenResponseSchema.safeParse(value); return result.success ? result.data : null; } @@ -33,16 +29,6 @@ export function parseTokenPair(value: unknown): TokenPair | null { export { API_GATEWAY_CREDENTIAL_FORMAT, type NativeCredentialBundleMetadata, type NativeTokenPair }; -function hasCredentialFormat(value: unknown): boolean { - const envelope = credentialEnvelopeSchema.safeParse(value); - return ( - envelope.success && - (Object.hasOwn(envelope.data, 'credentialFormat') || - Object.hasOwn(envelope.data, 'gatewayToken') || - Object.hasOwn(envelope.data, 'metadata')) - ); -} - const deviceAuthTokenStatusSchema = z.enum(['pending', 'approved', 'denied', 'expired']); const deviceAuthTokenResponseSchema = z.looseObject({ diff --git a/services/gastown/src/dos/town/runtime-authorization.ts b/services/gastown/src/dos/town/runtime-authorization.ts index 5284f5ac8d..c5fa6488b0 100644 --- a/services/gastown/src/dos/town/runtime-authorization.ts +++ b/services/gastown/src/dos/town/runtime-authorization.ts @@ -60,7 +60,7 @@ export async function initializePrivateTownIdentity( }); } -export function isModernControlToken(token: string): boolean { +function isModernControlToken(token: string): boolean { try { return typeof decodeJwt(token).tokenPurpose === 'string'; } catch { diff --git a/services/security-auto-analysis/src/token.ts b/services/security-auto-analysis/src/token.ts index 07b5c7a96e..344fe31888 100644 --- a/services/security-auto-analysis/src/token.ts +++ b/services/security-auto-analysis/src/token.ts @@ -13,7 +13,7 @@ type TokenUser = { const ONE_HOUR_SECONDS = 60 * 60; -export function isSharedResourceTokensEnabled(value: string | boolean | undefined): boolean { +function isSharedResourceTokensEnabled(value: string | boolean | undefined): boolean { return value === true || value === 'true'; } From 7351ece728171a65e82772eb5cef5ae3831a7f58 Mon Sep 17 00:00:00 2001 From: Florian Hines Date: Wed, 9 Sep 2026 09:04:17 -0500 Subject: [PATCH 4/5] fix(gastown): retain admin access to unmigrated towns --- .../middleware/town-auth.middleware.test.ts | 33 ++++++++++--------- .../src/middleware/town-auth.middleware.ts | 2 +- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/services/gastown/src/middleware/town-auth.middleware.test.ts b/services/gastown/src/middleware/town-auth.middleware.test.ts index 4f2175a6ff..b172c1f792 100644 --- a/services/gastown/src/middleware/town-auth.middleware.test.ts +++ b/services/gastown/src/middleware/town-auth.middleware.test.ts @@ -34,22 +34,25 @@ describe('townAuthMiddleware', () => { expect((await app.request('/api/towns/town-1/config', {}, {} as Env)).status).toBe(403); }); - it('preserves the cached admin bypass for legacy towns', async () => { - mocks.getTownIdentityState.mockResolvedValue({ - type: 'legacy', - identity: { ownerType: 'user', ownerUserId: 'owner', runtimeMode: 'legacy' }, - }); - const app = new Hono(); - app.use('*', async (c, next) => { - c.set('kiloUserId', 'admin'); - c.set('kiloIsAdmin', true); - await next(); - }); - app.use('/api/towns/:townId/*', townAuthMiddleware); - app.get('/api/towns/:townId/config', c => c.text('allowed')); + it.each([null, { ownerType: 'user', ownerUserId: 'owner', runtimeMode: 'legacy' }])( + 'preserves the cached admin bypass for legacy identity %j', + async identity => { + mocks.getTownIdentityState.mockResolvedValue({ + type: 'legacy', + identity, + }); + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('kiloUserId', 'admin'); + c.set('kiloIsAdmin', true); + await next(); + }); + app.use('/api/towns/:townId/*', townAuthMiddleware); + app.get('/api/towns/:townId/config', c => c.text('allowed')); - expect((await app.request('/api/towns/town-1/config', {}, {} as Env)).status).toBe(200); - }); + expect((await app.request('/api/towns/town-1/config', {}, {} as Env)).status).toBe(200); + } + ); it('fails closed for an invalid persisted authorization state', async () => { mocks.getTownIdentityState.mockResolvedValue({ type: 'invalid' }); diff --git a/services/gastown/src/middleware/town-auth.middleware.ts b/services/gastown/src/middleware/town-auth.middleware.ts index 74df293ffc..dfe9245102 100644 --- a/services/gastown/src/middleware/town-auth.middleware.ts +++ b/services/gastown/src/middleware/town-auth.middleware.ts @@ -41,8 +41,8 @@ export const townAuthMiddleware = createMiddleware(async (c, next) = throw error; } } + if (c.get('kiloIsAdmin')) return next(); if (identity) { - if (c.get('kiloIsAdmin')) return next(); if (identity.ownerType === 'user') { if (identity.ownerUserId !== userId) return c.json(resError('Forbidden'), 403); return next(); From 4ccf1ff9d3dad389481ea2fa4c430f30294a524c Mon Sep 17 00:00:00 2001 From: Florian Hines Date: Wed, 9 Sep 2026 09:04:17 -0500 Subject: [PATCH 5/5] fix(gastown): harden runtime reauthorization and legacy renewal --- services/gastown/src/dos/Town.do.ts | 8 +- .../dos/town/runtime-authorization.test.ts | 199 +++++++++++++++++- .../src/dos/town/runtime-authorization.ts | 59 ++++-- .../dos/town/unattended-token-renewal.test.ts | 68 +++++- .../src/dos/town/unattended-token-renewal.ts | 19 +- .../integration/town-private-identity.test.ts | 78 ++++++- 6 files changed, 399 insertions(+), 32 deletions(-) diff --git a/services/gastown/src/dos/Town.do.ts b/services/gastown/src/dos/Town.do.ts index aa79fa6327..03249084c4 100644 --- a/services/gastown/src/dos/Town.do.ts +++ b/services/gastown/src/dos/Town.do.ts @@ -995,12 +995,14 @@ export class TownDO extends DurableObject { userId: string, organizationId?: string ): Promise { - return runtimeAuthorization.createRuntimeAuthorization( + const token = await runtimeAuthorization.createRuntimeAuthorization( this.runtimeAuthorizationCtx, controlToken, userId, organizationId ); + if (token) this._ownerUserId = (await this.getTownConfig()).owner_user_id; + return token; } async reauthorizeRuntime( @@ -1008,12 +1010,14 @@ export class TownDO extends DurableObject { userId: string, organizationId?: string ): Promise { - return runtimeAuthorization.reauthorizeRuntime( + const authorized = await runtimeAuthorization.reauthorizeRuntime( this.runtimeAuthorizationCtx, controlToken, userId, organizationId ); + if (authorized) this._ownerUserId = (await this.getTownConfig()).owner_user_id; + return authorized; } private async renewRuntimeAuthorization(): Promise { diff --git a/services/gastown/src/dos/town/runtime-authorization.test.ts b/services/gastown/src/dos/town/runtime-authorization.test.ts index 13d1dd7663..e779260e1e 100644 --- a/services/gastown/src/dos/town/runtime-authorization.test.ts +++ b/services/gastown/src/dos/town/runtime-authorization.test.ts @@ -34,6 +34,7 @@ import { getTownIdentityState, initializePrivateTownIdentity, RUNTIME_AUTHORIZATION_KEY, + TOWN_IDENTITY_KEY, reauthorizeRuntime, requiresRuntimeAuthorization, renewRuntimeAuthorization, @@ -41,13 +42,24 @@ import { import { RuntimeAuthorizationRevokedError } from '@kilocode/worker-utils/runtime-authorization'; import { RuntimeAuthorizationExpiredError } from '@kilocode/worker-utils/runtime-authorization'; -type TestStorage = DurableObjectStorage & { putMock: ReturnType }; +type TestStorage = DurableObjectStorage & { + putMock: ReturnType Promise>>; +}; function storage(): TestStorage { const values = new Map(); const put = vi.fn(async (key: string, value: unknown) => values.set(key, value)); const store = { - transaction: async (fn: (txn: DurableObjectStorage) => Promise) => fn(store), + transaction: async (fn: (txn: DurableObjectStorage) => Promise) => { + const snapshot = new Map(values); + try { + return await fn(store); + } catch (error) { + values.clear(); + for (const [key, value] of snapshot) values.set(key, value); + throw error; + } + }, get: vi.fn(async (key: string) => values.get(key) as T), put, putMock: put, @@ -330,4 +342,187 @@ describe('runtime authorization persistence', () => { ).resolves.toBe('runtime-token'); await expect(getRuntimeAuthorizationState(store)).resolves.toBe('active'); }); + it('keeps legacy identity intact when the modern identity write fails', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, identity); + mocks.create.mockResolvedValue({ authorization: authorization(), token: 'runtime-token' }); + const originalPut = store.putMock.getMockImplementation(); + if (!originalPut) throw new Error('Missing storage writer'); + store.putMock.mockImplementationOnce(async (key: string, value: unknown) => { + // Use the normal writer for the authorization, then fail the identity write. + store.putMock.mockImplementationOnce(() => { + throw new Error('storage failure'); + }); + return originalPut(key, value); + }); + await expect( + createRuntimeAuthorization(context(store), 'control-token', 'user-1') + ).resolves.toBeUndefined(); + await expect(getTownIdentityState(store, 'town-1')).resolves.toEqual({ + type: 'legacy', + identity, + }); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toBeUndefined(); + }); + + it('rebinds an org runtime to the current owner and retains creator attribution', async () => { + const store = storage(); + const orgId = '00000000-0000-4000-8000-000000000003'; + const orgIdentity = { + ...identity, + ownerType: 'org' as const, + organizationId: orgId, + runtimeMode: 'modern' as const, + }; + await initializePrivateTownIdentity(store, orgIdentity); + await store.put(RUNTIME_AUTHORIZATION_KEY, { + ...authorization('revoked'), + organizationId: orgId, + }); + mocks.create.mockResolvedValue({ + authorization: { + ...authorization(), + organizationId: orgId, + userId: 'new-owner', + authorizationUserId: 'new-owner', + }, + token: 'replacement', + }); + + await expect( + reauthorizeRuntime(context(store), 'control-token', 'new-owner', orgId) + ).resolves.toBe(true); + await expect(getTownIdentityState(store, 'town-1')).resolves.toEqual({ + type: 'modern', + identity: { ...orgIdentity, ownerUserId: 'new-owner' }, + }); + expect(mocks.updateConfig).toHaveBeenLastCalledWith(store, { owner_user_id: 'new-owner' }); + }); + + it.each([ + { userId: 'another-user' }, + { authorizationUserId: 'another-user' }, + { organizationId: '00000000-0000-4000-8000-000000000003' }, + ])('rejects admission bound to another principal or organization: %j', async update => { + const store = storage(); + await initializePrivateTownIdentity(store, identity); + mocks.create.mockResolvedValue({ + authorization: { ...authorization(), ...update }, + token: 'runtime-token', + }); + await expect( + createRuntimeAuthorization(context(store), 'control-token', 'user-1') + ).resolves.toBeUndefined(); + await expect(getTownIdentityState(store, 'town-1')).resolves.toEqual({ + type: 'legacy', + identity, + }); + }); + + it('does not allow another user to reauthorize a personal town', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization('revoked')); + await expect(reauthorizeRuntime(context(store), 'control-token', 'another-user')).resolves.toBe( + false + ); + expect(mocks.create).not.toHaveBeenCalled(); + }); + + it.each(['active', 'revoked'] as const)( + 'preserves a concurrent %s authorization during admission', + async state => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization('revoked')); + const concurrent = { ...authorization(state), id: '00000000-0000-4000-8000-000000000002' }; + mocks.create.mockImplementation(async () => { + await store.put(RUNTIME_AUTHORIZATION_KEY, concurrent); + return { authorization: authorization(), token: 'runtime-token' }; + }); + await expect(reauthorizeRuntime(context(store), 'control-token', 'user-1')).resolves.toBe( + false + ); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toEqual(concurrent); + } + ); + it('does not overwrite an identity changed while admission is in flight', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, identity); + const changed = { ...identity, createdByUserId: 'corrected-creator' }; + mocks.create.mockImplementation(async () => { + await store.put(TOWN_IDENTITY_KEY, changed); + return { authorization: authorization(), token: 'runtime-token' }; + }); + await expect( + createRuntimeAuthorization(context(store), 'control-token', 'user-1') + ).resolves.toBeUndefined(); + expect(await store.get(TOWN_IDENTITY_KEY)).toEqual(changed); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toBeUndefined(); + }); + + it('does not replace a revoked authorization changed during the container check', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization('revoked')); + const replacement = { ...authorization(), id: '00000000-0000-4000-8000-000000000002' }; + mocks.getState.mockImplementation(async () => { + await store.put(RUNTIME_AUTHORIZATION_KEY, replacement); + return { status: 'stopped' }; + }); + await expect(reauthorizeRuntime(context(store), 'control-token', 'user-1')).resolves.toBe( + false + ); + expect(mocks.create).not.toHaveBeenCalled(); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toEqual(replacement); + }); + + it('does not persist admission if work starts during external verification', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + const previous = authorization('revoked'); + await store.put(RUNTIME_AUTHORIZATION_KEY, previous); + let active = false; + mocks.create.mockImplementation(async () => { + active = true; + return { authorization: authorization(), token: 'runtime-token' }; + }); + await expect( + reauthorizeRuntime( + { ...context(store), hasActiveWork: () => active }, + 'control-token', + 'user-1' + ) + ).resolves.toBe(false); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toEqual(previous); + }); + + it('leaves expired authorization unchanged when admission fails', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + const previous = authorization(); + await store.put(RUNTIME_AUTHORIZATION_KEY, previous); + mocks.create.mockRejectedValue(new Error('Invalid runtime admission')); + await expect(reauthorizeRuntime(context(store), 'control-token', 'user-1')).resolves.toBe( + false + ); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toEqual(previous); + }); + + it('preserves same-record revocation while expired admission is in flight', async () => { + const store = storage(); + await initializePrivateTownIdentity(store, { ...identity, runtimeMode: 'modern' }); + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization()); + mocks.create.mockImplementation(async () => { + await store.put(RUNTIME_AUTHORIZATION_KEY, authorization('revoked')); + return { + authorization: { ...authorization(), id: '00000000-0000-4000-8000-000000000002' }, + token: 'runtime-token', + }; + }); + await expect(reauthorizeRuntime(context(store), 'control-token', 'user-1')).resolves.toBe( + false + ); + expect(await store.get(RUNTIME_AUTHORIZATION_KEY)).toEqual(authorization('revoked')); + }); }); diff --git a/services/gastown/src/dos/town/runtime-authorization.ts b/services/gastown/src/dos/town/runtime-authorization.ts index c5fa6488b0..e70c1a937b 100644 --- a/services/gastown/src/dos/town/runtime-authorization.ts +++ b/services/gastown/src/dos/town/runtime-authorization.ts @@ -124,7 +124,8 @@ export async function createRuntimeAuthorization( ctx: RuntimeAuthorizationContext, controlToken: string, userId: string, - organizationId?: string + organizationId?: string, + expectedAuthorization?: RuntimeAuthorization ): Promise { const identity = await getPrivateTownIdentity(ctx.storage, ctx.townId); if ( @@ -136,6 +137,13 @@ export async function createRuntimeAuthorization( !ctx.env.HYPERDRIVE ) return undefined; + const previousAuthorization = await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY); + if ( + expectedAuthorization !== undefined && + JSON.stringify(RuntimeAuthorizationSchema.safeParse(previousAuthorization).data) !== + JSON.stringify(expectedAuthorization) + ) + return undefined; const secret = await resolveSecret(ctx.env.NEXTAUTH_SECRET); if (!secret) return undefined; try { @@ -149,13 +157,35 @@ export async function createRuntimeAuthorization( now: ctx.now?.(), }); if ( - created.authorization.userId !== identity.ownerUserId || - created.authorization.authorizationUserId !== identity.ownerUserId + created.authorization.userId !== userId || + created.authorization.authorizationUserId !== userId || + created.authorization.organizationId !== identity.organizationId || + created.authorization.resourceKind !== 'gastown' || + created.authorization.resourceId !== ctx.townId ) { throw new Error('Runtime authorization owner mismatch'); } - await ctx.storage.put(RUNTIME_AUTHORIZATION_KEY, created.authorization); - await ctx.storage.put(TOWN_IDENTITY_KEY, { ...identity, runtimeMode: 'modern' }); + await ctx.storage.transaction(async txn => { + const currentIdentity = await txn.get(TOWN_IDENTITY_KEY); + const currentAuthorization = await txn.get(RUNTIME_AUTHORIZATION_KEY); + if ( + JSON.stringify(currentIdentity) !== JSON.stringify(identity) || + JSON.stringify(currentAuthorization) !== JSON.stringify(previousAuthorization) || + (expectedAuthorization !== undefined && ctx.hasActiveWork()) + ) { + throw new Error('Town authorization changed during admission'); + } + await txn.put(RUNTIME_AUTHORIZATION_KEY, created.authorization); + // An org owner can take over runtime sponsorship; retain creator attribution. + await txn.put(TOWN_IDENTITY_KEY, { + ...identity, + ownerUserId: userId, + runtimeMode: 'modern', + } satisfies TownIdentity); + if (identity.ownerUserId !== userId) { + await config.updateTownConfig(txn, { owner_user_id: userId }); + } + }); return created.token; } catch { return undefined; @@ -204,20 +234,15 @@ export async function reauthorizeRuntime( return false; const container = await getTownContainerStub(ctx.env, ctx.townId).getState(); if (container.status === 'running' || container.status === 'healthy') return false; - if (expired) { - const latest = RuntimeAuthorizationSchema.safeParse( - await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY) - ); - if (!latest.success || latest.data.id !== current.data.id || latest.data.state !== 'active') { - return false; - } - await ctx.storage.put(RUNTIME_AUTHORIZATION_KEY, { - ...latest.data, - state: 'revoked', - } satisfies RuntimeAuthorization); + const latest = RuntimeAuthorizationSchema.safeParse( + await ctx.storage.get(RUNTIME_AUTHORIZATION_KEY) + ); + if (!latest.success || JSON.stringify(latest.data) !== JSON.stringify(current.data)) { + return false; } return ( - (await createRuntimeAuthorization(ctx, controlToken, userId, organizationId)) !== undefined + (await createRuntimeAuthorization(ctx, controlToken, userId, organizationId, current.data)) !== + undefined ); } diff --git a/services/gastown/src/dos/town/unattended-token-renewal.test.ts b/services/gastown/src/dos/town/unattended-token-renewal.test.ts index 3da84f77d7..f301765f4f 100644 --- a/services/gastown/src/dos/town/unattended-token-renewal.test.ts +++ b/services/gastown/src/dos/town/unattended-token-renewal.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { SignJWT, jwtVerify } from 'jose'; +import { CompactSign, SignJWT, jwtVerify } from 'jose'; const mocks = vi.hoisted(() => ({ userTown: vi.fn(), orgTown: vi.fn(), select: vi.fn() })); vi.mock('cloudflare:workers', () => ({ DurableObject: class {}, WorkerEntrypoint: class {} })); @@ -21,6 +21,7 @@ vi.mock('@kilocode/db/client', () => ({ getWorkerDb: () => ({ select: mocks.sele import { TownDO } from '../Town.do'; import * as config from './config'; +import * as runtimeAuthorization from './runtime-authorization'; import { getTownIdentityState, initializePrivateTownIdentity, @@ -213,6 +214,31 @@ describe('unattended legacy town renewal entry', () => { expect(mocks.userTown).not.toHaveBeenCalled(); }); + it.each([ + { exp: 'expired' }, + { exp: null }, + { exp: 1.5 }, + { exp: undefined }, + { exp: 1, nbf: 0 }, + { exp: 1, aud: 'kilo-api' }, + { exp: 1, iat: Math.floor(Date.now() / 1000) + 100 }, + ])('rejects malformed or restricted expired claims %j', async claims => { + const t = await town(false, await token(claims)); + await t.renew(); + expect(t.sync).not.toHaveBeenCalled(); + expect(mocks.userTown).not.toHaveBeenCalled(); + }); + + it('rejects authenticated bytes that are not JSON', async () => { + const bearer = await new CompactSign(new TextEncoder().encode('not JSON')) + .setProtectedHeader({ alg: 'HS256' }) + .sign(new TextEncoder().encode(secret)); + const t = await town(false, bearer); + await t.renew(); + expect(t.sync).not.toHaveBeenCalled(); + expect(mocks.userTown).not.toHaveBeenCalled(); + }); + it.each([ { rows: [] }, { rows: [{ pepper: 'new', blockedAt: null, blockedReason: null }] }, @@ -367,3 +393,43 @@ describe('unattended legacy town renewal entry', () => { expect(mocks.userTown).toHaveBeenCalledOnce(); }); }); + +describe('runtime sponsorship owner cache', () => { + it('refreshes the owner cache after committed reauthorization', async () => { + const t = await town(true); + Object.assign(t.instance, { _ownerUserId: identity.ownerUserId }); + const reauthorize = vi + .spyOn(runtimeAuthorization, 'reauthorizeRuntime') + .mockImplementation(async () => { + await config.updateTownConfig(t.store, { owner_user_id: 'new-owner' }); + return true; + }); + try { + await expect( + t.instance.reauthorizeRuntime('control-token', 'new-owner', 'org-1') + ).resolves.toBe(true); + expect(t.instance['_ownerUserId']).toBe('new-owner'); + } finally { + reauthorize.mockRestore(); + } + }); + + it('refreshes the owner cache after committed admission', async () => { + const t = await town(true); + Object.assign(t.instance, { _ownerUserId: identity.ownerUserId }); + const create = vi + .spyOn(runtimeAuthorization, 'createRuntimeAuthorization') + .mockImplementation(async () => { + await config.updateTownConfig(t.store, { owner_user_id: 'new-owner' }); + return 'runtime-token'; + }); + try { + await expect( + t.instance.createRuntimeAuthorization('control-token', 'new-owner', 'org-1') + ).resolves.toBe('runtime-token'); + expect(t.instance['_ownerUserId']).toBe('new-owner'); + } finally { + create.mockRestore(); + } + }); +}); diff --git a/services/gastown/src/dos/town/unattended-token-renewal.ts b/services/gastown/src/dos/town/unattended-token-renewal.ts index b9ba430912..b6932bf1c0 100644 --- a/services/gastown/src/dos/town/unattended-token-renewal.ts +++ b/services/gastown/src/dos/town/unattended-token-renewal.ts @@ -1,5 +1,5 @@ import { kiloTokenPayload } from '@kilocode/worker-utils'; -import { jwtVerify, errors } from 'jose'; +import { compactVerify } from 'jose'; import { z } from 'zod'; import { getGastownOrgStub } from '../GastownOrg.do'; import { getGastownUserStub } from '../GastownUser.do'; @@ -74,15 +74,16 @@ export async function renewUnattendedLegacyTownToken( if (!token || !env.NEXTAUTH_SECRET) return false; const secret = await resolveSecret(env.NEXTAUTH_SECRET); if (!secret) throw new Error('Town token signing unavailable'); - let raw; + let raw: unknown; try { - raw = (await jwtVerify(token, new TextEncoder().encode(secret), { algorithms: ['HS256'] })) - .payload; - } catch (error) { - // jose checks the signature and nbf before exp. Recover only this precise - // expiry failure, with no clock tolerance that also permits future tokens. - if (!(error instanceof errors.JWTExpired) || error.claim !== 'exp') return false; - raw = error.payload; + // Authenticate the bytes before parsing claims. Expiry is intentionally + // allowed here; the strict legacy schema rejects all other restrictions. + const { payload } = await compactVerify(token, new TextEncoder().encode(secret), { + algorithms: ['HS256'], + }); + raw = JSON.parse(new TextDecoder().decode(payload)); + } catch { + return false; } const parsed = legacyTownPayload.safeParse(raw); if (!parsed.success) return false; diff --git a/services/gastown/test/integration/town-private-identity.test.ts b/services/gastown/test/integration/town-private-identity.test.ts index b59a14886a..fb9fb02950 100644 --- a/services/gastown/test/integration/town-private-identity.test.ts +++ b/services/gastown/test/integration/town-private-identity.test.ts @@ -1,8 +1,10 @@ import { env, runInDurableObject } from 'cloudflare:test'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import * as admission from '@kilocode/worker-utils/runtime-authorization'; import { getTownDOStub } from '../../src/dos/Town.do'; import { initializePrivateTownIdentity, + createRuntimeAuthorization, TOWN_IDENTITY_KEY, RUNTIME_AUTHORIZATION_KEY, } from '../../src/dos/town/runtime-authorization'; @@ -77,3 +79,77 @@ describe('private town identity on real Durable Object storage', () => { }); }); }); + +// Exercise production admission persistence with real transactional storage; +// only the external PostgreSQL/token admission is substituted. +describe('runtime sponsorship on real Durable Object storage', () => { + afterEach(() => vi.restoreAllMocks()); + + it.each([false, true])( + 'atomically persists sponsorship (invalid config: %s)', + async invalidConfig => { + await runInDurableObject(town(), async (instance, state) => { + const organizationId = '00000000-0000-4000-8000-000000000003'; + const original = { ...identity, ownerType: 'org' as const, organizationId }; + await initializePrivateTownIdentity(state.storage, original); + if (invalidConfig) await state.storage.put('town:config', { kilocode_token: 123 }); + const previousConfig = await state.storage.get('town:config'); + const authorization = admission.RuntimeAuthorizationSchema.parse({ + version: 1, + id: '00000000-0000-4000-8000-000000000001', + resourceKind: 'gastown', + resourceId: instance['townId'], + organizationId, + userId: 'oauth/new-owner', + authorizationUserId: 'oauth/new-owner', + issuedAt: '2026-09-09T00:00:00.000Z', + delegationExpiresAt: '2026-10-09T00:00:00.000Z', + state: 'active', + bindings: { userPepperDigest: 'a'.repeat(64), authorizationPepperDigest: 'a'.repeat(64) }, + source: { admissionSource: 'user' }, + }); + vi.spyOn(admission, 'createRuntimeAuthorization').mockResolvedValue({ + authorization, + token: 'runtime-token', + expiresAt: '2026-09-09T01:00:00.000Z', + }); + const token = await createRuntimeAuthorization( + { + storage: state.storage, + env: { + ...env, + NEXTAUTH_SECRET: 'synthetic-test-secret', + HYPERDRIVE: { connectionString: 'postgres://test' }, + } as Env, + townId: instance['townId'], + hasActiveWork: () => false, + updateTownConfig: update => instance.updateTownConfig(update), + }, + 'control-token', + 'oauth/new-owner', + organizationId + ); + if (invalidConfig) { + expect(token).toBeUndefined(); + expect(await state.storage.get(TOWN_IDENTITY_KEY)).toEqual(original); + expect(await state.storage.get(RUNTIME_AUTHORIZATION_KEY)).toBeUndefined(); + expect(await state.storage.get('town:config')).toEqual(previousConfig); + } else { + expect(token).toBe('runtime-token'); + expect(await instance.getTownIdentityState()).toEqual({ + type: 'modern', + identity: { ...original, ownerUserId: 'oauth/new-owner', runtimeMode: 'modern' }, + }); + expect(await state.storage.get(RUNTIME_AUTHORIZATION_KEY)).toEqual(authorization); + expect(await instance.getTownConfig()).toMatchObject({ + owner_type: 'org', + owner_id: organizationId, + organization_id: organizationId, + owner_user_id: 'oauth/new-owner', + created_by_user_id: original.createdByUserId, + }); + } + }); + } + ); +});