Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(grok): add grok-llm-proxy and split redeem routes
Jose Gabriel Ramirez Encinas9b4eb344a101
diff --git a/.github/workflows/build-publish.yml b/.github/workflows/build-publish.ymlindex 85b8d6409..aed1563aa 100644--- a/.github/workflows/build-publish.yml+++ b/.github/workflows/build-publish.yml@@ -84,6 +84,7 @@ jobs:webhook-gateway: ${{ steps.filter.outputs.webhook-gateway }}webhook-proxy: ${{ steps.filter.outputs.webhook-proxy }}codex-llm-proxy: ${{ steps.filter.outputs.codex-llm-proxy }}+ grok-llm-proxy: ${{ steps.filter.outputs.grok-llm-proxy }}steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4with:@@ -187,6 +188,9 @@ jobs:codex-llm-proxy:- 'codex-llm-proxy/**'- 'packages/llm-provider-attempt-contract/**'+ grok-llm-proxy:+ - 'grok-llm-proxy/**'+ - 'packages/grok-provider-attempt-contract/**'build-push:name: Build & push (${{ matrix.image }}-${{ matrix.arch }})@@ -242,6 +246,7 @@ jobs:- webhook-gateway- webhook-proxy- codex-llm-proxy+ - grok-llm-proxyinclude:- image: channel-readerpath: channel-reader@@ -348,6 +353,10 @@ jobs:path: codex-llm-proxyrooted: truechanged: ${{ needs.detect.outputs.codex-llm-proxy }}+ - image: grok-llm-proxy+ path: grok-llm-proxy+ rooted: true+ changed: ${{ needs.detect.outputs.grok-llm-proxy }}steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4if: ${{ matrix.changed == 'true' || needs.detect.outputs.force_all == 'true' }}@@ -521,6 +530,8 @@ jobs:changed: ${{ needs.detect.outputs.webhook-proxy }}- image: codex-llm-proxychanged: ${{ needs.detect.outputs.codex-llm-proxy }}+ - image: grok-llm-proxy+ changed: ${{ needs.detect.outputs.grok-llm-proxy }}steps:- name: Set up Docker Buildxif: ${{ matrix.changed == 'true' || needs.detect.outputs.force_all == 'true' }}diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 317697c8a..545efe064 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -73,6 +73,7 @@ jobs:- packages/grok-provider-attempt-contract- packages/codex-catalog-projection- codex-llm-proxy+ - grok-llm-proxysteps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4diff --git a/Makefile b/Makefileindex ab71b9772..aa427eeda 100644--- a/Makefile+++ b/Makefile@@ -40,6 +40,7 @@ SERVICES := \mcp-proxy \webhook-proxy \codex-llm-proxy \+ grok-llm-proxy \webhook-gateway \stdio-bridge \profile-ui \@@ -66,6 +67,7 @@ TEST_SERVICES := \mcp-proxy \webhook-proxy \codex-llm-proxy \+ grok-llm-proxy \webhook-gateway \stdio-bridge \profile-ui \@@ -134,6 +136,10 @@ test-codex-subscription-t0: ## Run the Codex subscription T0 aggregator (counts,test-llm-subscription-extract-t0: ## Run the wave-1 oauth-broker extract T0 aggregator@bash scripts/tests/test-llm-subscription-extract-t0.sh+.PHONY: test-grok-subscription-t0+test-grok-subscription-t0: ## Run the Grok subscription T0 aggregator (counts, no skips)+ @bash scripts/tests/test-grok-subscription-t0.sh+# ── Build Preflight ──────────────────────────────────────────────────.PHONY: build-preflightbuild-preflight: ## Run local build preflight across deployable packagesdiff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c9035a7d4..c376d2a63 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.557",+ "version": "0.1.558","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.557",+ "version": "0.1.558","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 40ee6816b..ec70db9a6 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.557",+ "version": "0.1.558","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/config.ts b/control-api/src/config.tsindex bcb8002c7..95debffa3 100644--- a/control-api/src/config.ts+++ b/control-api/src/config.ts@@ -325,9 +325,24 @@ function parseInternalServiceTokens(input: string): Record<string, string> {assertNotPlaceholder(`CONTROL_API_INTERNAL_SERVICE_TOKENS[${key}]`, value)result[key] = value}+ assertDistinctBrokerProxyTokens(result)return result}+function assertDistinctBrokerProxyTokens(tokens: Record<string, string>): void {+ const brokers = ['codex-llm-proxy', 'grok-llm-proxy']+ const seen = new Map<string, string>()+ for (const name of brokers) {+ const token = tokens[name]+ if (!token) continue+ const owner = seen.get(token)+ if (owner) {+ throw new Error(`internal service tokens for "${owner}" and "${name}" must be distinct`)+ }+ seen.set(token, name)+ }+}+function parseCsvList(input: string): string[] {return Array.from(new Set(@@ -653,7 +668,7 @@ export const config: Config = {),internalServiceTokens: parseInternalServiceTokens(process.env.CONTROL_API_INTERNAL_SERVICE_TOKENS ||- 'external-rest-api=dev-external-rest-api-token,rpc-proxy=dev-rpc-proxy-token,webhook-proxy=dev-webhook-proxy-token,workflow-approval-reader=dev-wa-reader-token,codex-llm-proxy=dev-codex-llm-proxy-token'+ 'external-rest-api=dev-external-rest-api-token,rpc-proxy=dev-rpc-proxy-token,webhook-proxy=dev-webhook-proxy-token,workflow-approval-reader=dev-wa-reader-token,codex-llm-proxy=dev-codex-llm-proxy-token,grok-llm-proxy=dev-grok-llm-proxy-token'),internalControlJwtWrcHmacSecret: requiredOrDevDefault('INTERNAL_CONTROL_JWT_WRC_HMAC_SECRET',diff --git a/control-api/src/routes/internal/llmProviderAttempts.ts b/control-api/src/routes/internal/llmProviderAttempts.tsindex b2301314f..6862e067d 100644--- a/control-api/src/routes/internal/llmProviderAttempts.ts+++ b/control-api/src/routes/internal/llmProviderAttempts.ts@@ -2,6 +2,14 @@ import { Router } from 'express'import { asyncHandler } from '../../http/asyncHandler.js'import { requireInternalService } from '../../middleware/internalServiceAuth.js'import { rootLogger } from '../../observability/logger.js'+import {+ GrokProviderAttemptFinalizeError,+ finalizeGrokProviderAttempt,+} from '../../services/grokProviderAttemptFinalization.js'+import {+ GrokProviderAttemptRedeemError,+ redeemGrokProviderAttempt,+} from '../../services/grokProviderAttemptRedemption.js'import {LlmProviderAttemptFinalizeError,finalizeLlmProviderAttempt,@@ -85,5 +93,55 @@ export function createInternalLlmProviderAttemptRoutes(): Router {}))+ router.use('/internal/llm/grok/provider-attempts', requireInternalService('grok-llm-proxy'))++ router.post(+ '/internal/llm/grok/provider-attempts/redeem',+ asyncHandler(async (req, res) => {+ const body = isPlainObject(req.body) ? req.body : {}+ try {+ const result = await redeemGrokProviderAttempt({+ executionTicket: typeof body.executionTicket === 'string' ? body.executionTicket : '',+ requestHash: typeof body.requestHash === 'string' ? body.requestHash : '',+ model: typeof body.model === 'string' ? body.model : undefined,+ hostRef: typeof body.hostRef === 'string' ? body.hostRef : undefined,+ operation:+ body.operation === 'completion_cancel' || body.operation === 'connection_test'+ ? body.operation+ : 'completion_stream',+ })+ res.status(200).json(result)+ } catch (err) {+ if (err instanceof GrokProviderAttemptRedeemError) {+ log.warn({ event: 'grok_attempt_redeem_denied', code: err.code }, err.message)+ res.status(REDEEM_STATUS[err.code] ?? 400).json({ error: err.code })+ return+ }+ throw err+ }+ })+ )++ router.post(+ '/internal/llm/grok/provider-attempts/finalize',+ asyncHandler(async (req, res) => {+ const body = isPlainObject(req.body) ? req.body : {}+ try {+ const result = await finalizeGrokProviderAttempt({+ attemptReceipt: typeof body.attemptReceipt === 'string' ? body.attemptReceipt : '',+ receipt: body.receipt,+ })+ res.status(200).json(result)+ } catch (err) {+ if (err instanceof GrokProviderAttemptFinalizeError) {+ log.warn({ event: 'grok_attempt_finalize_denied', code: err.code }, err.message)+ res.status(FINALIZE_STATUS[err.code] ?? 400).json({ error: err.code })+ return+ }+ throw err+ }+ })+ )+return router}diff --git a/control-api/src/services/grokProviderAttemptFinalization.ts b/control-api/src/services/grokProviderAttemptFinalization.tsnew file mode 100644index 000000000..fd2e7b179--- /dev/null+++ b/control-api/src/services/grokProviderAttemptFinalization.ts@@ -0,0 +1,199 @@+import { createHash } from 'node:crypto'+import {+ type GrokAttemptReceiptV1,+ parseGrokAttemptReceiptV1,+} from '@clerum/grok-provider-attempt-contract'+import { config } from '../config.js'+import { type DbClient, withTransaction } from '../db.js'+import { rootLogger } from '../observability/logger.js'+import { stableStringify } from '../utils/stableStringify.js'+import { releaseReservation } from './budgets/reservations.js'+import { opaqueAttemptReceipt } from './llmProviderAttemptRedemption.js'+import {+ type LlmProviderAttemptRow,+ loadLlmProviderAttempt,+ markLlmProviderAttemptFinalized,+} from './llmProviderAttemptStore.js'+import { ingestUsageEventsInTransaction } from './usageEvents.js'++const log = rootLogger.child({ module: 'grok-provider-attempt-finalization' })++export type GrokProviderAttemptFinalizeErrorCode =+ | 'disabled'+ | 'ticket_invalid'+ | 'request_hash_mismatch'+ | 'invalid_receipt'+ | 'conflict'++export class GrokProviderAttemptFinalizeError extends Error {+ constructor(+ readonly code: GrokProviderAttemptFinalizeErrorCode,+ message: string+ ) {+ super(message)+ this.name = 'GrokProviderAttemptFinalizeError'+ }+}++export type FinalizeGrokAttemptInput = {+ attemptReceipt: string+ receipt: unknown+}++export type FinalizeGrokAttemptSuccess = {+ providerAttemptId: string+ outcome: 'success' | 'canceled' | 'error' | 'unknown'+ duplicate: boolean+}++function hashGrokAttemptReceipt(receipt: GrokAttemptReceiptV1): string {+ return createHash('sha256').update(stableStringify(receipt)).digest('hex')+}++export async function finalizeGrokProviderAttempt(+ input: FinalizeGrokAttemptInput,+ runTransaction: typeof withTransaction = withTransaction+): Promise<FinalizeGrokAttemptSuccess> {+ if (!config.grokSubscriptionEnabled) {+ throw new GrokProviderAttemptFinalizeError('disabled', 'Grok subscription is disabled')+ }+ if (typeof input.attemptReceipt !== 'string' || !/^[a-f0-9]{64}$/.test(input.attemptReceipt)) {+ throw new GrokProviderAttemptFinalizeError('invalid_receipt', 'attemptReceipt is invalid')+ }+ const parsed = parseGrokAttemptReceiptV1(input.receipt)+ if (!parsed.ok) {+ throw new GrokProviderAttemptFinalizeError('invalid_receipt', parsed.message)+ }+ const receipt = parsed.value++ return runTransaction(async tx => {+ const attempt = await loadLlmProviderAttempt(tx, receipt.providerAttemptId)+ if (!attempt) {+ throw new GrokProviderAttemptFinalizeError('ticket_invalid', 'provider attempt was not found')+ }+ if (attempt.provider !== 'grok-subscription') {+ throw new GrokProviderAttemptFinalizeError(+ 'ticket_invalid',+ 'attempt provider is not grok-subscription'+ )+ }+ if (attempt.requestHash !== receipt.requestHash) {+ throw new GrokProviderAttemptFinalizeError(+ 'request_hash_mismatch',+ 'receipt requestHash does not match the attempt'+ )+ }++ const ticketRow = (+ await tx.query(+ `SELECT jti::text FROM llm_provider_attempt_tickets WHERE provider_attempt_id = $1`,+ [attempt.id]+ )+ ).rows[0] as { jti?: string } | undefined+ const jti = ticketRow?.jti ? String(ticketRow.jti) : ''+ const opaque = opaqueAttemptReceipt({+ jti,+ providerAttemptId: attempt.id,+ requestHash: attempt.requestHash,+ })+ if (opaque !== input.attemptReceipt) {+ throw new GrokProviderAttemptFinalizeError(+ 'ticket_invalid',+ 'attemptReceipt does not authorize this attempt'+ )+ }++ const receiptHash = hashGrokAttemptReceipt(receipt)+ const result = await markLlmProviderAttemptFinalized(tx, {+ providerAttemptId: attempt.id,+ receiptHash,+ outcome: receipt.outcome,+ usageInputTokens: receipt.usage?.inputTokens,+ usageOutputTokens: receipt.usage?.outputTokens,+ })+ if (result === 'missing') {+ throw new GrokProviderAttemptFinalizeError('ticket_invalid', 'provider attempt was not found')+ }+ if (result === 'conflict') {+ throw new GrokProviderAttemptFinalizeError(+ 'conflict',+ 'provider attempt already has a different terminal outcome'+ )+ }+ if (result === 'applied') {+ await ingestGrokFinalizeLedgerRow(tx, attempt, receipt)+ }+ if (attempt.budgetReservationId && attempt.budgetReservationId !== 'unbudgeted') {+ await releaseReservation(+ { reservationId: attempt.budgetReservationId, hostRef: attempt.hostRef },+ tx+ )+ }+ log.info(+ {+ event: 'grok_attempt_finalized',+ providerAttemptId: attempt.id,+ outcome: receipt.outcome,+ duplicate: result === 'duplicate',+ },+ 'finalized Grok provider attempt'+ )+ return {+ providerAttemptId: attempt.id,+ outcome: receipt.outcome,+ duplicate: result === 'duplicate',+ }+ })+}++async function ingestGrokFinalizeLedgerRow(+ tx: DbClient,+ attempt: LlmProviderAttemptRow,+ receipt: GrokAttemptReceiptV1+): Promise<void> {+ if (receipt.outcome !== 'success') return+ const inputTokens = receipt.usage?.inputTokens+ const outputTokens = receipt.usage?.outputTokens+ if (+ typeof inputTokens !== 'number' ||+ typeof outputTokens !== 'number' ||+ !Number.isInteger(inputTokens) ||+ !Number.isInteger(outputTokens) ||+ inputTokens < 0 ||+ outputTokens < 0+ ) {+ return+ }+ await ingestUsageEventsInTransaction(+ [+ {+ request_id: attempt.id,+ ts: new Date().toISOString(),+ run_id: null,+ host_ref: attempt.hostRef,+ context_ref: null,+ team_id: null,+ provider: attempt.provider,+ model: attempt.model,+ llm_secret_name: null,+ source_kind: 'channel',+ user_id: null,+ sender: null,+ channel_type: null,+ recipe_name: attempt.recipeName ?? null,+ cron_job_id: null,+ task_id: null,+ iteration: null,+ input_tokens: inputTokens,+ output_tokens: outputTokens,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ cache_tokens_reported: false,+ prompt_bridge_metadata: null,+ },+ ],+ tx,+ undefined,+ { origin: 'finalize' }+ )+}diff --git a/control-api/src/services/grokProviderAttemptRedemption.ts b/control-api/src/services/grokProviderAttemptRedemption.tsnew file mode 100644index 000000000..a1a5a3a67--- /dev/null+++ b/control-api/src/services/grokProviderAttemptRedemption.ts@@ -0,0 +1,275 @@+import {+ CATALOG_ORIGIN,+ COMPLETIONS_ORIGIN,+ TRANSPORT_PROTOCOL_VERSION,+} from '@clerum/grok-provider-attempt-contract'+import { config } from '../config.js'+import { type DbClient, pool, withTransaction } from '../db.js'+import { deriveOAuthEncryptionKey } from '../oauth/encryption.js'+import { rootLogger } from '../observability/logger.js'+import { verifyGrokExecutionTicket } from './grokProviderAttemptTicket.js'+import {+ getSafeGrokSubscriptionConnectionById,+ loadGrokSubscriptionSecrets,+} from './grokSubscriptionConnection.js'+import { GrokSubscriptionOAuthError, ensureFreshGrokAccessToken } from './grokSubscriptionOAuth.js'+import { opaqueAttemptReceipt } from './llmProviderAttemptRedemption.js'+import {+ loadLlmProviderAttempt,+ lockLlmProviderAttemptTicket,+ markLlmProviderAttemptTicketRedeemed,+ peekLlmProviderAttemptTicket,+} from './llmProviderAttemptStore.js'++const log = rootLogger.child({ module: 'grok-provider-attempt-redemption' })++export const GROK_COMPLETIONS_ORIGIN = COMPLETIONS_ORIGIN+export const GROK_CATALOG_ORIGIN = CATALOG_ORIGIN+export const GROK_TRANSPORT_PROTOCOL = TRANSPORT_PROTOCOL_VERSION+export const GROK_MAX_STREAM_DURATION_MS = 300_000++export type GrokProviderAttemptRedeemErrorCode =+ | 'disabled'+ | 'ticket_invalid'+ | 'ticket_replayed'+ | 'ticket_expired'+ | 'request_hash_mismatch'+ | 'connection_unavailable'+ | 'no_grant'+ | 'provider_unavailable'++export class GrokProviderAttemptRedeemError extends Error {+ constructor(+ readonly code: GrokProviderAttemptRedeemErrorCode,+ message: string+ ) {+ super(message)+ this.name = 'GrokProviderAttemptRedeemError'+ }+}++export type RedeemGrokAttemptSuccess = {+ accessToken: string+ transport: {+ protocolVersion: typeof GROK_TRANSPORT_PROTOCOL+ completionsOrigin: typeof GROK_COMPLETIONS_ORIGIN+ catalogOrigin: typeof GROK_CATALOG_ORIGIN+ operation: 'completion_stream' | 'completion_cancel' | 'connection_test'+ servedModel: string+ maxStreamDurationMs: number+ }+ expiryClass: 'short_lived' | 'upstream_managed'+ attemptReceipt: string+}++export type RedeemGrokAttemptInput = {+ executionTicket: string+ requestHash: string+ model?: string+ hostRef?: string+ operation?: 'completion_stream' | 'completion_cancel' | 'connection_test'+}++export type RedeemGrokAttemptDeps = {+ enabled: boolean+ db: DbClient+ withTransaction: typeof withTransaction+ loadSecrets: typeof loadGrokSubscriptionSecrets+ getConnectionById: typeof getSafeGrokSubscriptionConnectionById+ encryptionKey: Buffer+ ensureFreshAccessToken?: (connectionKey?: string) => Promise<void>+}++const defaultRedeemDeps = (): RedeemGrokAttemptDeps => ({+ enabled: config.grokSubscriptionEnabled,+ db: pool,+ withTransaction,+ loadSecrets: loadGrokSubscriptionSecrets,+ getConnectionById: getSafeGrokSubscriptionConnectionById,+ encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),+ ensureFreshAccessToken: connectionKey =>+ ensureFreshGrokAccessToken({+ db: { query: (text, values) => pool.query(text, values) },+ encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),+ fetchFn: fetch,+ clientId: config.grokOAuthClientId,+ enabled: config.grokSubscriptionEnabled,+ connectionKey: connectionKey ?? '',+ }),+})++export async function redeemGrokProviderAttempt(+ input: RedeemGrokAttemptInput,+ deps: RedeemGrokAttemptDeps = defaultRedeemDeps()+): Promise<RedeemGrokAttemptSuccess> {+ if (!deps.enabled) {+ throw new GrokProviderAttemptRedeemError('disabled', 'Grok subscription is disabled')+ }+ const claims = verifyGrokExecutionTicket(input.executionTicket)+ if (!claims) {+ throw new GrokProviderAttemptRedeemError('ticket_invalid', 'execution ticket is invalid')+ }+ if (claims.provider !== 'grok-subscription') {+ throw new GrokProviderAttemptRedeemError(+ 'ticket_invalid',+ 'ticket provider is not grok-subscription'+ )+ }+ if (claims.requestHash !== input.requestHash) {+ throw new GrokProviderAttemptRedeemError(+ 'request_hash_mismatch',+ 'requestHash does not match the ticket'+ )+ }+ if (input.model && input.model !== claims.model) {+ throw new GrokProviderAttemptRedeemError('ticket_invalid', 'model does not match the ticket')+ }+ if (input.hostRef && input.hostRef !== claims.hostRef) {+ throw new GrokProviderAttemptRedeemError('ticket_invalid', 'hostRef does not match the ticket')+ }++ const previewTicket = await peekLlmProviderAttemptTicket(deps.db, claims.jti)+ if (!previewTicket) {+ throw new GrokProviderAttemptRedeemError('ticket_invalid', 'execution ticket is not registered')+ }+ if (previewTicket.status !== 'issued') {+ throw new GrokProviderAttemptRedeemError('ticket_replayed', 'execution ticket already used')+ }+ const previewAttempt = await loadLlmProviderAttempt(deps.db, previewTicket.providerAttemptId)+ if (+ !previewAttempt ||+ previewAttempt.provider !== 'grok-subscription' ||+ previewAttempt.connectionId !== claims.connectionId+ ) {+ throw new GrokProviderAttemptRedeemError(+ 'ticket_invalid',+ 'ticket provider or connectionId does not match the attempt'+ )+ }++ if (deps.ensureFreshAccessToken) {+ try {+ const assigned = await deps.getConnectionById(deps.db, claims.connectionId)+ await deps.ensureFreshAccessToken(assigned?.connectionKey)+ } catch (err) {+ if (err instanceof GrokSubscriptionOAuthError) {+ throw new GrokProviderAttemptRedeemError(+ err.code === 'no_grant' || err.code === 'not_connected'+ ? 'no_grant'+ : err.code === 'provider_unavailable'+ ? 'provider_unavailable'+ : 'connection_unavailable',+ 'Grok access token could not be refreshed'+ )+ }+ throw err+ }+ }++ return deps.withTransaction(async tx => {+ const ticket = await lockLlmProviderAttemptTicket(tx, claims.jti)+ if (!ticket) {+ throw new GrokProviderAttemptRedeemError(+ 'ticket_invalid',+ 'execution ticket is not registered'+ )+ }+ if (ticket.status !== 'issued') {+ throw new GrokProviderAttemptRedeemError('ticket_replayed', 'execution ticket already used')+ }+ if (ticket.expiresAt.getTime() <= Date.now()) {+ throw new GrokProviderAttemptRedeemError('ticket_expired', 'execution ticket expired')+ }++ const attempt = await loadLlmProviderAttempt(tx, ticket.providerAttemptId)+ if (!attempt || attempt.status !== 'authorized') {+ throw new GrokProviderAttemptRedeemError(+ 'ticket_invalid',+ 'provider attempt is not redeemable'+ )+ }+ if (attempt.provider !== 'grok-subscription' || attempt.connectionId !== claims.connectionId) {+ throw new GrokProviderAttemptRedeemError(+ 'ticket_invalid',+ 'ticket provider or connectionId does not match the attempt'+ )+ }+ if (+ attempt.requestHash !== claims.requestHash ||+ attempt.model !== claims.model ||+ attempt.hostRef !== claims.hostRef ||+ attempt.invocationId !== claims.invocationId ||+ attempt.attemptGeneration !== claims.attemptGeneration ||+ attempt.policyHash !== claims.policyHash ||+ attempt.policyRevision !== claims.policyRevision ||+ attempt.budgetReservationId !== claims.budgetReservationId ||+ attempt.connectionRevision !== claims.connectionRevision+ ) {+ throw new GrokProviderAttemptRedeemError(+ 'no_grant',+ 'ticket bindings no longer match the attempt'+ )+ }++ if (!attempt.connectionId) {+ throw new GrokProviderAttemptRedeemError(+ 'connection_unavailable',+ 'Grok attempt is missing a connection binding'+ )+ }+ const connection = await getSafeGrokSubscriptionConnectionById(tx, attempt.connectionId)+ if (+ !connection ||+ connection.status !== 'connected' ||+ connection.revokedAt ||+ connection.credentialRevision !== attempt.connectionRevision ||+ connection.id !== attempt.connectionId+ ) {+ throw new GrokProviderAttemptRedeemError(+ 'connection_unavailable',+ 'Grok subscription connection is not usable'+ )+ }++ const redeemed = await markLlmProviderAttemptTicketRedeemed(tx, claims.jti)+ if (!redeemed) {+ throw new GrokProviderAttemptRedeemError('ticket_replayed', 'execution ticket already used')+ }++ const secrets = await deps.loadSecrets(tx, deps.encryptionKey, connection.connectionKey)+ if (!secrets?.accessToken) {+ throw new GrokProviderAttemptRedeemError(+ 'connection_unavailable',+ 'no usable access token is available'+ )+ }++ const expiryClass =+ secrets.accessTokenExpiresAt &&+ secrets.accessTokenExpiresAt.getTime() - Date.now() < 3_600_000+ ? 'short_lived'+ : 'upstream_managed'++ log.info(+ { event: 'grok_attempt_redeemed', providerAttemptId: attempt.id },+ 'redeemed Grok execution ticket'+ )+ return {+ accessToken: secrets.accessToken,+ transport: {+ protocolVersion: GROK_TRANSPORT_PROTOCOL,+ completionsOrigin: GROK_COMPLETIONS_ORIGIN,+ catalogOrigin: GROK_CATALOG_ORIGIN,+ operation: input.operation ?? 'completion_stream',+ servedModel: attempt.model,+ maxStreamDurationMs: GROK_MAX_STREAM_DURATION_MS,+ },+ expiryClass,+ attemptReceipt: opaqueAttemptReceipt({+ jti: claims.jti,+ providerAttemptId: attempt.id,+ requestHash: attempt.requestHash,+ }),+ }+ })+}diff --git a/control-api/src/services/grokProviderAttemptTicket.ts b/control-api/src/services/grokProviderAttemptTicket.tsnew file mode 100644index 000000000..9bcc1ac0c--- /dev/null+++ b/control-api/src/services/grokProviderAttemptTicket.ts@@ -0,0 +1,101 @@+import jwt from 'jsonwebtoken'+import { createPublicKey, randomUUID } from 'node:crypto'+import { config } from '../config.js'+import type { DbClient } from '../db.js'+import { registerLlmProviderAttemptTicket } from './llmProviderAttemptStore.js'++export const GROK_EXECUTION_TICKET_TYP = 'grok-execution-ticket' as const+export const GROK_EXECUTION_TICKET_AUDIENCE = 'grok-llm-proxy'+export const GROK_EXECUTION_TICKET_TTL_SECONDS = 60++export type GrokExecutionTicketClaims = {+ jti: string+ typ: typeof GROK_EXECUTION_TICKET_TYP+ sub: string+ hostRef: string+ recipeNamespace?: string+ recipeName?: string+ invocationId: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: number+ provider: 'grok-subscription'+ model: string+ requestHash: string+ policyRevision: number+ policyHash: string+ budgetReservationId: string+ connectionRevision: number+ connectionId: string+}++export type IssuedGrokExecutionTicket = {+ executionTicket: string+ claims: GrokExecutionTicketClaims+ expiresAt: Date+}++export async function issueRegisteredGrokExecutionTicket(+ db: DbClient,+ input: Omit<GrokExecutionTicketClaims, 'jti' | 'typ' | 'provider'>+): Promise<IssuedGrokExecutionTicket> {+ if (!input.connectionId) {+ throw new Error('Grok execution tickets require connectionId')+ }+ const jti = randomUUID()+ const expiresAt = new Date(Date.now() + GROK_EXECUTION_TICKET_TTL_SECONDS * 1000)+ await registerLlmProviderAttemptTicket(db, {+ jti,+ providerAttemptId: input.providerAttemptId,+ expiresAt,+ })+ const claims: GrokExecutionTicketClaims = {+ ...input,+ jti,+ typ: GROK_EXECUTION_TICKET_TYP,+ provider: 'grok-subscription',+ }+ const executionTicket = jwt.sign(claims, config.adminJwtPrivateKey, {+ algorithm: 'RS256',+ issuer: config.adminJwtIssuer,+ audience: GROK_EXECUTION_TICKET_AUDIENCE,+ expiresIn: GROK_EXECUTION_TICKET_TTL_SECONDS,+ })+ return { executionTicket, claims, expiresAt }+}++export function verifyGrokExecutionTicket(ticket: string): GrokExecutionTicketClaims | null {+ try {+ const publicKey = createPublicKey(config.adminJwtPrivateKey).export({+ type: 'spki',+ format: 'pem',+ })+ const verified = jwt.verify(ticket, publicKey, {+ algorithms: ['RS256'],+ issuer: config.adminJwtIssuer,+ audience: GROK_EXECUTION_TICKET_AUDIENCE,+ })+ if (typeof verified !== 'object' || verified === null) return null+ const claims = verified as jwt.JwtPayload+ if (+ typeof claims.jti !== 'string' ||+ claims.typ !== GROK_EXECUTION_TICKET_TYP ||+ claims.provider !== 'grok-subscription' ||+ typeof claims.sub !== 'string' ||+ typeof claims.hostRef !== 'string' ||+ typeof claims.invocationId !== 'string' ||+ typeof claims.providerAttemptId !== 'string' ||+ typeof claims.model !== 'string' ||+ typeof claims.requestHash !== 'string' ||+ typeof claims.policyHash !== 'string' ||+ typeof claims.budgetReservationId !== 'string' ||+ typeof claims.connectionId !== 'string' ||+ typeof claims.exp !== 'number'+ ) {+ return null+ }+ return claims as unknown as GrokExecutionTicketClaims+ } catch {+ return null+ }+}diff --git a/control-api/src/services/llmProviderAttemptStore.ts b/control-api/src/services/llmProviderAttemptStore.tsindex da7b06861..2b734b9f5 100644--- a/control-api/src/services/llmProviderAttemptStore.ts+++ b/control-api/src/services/llmProviderAttemptStore.ts@@ -1,6 +1,10 @@import type { DbClient } from '../db.js'export const LLM_PROVIDER_ATTEMPT_PROVIDER = 'codex-subscription' as const+export const GROK_PROVIDER_ATTEMPT_PROVIDER = 'grok-subscription' as const+export type LlmProviderAttemptProvider =+ | typeof LLM_PROVIDER_ATTEMPT_PROVIDER+ | typeof GROK_PROVIDER_ATTEMPT_PROVIDERexport type LlmProviderAttemptStatus = 'authorized' | 'redeemed' | 'finalized'export type LlmProviderAttemptTicketStatus = 'issued' | 'redeemed' | 'finalized'@@ -23,11 +27,12 @@ export type LlmProviderAttemptInsert = {connectionId?: string | nullcorrelationId?: string | nullpluginWorkloadSdkProviderAttemptId?: string | null+ provider?: LlmProviderAttemptProvider}-export type LlmProviderAttemptRow = LlmProviderAttemptInsert & {+export type LlmProviderAttemptRow = Omit<LlmProviderAttemptInsert, 'provider'> & {id: string- provider: typeof LLM_PROVIDER_ATTEMPT_PROVIDER+ provider: LlmProviderAttemptProviderstatus: LlmProviderAttemptStatusoutcome: LlmProviderAttemptOutcome | nullusageInputTokens?: number | null@@ -233,8 +238,8 @@ export async function insertLlmProviderAttempt(policy_revision, policy_hash, budget_reservation_id, connection_revision,connection_id, plugin_workload_sdk_provider_attempt_id, status, correlation_id) VALUES (- $1, $2, $3, $4, $5, $6, $7, 'codex-subscription', $8, $9, $10, $11, $12, $13,- $14, $15, 'authorized', $16+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,+ $15, $16, 'authorized', $17)RETURNING id, caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,attempt_generation, provider_attempt_index, provider, model, request_hash,@@ -249,6 +254,7 @@ export async function insertLlmProviderAttempt(input.invocationId,input.attemptGeneration,input.providerAttemptIndex,+ input.provider ?? LLM_PROVIDER_ATTEMPT_PROVIDER,input.model,input.requestHash,input.policyRevision,@@ -274,7 +280,10 @@ function mapLlmProviderAttemptRow(row: Record<string, unknown>): LlmProviderAtteinvocationId: String(row.invocation_id),attemptGeneration: Number(row.attempt_generation),providerAttemptIndex: Number(row.provider_attempt_index),- provider: LLM_PROVIDER_ATTEMPT_PROVIDER,+ provider:+ row.provider === GROK_PROVIDER_ATTEMPT_PROVIDER+ ? GROK_PROVIDER_ATTEMPT_PROVIDER+ : LLM_PROVIDER_ATTEMPT_PROVIDER,model: String(row.model),requestHash: String(row.request_hash),policyRevision: Number(row.policy_revision),@@ -349,6 +358,30 @@ export async function loadLlmProviderAttemptBySdkAttemptId(return row ? mapLlmProviderAttemptRow(row) : null}+function mapTicketRow(row: Record<string, unknown>): LlmProviderAttemptTicketRow {+ return {+ jti: String(row.jti),+ providerAttemptId: String(row.provider_attempt_id),+ status: row.status as LlmProviderAttemptTicketStatus,+ expiresAt: row.expires_at instanceof Date ? row.expires_at : new Date(String(row.expires_at)),+ receiptHash: (row.receipt_hash as string | null) ?? null,+ }+}++export async function peekLlmProviderAttemptTicket(+ db: DbClient,+ jti: string+): Promise<LlmProviderAttemptTicketRow | null> {+ const result = await db.query(+ `SELECT jti::text, provider_attempt_id::text, status, expires_at, receipt_hash+ FROM llm_provider_attempt_tickets+ WHERE jti = $1`,+ [jti]+ )+ const row = result.rows[0] as Record<string, unknown> | undefined+ return row ? mapTicketRow(row) : null+}+export async function lockLlmProviderAttemptTicket(db: DbClient,jti: string@@ -361,14 +394,7 @@ export async function lockLlmProviderAttemptTicket([jti])const row = result.rows[0] as Record<string, unknown> | undefined- if (!row) return null- return {- jti: String(row.jti),- providerAttemptId: String(row.provider_attempt_id),- status: row.status as LlmProviderAttemptTicketStatus,- expiresAt: row.expires_at instanceof Date ? row.expires_at : new Date(String(row.expires_at)),- receiptHash: (row.receipt_hash as string | null) ?? null,- }+ return row ? mapTicketRow(row) : null}export async function markLlmProviderAttemptTicketRedeemed(diff --git a/control-api/test/services.grokProviderAttemptRedemption.test.ts b/control-api/test/services.grokProviderAttemptRedemption.test.tsnew file mode 100644index 000000000..6d6ffe51c--- /dev/null+++ b/control-api/test/services.grokProviderAttemptRedemption.test.ts@@ -0,0 +1,89 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { config } from '../src/config.js'+import {+ GrokProviderAttemptRedeemError,+ redeemGrokProviderAttempt,+} from '../src/services/grokProviderAttemptRedemption.js'+import * as ticket from '../src/services/grokProviderAttemptTicket.js'+import * as connection from '../src/services/grokSubscriptionConnection.js'+import * as store from '../src/services/llmProviderAttemptStore.js'++vi.mock('../src/db.js', () => ({+ pool: { query: vi.fn() },+ withTransaction: async (work: (tx: { query: typeof vi.fn }) => unknown) =>+ work({ query: vi.fn() }),+}))++const CONNECTION_ID = '11111111-1111-4111-8111-111111111111'+const CLAIMS = {+ jti: '22222222-2222-4222-8222-222222222222',+ typ: 'grok-execution-ticket' as const,+ sub: 'host/research-host',+ hostRef: 'research-host',+ invocationId: 'invocation-1',+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',+ providerAttemptIndex: 1,+ provider: 'grok-subscription' as const,+ model: 'grok-4.6',+ requestHash: 'a'.repeat(64),+ policyRevision: 4,+ policyHash: 'b'.repeat(64),+ budgetReservationId: 'unbudgeted',+ connectionRevision: 3,+ connectionId: CONNECTION_ID,+}++describe('redeemGrokProviderAttempt', () => {+ beforeEach(() => {+ config.grokSubscriptionEnabled = true+ vi.spyOn(ticket, 'verifyGrokExecutionTicket').mockReturnValue(CLAIMS)+ })++ it('rejects a replayed ticket before rotating the refresh token', async () => {+ const ensureFresh = vi.fn()+ vi.spyOn(store, 'peekLlmProviderAttemptTicket').mockResolvedValue({+ jti: CLAIMS.jti,+ providerAttemptId: CLAIMS.providerAttemptId,+ status: 'redeemed',+ expiresAt: new Date(Date.now() + 30_000),+ receiptHash: null,+ })+ await expect(+ redeemGrokProviderAttempt(+ { executionTicket: 'ticket', requestHash: CLAIMS.requestHash },+ {+ enabled: true,+ db: { query: vi.fn() },+ withTransaction: async work => work({ query: vi.fn() }),+ loadSecrets: vi.fn(),+ getConnectionById: connection.getSafeGrokSubscriptionConnectionById,+ encryptionKey: Buffer.alloc(32),+ ensureFreshAccessToken: ensureFresh,+ }+ )+ ).rejects.toMatchObject({+ code: 'ticket_replayed',+ } satisfies Partial<GrokProviderAttemptRedeemError>)+ expect(ensureFresh).not.toHaveBeenCalled()+ })++ it('rejects a Codex-shaped ticket before loading Grok secrets', async () => {+ vi.spyOn(ticket, 'verifyGrokExecutionTicket').mockReturnValue(null)+ const loadSecrets = vi.fn()+ await expect(+ redeemGrokProviderAttempt(+ { executionTicket: 'codex-ticket', requestHash: CLAIMS.requestHash },+ {+ enabled: true,+ db: { query: vi.fn() },+ withTransaction: async work => work({ query: vi.fn() }),+ loadSecrets,+ getConnectionById: connection.getSafeGrokSubscriptionConnectionById,+ encryptionKey: Buffer.alloc(32),+ }+ )+ ).rejects.toMatchObject({ code: 'ticket_invalid' })+ expect(loadSecrets).not.toHaveBeenCalled()+ })+})diff --git a/deploy/base/control-plane/configmaps.yaml b/deploy/base/control-plane/configmaps.yamlindex 5b9b634d3..1cebd5367 100644--- a/deploy/base/control-plane/configmaps.yaml+++ b/deploy/base/control-plane/configmaps.yaml@@ -24,8 +24,10 @@ data:CONTROL_API_ADMIN_JWT_AUDIENCE: control-uiCONTROL_API_ADMIN_JWT_TTL_SECONDS: '3600'CONTROL_API_CODEX_SUBSCRIPTION_ENABLED: 'false'+ CONTROL_API_GROK_SUBSCRIPTION_ENABLED: 'false'# ClusterIP admin port only. NetworkPolicy admits Control API, not siblings.CODEX_LLM_PROXY_ADMIN_URL: http://codex-llm-proxy.control-plane.svc.cluster.local:8081+ GROK_LLM_PROXY_ADMIN_URL: http://grok-llm-proxy.control-plane.svc.cluster.local:8081CONTROL_API_ADMIN_BOOTSTRAP_USERNAME: adminCONTROL_API_ADMIN_BOOTSTRAP_EMAIL: ''CONTROL_API_ADMIN_AUTH_MAX_FAILURES: '5'@@ -302,6 +304,28 @@ data:proxy_set_header X-Forwarded-Proto $scheme;}+ location = /api/v1/internal/llm/grok/provider-attempts/redeem {+ limit_except POST {+ deny all;+ }+ proxy_pass http://control_api_upstream;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }++ location = /api/v1/internal/llm/grok/provider-attempts/finalize {+ limit_except POST {+ deny all;+ }+ proxy_pass http://control_api_upstream;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }+location / {return 403;}diff --git a/deploy/base/control-plane/grok-llm-proxy.yaml b/deploy/base/control-plane/grok-llm-proxy.yamlnew file mode 100644index 000000000..0ef0e570c--- /dev/null+++ b/deploy/base/control-plane/grok-llm-proxy.yaml@@ -0,0 +1,144 @@+apiVersion: v1+kind: ServiceAccount+metadata:+ name: grok-llm-proxy+ namespace: control-plane+ labels:+ app: grok-llm-proxy+automountServiceAccountToken: false+---+apiVersion: v1+kind: ConfigMap+metadata:+ name: grok-llm-proxy-config+ namespace: control-plane+ labels:+ app: grok-llm-proxy+data:+ GROK_LLM_PROXY_RUNTIME_PORT: "8080"+ GROK_LLM_PROXY_ADMIN_PORT: "8081"+ GROK_LLM_PROXY_PROBE_PORT: "9090"+ GROK_LLM_PROXY_MAX_BODY_BYTES: "1048576"+ GROK_LLM_PROXY_MAX_STREAM_DURATION_MS: "300000"+ GROK_LLM_PROXY_MAX_DEADLINE_MS: "300000"+ GROK_LLM_PROXY_JWT_ISSUER: control-api+ GROK_LLM_PROXY_EXECUTION_ENABLED: "false"+ GROK_LLM_PROXY_CONTROL_API_URL: http://control-api-rpc-gateway.control-plane.svc.cluster.local:8090/api/v1+ GROK_LLM_PROXY_CONTROL_API_SERVICE: grok-llm-proxy+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: grok-llm-proxy+ namespace: control-plane+ labels:+ app: grok-llm-proxy+spec:+ replicas: 1+ revisionHistoryLimit: 3+ selector:+ matchLabels:+ app: grok-llm-proxy+ strategy:+ type: RollingUpdate+ rollingUpdate:+ maxSurge: 1+ maxUnavailable: 0+ template:+ metadata:+ labels:+ app: grok-llm-proxy+ spec:+ serviceAccountName: grok-llm-proxy+ automountServiceAccountToken: false+ terminationGracePeriodSeconds: 30+ securityContext:+ runAsNonRoot: true+ seccompProfile:+ type: RuntimeDefault+ containers:+ - name: grok-llm-proxy+ image: clerum/grok-llm-proxy:0.1.0+ imagePullPolicy: IfNotPresent+ envFrom:+ - configMapRef:+ name: grok-llm-proxy-config+ env:+ - name: GROK_LLM_PROXY_JWT_PUBLIC_KEY+ valueFrom:+ configMapKeyRef:+ name: control-api-public-key+ key: CONTROL_API_PUBLIC_KEY_PEM+ - name: GROK_LLM_PROXY_CONTROL_API_TOKEN+ valueFrom:+ secretKeyRef:+ name: grok-llm-proxy-secrets+ key: GROK_LLM_PROXY_CONTROL_API_TOKEN+ ports:+ - name: runtime+ containerPort: 8080+ protocol: TCP+ - name: admin+ containerPort: 8081+ protocol: TCP+ - name: metrics+ containerPort: 9090+ protocol: TCP+ readinessProbe:+ httpGet: { path: /readyz, port: metrics }+ initialDelaySeconds: 4+ periodSeconds: 8+ timeoutSeconds: 2+ livenessProbe:+ httpGet: { path: /healthz, port: metrics }+ initialDelaySeconds: 8+ periodSeconds: 12+ timeoutSeconds: 2+ resources:+ requests:+ cpu: 50m+ memory: 64Mi+ limits:+ cpu: 250m+ memory: 256Mi+ securityContext:+ allowPrivilegeEscalation: false+ readOnlyRootFilesystem: true+ runAsNonRoot: true+ runAsUser: 1001+ runAsGroup: 1001+ seccompProfile:+ type: RuntimeDefault+ capabilities:+ drop: [ALL]+ volumeMounts:+ - name: tmp+ mountPath: /tmp+ volumes:+ - name: tmp+ emptyDir: {}+---+apiVersion: v1+kind: Service+metadata:+ name: grok-llm-proxy+ namespace: control-plane+ labels:+ app: grok-llm-proxy+spec:+ type: ClusterIP+ selector:+ app: grok-llm-proxy+ ports:+ - name: runtime+ port: 8080+ protocol: TCP+ targetPort: runtime+ - name: admin+ port: 8081+ protocol: TCP+ targetPort: admin+ - name: metrics+ port: 9090+ protocol: TCP+ targetPort: metricsdiff --git a/deploy/base/control-plane/kustomization.yaml b/deploy/base/control-plane/kustomization.yamlindex 5b1cd8308..15c707b6e 100644--- a/deploy/base/control-plane/kustomization.yaml+++ b/deploy/base/control-plane/kustomization.yaml@@ -13,6 +13,7 @@ resources:- trace-postgres-runtime-secrets.yaml- configmaps.yaml- codex-llm-proxy.yaml+ - grok-llm-proxy.yaml# Empty-by-design Secrets. Populated out-of-band by# `deploy/scripts/apply-inter-service-tokens.sh` (kubectl patch) BEFORE# `kubectl apply -k` runs. Declared in base so every overlay gets thediff --git a/deploy/base/control-plane/networkpolicies.yaml b/deploy/base/control-plane/networkpolicies.yamlindex a0c3bfb47..b51a1dc6c 100644--- a/deploy/base/control-plane/networkpolicies.yaml+++ b/deploy/base/control-plane/networkpolicies.yaml@@ -425,6 +425,9 @@ spec:- podSelector:matchLabels:app: codex-llm-proxy+ - podSelector:+ matchLabels:+ app: grok-llm-proxyports:- port: 8090protocol: TCP@@ -650,6 +653,28 @@ spec:- port: 8081protocol: TCP---+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: control-api-to-grok-llm-proxy+ namespace: control-plane+ labels:+ clerum.io/policy-type: service+spec:+ podSelector:+ matchLabels:+ app: control-api+ policyTypes:+ - Egress+ egress:+ - to:+ - podSelector:+ matchLabels:+ app: grok-llm-proxy+ ports:+ - port: 8081+ protocol: TCP+---# Ingress side: allow control-api to reach WRCapiVersion: networking.k8s.io/v1kind: NetworkPolicy@@ -894,3 +919,83 @@ spec:# Filled at deploy time by deploy/base/kustomization.yaml replacements# from PublicEgressExceptionSet. Keep empty here.except: []+---+# Grok LLM proxy: runtime from eligible mcp-host pods, admin from Control API,+# metrics from monitoring. No sibling or namespace-wide ingress.+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: grok-llm-proxy-ingress+ namespace: control-plane+ labels:+ clerum.io/policy-type: service+spec:+ podSelector:+ matchLabels:+ app: grok-llm-proxy+ policyTypes:+ - Ingress+ ingress:+ - from:+ - namespaceSelector:+ matchLabels:+ kubernetes.io/metadata.name: mcp-host+ podSelector:+ matchLabels:+ clerum.io/managed-by: host-context-controller+ - namespaceSelector:+ matchLabels:+ kubernetes.io/metadata.name: sandbox-recipes+ podSelector:+ matchLabels:+ clerum.io/component: workflow-mcp-host+ ports:+ - port: 8080+ protocol: TCP+ - from:+ - podSelector:+ matchLabels:+ app: control-api+ ports:+ - port: 8081+ protocol: TCP+ - from:+ - namespaceSelector:+ matchLabels:+ kubernetes.io/metadata.name: monitoring+ ports:+ - port: 9090+ protocol: TCP+---+# Grok LLM proxy egress: DNS is inherited from allow-dns-egress-control-plane.+# This policy adds only the RPC gateway redeem/finalize hop and public HTTPS+# with the canonical private/special-use exclusions. Direct Control API,+# Postgres, Kubernetes API, metadata, HCC/WRC, and sibling hops stay denied.+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: grok-llm-proxy-egress+ namespace: control-plane+ labels:+ clerum.io/policy-type: service+spec:+ podSelector:+ matchLabels:+ app: grok-llm-proxy+ policyTypes:+ - Egress+ egress:+ - ports:+ - port: 8090+ protocol: TCP+ to:+ - podSelector:+ matchLabels:+ app: control-api-rpc-gateway+ - ports:+ - port: 443+ protocol: TCP+ to:+ - ipBlock:+ cidr: 0.0.0.0/0+ except: []diff --git a/deploy/base/control-plane/secrets-canary.yaml b/deploy/base/control-plane/secrets-canary.yamlindex 440b598bd..44b41ef7e 100644--- a/deploy/base/control-plane/secrets-canary.yaml+++ b/deploy/base/control-plane/secrets-canary.yaml@@ -44,6 +44,18 @@ stringData: {}---apiVersion: v1kind: Secret+metadata:+ name: grok-llm-proxy-secrets+ namespace: control-plane+ labels:+ app: grok-llm-proxy+type: Opaque+# Populated keys (via kubectl patch, NOT kubectl apply):+# GROK_LLM_PROXY_CONTROL_API_TOKEN — dedicated redeem/finalize token+stringData: {}+---+apiVersion: v1+kind: Secretmetadata:name: internal-control-jwt-secretsnamespace: control-planediff --git a/deploy/base/kustomization.yaml b/deploy/base/kustomization.yamlindex c1f6e4432..cee1360ed 100644--- a/deploy/base/kustomization.yaml+++ b/deploy/base/kustomization.yaml@@ -83,3 +83,10 @@ replacements:name: codex-llm-proxy-egressfieldPaths:- spec.egress.*.to.*.ipBlock.except+ - select:+ group: networking.k8s.io+ version: v1+ kind: NetworkPolicy+ name: grok-llm-proxy-egress+ fieldPaths:+ - spec.egress.*.to.*.ipBlock.exceptdiff --git a/deploy/components/ghcr-images/kustomization.yaml b/deploy/components/ghcr-images/kustomization.yamlindex d3eab521b..cc99f72f8 100644--- a/deploy/components/ghcr-images/kustomization.yaml+++ b/deploy/components/ghcr-images/kustomization.yaml@@ -101,3 +101,6 @@ images:- name: clerum/codex-llm-proxynewName: ghcr.io/evenfire-ai/codex-llm-proxynewTag: v0.8.0+ - name: clerum/grok-llm-proxy+ newName: ghcr.io/evenfire-ai/grok-llm-proxy+ newTag: v0.8.0diff --git a/deploy/images.json b/deploy/images.jsonindex 4cf52cbf3..fefd7aca7 100644--- a/deploy/images.json+++ b/deploy/images.json@@ -3,14 +3,18 @@{"name": "channel-reader","path": "channel-reader",- "source_paths": ["channel-reader/**"],+ "source_paths": [+ "channel-reader/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "workflow-approval-request-reader","path": "workflow-approval-request-reader",- "source_paths": ["workflow-approval-request-reader/**"],+ "source_paths": [+ "workflow-approval-request-reader/**"+ ],"published": true,"deployed_to_minikube": true},@@ -24,7 +28,8 @@"packages/workflow-recipe-capability-policy/**","packages/image-policy/**","packages/display-field/**",- "packages/llm-provider-attempt-contract/**"+ "packages/llm-provider-attempt-contract/**",+ "packages/grok-provider-attempt-contract/**"],"published": true,"deployed_to_minikube": true@@ -46,7 +51,9 @@{"name": "external-rest-api","path": "external-rest-api",- "source_paths": ["external-rest-api/**"],+ "source_paths": [+ "external-rest-api/**"+ ],"published": true,"deployed_to_minikube": true},@@ -71,7 +78,8 @@"source_paths": ["mcp-host/**","packages/llm-provider-attempt-contract/**",- "packages/codex-catalog-projection/**"+ "packages/codex-catalog-projection/**",+ "packages/grok-provider-attempt-contract/**"],"published": true,"deployed_to_minikube": true@@ -84,7 +92,8 @@"source_paths": ["mcp-host/**","packages/llm-provider-attempt-contract/**",- "packages/codex-catalog-projection/**"+ "packages/codex-catalog-projection/**",+ "packages/grok-provider-attempt-contract/**"],"published": true,"deployed_to_minikube": true@@ -97,7 +106,8 @@"source_paths": ["mcp-host/**","packages/llm-provider-attempt-contract/**",- "packages/codex-catalog-projection/**"+ "packages/codex-catalog-projection/**",+ "packages/grok-provider-attempt-contract/**"],"published": true,"deployed_to_minikube": true@@ -110,7 +120,8 @@"source_paths": ["mcp-host/**","packages/llm-provider-attempt-contract/**",- "packages/codex-catalog-projection/**"+ "packages/codex-catalog-projection/**",+ "packages/grok-provider-attempt-contract/**"],"published": true,"deployed_to_minikube": false@@ -118,21 +129,27 @@{"name": "mcp-proxy","path": "mcp-proxy",- "source_paths": ["mcp-proxy/**"],+ "source_paths": [+ "mcp-proxy/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "gfs-controller","path": "gfs-controller",- "source_paths": ["gfs-controller/**"],+ "source_paths": [+ "gfs-controller/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "nginx-egress-proxy","path": "nginx-egress-proxy",- "source_paths": ["nginx-egress-proxy/**"],+ "source_paths": [+ "nginx-egress-proxy/**"+ ],"published": true,"deployed_to_minikube": true},@@ -151,7 +168,9 @@{"name": "rpc-proxy","path": "rpc-proxy",- "source_paths": ["rpc-proxy/**"],+ "source_paths": [+ "rpc-proxy/**"+ ],"published": true,"deployed_to_minikube": true},@@ -236,21 +255,27 @@{"name": "stdio-bridge","path": "stdio-bridge",- "source_paths": ["stdio-bridge/**"],+ "source_paths": [+ "stdio-bridge/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "workspace-files-controller","path": "workspace-files-controller",- "source_paths": ["workspace-files-controller/**"],+ "source_paths": [+ "workspace-files-controller/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "airtable-mcp-server","path": "mcp-servers/airtable",- "source_paths": ["mcp-servers/airtable/**"],+ "source_paths": [+ "mcp-servers/airtable/**"+ ],"published": true,"deployed_to_minikube": false},@@ -258,7 +283,9 @@"name": "playwright-server","path": "mcp-servers/playwright","local_name": "playwright-mcp-server",- "source_paths": ["mcp-servers/playwright/**"],+ "source_paths": [+ "mcp-servers/playwright/**"+ ],"published": true,"deployed_to_minikube": false},@@ -266,35 +293,45 @@"name": "web-search-mcp","path": "mcp-servers/web-search","local_tag": "v1",- "source_paths": ["mcp-servers/web-search/**"],+ "source_paths": [+ "mcp-servers/web-search/**"+ ],"published": true,"deployed_to_minikube": false},{"name": "mock-mcp-server","path": "tests/e2e/fixtures/mock-mcp-server",- "source_paths": ["tests/e2e/fixtures/mock-mcp-server/**"],+ "source_paths": [+ "tests/e2e/fixtures/mock-mcp-server/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "mock-stdio-mcp-server","path": "tests/e2e/fixtures/mock-stdio-mcp-server",- "source_paths": ["tests/e2e/fixtures/mock-stdio-mcp-server/**"],+ "source_paths": [+ "tests/e2e/fixtures/mock-stdio-mcp-server/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "webhook-gateway","path": "webhook-gateway",- "source_paths": ["webhook-gateway/**"],+ "source_paths": [+ "webhook-gateway/**"+ ],"published": true,"deployed_to_minikube": true},{"name": "webhook-proxy","path": "webhook-proxy",- "source_paths": ["webhook-proxy/**"],+ "source_paths": [+ "webhook-proxy/**"+ ],"published": true,"deployed_to_minikube": true},@@ -302,7 +339,21 @@"name": "codex-llm-proxy","path": "codex-llm-proxy","rooted": true,- "source_paths": ["codex-llm-proxy/**", "packages/llm-provider-attempt-contract/**"],+ "source_paths": [+ "codex-llm-proxy/**",+ "packages/llm-provider-attempt-contract/**"+ ],+ "published": true,+ "deployed_to_minikube": true+ },+ {+ "name": "grok-llm-proxy",+ "path": "grok-llm-proxy",+ "rooted": true,+ "source_paths": [+ "grok-llm-proxy/**",+ "packages/grok-provider-attempt-contract/**"+ ],"published": true,"deployed_to_minikube": true},diff --git a/deploy/overlays/minikube/configmaps/grok-llm-proxy-config.yaml b/deploy/overlays/minikube/configmaps/grok-llm-proxy-config.yamlnew file mode 100644index 000000000..2da7d826d--- /dev/null+++ b/deploy/overlays/minikube/configmaps/grok-llm-proxy-config.yaml@@ -0,0 +1,9 @@+apiVersion: v1+kind: ConfigMap+metadata:+ name: grok-llm-proxy-config+ namespace: control-plane+ labels:+ app: grok-llm-proxy+data:+ GROK_LLM_PROXY_EXECUTION_ENABLED: 'false'diff --git a/deploy/overlays/minikube/kustomization.yaml b/deploy/overlays/minikube/kustomization.yamlindex 693af4dde..f5f20b1d3 100644--- a/deploy/overlays/minikube/kustomization.yaml+++ b/deploy/overlays/minikube/kustomization.yaml@@ -67,6 +67,8 @@ images:newTag: test- name: clerum/codex-llm-proxynewTag: test+ - name: clerum/grok-llm-proxy+ newTag: test- name: clerum/webhook-gatewaynewTag: test- name: clerum/stdio-bridge@@ -110,4 +112,5 @@ patches:# ConfigMap overrides: replace base values with minikube-specific config- path: configmaps/control-api-config.yaml- path: configmaps/codex-llm-proxy-config.yaml+ - path: configmaps/grok-llm-proxy-config.yaml- path: configmaps/channel-reader-config.yamldiff --git a/deploy/scripts/apply-inter-service-tokens.sh b/deploy/scripts/apply-inter-service-tokens.shindex 79253e248..0df10f923 100755--- a/deploy/scripts/apply-inter-service-tokens.sh+++ b/deploy/scripts/apply-inter-service-tokens.sh@@ -185,6 +185,8 @@ TOKEN_WA_READER="$(resolve_token CONTROL_API_INTERNAL_TOKEN_WA_READER \channels workflow-approval-request-reader-credentials control-api-token)"TOKEN_CODEX_LLM_PROXY="$(resolve_token CONTROL_API_INTERNAL_TOKEN_CODEX_LLM_PROXY \control-plane codex-llm-proxy-secrets CODEX_LLM_PROXY_CONTROL_API_TOKEN)"+TOKEN_GROK_LLM_PROXY="$(resolve_token CONTROL_API_INTERNAL_TOKEN_GROK_LLM_PROXY \+ control-plane grok-llm-proxy-secrets GROK_LLM_PROXY_CONTROL_API_TOKEN)"READER_HANDOFF_TOKEN_VALUE="$(resolve_token CHANNEL_READER_HANDOFF_TOKEN \channels workflow-approval-request-reader-credentials channel-reader-handoff-token)"INTERNAL_CONTROL_WRC_HMAC="$(resolve_token INTERNAL_CONTROL_JWT_WRC_HMAC_SECRET \@@ -199,6 +201,7 @@ for pair in \"WEBHOOK_PROXY:$TOKEN_WEBHOOK_PROXY" \"WA_READER:$TOKEN_WA_READER" \"CODEX_LLM_PROXY:$TOKEN_CODEX_LLM_PROXY" \+ "GROK_LLM_PROXY:$TOKEN_GROK_LLM_PROXY" \"CHANNEL_READER_HANDOFF:$READER_HANDOFF_TOKEN_VALUE" \"INTERNAL_CONTROL_WRC_HMAC:$INTERNAL_CONTROL_WRC_HMAC" \"INTERNAL_CONTROL_HCC_HMAC:$INTERNAL_CONTROL_HCC_HMAC" \@@ -208,8 +211,11 @@ for pair in \[ -n "$val" ] || die "token $name resolved to empty — refusing to patch"done-SERVICE_TOKENS_MAP="external-rest-api=${TOKEN_EXT_REST},rpc-proxy=${TOKEN_RPC},webhook-proxy=${TOKEN_WEBHOOK_PROXY},workflow-approval-reader=${TOKEN_WA_READER},codex-llm-proxy=${TOKEN_CODEX_LLM_PROXY}"-INTERNAL_TOKENS_LIST="${TOKEN_EXT_REST},${TOKEN_RPC},${TOKEN_WEBHOOK_PROXY},${TOKEN_WA_READER},${TOKEN_CODEX_LLM_PROXY}"+if [ "$TOKEN_CODEX_LLM_PROXY" = "$TOKEN_GROK_LLM_PROXY" ]; then+ die "codex-llm-proxy and grok-llm-proxy tokens must be distinct"+fi+SERVICE_TOKENS_MAP="external-rest-api=${TOKEN_EXT_REST},rpc-proxy=${TOKEN_RPC},webhook-proxy=${TOKEN_WEBHOOK_PROXY},workflow-approval-reader=${TOKEN_WA_READER},codex-llm-proxy=${TOKEN_CODEX_LLM_PROXY},grok-llm-proxy=${TOKEN_GROK_LLM_PROXY}"+INTERNAL_TOKENS_LIST="${TOKEN_EXT_REST},${TOKEN_RPC},${TOKEN_WEBHOOK_PROXY},${TOKEN_WA_READER},${TOKEN_CODEX_LLM_PROXY},${TOKEN_GROK_LLM_PROXY}"# --- 1. control-api-internal-tokens (control-plane) ---log "Patching Secret control-api-internal-tokens (control-plane)"@@ -304,6 +310,13 @@ CODEX_LLM_PROXY_PATCH="$(jq -cn --arg t "$TOKEN_CODEX_LLM_PROXY" \'{stringData: {CODEX_LLM_PROXY_CONTROL_API_TOKEN: $t}}')"kctl -n control-plane patch secret codex-llm-proxy-secrets --type=merge -p "$CODEX_LLM_PROXY_PATCH"+# --- 4e. grok-llm-proxy-secrets (control-plane) ---+log "Patching Secret grok-llm-proxy-secrets (control-plane)"+ensure_secret control-plane grok-llm-proxy-secrets+GROK_LLM_PROXY_PATCH="$(jq -cn --arg t "$TOKEN_GROK_LLM_PROXY" \+ '{stringData: {GROK_LLM_PROXY_CONTROL_API_TOKEN: $t}}')"+kctl -n control-plane patch secret grok-llm-proxy-secrets --type=merge -p "$GROK_LLM_PROXY_PATCH"+# --- 4c. workflow-approval-request-reader-credentials (channels) ---# Figure D cross-bot fix (PR1): the reader uses this token to authenticate its# consulta call to control-apidiff --git a/docs/architecture/grok-subscription-transport-contract.md b/docs/architecture/grok-subscription-transport-contract.mdindex 7e0587b17..5f1c741e7 100644--- a/docs/architecture/grok-subscription-transport-contract.md+++ b/docs/architecture/grok-subscription-transport-contract.md@@ -40,3 +40,14 @@ OAuth `device/code` and `token` use `redirect: 'manual'`; any 3xx is an error.Owned by `@clerum/grok-provider-attempt-contract`. Independent of Codex`LIMITS` (`maxToolCalls` is 64, not 32).++## Identity headers++Stamped in `grok-llm-proxy`, never taken from mcp-host or the hashed request:++- `user-agent: evenfire-grok-subscription`+- `accept: text/event-stream` on stream++CLI impersonation headers (`x-xai-token-auth`, `x-grok-client-identifier`) stay+off until a recorded SuperGrok probe requires them. Do not send `OpenAI-Beta`+or `service_tier`. `max_output_tokens` is bindable on this wire.diff --git a/grok-llm-proxy/.gitignore b/grok-llm-proxy/.gitignorenew file mode 100644index 000000000..dd6e803c7--- /dev/null+++ b/grok-llm-proxy/.gitignore@@ -0,0 +1,4 @@+node_modules/+dist/+*.log+.DS_Storediff --git a/grok-llm-proxy/Dockerfile b/grok-llm-proxy/Dockerfilenew file mode 100644index 000000000..aa43e7a1c--- /dev/null+++ b/grok-llm-proxy/Dockerfile@@ -0,0 +1,28 @@+# BUILD CONTEXT = repo root. The proxy consumes+# @clerum/grok-provider-attempt-contract via file:.+FROM node:24.16.0-alpine@sha256:21f403ab171f2dc89bad4dd69d7721bfd15f084ccb46cdd225f31f2bc59b5c9a AS builder++WORKDIR /app+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract+COPY grok-llm-proxy/package*.json ./grok-llm-proxy/+WORKDIR /app/grok-llm-proxy+RUN npm ci+COPY grok-llm-proxy/tsconfig.json grok-llm-proxy/tsconfig.build.json ./+COPY grok-llm-proxy/src ./src+RUN npm run build++FROM node:24.16.0-alpine@sha256:21f403ab171f2dc89bad4dd69d7721bfd15f084ccb46cdd225f31f2bc59b5c9a++WORKDIR /app+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract+COPY grok-llm-proxy/package*.json ./grok-llm-proxy/+WORKDIR /app/grok-llm-proxy+RUN npm ci --only=production+COPY --from=builder /app/grok-llm-proxy/dist ./dist++RUN addgroup -g 1001 -S nodejs && \+ adduser -S nodejs -u 1001+USER nodejs++EXPOSE 8080 8081 9090+CMD ["node", "dist/main.js"]diff --git a/grok-llm-proxy/package-lock.json b/grok-llm-proxy/package-lock.jsonnew file mode 100644index 000000000..b9d6dd63a--- /dev/null+++ b/grok-llm-proxy/package-lock.json@@ -0,0 +1,2871 @@+{+ "name": "clerum-grok-llm-proxy",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "clerum-grok-llm-proxy",+ "version": "0.1.0",+ "license": "SEE LICENSE IN LICENSE",+ "dependencies": {+ "@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",+ "express": "^4.21.2",+ "express-rate-limit": "^8.6.2",+ "jsonwebtoken": "^9.0.2",+ "pino": "^10.3.1",+ "prom-client": "^15.1.3",+ "zod": "^4.3.6"+ },+ "devDependencies": {+ "@types/express": "^4.17.21",+ "@types/jsonwebtoken": "^9.0.10",+ "@types/node": "^24.3.0",+ "@types/supertest": "^7.2.0",+ "supertest": "^7.2.2",+ "typescript": "^5.9.2",+ "vitest": "^4.0.18"+ },+ "engines": {+ "node": ">=24"+ }+ },+ "../packages/grok-provider-attempt-contract": {+ "name": "@clerum/grok-provider-attempt-contract",+ "version": "0.1.0",+ "license": "MIT"+ },+ "node_modules/@clerum/grok-provider-attempt-contract": {+ "resolved": "../packages/grok-provider-attempt-contract",+ "link": true+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@noble/hashes": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",+ "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^14.21.3 || >=16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@opentelemetry/api": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",+ "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/@oxc-project/types": {+ "version": "0.146.0",+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.146.0.tgz",+ "integrity": "sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/Boshen"+ }+ },+ "node_modules/@paralleldrive/cuid2": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz",+ "integrity": "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@noble/hashes": "^1.1.5"+ }+ },+ "node_modules/@pinojs/redact": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",+ "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",+ "license": "MIT"+ },+ "node_modules/@rolldown/binding-android-arm-eabi": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.5.tgz",+ "integrity": "sha512-DLe/i+l8ynIBY7XEQ191TeZvCoowIGa18R+dIV30GW7DiOtp74i/xX8hs8GUjW5ARV7VZuie3d6AumSmCwbeRA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-android-arm64": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.5.tgz",+ "integrity": "sha512-zXcwKlQApYAOELHd8PwKDFkagYF9Wy4e0RJ+0qnzl9Pjnpj75TEG8ufv40p2J7kCEfwZAsNiuzRIyNNMWT38ig==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-arm64": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.5.tgz",+ "integrity": "sha512-dK4QakI42nzWgJT5sm4y4y/O//D4OxM75/cH28RLV+nzIN9AY+YsbuUVrUTjlLjXR6vpyxFbSsbmNuJ6BP9sww==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-x64": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.5.tgz",+ "integrity": "sha512-fqSALaUu1Wjd1nK2uW2kJDWdLCc8lx1IcY+MTY26Aurfdx19anlzhqXOgCFbBFQnlFDTn4TC1/7Nz4Bl2mLP3A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-freebsd-x64": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.5.tgz",+ "integrity": "sha512-/vCnNxlkxs9tKxNDcyWUePpJ/PgTzxIaVhoM5SmG8UV+GR/IcPam4VYxi7GIMo7PSDuNqlJqvprqii9NqqVCMw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.5.tgz",+ "integrity": "sha512-abk0NLA519LxRCszmbE0jYKuQ9YPocOXTiOXOo6Yr+YAT95VH+PtqYAjOJvGKt3viEd/x4qzabAlwd5bHOOARg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-gnu": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.5.tgz",+ "integrity": "sha512-Y7eALiJ8lr0M2HH103Js+g7V34wf6snlpZLAsHI90uLhr3PVlNsbFVAXJC9d/V6BnPyKtpSwI+NcB/RLxsQxuA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-musl": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.5.tgz",+ "integrity": "sha512-xMvZgnbZg4YVnR/AX2b3oOPDTFYJvUVaJg5FedA/LuvexAtXibZQej4cnTkw3rjsJ/ggUROB64TdtETiim+FYA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.5.tgz",+ "integrity": "sha512-GRjeqTUDHTo5GwntsLaAMcBahG3nlpjftXWZLN73HiYQlhwEowvarFgQnRnQZtIp4keXX7quXFbG38uPZBa2EA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-s390x-gnu": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.5.tgz",+ "integrity": "sha512-vLNTR45F2Uwc8AufkNXPmB4VliaXs+FvcheEogIzOXzO4l+LzieXF5A/TWxLy5HtqpsRCHUfd0lPVrrdgXdLHQ==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-gnu": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.5.tgz",+ "integrity": "sha512-Mgj59/HTuYeK9Gz2MA+mBWKnHsAgkBSec15ZMb1st3oIfFbX7gCjOae7GydHhzcyQi9Z/7M1QuN9bR3oFqF0jQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-musl": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.5.tgz",+ "integrity": "sha512-mY8AP0/ichsbhAxGnLa3d3+MwV0EfgrPND2bplI3Ym8T6R2pJ0N87bvrKVwNXmdy3jnr6eQBecdqx/HMknBmpA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-openharmony-arm64": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.5.tgz",+ "integrity": "sha512-8SLssA2oweAxyRgDp789ACfRb/3P+zNRJpzZxSizxF9m8NUDQ4+3xjo8ttjhVGGw6Qxb70oZiEtIjaKikCO7Yw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-arm64-msvc": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.5.tgz",+ "integrity": "sha512-vGbruD5zquhoc8D9SViXgN2FBJtNdTyQ4DtG+SWiEGlJiAzoKcZ2xp+xuXCffhubVdt0NJlTZqkeRuERy7g8Cw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-x64-msvc": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.5.tgz",+ "integrity": "sha512-e/SXpgISz+IoqVcSSI0rx/d/he8zqLex+/rCWpnHpmVfmPIUjag9H6P7zotf0gJHwPUhQxZ/mF8tr6acebT9yw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/pluginutils": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@standard-schema/spec": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/body-parser": {+ "version": "1.19.6",+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/connect": "*",+ "@types/node": "*"+ }+ },+ "node_modules/@types/chai": {+ "version": "5.2.3",+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/deep-eql": "*",+ "assertion-error": "^2.0.1"+ }+ },+ "node_modules/@types/connect": {+ "version": "3.4.38",+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/cookiejar": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz",+ "integrity": "sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/deep-eql": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/express": {+ "version": "4.17.25",+ "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz",+ "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/body-parser": "*",+ "@types/express-serve-static-core": "^4.17.33",+ "@types/qs": "*",+ "@types/serve-static": "^1"+ }+ },+ "node_modules/@types/express-serve-static-core": {+ "version": "4.19.9",+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.9.tgz",+ "integrity": "sha512-QP2ESEe/ImWY0HDwNAnK9PvEffUyhLTnWkk7KXzHfyeWAnlrDe1fN77bXl6ia8KT3wPlmA7t9/VPRpnf4Ex9sg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "@types/qs": "*",+ "@types/range-parser": "*",+ "@types/send": "*"+ }+ },+ "node_modules/@types/http-errors": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/jsonwebtoken": {+ "version": "9.0.10",+ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",+ "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*",+ "@types/node": "*"+ }+ },+ "node_modules/@types/methods": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",+ "integrity": "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/mime": {+ "version": "1.3.5",+ "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",+ "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "24.13.3",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",+ "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.18.0"+ }+ },+ "node_modules/@types/qs": {+ "version": "6.15.1",+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",+ "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/range-parser": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/serve-static": {+ "version": "1.15.10",+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz",+ "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/http-errors": "*",+ "@types/node": "*",+ "@types/send": "<1"+ }+ },+ "node_modules/@types/serve-static/node_modules/@types/send": {+ "version": "0.17.6",+ "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz",+ "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/mime": "^1",+ "@types/node": "*"+ }+ },+ "node_modules/@types/superagent": {+ "version": "8.1.11",+ "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-8.1.11.tgz",+ "integrity": "sha512-KA7srSW/HENDtOw9DOqaFLgWuMqN9WgjEw62lh9dpvRaZDkhdOkazASd7X7i2eMUYLHa1U37ZttnePsH5zTDHw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/cookiejar": "^2.1.5",+ "@types/methods": "^1.1.4",+ "@types/node": "*",+ "form-data": "^4.0.0"+ }+ },+ "node_modules/@types/supertest": {+ "version": "7.2.1",+ "resolved": "https://registry.npmjs.org/@types/supertest/-/supertest-7.2.1.tgz",+ "integrity": "sha512-4CbBvoYVLHL7+yhbYrZET0vsvuyXTC05aRe7dNQkwMzm56auceoy6Yu3K50uZmwfHna1os3CMSgM/3QVkUtPTw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/methods": "^1.1.4",+ "@types/superagent": "^8.1.0"+ }+ },+ "node_modules/@vitest/expect": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",+ "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@standard-schema/spec": "^1.1.0",+ "@types/chai": "^5.2.2",+ "@vitest/spy": "4.1.11",+ "@vitest/utils": "4.1.11",+ "chai": "^6.2.2",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/mocker": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",+ "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "4.1.11",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.21"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/pretty-format": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",+ "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/runner": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",+ "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "4.1.11",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/snapshot": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",+ "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "4.1.11",+ "@vitest/utils": "4.1.11",+ "magic-string": "^0.30.21",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/spy": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",+ "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/utils": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",+ "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "4.1.11",+ "convert-source-map": "^2.0.0",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/accepts": {+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",+ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "~2.1.34",+ "negotiator": "0.6.3"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/array-flatten": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",+ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",+ "license": "MIT"+ },+ "node_modules/asap": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",+ "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/assertion-error": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/atomic-sleep": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",+ "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/bintrees": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz",+ "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",+ "license": "MIT"+ },+ "node_modules/body-parser": {+ "version": "1.20.6",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz",+ "integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "content-type": "~1.0.5",+ "debug": "2.6.9",+ "depd": "2.0.0",+ "destroy": "~1.2.0",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.4.24",+ "on-finished": "~2.4.1",+ "qs": "~6.15.1",+ "raw-body": "~2.5.3",+ "type-is": "~1.6.18",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8",+ "npm": "1.2.8000 || >= 1.4.16"+ }+ },+ "node_modules/buffer-equal-constant-time": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",+ "license": "BSD-3-Clause"+ },+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/chai": {+ "version": "6.2.2",+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/component-emitter": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz",+ "integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/content-disposition": {+ "version": "0.5.4",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",+ "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "5.2.1"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/convert-source-map": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",+ "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",+ "license": "MIT"+ },+ "node_modules/cookiejar": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz",+ "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/debug": {+ "version": "2.6.9",+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",+ "license": "MIT",+ "dependencies": {+ "ms": "2.0.0"+ }+ },+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/destroy": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8",+ "npm": "1.2.8000 || >= 1.4.16"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/dezalgo": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz",+ "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "asap": "^2.0.0",+ "wrappy": "1"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ecdsa-sig-formatter": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/expect-type": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/express": {+ "version": "4.22.2",+ "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",+ "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",+ "license": "MIT",+ "dependencies": {+ "accepts": "~1.3.8",+ "array-flatten": "1.1.1",+ "body-parser": "~1.20.5",+ "content-disposition": "~0.5.4",+ "content-type": "~1.0.4",+ "cookie": "~0.7.1",+ "cookie-signature": "~1.0.6",+ "debug": "2.6.9",+ "depd": "2.0.0",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "etag": "~1.8.1",+ "finalhandler": "~1.3.1",+ "fresh": "~0.5.2",+ "http-errors": "~2.0.0",+ "merge-descriptors": "1.0.3",+ "methods": "~1.1.2",+ "on-finished": "~2.4.1",+ "parseurl": "~1.3.3",+ "path-to-regexp": "~0.1.12",+ "proxy-addr": "~2.0.7",+ "qs": "~6.15.1",+ "range-parser": "~1.2.1",+ "safe-buffer": "5.2.1",+ "send": "~0.19.0",+ "serve-static": "~1.16.2",+ "setprototypeof": "1.2.0",+ "statuses": "~2.0.1",+ "type-is": "~1.6.18",+ "utils-merge": "1.0.1",+ "vary": "~1.1.2"+ },+ "engines": {+ "node": ">= 0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.6.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.2.tgz",+ "integrity": "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/express-rate-limit/node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/express-rate-limit/node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/fast-safe-stringify": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",+ "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/finalhandler": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",+ "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",+ "license": "MIT",+ "dependencies": {+ "debug": "2.6.9",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "on-finished": "~2.4.1",+ "parseurl": "~1.3.3",+ "statuses": "~2.0.2",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/form-data": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.4",+ "mime-types": "^2.1.35"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/formidable": {+ "version": "3.5.4",+ "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.4.tgz",+ "integrity": "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@paralleldrive/cuid2": "^2.2.2",+ "dezalgo": "^1.0.4",+ "once": "^1.4.0"+ },+ "engines": {+ "node": ">=14.0.0"+ },+ "funding": {+ "url": "https://ko-fi.com/tunnckoCore/commissions"+ }+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",+ "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.4.24",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",+ "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ip-address": {+ "version": "10.5.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",+ "integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/jsonwebtoken": {+ "version": "9.0.3",+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",+ "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",+ "license": "MIT",+ "dependencies": {+ "jws": "^4.0.1",+ "lodash.includes": "^4.3.0",+ "lodash.isboolean": "^3.0.3",+ "lodash.isinteger": "^4.0.4",+ "lodash.isnumber": "^3.0.3",+ "lodash.isplainobject": "^4.0.6",+ "lodash.isstring": "^4.0.1",+ "lodash.once": "^4.0.0",+ "ms": "^2.1.1",+ "semver": "^7.5.4"+ },+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ }+ },+ "node_modules/jsonwebtoken/node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/jwa": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",+ "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",+ "license": "MIT",+ "dependencies": {+ "buffer-equal-constant-time": "^1.0.1",+ "ecdsa-sig-formatter": "1.0.11",+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/jws": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",+ "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",+ "license": "MIT",+ "dependencies": {+ "jwa": "^2.0.1",+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/lightningcss": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.33.0",+ "lightningcss-darwin-arm64": "1.33.0",+ "lightningcss-darwin-x64": "1.33.0",+ "lightningcss-freebsd-x64": "1.33.0",+ "lightningcss-linux-arm-gnueabihf": "1.33.0",+ "lightningcss-linux-arm64-gnu": "1.33.0",+ "lightningcss-linux-arm64-musl": "1.33.0",+ "lightningcss-linux-x64-gnu": "1.33.0",+ "lightningcss-linux-x64-musl": "1.33.0",+ "lightningcss-win32-arm64-msvc": "1.33.0",+ "lightningcss-win32-x64-msvc": "1.33.0"+ }+ },+ "node_modules/lightningcss-android-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-arm64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-freebsd-x64": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-musl": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.33.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lodash.includes": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",+ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",+ "license": "MIT"+ },+ "node_modules/lodash.isboolean": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",+ "license": "MIT"+ },+ "node_modules/lodash.isinteger": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",+ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",+ "license": "MIT"+ },+ "node_modules/lodash.isnumber": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",+ "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",+ "license": "MIT"+ },+ "node_modules/lodash.isplainobject": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",+ "license": "MIT"+ },+ "node_modules/lodash.isstring": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",+ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",+ "license": "MIT"+ },+ "node_modules/lodash.once": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",+ "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",+ "license": "MIT"+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",+ "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/methods": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",+ "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",+ "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/ms": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.18",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/negotiator": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",+ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/obug": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",+ "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==",+ "dev": true,+ "funding": [+ "https://github.com/sponsors/sxzz",+ "https://opencollective.com/debug"+ ],+ "license": "MIT",+ "engines": {+ "node": ">=12.20.0"+ }+ },+ "node_modules/on-exit-leak-free": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",+ "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "0.1.13",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",+ "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",+ "license": "MIT"+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/pino": {+ "version": "10.3.1",+ "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",+ "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==",+ "license": "MIT",+ "dependencies": {+ "@pinojs/redact": "^0.4.0",+ "atomic-sleep": "^1.0.0",+ "on-exit-leak-free": "^2.1.0",+ "pino-abstract-transport": "^3.0.0",+ "pino-std-serializers": "^7.0.0",+ "process-warning": "^5.0.0",+ "quick-format-unescaped": "^4.0.3",+ "real-require": "^0.2.0",+ "safe-stable-stringify": "^2.3.1",+ "sonic-boom": "^4.0.1",+ "thread-stream": "^4.0.0"+ },+ "bin": {+ "pino": "bin.js"+ }+ },+ "node_modules/pino-abstract-transport": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",+ "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",+ "license": "MIT",+ "dependencies": {+ "split2": "^4.0.0"+ }+ },+ "node_modules/pino-std-serializers": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",+ "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",+ "license": "MIT"+ },+ "node_modules/postcss": {+ "version": "8.5.26",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.17",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/process-warning": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.0.tgz",+ "integrity": "sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "MIT"+ },+ "node_modules/prom-client": {+ "version": "15.1.3",+ "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz",+ "integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/api": "^1.4.0",+ "tdigest": "^0.1.1"+ },+ "engines": {+ "node": "^16 || ^18 || >=20"+ }+ },+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/qs": {+ "version": "6.15.3",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",+ "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "es-define-property": "^1.0.1",+ "side-channel": "^1.1.1"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/quick-format-unescaped": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",+ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",+ "license": "MIT"+ },+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "2.5.3",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",+ "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.4.24",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/real-require": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",+ "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",+ "license": "MIT",+ "engines": {+ "node": ">= 12.13.0"+ }+ },+ "node_modules/rolldown": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.5.tgz",+ "integrity": "sha512-VD2IE5PUG4Oj8zz2VGykiYd5wbnjdIiSsNQb8Qu5B+noEp+A78mu2iVvpp27g8es14Tk9rofNs5Tku9iQCS4fA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@oxc-project/types": "=0.146.0",+ "@rolldown/pluginutils": "^1.0.0"+ },+ "bin": {+ "rolldown": "bin/cli.mjs"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "optionalDependencies": {+ "@rolldown/binding-android-arm-eabi": "1.2.5",+ "@rolldown/binding-android-arm64": "1.2.5",+ "@rolldown/binding-darwin-arm64": "1.2.5",+ "@rolldown/binding-darwin-x64": "1.2.5",+ "@rolldown/binding-freebsd-x64": "1.2.5",+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.5",+ "@rolldown/binding-linux-arm64-gnu": "1.2.5",+ "@rolldown/binding-linux-arm64-musl": "1.2.5",+ "@rolldown/binding-linux-ppc64-gnu": "1.2.5",+ "@rolldown/binding-linux-s390x-gnu": "1.2.5",+ "@rolldown/binding-linux-x64-gnu": "1.2.5",+ "@rolldown/binding-linux-x64-musl": "1.2.5",+ "@rolldown/binding-openharmony-arm64": "1.2.5",+ "@rolldown/binding-win32-arm64-msvc": "1.2.5",+ "@rolldown/binding-win32-x64-msvc": "1.2.5"+ }+ },+ "node_modules/safe-buffer": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/safe-stable-stringify": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/send": {+ "version": "0.19.2",+ "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",+ "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",+ "license": "MIT",+ "dependencies": {+ "debug": "2.6.9",+ "depd": "2.0.0",+ "destroy": "1.2.0",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "etag": "~1.8.1",+ "fresh": "~0.5.2",+ "http-errors": "~2.0.1",+ "mime": "1.6.0",+ "ms": "2.1.3",+ "on-finished": "~2.4.1",+ "range-parser": "~1.2.1",+ "statuses": "~2.0.2"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/send/node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/serve-static": {+ "version": "1.16.3",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",+ "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "parseurl": "~1.3.3",+ "send": "~0.19.1"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/side-channel": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4",+ "side-channel-list": "^1.0.1",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/siginfo": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/sonic-boom": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",+ "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==",+ "license": "MIT",+ "dependencies": {+ "atomic-sleep": "^1.0.0"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/split2": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",+ "license": "ISC",+ "engines": {+ "node": ">= 10.x"+ }+ },+ "node_modules/stackback": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/std-env": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/superagent": {+ "version": "10.3.0",+ "resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz",+ "integrity": "sha512-B+4Ik7ROgVKrQsXTV0Jwp2u+PXYLSlqtDAhYnkkD+zn3yg8s/zjA2MeGayPoY/KICrbitwneDHrjSotxKL+0XQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "component-emitter": "^1.3.1",+ "cookiejar": "^2.1.4",+ "debug": "^4.3.7",+ "fast-safe-stringify": "^2.1.1",+ "form-data": "^4.0.5",+ "formidable": "^3.5.4",+ "methods": "^1.1.2",+ "mime": "2.6.0",+ "qs": "^6.14.1"+ },+ "engines": {+ "node": ">=14.18.0"+ }+ },+ "node_modules/superagent/node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/superagent/node_modules/mime": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",+ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/superagent/node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/supertest": {+ "version": "7.2.2",+ "resolved": "https://registry.npmjs.org/supertest/-/supertest-7.2.2.tgz",+ "integrity": "sha512-oK8WG9diS3DlhdUkcFn4tkNIiIbBx9lI2ClF8K+b2/m8Eyv47LSawxUzZQSNKUrVb2KsqeTDCcjAAVPYaSLVTA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cookie-signature": "^1.2.2",+ "methods": "^1.1.2",+ "superagent": "^10.3.0"+ },+ "engines": {+ "node": ">=14.18.0"+ }+ },+ "node_modules/supertest/node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/tdigest": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",+ "integrity": "sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==",+ "license": "MIT",+ "dependencies": {+ "bintrees": "1.0.2"+ }+ },+ "node_modules/thread-stream": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",+ "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==",+ "license": "MIT",+ "dependencies": {+ "real-require": "^1.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/thread-stream/node_modules/real-require": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",+ "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",+ "license": "MIT"+ },+ "node_modules/tinybench": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinyexec": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz",+ "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/tinyrainbow": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",+ "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/type-is": {+ "version": "1.6.18",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",+ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",+ "license": "MIT",+ "dependencies": {+ "media-typer": "0.3.0",+ "mime-types": "~2.1.24"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "7.18.2",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/utils-merge": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",+ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4.0"+ }+ },+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/vite": {+ "version": "8.2.2",+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz",+ "integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "lightningcss": "^1.33.0",+ "picomatch": "^4.0.5",+ "postcss": "^8.5.26",+ "rolldown": "~1.2.4",+ "tinyglobby": "^0.2.17"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "@vitejs/devtools": "^0.4.0 || ^0.5.0",+ "esbuild": "^0.27.0 || ^0.28.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "@vitejs/devtools": {+ "optional": true+ },+ "esbuild": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/vitest": {+ "version": "4.1.11",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",+ "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/expect": "4.1.11",+ "@vitest/mocker": "4.1.11",+ "@vitest/pretty-format": "4.1.11",+ "@vitest/runner": "4.1.11",+ "@vitest/snapshot": "4.1.11",+ "@vitest/spy": "4.1.11",+ "@vitest/utils": "4.1.11",+ "es-module-lexer": "^2.0.0",+ "expect-type": "^1.3.0",+ "magic-string": "^0.30.21",+ "obug": "^2.1.1",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.3",+ "std-env": "^4.0.0-rc.1",+ "tinybench": "^2.9.0",+ "tinyexec": "^1.0.2",+ "tinyglobby": "^0.2.15",+ "tinyrainbow": "^3.1.0",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@opentelemetry/api": "^1.9.0",+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",+ "@vitest/browser-playwright": "4.1.11",+ "@vitest/browser-preview": "4.1.11",+ "@vitest/browser-webdriverio": "4.1.11",+ "@vitest/coverage-istanbul": "4.1.11",+ "@vitest/coverage-v8": "4.1.11",+ "@vitest/ui": "4.1.11",+ "happy-dom": "*",+ "jsdom": "*",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@opentelemetry/api": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser-playwright": {+ "optional": true+ },+ "@vitest/browser-preview": {+ "optional": true+ },+ "@vitest/browser-webdriverio": {+ "optional": true+ },+ "@vitest/coverage-istanbul": {+ "optional": true+ },+ "@vitest/coverage-v8": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ },+ "vite": {+ "optional": false+ }+ }+ },+ "node_modules/why-is-node-running": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "siginfo": "^2.0.0",+ "stackback": "0.0.2"+ },+ "bin": {+ "why-is-node-running": "cli.js"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/zod": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/grok-llm-proxy/package.json b/grok-llm-proxy/package.jsonnew file mode 100644index 000000000..c0c9b3d44--- /dev/null+++ b/grok-llm-proxy/package.json@@ -0,0 +1,35 @@+{+ "name": "clerum-grok-llm-proxy",+ "version": "0.1.0",+ "description": "Bounded Grok subscription transport process. No database, Kubernetes, or tool execution.",+ "main": "dist/main.js",+ "engines": {+ "node": ">=24"+ },+ "scripts": {+ "build": "tsc -p tsconfig.build.json",+ "typecheck": "tsc --noEmit",+ "start": "node dist/main.js",+ "test": "vitest run",+ "test:watch": "vitest"+ },+ "license": "SEE LICENSE IN LICENSE",+ "dependencies": {+ "@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",+ "express": "^4.21.2",+ "express-rate-limit": "^8.6.2",+ "jsonwebtoken": "^9.0.2",+ "pino": "^10.3.1",+ "prom-client": "^15.1.3",+ "zod": "^4.3.6"+ },+ "devDependencies": {+ "@types/express": "^4.17.21",+ "@types/jsonwebtoken": "^9.0.10",+ "@types/node": "^24.3.0",+ "@types/supertest": "^7.2.0",+ "supertest": "^7.2.2",+ "typescript": "^5.9.2",+ "vitest": "^4.0.18"+ }+}diff --git a/grok-llm-proxy/src/auth/adminPermitVerifier.ts b/grok-llm-proxy/src/auth/adminPermitVerifier.tsnew file mode 100644index 000000000..b7232fde6--- /dev/null+++ b/grok-llm-proxy/src/auth/adminPermitVerifier.ts@@ -0,0 +1,33 @@+import jwt from 'jsonwebtoken'+import type { GrokLlmProxyConfig } from '../config.js'++export type AdminPermitOperation = 'catalog_list' | 'connection_test'++export type AdminPermitClaims = {+ sub: string+ typ: 'grok-admin-permit'+ operation: AdminPermitOperation+}++export function verifyAdminPermit(+ token: string,+ config: GrokLlmProxyConfig,+ operation?: AdminPermitOperation+): AdminPermitClaims | null {+ try {+ const verified = jwt.verify(token, config.jwtPublicKey, {+ algorithms: ['RS256'],+ issuer: config.jwtIssuer,+ audience: 'grok-llm-proxy-admin',+ })+ if (typeof verified !== 'object' || verified === null) return null+ const claims = verified as jwt.JwtPayload+ if (typeof claims.exp !== 'number') return null+ if (claims.typ !== 'grok-admin-permit' || typeof claims.sub !== 'string') return null+ if (claims.operation !== 'catalog_list' && claims.operation !== 'connection_test') return null+ if (operation && claims.operation !== operation) return null+ return { sub: claims.sub, typ: 'grok-admin-permit', operation: claims.operation }+ } catch {+ return null+ }+}diff --git a/grok-llm-proxy/src/auth/executionTicketVerifier.ts b/grok-llm-proxy/src/auth/executionTicketVerifier.tsnew file mode 100644index 000000000..404a9121c--- /dev/null+++ b/grok-llm-proxy/src/auth/executionTicketVerifier.ts@@ -0,0 +1,41 @@+import jwt from 'jsonwebtoken'+import type { GrokLlmProxyConfig } from '../config.js'++export type ExecutionTicketClaims = {+ jti: string+ typ: 'grok-execution-ticket'+ hostRef: string+ model: string+ requestHash: string+ providerAttemptId: string+}++export function verifyExecutionTicket(+ token: string,+ config: GrokLlmProxyConfig+): ExecutionTicketClaims | null {+ try {+ const verified = jwt.verify(token, config.jwtPublicKey, {+ algorithms: ['RS256'],+ issuer: config.jwtIssuer,+ audience: 'grok-llm-proxy',+ })+ if (typeof verified !== 'object' || verified === null) return null+ const claims = verified as jwt.JwtPayload+ if (typeof claims.exp !== 'number') return null+ if (claims.typ !== 'grok-execution-ticket') return null+ if (typeof claims.jti !== 'string' || typeof claims.hostRef !== 'string') return null+ if (typeof claims.model !== 'string' || typeof claims.requestHash !== 'string') return null+ if (typeof claims.providerAttemptId !== 'string') return null+ return {+ jti: claims.jti,+ typ: 'grok-execution-ticket',+ hostRef: claims.hostRef,+ model: claims.model,+ requestHash: claims.requestHash,+ providerAttemptId: claims.providerAttemptId,+ }+ } catch {+ return null+ }+}diff --git a/grok-llm-proxy/src/auth/platformJwtVerifier.ts b/grok-llm-proxy/src/auth/platformJwtVerifier.tsnew file mode 100644index 000000000..0888088d4--- /dev/null+++ b/grok-llm-proxy/src/auth/platformJwtVerifier.ts@@ -0,0 +1,45 @@+import jwt from 'jsonwebtoken'+import type { GrokLlmProxyConfig } from '../config.js'++export type PlatformJwtClaims = {+ sub: string+ hostRefs: string[]+ workflowControlScopes: string[]+}++export function verifyPlatformJwt(+ token: string,+ config: GrokLlmProxyConfig+): PlatformJwtClaims | null {+ try {+ const verified = jwt.verify(token, config.jwtPublicKey, {+ algorithms: ['RS256'],+ issuer: config.jwtIssuer,+ audience: 'workflow-approvals',+ })+ if (typeof verified !== 'object' || verified === null) return null+ const claims = verified as jwt.JwtPayload+ if (+ claims.typ === 'grok-admin-permit' ||+ claims.typ === 'grok-execution-ticket' ||+ claims.typ === 'codex-admin-permit' ||+ claims.typ === 'codex-execution-ticket'+ ) {+ return null+ }+ if (!Array.isArray(claims.hostRefs) || !Array.isArray(claims.workflowControlScopes)) {+ return null+ }+ if (typeof claims.exp !== 'number') return null+ if (claims.scope !== 'workflow:approval:request') return null+ if (claims.hostRefs.some(ref => String(ref) === '*')) return null+ if (!claims.workflowControlScopes.includes('llm:grok:execute')) return null+ return {+ sub: String(claims.sub),+ hostRefs: claims.hostRefs.map(String),+ workflowControlScopes: claims.workflowControlScopes.map(String),+ }+ } catch {+ return null+ }+}diff --git a/grok-llm-proxy/src/config.ts b/grok-llm-proxy/src/config.tsnew file mode 100644index 000000000..be667fddd--- /dev/null+++ b/grok-llm-proxy/src/config.ts@@ -0,0 +1,62 @@+export type GrokLlmProxyConfig = {+ runtimePort: number+ adminPort: number+ probePort: number+ maxBodyBytes: number+ maxStreamDurationMs: number+ maxDeadlineMs: number+ jwtIssuer: string+ jwtPublicKey: string+ executionEnabled: boolean+ controlApiBaseUrl: string+ controlApiServiceName: string+ controlApiServiceToken: string+}++function requiredPositiveInt(name: string, raw: string | undefined, fallback?: number): number {+ const value = raw === undefined || raw === '' ? fallback : Number(raw)+ if (value === undefined || !Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {+ throw new Error(`${name} must be a finite integer greater than zero`)+ }+ if (value === Number.MAX_SAFE_INTEGER) {+ throw new Error(`${name} must be a bounded positive integer`)+ }+ return value+}++function requiredPem(name: string, raw: string | undefined): string {+ const value = raw?.trim() ?? ''+ if (!value.includes('BEGIN') || !value.includes('KEY')) {+ throw new Error(`${name} must be a PEM-encoded public key`)+ }+ return value+}++export function loadConfig(env: NodeJS.ProcessEnv = process.env): GrokLlmProxyConfig {+ return {+ runtimePort: requiredPositiveInt('GROK_LLM_PROXY_RUNTIME_PORT', env.GROK_LLM_PROXY_RUNTIME_PORT, 8080),+ adminPort: requiredPositiveInt('GROK_LLM_PROXY_ADMIN_PORT', env.GROK_LLM_PROXY_ADMIN_PORT, 8081),+ probePort: requiredPositiveInt('GROK_LLM_PROXY_PROBE_PORT', env.GROK_LLM_PROXY_PROBE_PORT, 9090),+ maxBodyBytes: requiredPositiveInt(+ 'GROK_LLM_PROXY_MAX_BODY_BYTES',+ env.GROK_LLM_PROXY_MAX_BODY_BYTES,+ 1_048_576+ ),+ maxStreamDurationMs: requiredPositiveInt(+ 'GROK_LLM_PROXY_MAX_STREAM_DURATION_MS',+ env.GROK_LLM_PROXY_MAX_STREAM_DURATION_MS,+ 300_000+ ),+ maxDeadlineMs: requiredPositiveInt(+ 'GROK_LLM_PROXY_MAX_DEADLINE_MS',+ env.GROK_LLM_PROXY_MAX_DEADLINE_MS,+ 300_000+ ),+ jwtIssuer: env.GROK_LLM_PROXY_JWT_ISSUER?.trim() || 'control-api',+ jwtPublicKey: requiredPem('GROK_LLM_PROXY_JWT_PUBLIC_KEY', env.GROK_LLM_PROXY_JWT_PUBLIC_KEY),+ executionEnabled: env.GROK_LLM_PROXY_EXECUTION_ENABLED === 'true',+ controlApiBaseUrl: env.GROK_LLM_PROXY_CONTROL_API_URL?.trim() || '',+ controlApiServiceName: env.GROK_LLM_PROXY_CONTROL_API_SERVICE?.trim() || 'grok-llm-proxy',+ controlApiServiceToken: env.GROK_LLM_PROXY_CONTROL_API_TOKEN?.trim() || '',+ }+}diff --git a/grok-llm-proxy/src/controlApiClient.ts b/grok-llm-proxy/src/controlApiClient.tsnew file mode 100644index 000000000..5a5672a76--- /dev/null+++ b/grok-llm-proxy/src/controlApiClient.ts@@ -0,0 +1,169 @@+import { logger } from './logger.js'+import {+ GROK_CATALOG_ORIGIN,+ GROK_COMPLETIONS_ORIGIN,+ GROK_TRANSPORT_PROTOCOL,+} from './originPolicy.js'++export type RedeemOperation = 'completion_stream' | 'completion_cancel' | 'connection_test'++export type RedeemAttemptSuccess = {+ accessToken: string+ grokAccountId?: string+ transport: {+ protocolVersion: typeof GROK_TRANSPORT_PROTOCOL+ completionsOrigin: typeof GROK_COMPLETIONS_ORIGIN+ catalogOrigin: typeof GROK_CATALOG_ORIGIN+ operation: RedeemOperation+ servedModel: string+ maxStreamDurationMs: number+ }+ expiryClass: 'short_lived' | 'upstream_managed'+ attemptReceipt: string+}++export type FinalizeAttemptSuccess = {+ providerAttemptId: string+ outcome: 'success' | 'canceled' | 'error' | 'unknown'+ duplicate: boolean+}++export type ControlApiClientConfig = {+ baseUrl: string+ serviceName: string+ serviceToken: string+ fetchFn?: typeof fetch+}++export class ControlApiClientError extends Error {+ constructor(+ readonly code: string,+ message: string+ ) {+ super(message)+ this.name = 'ControlApiClientError'+ }+}++export class ControlApiClient {+ constructor(private readonly config: ControlApiClientConfig) {}++ async redeem(input: {+ executionTicket: string+ requestHash: string+ model?: string+ hostRef?: string+ operation: RedeemOperation+ }): Promise<RedeemAttemptSuccess> {+ const body = await this.post('/internal/llm/grok/provider-attempts/redeem', {+ executionTicket: input.executionTicket,+ requestHash: input.requestHash,+ model: input.model,+ hostRef: input.hostRef,+ operation: input.operation,+ })+ return parseRedeem(body)+ }++ async finalize(input: {+ attemptReceipt: string+ receipt: {+ schemaVersion: 'grok-attempt-receipt.v1'+ providerAttemptId: string+ requestHash: string+ outcome: 'success' | 'canceled' | 'error' | 'unknown'+ usage?: { inputTokens?: number; outputTokens?: number }+ }+ }): Promise<FinalizeAttemptSuccess> {+ const body = await this.post('/internal/llm/grok/provider-attempts/finalize', {+ attemptReceipt: input.attemptReceipt,+ receipt: input.receipt,+ })+ if (!isPlainObject(body)) {+ return { providerAttemptId: input.receipt.providerAttemptId, outcome: input.receipt.outcome, duplicate: false }+ }+ return {+ providerAttemptId: String(body.providerAttemptId ?? input.receipt.providerAttemptId),+ outcome:+ body.outcome === 'canceled' || body.outcome === 'error' || body.outcome === 'unknown'+ ? body.outcome+ : 'success',+ duplicate: body.duplicate === true,+ }+ }++ private async post(path: string, payload: Record<string, unknown>): Promise<unknown> {+ const base = this.config.baseUrl.replace(/\/+$/, '')+ const fetchFn = this.config.fetchFn ?? fetch+ const response = await fetchFn(`${base}${path.startsWith('/') ? path : `/${path}`}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${this.config.serviceToken}`,+ 'x-service-token': this.config.serviceName,+ },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(15_000),+ })+ const raw = await response.text()+ let parsed: unknown = null+ if (raw) {+ try {+ parsed = JSON.parse(raw)+ } catch {+ parsed = null+ }+ }+ if (!response.ok) {+ const code =+ isPlainObject(parsed) && typeof parsed.error === 'string' ? parsed.error : 'provider_unavailable'+ logger.warn({ event: 'grok_proxy_control_api_denied', code, path }, 'control API request denied')+ throw new ControlApiClientError(code, 'control API request denied')+ }+ return parsed+ }+}++function parseRedeem(body: unknown): RedeemAttemptSuccess {+ if (!isPlainObject(body) || typeof body.accessToken !== 'string' || !isPlainObject(body.transport)) {+ throw new ControlApiClientError('provider_unavailable', 'redeem response is invalid')+ }+ const transport = body.transport+ if (+ transport.protocolVersion !== GROK_TRANSPORT_PROTOCOL ||+ transport.completionsOrigin !== GROK_COMPLETIONS_ORIGIN ||+ transport.catalogOrigin !== GROK_CATALOG_ORIGIN ||+ typeof transport.servedModel !== 'string'+ ) {+ throw new ControlApiClientError('origin_denied', 'redeem transport metadata is not frozen')+ }+ if (typeof body.attemptReceipt !== 'string' || !/^[a-f0-9]{64}$/.test(body.attemptReceipt)) {+ throw new ControlApiClientError('provider_unavailable', 'attemptReceipt is invalid')+ }+ return {+ accessToken: body.accessToken,+ ...(typeof body.grokAccountId === 'string' && body.grokAccountId.trim()+ ? { grokAccountId: body.grokAccountId.trim() }+ : {}),+ transport: {+ protocolVersion: GROK_TRANSPORT_PROTOCOL,+ completionsOrigin: GROK_COMPLETIONS_ORIGIN,+ catalogOrigin: GROK_CATALOG_ORIGIN,+ operation:+ transport.operation === 'completion_cancel' || transport.operation === 'connection_test'+ ? transport.operation+ : 'completion_stream',+ servedModel: transport.servedModel,+ maxStreamDurationMs:+ typeof transport.maxStreamDurationMs === 'number' && Number.isFinite(transport.maxStreamDurationMs)+ ? transport.maxStreamDurationMs+ : 300_000,+ },+ expiryClass: body.expiryClass === 'upstream_managed' ? 'upstream_managed' : 'short_lived',+ attemptReceipt: body.attemptReceipt,+ }+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}diff --git a/grok-llm-proxy/src/grokTransport.ts b/grok-llm-proxy/src/grokTransport.tsnew file mode 100644index 000000000..c812e7a99--- /dev/null+++ b/grok-llm-proxy/src/grokTransport.ts@@ -0,0 +1,606 @@+import {+ type GrokCompletionRequestV1,+ LIMITS,+ hashGrokCompletionRequestV1,+ parseGrokCompletionRequestV1,+} from '@clerum/grok-provider-attempt-contract'+import { grokUpstreamHeaders } from './grokUpstreamHeaders.js'+import type { FinalizeAttemptSuccess, RedeemAttemptSuccess } from './controlApiClient.js'+import { logger } from './logger.js'+import {+ GROK_CATALOG_ORIGIN,+ GROK_COMPLETIONS_ORIGIN,+ OriginDeniedError,+ type OriginPolicyOptions,+ assertAllowedUpstreamUrl,+ fetchFrozenOrigin,+} from './originPolicy.js'+import { assertBoundedDeadline } from './requestLimits.js'+import { ToolNameMap } from './toolNameMap.js'+import { type SafeUsage, parseSafeUsage } from './usage.js'++export type StreamFrame =+ | { type: 'text'; text: string }+ | { type: 'tool_call'; id: string; name: string; arguments: Record<string, unknown> }++export type TransportTicket = {+ jti: string+ hostRef: string+ model: string+ requestHash: string+ providerAttemptId: string+}++export class GrokTransportError extends Error {+ constructor(+ readonly code: string,+ message: string+ ) {+ super(message)+ this.name = 'GrokTransportError'+ }+}++export type StreamGrokCompletionInput = {+ executionTicket: string+ requestHash: string+ request: unknown+ ticket: TransportTicket+ deadlineMs?: number+ maxDeadlineMs?: number+ signal?: AbortSignal+ redeem: (input: {+ executionTicket: string+ requestHash: string+ model: string+ hostRef: string+ operation: 'completion_stream'+ }) => Promise<RedeemAttemptSuccess>+ finalize: (input: {+ attemptReceipt: string+ receipt: {+ schemaVersion: 'grok-attempt-receipt.v1'+ providerAttemptId: string+ requestHash: string+ outcome: 'success' | 'canceled' | 'error' | 'unknown'+ usage?: SafeUsage+ }+ }) => Promise<FinalizeAttemptSuccess>+ fetchFn: typeof fetch+ lookup?: OriginPolicyOptions['lookup']+ onFrame?: (frame: StreamFrame) => void+}++export type StreamGrokCompletionResult = {+ outcome: 'success' | 'canceled' | 'error' | 'unknown'+ usage?: SafeUsage+}++export async function streamGrokCompletion(+ input: StreamGrokCompletionInput+): Promise<StreamGrokCompletionResult> {+ const parsed = parseGrokCompletionRequestV1(input.request)+ if (!parsed.ok) {+ throw new GrokTransportError('invalid_request', parsed.message)+ }+ const request = parsed.value+ const digest = hashGrokCompletionRequestV1(request)+ if (digest !== input.requestHash || input.ticket.requestHash !== input.requestHash) {+ throw new GrokTransportError('request_hash_mismatch', 'request hash does not match the ticket')+ }+ if (request.model !== input.ticket.model) {+ throw new GrokTransportError('model_not_allowed', 'request model does not match the ticket')+ }+ const redeemed = await input.redeem({+ executionTicket: input.executionTicket,+ requestHash: input.requestHash,+ model: request.model,+ hostRef: input.ticket.hostRef,+ operation: 'completion_stream',+ })+ if (redeemed.transport.servedModel !== request.model) {+ await finalizeQuietly(input, redeemed, 'error')+ throw new GrokTransportError('model_not_allowed', 'served model does not match the request')+ }+ const deadlineMs = Math.min(+ assertBoundedDeadline(input.deadlineMs ?? request.deadlineMs, input.maxDeadlineMs ?? 300_000),+ redeemed.transport.maxStreamDurationMs+ )++ const accessToken = redeemed.accessToken+ let outcome: StreamGrokCompletionResult['outcome'] = 'unknown'+ let usage: SafeUsage | undefined+ const started = Date.now()+ try {+ const streamed = await readUpstreamStream({+ request,+ accessToken,+ deadlineMs,+ signal: input.signal,+ fetchFn: input.fetchFn,+ lookup: input.lookup,+ onFrame: input.onFrame,+ })+ outcome = streamed.outcome+ usage = streamed.usage+ return { outcome, usage }+ } catch (err) {+ if (input.signal?.aborted || (err instanceof DOMException && err.name === 'AbortError')) {+ outcome = 'canceled'+ return { outcome, usage }+ }+ if (err instanceof OriginDeniedError) {+ outcome = 'error'+ throw new GrokTransportError('origin_denied', err.message)+ }+ if (err instanceof GrokTransportError) {+ outcome = 'error'+ throw err+ }+ outcome = 'error'+ throw err+ } finally {+ void accessToken+ await finalizeQuietly(input, redeemed, outcome, usage)+ logger.info(+ {+ event: 'grok_proxy_attempt_closed',+ outcome,+ durationMs: Date.now() - started,+ },+ 'grok stream finalized'+ )+ }+}++async function finalizeQuietly(+ input: StreamGrokCompletionInput,+ redeemed: RedeemAttemptSuccess,+ outcome: StreamGrokCompletionResult['outcome'],+ usage?: SafeUsage+): Promise<void> {+ const payload = {+ attemptReceipt: redeemed.attemptReceipt,+ receipt: {+ schemaVersion: 'grok-attempt-receipt.v1' as const,+ providerAttemptId: input.ticket.providerAttemptId,+ requestHash: input.requestHash,+ outcome,+ ...(usage ? { usage } : {}),+ },+ }+ try {+ await input.finalize(payload)+ } catch {+ try {+ await input.finalize(payload)+ } catch (err) {+ logger.error({ event: 'grok_proxy_finalize_failed', err }, 'finalize retry exhausted')+ }+ }+}++async function readUpstreamStream(input: {+ request: GrokCompletionRequestV1+ accessToken: string+ deadlineMs: number+ signal?: AbortSignal+ fetchFn: typeof fetch+ lookup?: OriginPolicyOptions['lookup']+ onFrame?: (frame: StreamFrame) => void+}): Promise<StreamGrokCompletionResult> {+ const url = assertAllowedUpstreamUrl(GROK_COMPLETIONS_ORIGIN, 'completions')+ const timeout = AbortSignal.timeout(input.deadlineMs)+ const signal = input.signal ? AbortSignal.any([input.signal, timeout]) : timeout+ const headers = grokUpstreamHeaders(input.accessToken, {+ 'content-type': 'application/json',+ accept: 'text/event-stream',+ })+ const names = new ToolNameMap([+ ...(input.request.tools ?? []).map(tool => tool.name),+ ...input.request.messages.flatMap(message =>+ message.role === 'assistant' ? (message.toolCalls ?? []).map(call => call.name) : []+ ),+ ])+ const response = await fetchFrozenOrigin({+ url,+ fetchFn: input.fetchFn,+ lookup: input.lookup,+ init: {+ method: 'POST',+ signal,+ headers,+ body: JSON.stringify(toUpstreamPayload(input.request, names)),+ },+ })+ if (!response.ok || !response.body) {+ logger.warn(+ {+ event: 'grok_upstream_http',+ operation: 'completion_stream',+ status: response.status,+ },+ 'Grok completions upstream returned a non-success status'+ )+ if (response.status === 400) {+ throw new GrokTransportError('invalid_request', 'upstream rejected the Grok request')+ }+ if (response.status === 401) {+ throw new GrokTransportError(+ 'connection_unavailable',+ 'upstream rejected the Grok credential'+ )+ }+ if (response.status === 402 || response.status === 403) {+ throw new GrokTransportError(+ 'provider_unavailable',+ 'upstream entitlement denied the Grok request'+ )+ }+ throw new GrokTransportError('provider_unavailable', 'upstream completion failed')+ }+ return consumeSse(response.body, input.onFrame, signal, names)+}++function toUpstreamPayload(+ request: GrokCompletionRequestV1,+ names: ToolNameMap+): Record<string, unknown> {+ const instructions = request.messages+ .filter(message => message.role === 'system' && message.content.trim())+ .map(message => message.content)+ .join('\n\n')+ const input: Record<string, unknown>[] = []+ for (const message of request.messages) {+ if (message.role === 'system') continue+ if (message.role === 'tool') {+ input.push({+ type: 'function_call_output',+ call_id: message.toolCallId || message.name || 'tool',+ output: message.content,+ })+ continue+ }+ if (message.role === 'assistant' && message.toolCalls && message.toolCalls.length > 0) {+ if (message.content.trim()) {+ input.push({ role: 'assistant', content: message.content })+ }+ for (const call of message.toolCalls) {+ input.push({+ type: 'function_call',+ call_id: call.id,+ name: names.toWire(call.name),+ arguments: JSON.stringify(call.arguments ?? {}),+ })+ }+ continue+ }+ input.push({ role: message.role, content: message.content })+ }+ const payload: Record<string, unknown> = {+ model: request.model,+ stream: true,+ store: false,+ input,+ }+ if (instructions) payload.instructions = instructions+ if (request.tools && request.tools.length > 0) {+ payload.tools = request.tools.map(tool => ({+ type: 'function',+ name: names.toWire(tool.name),+ description: tool.description,+ parameters: tool.parameters,+ }))+ payload.parallel_tool_calls = true+ }+ if (request.generation?.maxOutputTokens) {+ payload.max_output_tokens = request.generation.maxOutputTokens+ }+ if (request.generation?.temperature !== undefined) {+ payload.temperature = request.generation.temperature+ }+ if (request.generation?.toolChoice) {+ payload.tool_choice = request.generation.toolChoice+ }+ if (request.transportHints?.promptCacheKey) {+ payload.prompt_cache_key = request.transportHints.promptCacheKey+ }+ return payload+}++async function consumeSse(+ body: ReadableStream<Uint8Array>,+ onFrame: ((frame: StreamFrame) => void) | undefined,+ signal: AbortSignal,+ names: ToolNameMap+): Promise<StreamGrokCompletionResult> {+ const reader = body.getReader()+ const decoder = new TextDecoder()+ const pending = new Map<string, PendingToolCall>()+ // Text stays streaming. Calls become executable only once the entire+ // response succeeds and its independent call budget has been validated.+ const toolFrames: Array<Extract<StreamFrame, { type: 'tool_call' }>> = []+ const acceptFrame = (frame?: StreamFrame) => {+ if (pending.size > LIMITS.maxToolCalls) {+ throw new GrokTransportError(+ 'provider_unavailable',+ `tool calls exceed ${LIMITS.maxToolCalls}`+ )+ }+ if (frame?.type === 'tool_call') {+ if (toolFrames.length >= LIMITS.maxToolCalls) {+ throw new GrokTransportError(+ 'provider_unavailable',+ `tool calls exceed ${LIMITS.maxToolCalls}`+ )+ }+ const canonicalName = names.fromWire(frame.name)+ if (canonicalName === undefined) {+ throw new GrokTransportError(+ 'provider_unavailable',+ 'upstream returned an unknown tool name'+ )+ }+ toolFrames.push({ ...frame, name: canonicalName })+ } else if (frame) onFrame?.(frame)+ }+ let buffer = ''+ let completed = false+ let failed = false+ let usage: SafeUsage | undefined+ const maxSseBufferBytes = 1_048_576+ try {+ while (!signal.aborted) {+ const { done, value } = await reader.read()+ if (done) break+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n').replace(/\r/g, '\n')+ if (buffer.length > maxSseBufferBytes) {+ throw new GrokTransportError('sse_buffer_exceeded', 'upstream SSE buffer exceeded')+ }+ const parts = buffer.split('\n\n')+ buffer = parts.pop() ?? ''+ for (const part of parts) {+ const mapped = ingestSseBlock(part, pending)+ acceptFrame(mapped.frame)+ if (mapped.usage) usage = mapped.usage+ if (mapped.completed) completed = true+ if (mapped.failed) failed = true+ }+ if (signal.aborted) break+ }+ buffer += decoder.decode().replace(/\r\n/g, '\n').replace(/\r/g, '\n')+ if (buffer.trim()) {+ const mapped = ingestSseBlock(buffer, pending)+ acceptFrame(mapped.frame)+ if (mapped.usage) usage = mapped.usage+ if (mapped.completed) completed = true+ if (mapped.failed) failed = true+ }+ } catch (error) {+ await reader.cancel().catch(() => undefined)+ throw error+ } finally {+ reader.releaseLock()+ }+ for (const call of pending.values()) {+ if (call.emitted) continue+ const args = parseToolArguments(call.arguments)+ acceptFrame({ type: 'tool_call', id: call.id, name: call.name, arguments: args })+ call.emitted = true+ }+ if (signal.aborted) return { outcome: 'canceled', usage }+ if (failed) {+ throw new GrokTransportError('provider_unavailable', 'upstream response failed')+ }+ if (completed) {+ for (const frame of toolFrames) onFrame?.(frame)+ return { outcome: 'success', usage }+ }+ return { outcome: 'unknown', usage }+}++function ingestSseBlock(+ part: string,+ pending: Map<string, PendingToolCall>+): ReturnType<typeof mapUpstreamEvent> {+ const dataLine = part+ .split('\n')+ .map(line => line.trim())+ .find(line => line.startsWith('data:'))+ if (!dataLine) return {}+ const payload = dataLine.slice(5).trim()+ if (!payload || payload === '[DONE]') return {}+ try {+ return mapUpstreamEvent(JSON.parse(payload), pending)+ } catch {+ return {}+ }+}++type PendingToolCall = {+ id: string+ name: string+ arguments: string+ emitted: boolean+}++function mapUpstreamEvent(+ event: unknown,+ pending: Map<string, PendingToolCall>+): {+ frame?: StreamFrame+ usage?: SafeUsage+ completed?: boolean+ failed?: boolean+} {+ if (!event || typeof event !== 'object') return {}+ const row = event as Record<string, unknown>+ const type = String(row.type || '')+ if (type === 'response.output_text.delta' && typeof row.delta === 'string') {+ return { frame: { type: 'text', text: row.delta } }+ }+ if (+ type === 'response.output_item.added' &&+ isPlainObject(row.item) &&+ row.item.type === 'function_call'+ ) {+ const call = upsertPendingTool(pending, row.item)+ if (isCompleteJson(call.arguments)) return { frame: emitToolCall(call) }+ return {}+ }+ if (type === 'response.function_call_arguments.delta') {+ upsertPendingTool(pending, {+ id: row.item_id,+ item_id: row.item_id,+ arguments: typeof row.delta === 'string' ? row.delta : '',+ append: true,+ })+ return {}+ }+ if (+ type === 'response.function_call_arguments.done' ||+ (type === 'response.output_item.done' &&+ isPlainObject(row.item) &&+ row.item.type === 'function_call')+ ) {+ const source = isPlainObject(row.item) ? row.item : row+ const call = upsertPendingTool(pending, source)+ if (call && !call.emitted) return { frame: emitToolCall(call) }+ return {}+ }+ if (type === 'response.completed') {+ const response = isPlainObject(row.response) ? row.response : row+ return { completed: true, usage: parseSafeUsage(response.usage) }+ }+ if (type === 'response.failed' || type === 'response.incomplete' || type === 'error') {+ return { failed: true }+ }+ return {}+}++function upsertPendingTool(+ pending: Map<string, PendingToolCall>,+ source: Record<string, unknown> & { append?: boolean }+): PendingToolCall {+ const key = String(source.item_id || source.id || source.call_id || 'tool')+ const current =+ pending.get(key) ??+ ({+ id: String(source.call_id || source.id || key),+ name: 'tool',+ arguments: '',+ emitted: false,+ } satisfies PendingToolCall)+ if (typeof source.call_id === 'string' && source.call_id.trim()) current.id = source.call_id+ if (typeof source.name === 'string' && source.name.trim()) current.name = source.name+ const rawArgs = source.arguments+ if (typeof rawArgs === 'string') {+ current.arguments = source.append+ ? `${current.arguments}${rawArgs}`+ : rawArgs || current.arguments+ } else if (isPlainObject(rawArgs) && !source.append) {+ current.arguments = JSON.stringify(rawArgs)+ }+ pending.set(key, current)+ return current+}++function emitToolCall(call: PendingToolCall): StreamFrame {+ call.emitted = true+ return {+ type: 'tool_call',+ id: call.id,+ name: call.name,+ arguments: parseToolArguments(call.arguments),+ }+}++function isCompleteJson(raw: string): boolean {+ const trimmed = raw.trim()+ if (!trimmed) return false+ try {+ JSON.parse(trimmed)+ return true+ } catch {+ return false+ }+}++function parseToolArguments(raw: unknown): Record<string, unknown> {+ if (isPlainObject(raw)) return raw+ if (typeof raw !== 'string' || raw.length === 0) return {}+ try {+ const parsed = JSON.parse(raw)+ return isPlainObject(parsed) ? parsed : {}+ } catch {+ return {}+ }+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && Array.isArray(value) === false+}++export async function listGrokModels(input: {+ accessToken: string+ fetchFn: typeof fetch+ lookup?: OriginPolicyOptions['lookup']+}): Promise<{+ outcome: 'ready' | 'auth-rejected' | 'unavailable'+ models: Array<{ model: string; displayName?: string }>+}> {+ const url = assertAllowedUpstreamUrl(GROK_CATALOG_ORIGIN, 'catalog')+ const headers = grokUpstreamHeaders(input.accessToken, { accept: 'application/json' })+ const response = await fetchFrozenOrigin({+ url,+ fetchFn: input.fetchFn,+ lookup: input.lookup,+ init: {+ method: 'GET',+ headers,+ },+ })+ if (response.status === 401) return { outcome: 'auth-rejected', models: [] }+ if (!response.ok) {+ logger.warn(+ { event: 'grok_catalog_upstream', status: response.status },+ 'Grok catalog upstream returned a non-success status'+ )+ return { outcome: 'unavailable', models: [] }+ }+ const body = (await response.json()) as unknown+ return { outcome: 'ready', models: normalizeModels(body) }+}++export async function testGrokConnection(input: {+ accessToken: string+ fetchFn: typeof fetch+ lookup?: OriginPolicyOptions['lookup']+}): Promise<{ outcome: 'ready' | 'auth-rejected' | 'unavailable' }> {+ const listed = await listGrokModels(input)+ return { outcome: listed.outcome }+}++function normalizeModels(body: unknown): Array<{ model: string; displayName?: string }> {+ const rows = Array.isArray(body)+ ? body+ : isPlainObject(body) && Array.isArray(body.models)+ ? body.models+ : isPlainObject(body) && Array.isArray(body.data)+ ? body.data+ : []+ const models: Array<{ model: string; displayName?: string }> = []+ for (const row of rows) {+ if (!isPlainObject(row)) continue+ const model = String(row.model || row.slug || row.id || '').trim()+ if (!model) continue+ const displayName =+ typeof row.displayName === 'string'+ ? row.displayName+ : typeof row.title === 'string'+ ? row.title+ : undefined+ models.push(displayName ? { model, displayName } : { model })+ }+ return models+}diff --git a/grok-llm-proxy/src/grokUpstreamHeaders.ts b/grok-llm-proxy/src/grokUpstreamHeaders.tsnew file mode 100644index 000000000..506f03279--- /dev/null+++ b/grok-llm-proxy/src/grokUpstreamHeaders.ts@@ -0,0 +1,18 @@+/**+ * Identity headers stamped in the proxy. Live SuperGrok may later require+ * Grok-CLI impersonation headers; the starting freeze uses Evenfire identity+ * only and never sends OpenAI-Beta or api.x.ai headers.+ */+export const GROK_UPSTREAM_USER_AGENT = 'evenfire-grok-subscription'++export function grokUpstreamHeaders(+ accessToken: string,+ extra: Record<string, string> = {}+): Record<string, string> {+ return {+ authorization: `Bearer ${accessToken}`,+ 'user-agent': GROK_UPSTREAM_USER_AGENT,+ accept: extra.accept ?? 'text/event-stream',+ ...extra,+ }+}diff --git a/grok-llm-proxy/src/logger.ts b/grok-llm-proxy/src/logger.tsnew file mode 100644index 000000000..0ee3e10f1--- /dev/null+++ b/grok-llm-proxy/src/logger.ts@@ -0,0 +1,42 @@+import pino, { type DestinationStream } from 'pino'++export const REDACT_PATHS = [+ 'accessToken',+ 'access_token',+ 'refreshToken',+ 'refresh_token',+ 'deviceCode',+ 'device_code',+ 'userCode',+ 'user_code',+ 'accountSubject',+ 'account_subject',+ 'accountId',+ 'executionTicket',+ 'authorization',+ 'headers.authorization',+ 'req.headers.authorization',+ "req.headers['x-service-token']",+ 'attemptReceipt',+ 'id_token',+ 'idToken',+ '*.access_token',+ '*.refresh_token',+ '*.id_token',+]++export function createProxyLogger(destination?: DestinationStream) {+ return pino(+ {+ level: destination+ ? 'info'+ : (process.env.LOG_LEVEL ?? (process.env.NODE_ENV === 'test' ? 'silent' : 'info')),+ base: { svc: 'grok-llm-proxy' },+ timestamp: pino.stdTimeFunctions.isoTime,+ redact: { paths: REDACT_PATHS, remove: true },+ },+ destination+ )+}++export const logger = createProxyLogger()diff --git a/grok-llm-proxy/src/main.ts b/grok-llm-proxy/src/main.tsnew file mode 100644index 000000000..ab2b4d02d--- /dev/null+++ b/grok-llm-proxy/src/main.ts@@ -0,0 +1,26 @@+import { loadConfig } from './config.js'+import { logger } from './logger.js'+import { startProxy } from './server.js'++async function main(): Promise<void> {+ const config = loadConfig()+ const servers = startProxy(config)+ const shutdown = async (signal: string) => {+ logger.info({ event: 'grok_proxy_shutdown', signal }, 'shutting down')+ await servers.close()+ process.exit(0)+ }+ process.on('SIGTERM', () => void shutdown('SIGTERM'))+ process.on('SIGINT', () => void shutdown('SIGINT'))+}++main().catch(err => {+ process.stderr.write(+ `${JSON.stringify({+ svc: 'grok-llm-proxy',+ event: 'grok_proxy_fatal',+ err: err instanceof Error ? err.message : String(err),+ })}\n`+ )+ process.exit(1)+})diff --git a/grok-llm-proxy/src/metrics.ts b/grok-llm-proxy/src/metrics.tsnew file mode 100644index 000000000..40100342c--- /dev/null+++ b/grok-llm-proxy/src/metrics.ts@@ -0,0 +1,26 @@+import { Counter, Histogram, Registry } from 'prom-client'++export function createProxyMetrics(register: Registry) {+ const outcomes = new Counter({+ name: 'grok_llm_proxy_attempts_total',+ help: 'Grok proxy attempt outcomes',+ labelNames: ['outcome', 'operation'],+ registers: [register],+ })+ const streamSeconds = new Histogram({+ name: 'grok_llm_proxy_stream_duration_seconds',+ help: 'Grok proxy stream duration',+ buckets: [0.1, 0.5, 1, 2, 5, 15, 30, 60, 120, 300],+ registers: [register],+ })+ return {+ observeAttempt(outcome: string, operation: string) {+ outcomes.inc({ outcome, operation })+ },+ observeStream(durationMs: number) {+ streamSeconds.observe(durationMs / 1000)+ },+ }+}++export type ProxyMetrics = ReturnType<typeof createProxyMetrics>diff --git a/grok-llm-proxy/src/originPolicy.ts b/grok-llm-proxy/src/originPolicy.tsnew file mode 100644index 000000000..cc53a57d0--- /dev/null+++ b/grok-llm-proxy/src/originPolicy.ts@@ -0,0 +1,156 @@+import {+ CATALOG_ORIGIN,+ COMPLETIONS_ORIGIN,+ TRANSPORT_PROTOCOL_VERSION,+} from '@clerum/grok-provider-attempt-contract'++export const GROK_COMPLETIONS_ORIGIN = COMPLETIONS_ORIGIN+export const GROK_CATALOG_ORIGIN = CATALOG_ORIGIN+export const GROK_TRANSPORT_PROTOCOL = TRANSPORT_PROTOCOL_VERSION++export type UpstreamKind = 'completions' | 'catalog'++export class OriginDeniedError extends Error {+ readonly code = 'origin_denied'+ constructor(message: string) {+ super(message)+ this.name = 'OriginDeniedError'+ }+}++const FROZEN: Record<UpstreamKind, URL> = {+ completions: new URL(GROK_COMPLETIONS_ORIGIN),+ catalog: new URL(GROK_CATALOG_ORIGIN),+}++export type AddressLookup = () => Promise<Array<{ address: string; family: number }>>++export type OriginPolicyOptions = {+ lookup?: (hostname: string) => Promise<Array<{ address: string; family: number }>>+}++export function assertAllowedUpstreamUrl(raw: string, kind: UpstreamKind): URL {+ let parsed: URL+ try {+ parsed = new URL(raw)+ } catch {+ throw new OriginDeniedError('origin_denied')+ }+ const frozen = FROZEN[kind]+ if (parsed.protocol !== 'https:') throw new OriginDeniedError('origin_denied')+ if (parsed.username || parsed.password) throw new OriginDeniedError('origin_denied')+ if (parsed.hash) throw new OriginDeniedError('origin_denied')+ if (parsed.search !== frozen.search) throw new OriginDeniedError('origin_denied')+ if (parsed.origin !== frozen.origin || parsed.pathname !== frozen.pathname) {+ throw new OriginDeniedError('origin_denied')+ }+ if (isIpLiteral(parsed.hostname) || isBlockedHostname(parsed.hostname)) {+ throw new OriginDeniedError('origin_denied')+ }+ return parsed+}++export async function defaultAddressLookup(+ hostname: string+): Promise<Array<{ address: string; family: number }>> {+ const { lookup } = await import('node:dns/promises')+ const records = await lookup(hostname, { all: true })+ return records.map(record => ({ address: record.address, family: record.family }))+}++export async function assertResolvedUpstream(+ url: URL,+ lookup: OriginPolicyOptions['lookup'] = defaultAddressLookup+): Promise<void> {+ const records = await lookup(url.hostname)+ if (!records.length) throw new OriginDeniedError('origin_denied')+ for (const record of records) {+ if (isBlockedAddress(record.address)) throw new OriginDeniedError('origin_denied')+ }+}++/**+ * POST/GET the frozen origin with redirects disabled. Follow at most one+ * same-origin/same-path/same-search HTTPS redirect; anything else is denied.+ */+export async function fetchFrozenOrigin(input: {+ url: URL+ init: RequestInit+ fetchFn: typeof fetch+ lookup?: OriginPolicyOptions['lookup']+}): Promise<Response> {+ await assertResolvedUpstream(input.url, input.lookup ?? defaultAddressLookup)+ const init: RequestInit = { ...input.init, redirect: 'manual' }+ const first = await input.fetchFn(input.url.href, init)+ if (first.status < 300 || first.status >= 400) return first+ const next = assertRedirectLocation(first.headers.get('location') || '', input.url)+ const second = await input.fetchFn(next.href, init)+ if (second.status >= 300 && second.status < 400) {+ throw new OriginDeniedError('origin_denied')+ }+ return second+}++export function assertRedirectLocation(location: string, from: URL): URL {+ let next: URL+ try {+ next = new URL(location, from)+ } catch {+ throw new OriginDeniedError('origin_denied')+ }+ if (next.protocol !== 'https:') throw new OriginDeniedError('origin_denied')+ if (next.origin !== from.origin) throw new OriginDeniedError('origin_denied')+ if (isIpLiteral(next.hostname) || isBlockedHostname(next.hostname)) {+ throw new OriginDeniedError('origin_denied')+ }+ if (next.pathname !== from.pathname) throw new OriginDeniedError('origin_denied')+ if (next.search !== from.search) throw new OriginDeniedError('origin_denied')+ return next+}++export function isBlockedAddress(address: string): boolean {+ if (address.includes(':')) return isBlockedV6(address)+ const parts = address.split('.').map(part => Number(part))+ if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) {+ return true+ }+ const [a, b] = parts+ if (a === 0 || a === 10 || a === 127) return true+ if (a === 169 && b === 254) return true+ if (a === 172 && b >= 16 && b <= 31) return true+ if (a === 192 && b === 168) return true+ if (a === 192 && b === 0) return true+ if (a === 100 && b >= 64 && b <= 127) return true+ if (a === 198 && (b === 18 || b === 19 || b === 51)) return true+ if (a === 203 && b === 113) return true+ if (a >= 224) return true+ return false+}++function isBlockedV6(address: string): boolean {+ const normalized = address.toLowerCase()+ return (+ normalized === '::1' ||+ normalized === '::' ||+ normalized.startsWith('fc') ||+ normalized.startsWith('fd') ||+ normalized.startsWith('fe80') ||+ normalized.startsWith('ff') ||+ normalized.startsWith('64:ff9b:') ||+ normalized.startsWith('::ffff:')+ )+}++function isIpLiteral(hostname: string): boolean {+ return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) || hostname.includes(':')+}++function isBlockedHostname(hostname: string): boolean {+ const host = hostname.toLowerCase()+ return (+ host === 'localhost' ||+ host.endsWith('.localhost') ||+ host.endsWith('.local') ||+ host.endsWith('.internal')+ )+}diff --git a/grok-llm-proxy/src/requestLimits.ts b/grok-llm-proxy/src/requestLimits.tsnew file mode 100644index 000000000..6389c66f3--- /dev/null+++ b/grok-llm-proxy/src/requestLimits.ts@@ -0,0 +1,60 @@+import { LIMITS as CONTRACT_LIMITS } from '@clerum/grok-provider-attempt-contract'++export const STREAM_LIMITS = {+ maxConcurrentStreams: 8,+ maxQueuedRequests: 16,+ maxStreamDurationMs: 300_000,+} as const++export class RequestLimitError extends Error {+ readonly code = 'provider_unavailable'+ constructor(message: string) {+ super(message)+ this.name = 'RequestLimitError'+ }+}++export function assertBoundedDeadline(deadlineMs: number | undefined, maxDeadlineMs: number): number {+ const requested = deadlineMs ?? Math.min(maxDeadlineMs, STREAM_LIMITS.maxStreamDurationMs)+ if (!Number.isFinite(requested) || !Number.isInteger(requested) || requested <= 0) {+ throw new RequestLimitError('deadline is invalid')+ }+ return Math.min(requested, maxDeadlineMs, STREAM_LIMITS.maxStreamDurationMs, CONTRACT_LIMITS.maxDeadlineMs)+}++export class StreamGate {+ private running = 0+ private queued = 0++ constructor(+ private readonly maxConcurrent = STREAM_LIMITS.maxConcurrentStreams,+ private readonly maxQueued = STREAM_LIMITS.maxQueuedRequests+ ) {}++ async acquire(): Promise<() => void> {+ if (this.running >= this.maxConcurrent) {+ if (this.queued >= this.maxQueued) throw new RequestLimitError('stream queue is full')+ this.queued += 1+ try {+ await new Promise<void>(resolve => {+ const wait = () => {+ if (this.running < this.maxConcurrent) {+ resolve()+ return+ }+ setTimeout(wait, 10)+ }+ wait()+ })+ } finally {+ this.queued -= 1+ }+ }+ this.running += 1+ return () => {+ this.running = Math.max(0, this.running - 1)+ }+ }+}++export const streamGate = new StreamGate()diff --git a/grok-llm-proxy/src/server.ts b/grok-llm-proxy/src/server.tsnew file mode 100644index 000000000..a3c6344e3--- /dev/null+++ b/grok-llm-proxy/src/server.ts@@ -0,0 +1,356 @@+import express, { type Express, type Request, type Response } from 'express'+import { rateLimit } from 'express-rate-limit'+import { createServer, type Server } from 'node:http'+import { Registry, collectDefaultMetrics } from 'prom-client'+import { z } from 'zod'+import { verifyAdminPermit } from './auth/adminPermitVerifier.js'+import { verifyExecutionTicket } from './auth/executionTicketVerifier.js'+import { verifyPlatformJwt } from './auth/platformJwtVerifier.js'+import {+ GrokTransportError,+ listGrokModels,+ streamGrokCompletion,+ testGrokConnection,+} from './grokTransport.js'+import type { GrokLlmProxyConfig } from './config.js'+import { ControlApiClient, ControlApiClientError } from './controlApiClient.js'+import { logger } from './logger.js'+import { createProxyMetrics } from './metrics.js'+import {+ defaultAddressLookup,+ OriginDeniedError,+ type OriginPolicyOptions,+} from './originPolicy.js'+import { RequestLimitError, streamGate } from './requestLimits.js'++const COMPLETION_KEYS = new Set(['executionTicket', 'requestHash', 'request', 'deadlineMs'])+const ADMIN_KEYS = new Set(['accessToken'])++const completionBodySchema = z+ .object({+ executionTicket: z.string().min(1),+ requestHash: z.string().regex(/^[a-f0-9]{64}$/),+ request: z.object({}).passthrough(),+ deadlineMs: z.number().int().positive().optional(),+ })+ .strict()++const adminBodySchema = z.object({ accessToken: z.string().min(1) }).strict()++function bearer(req: Request): string {+ const raw = String(req.header('authorization') || '')+ return raw.replace(/^bearer\s+/i, '').trim()+}++function reject(res: Response, status: number, code: string): void {+ if (res.headersSent) return+ logger.warn({ event: 'grok_proxy_denied', code }, 'request denied')+ res.status(status).json({ error: code })+}++function boundedErrorHandler(err: unknown, _req: Request, res: Response, _next: () => void): void {+ const typed = err as { type?: string; status?: number }+ if (typed?.type === 'entity.too.large' || typed?.status === 413) {+ reject(res, 413, 'payload_too_large')+ return+ }+ if (err instanceof SyntaxError) {+ reject(res, 400, 'invalid_request')+ return+ }+ logger.error({ event: 'grok_proxy_error', err }, 'unhandled request error')+ reject(res, 500, 'internal_error')+}++export type ProxyRuntimeDeps = {+ controlApiClient?: ControlApiClient+ fetchFn?: typeof fetch+ /**+ * Test seam for the DNS half of the origin policy. Production always uses+ * `defaultAddressLookup`; hermetic e2e injects a resolver so the frozen+ * cli-chat-proxy.grok.com origin check runs without live DNS. The URL freeze in+ * `assertAllowedUpstreamUrl` is unaffected by this seam.+ */+ lookup?: OriginPolicyOptions['lookup']+}++export type ProxyServers = {+ runtime: Server+ admin: Server+ probe: Server+ runtimeApp: Express+ adminApp: Express+ probeApp: Express+ close: () => Promise<void>+}++export function createProxyApps(config: GrokLlmProxyConfig, deps: ProxyRuntimeDeps = {}): ProxyServers {+ const metricsRegistry = new Registry()+ collectDefaultMetrics({ register: metricsRegistry })+ const metrics = createProxyMetrics(metricsRegistry)+ const client =+ deps.controlApiClient ??+ new ControlApiClient({+ baseUrl: config.controlApiBaseUrl,+ serviceName: config.controlApiServiceName,+ serviceToken: config.controlApiServiceToken,+ })+ const fetchFn = deps.fetchFn ?? fetch+ const lookup = deps.lookup ?? defaultAddressLookup+ const runtimeRateLimit = rateLimit({+ windowMs: 60_000,+ limit: 60,+ standardHeaders: 'draft-7',+ legacyHeaders: false,+ })+ const adminRateLimit = rateLimit({+ windowMs: 60_000,+ limit: 30,+ standardHeaders: 'draft-7',+ legacyHeaders: false,+ })++ const runtimeApp = express()+ runtimeApp.use(express.json({ limit: config.maxBodyBytes }))+ runtimeApp.post('/internal/runtime/v1/grok/completions', runtimeRateLimit, (req, res) => {+ if (!req.is('application/json')) {+ reject(res, 415, 'unsupported_media_type')+ return+ }+ if (verifyAdminPermit(bearer(req), config)) {+ reject(res, 403, 'insufficient_scope')+ return+ }+ const platform = verifyPlatformJwt(bearer(req), config)+ if (!platform) {+ reject(res, 401, 'Unauthorized')+ return+ }+ const extra = Object.keys(req.body ?? {}).find(key => !COMPLETION_KEYS.has(key))+ if (extra) {+ reject(res, 400, 'unknown_field')+ return+ }+ const parsed = completionBodySchema.safeParse(req.body)+ if (!parsed.success) {+ reject(res, 400, 'invalid_request')+ return+ }+ if (parsed.data.deadlineMs !== undefined && parsed.data.deadlineMs > config.maxDeadlineMs) {+ reject(res, 400, 'invalid_request')+ return+ }+ const ticket = verifyExecutionTicket(parsed.data.executionTicket, config)+ if (!ticket) {+ reject(res, 403, 'ticket_invalid')+ return+ }+ if (platform.hostRefs.includes('*') || !platform.hostRefs.includes(ticket.hostRef)) {+ reject(res, 403, 'host_binding_mismatch')+ return+ }+ if (!config.executionEnabled) {+ reject(res, 404, 'disabled')+ return+ }++ void (async () => {+ let release: (() => void) | undefined+ const abort = new AbortController()+ // After express.json() the incoming request is already complete. Listening+ // to req 'close' aborts the Grok hop on every call (3–12ms canceled).+ // Abort only when the client drops the response before we finish writing.+ abortWhenClientDisconnects(req, res, abort)+ try {+ release = await streamGate.acquire()+ res.status(200)+ res.setHeader('content-type', 'text/event-stream')+ res.setHeader('cache-control', 'no-cache')+ const started = Date.now()+ const result = await streamGrokCompletion({+ executionTicket: parsed.data.executionTicket,+ requestHash: parsed.data.requestHash,+ request: parsed.data.request,+ deadlineMs: parsed.data.deadlineMs,+ maxDeadlineMs: Math.min(config.maxDeadlineMs, config.maxStreamDurationMs),+ ticket: {+ jti: ticket.jti,+ hostRef: ticket.hostRef,+ model: ticket.model,+ requestHash: ticket.requestHash,+ providerAttemptId: ticket.providerAttemptId,+ },+ signal: abort.signal,+ redeem: input => client.redeem(input),+ finalize: input => client.finalize(input),+ fetchFn,+ lookup,+ onFrame: frame => {+ res.write(`data: ${JSON.stringify(frame)}\n\n`)+ },+ })+ res.write(+ `data: ${JSON.stringify({ type: 'done', outcome: result.outcome, ...(result.usage ? { usage: result.usage } : {}) })}\n\n`+ )+ metrics.observeAttempt(result.outcome, 'completion_stream')+ metrics.observeStream(Date.now() - started)+ res.end()+ } catch (err) {+ const mapped = mapError(err)+ metrics.observeAttempt('error', 'completion_stream')+ if (res.headersSent) {+ res.write(`data: ${JSON.stringify({ type: 'error', code: mapped.code })}\n\n`)+ res.end()+ return+ }+ reject(res, mapped.status, mapped.code)+ } finally {+ release?.()+ }+ })()+ })+ runtimeApp.use((_req, res) => reject(res, 404, 'not_found'))+ runtimeApp.use(boundedErrorHandler)++ const adminApp = express()+ adminApp.use(express.json({ limit: config.maxBodyBytes }))+ const adminHandler = (kind: 'models' | 'test') => (req: Request, res: Response) => {+ if (!req.is('application/json')) {+ reject(res, 415, 'unsupported_media_type')+ return+ }+ if (verifyExecutionTicket(bearer(req), config)) {+ reject(res, 403, 'insufficient_scope')+ return+ }+ if (!verifyAdminPermit(bearer(req), config, kind === 'models' ? 'catalog_list' : 'connection_test')) {+ reject(res, 401, 'Unauthorized')+ return+ }+ if (!config.executionEnabled) {+ reject(res, 404, 'disabled')+ return+ }+ const extra = Object.keys(req.body ?? {}).find(key => !ADMIN_KEYS.has(key))+ if (extra) {+ reject(res, 400, 'unknown_field')+ return+ }+ const parsed = adminBodySchema.safeParse(req.body)+ if (!parsed.success) {+ reject(res, 400, 'invalid_request')+ return+ }+ void (async () => {+ try {+ if (kind === 'models') {+ const listed = await listGrokModels({+ accessToken: parsed.data.accessToken,+ fetchFn,+ lookup,+ })+ res.status(200).json(listed)+ return+ }+ const tested = await testGrokConnection({+ accessToken: parsed.data.accessToken,+ fetchFn,+ lookup,+ })+ res.status(200).json(tested)+ } catch (err) {+ const mapped = mapError(err)+ reject(res, mapped.status, mapped.code)+ }+ })()+ }+ adminApp.post('/internal/admin/v1/grok/models', adminRateLimit, adminHandler('models'))+ adminApp.post('/internal/admin/v1/grok/test', adminRateLimit, adminHandler('test'))+ adminApp.use((_req, res) => reject(res, 404, 'not_found'))+ adminApp.use(boundedErrorHandler)++ const probeApp = express()+ probeApp.get('/healthz', (_req, res) => res.status(200).json({ ok: true }))+ probeApp.get('/readyz', (_req, res) => res.status(200).json({ ok: true }))+ probeApp.get('/metrics', async (_req, res) => {+ res.set('content-type', metricsRegistry.contentType)+ res.status(200).send(await metricsRegistry.metrics())+ })+ probeApp.use((_req, res) => reject(res, 404, 'not_found'))++ const runtime = createServer(runtimeApp)+ const admin = createServer(adminApp)+ const probe = createServer(probeApp)++ return {+ runtime,+ admin,+ probe,+ runtimeApp,+ adminApp,+ probeApp,+ close: async () => {+ await Promise.all([runtime, admin, probe].map(server => closeServer(server)))+ },+ }+}++export function startProxy(config: GrokLlmProxyConfig): ProxyServers {+ const servers = createProxyApps(config)+ servers.runtime.listen(config.runtimePort)+ servers.admin.listen(config.adminPort)+ servers.probe.listen(config.probePort)+ logger.info(+ {+ event: 'grok_proxy_listen',+ runtimePort: config.runtimePort,+ adminPort: config.adminPort,+ probePort: config.probePort,+ },+ 'grok-llm-proxy listeners ready'+ )+ return servers+}++function mapError(err: unknown): { status: number; code: string } {+ if (err instanceof OriginDeniedError) return { status: 403, code: 'origin_denied' }+ if (err instanceof RequestLimitError) return { status: 503, code: 'provider_unavailable' }+ if (err instanceof GrokTransportError || err instanceof ControlApiClientError) {+ const statusByCode: Record<string, number> = {+ invalid_request: 400,+ Unauthorized: 401,+ origin_denied: 403,+ request_hash_mismatch: 403,+ ticket_invalid: 403,+ ticket_expired: 403,+ no_grant: 403,+ host_binding_mismatch: 403,+ model_not_allowed: 403,+ insufficient_scope: 403,+ disabled: 404,+ ticket_replayed: 409,+ connection_unavailable: 503,+ provider_unavailable: 503,+ }+ return { status: statusByCode[err.code] ?? 503, code: err.code }+ }+ return { status: 503, code: 'provider_unavailable' }+}++export function abortWhenClientDisconnects(+ req: Request,+ res: Response,+ abort: AbortController+): void {+ const cancel = () => {+ if (!res.writableEnded) abort.abort()+ }+ res.on('close', cancel)+ req.on('aborted', cancel)+}++function closeServer(server: Server): Promise<void> {+ return new Promise(resolve => {+ server.close(() => resolve())+ })+}diff --git a/grok-llm-proxy/src/toolNameMap.ts b/grok-llm-proxy/src/toolNameMap.tsnew file mode 100644index 000000000..73a4fc7d1--- /dev/null+++ b/grok-llm-proxy/src/toolNameMap.ts@@ -0,0 +1,53 @@+import { createHash } from 'node:crypto'++// Conservative standard OpenAI function-name envelope. This is not evidence+// that the Grok /grok/responses endpoint rejects wider canonical MCP names.+const wireNamePattern = /^[A-Za-z0-9_-]{1,64}$/++export class ToolNameMap {+ private readonly outbound = new Map<string, string>()+ private readonly inbound = new Map<string, string>()++ constructor(names: Iterable<string>) {+ const canonicalNames = [...new Set(names)].sort()+ // Reserve compliant canonical names before allocating any aliases, including+ // legitimate tool names that happen to look like our generated aliases.+ const occupied = new Set(canonicalNames.filter(name => wireNamePattern.test(name)))+ for (const name of canonicalNames) {+ let wireName = name+ if (!wireNamePattern.test(name)) {+ const base = `__grok_tool_${createHash('sha256').update(name).digest('hex').slice(0, 40)}`+ wireName = base+ // At most N occupied names exist. N + 1 distinct candidates guarantee+ // allocation without assuming that truncated hashes never collide.+ for (let suffix = 0; occupied.has(wireName) && suffix < canonicalNames.length; suffix++) {+ wireName = `${base}_${suffix.toString(36)}`+ }+ if (occupied.has(wireName) || !wireNamePattern.test(wireName)) {+ throw new Error('Unable to allocate a unique transport tool name')+ }+ }+ occupied.add(wireName)+ this.outbound.set(name, wireName)+ this.inbound.set(wireName, name)+ }+ }++ toWire(name: string): string {+ const mapped = this.outbound.get(name)+ if (mapped === undefined) throw new Error('Unknown canonical tool name')+ return mapped+ }++ fromWire(name: string): string | undefined {+ const canonical = this.inbound.get(name)+ if (canonical !== undefined) return canonical+ // Some providers echo the registered canonical name despite receiving an+ // alias. Accept only an exact known key; do not infer or normalize targets.+ if (this.outbound.has(name)) return name+ // Ordinary unknown names still reach the Host registry for rejection.+ // Never infer a target from an unregistered alias or unsafe name.+ if (wireNamePattern.test(name) && !name.startsWith('__grok_tool_')) return name+ return undefined+ }+}diff --git a/grok-llm-proxy/src/usage.ts b/grok-llm-proxy/src/usage.tsnew file mode 100644index 000000000..d935531ce--- /dev/null+++ b/grok-llm-proxy/src/usage.ts@@ -0,0 +1,20 @@+export type SafeUsage = { inputTokens?: number; outputTokens?: number }++export function parseSafeUsage(input: unknown): SafeUsage | undefined {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return undefined+ const row = input as Record<string, unknown>+ const inputTokens = asNonNegativeInt(row.input_tokens ?? row.inputTokens ?? row.prompt_tokens)+ const outputTokens = asNonNegativeInt(row.output_tokens ?? row.outputTokens ?? row.completion_tokens)+ if (inputTokens === undefined && outputTokens === undefined) return undefined+ const usage: SafeUsage = {}+ if (inputTokens !== undefined) usage.inputTokens = inputTokens+ if (outputTokens !== undefined) usage.outputTokens = outputTokens+ return usage+}++function asNonNegativeInt(value: unknown): number | undefined {+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value) || value < 0) {+ return undefined+ }+ return value+}diff --git a/grok-llm-proxy/test/abortWhenClientDisconnects.test.ts b/grok-llm-proxy/test/abortWhenClientDisconnects.test.tsnew file mode 100644index 000000000..7ada74ba6--- /dev/null+++ b/grok-llm-proxy/test/abortWhenClientDisconnects.test.ts@@ -0,0 +1,39 @@+import { EventEmitter } from 'node:events'+import { describe, expect, it } from 'vitest'+import { abortWhenClientDisconnects } from '../src/server.js'++function fakeReqRes(): {+ req: EventEmitter & { on: EventEmitter['on'] }+ res: EventEmitter & { writableEnded: boolean }+} {+ const req = new EventEmitter()+ const res = Object.assign(new EventEmitter(), { writableEnded: false })+ return { req, res }+}++describe('abortWhenClientDisconnects', () => {+ it('does not abort when the request body stream closes after JSON parse', () => {+ const { req, res } = fakeReqRes()+ const abort = new AbortController()+ abortWhenClientDisconnects(req as never, res as never, abort)+ req.emit('close')+ expect(abort.signal.aborted).toBe(false)+ })++ it('aborts when the client drops the response before it ends', () => {+ const { req, res } = fakeReqRes()+ const abort = new AbortController()+ abortWhenClientDisconnects(req as never, res as never, abort)+ res.emit('close')+ expect(abort.signal.aborted).toBe(true)+ })++ it('does not abort after the proxy finished writing the SSE response', () => {+ const { req, res } = fakeReqRes()+ const abort = new AbortController()+ abortWhenClientDisconnects(req as never, res as never, abort)+ res.writableEnded = true+ res.emit('close')+ expect(abort.signal.aborted).toBe(false)+ })+})diff --git a/grok-llm-proxy/test/approvedToolsUpstream.test.ts b/grok-llm-proxy/test/approvedToolsUpstream.test.tsnew file mode 100644index 000000000..3c5cb7eb5--- /dev/null+++ b/grok-llm-proxy/test/approvedToolsUpstream.test.ts@@ -0,0 +1,353 @@+import { describe, expect, it } from 'vitest'+import { randomUUID } from 'node:crypto'+import { createApprovedToolsUpstream } from './approvedToolsUpstream'++const URL = 'https://cli-chat-proxy.grok.com/v1/responses'+const bridges = ['clerum__tool_search', 'clerum__tool_describe', 'clerum__tool_call']+const target = 'fixture__workitem_read_receipt'+const tools = bridges.map(name => ({ type: 'function', name, parameters: { type: 'object' } }))+type Entry = Record<string, unknown>++async function request(+ simulator: ReturnType<typeof createApprovedToolsUpstream>,+ input: Entry[],+ definitions = tools+) {+ const response = await simulator.fetchFn(URL, {+ method: 'POST',+ body: JSON.stringify({+ model: 'gpt-5.3-grok',+ stream: true,+ store: false,+ input,+ tools: definitions,+ }),+ })+ const body = await response.text()+ return { response, body, event: response.ok ? JSON.parse(body.split('\n')[0]!.slice(6)) : null }+}++async function complete(+ simulator: ReturnType<typeof createApprovedToolsUpstream>,+ input: Entry[],+ runId: string,+ wrapped = false+) {+ const result = {+ runId,+ tool: 'workitem_read_receipt',+ callId: randomUUID(),+ businessId: randomUUID(),+ }+ const outputs = [+ {+ found: 1,+ returned: 1,+ results: [{ name: target, server: 'fixture', description: 'verification receipt' }],+ },+ {+ found: true,+ name: target,+ parameters: { type: 'object', properties: {}, additionalProperties: false },+ },+ { content: [{ type: 'text', text: JSON.stringify(result) }] },+ ]+ for (let index = 0; index < 3; index++) {+ const step = await request(simulator, input)+ expect(step.response.status).toBe(200)+ expect(step.event.item.name).toBe(bridges[index])+ const item = step.event.item+ input.push(item, {+ type: 'function_call_output',+ call_id: item.call_id,+ output: wrapped+ ? `<tool_output name="${index === 2 ? target : bridges[index]}" sanitized="false">\n${JSON.stringify(outputs[index])}\n</tool_output>`+ : JSON.stringify(outputs[index]),+ })+ }+ const final = await request(simulator, input)+ expect(final.response.status).toBe(200)+ expect(JSON.parse(final.event.delta)).toEqual(result)+ return result+}++describe('approved-tools isolated upstream boundary', () => {+ it('accepts the BasicSafety envelope with the real bridge execution target', async () => {+ await complete(+ createApprovedToolsUpstream(),+ [{ role: 'user', content: 'verification receipt' }],+ 'wrapped',+ true+ )+ })+ it('rejects a safety envelope attributed to another tool or malformed closing tags', async () => {+ const simulator = createApprovedToolsUpstream()+ const user = { role: 'user', content: 'verification receipt' }+ const { event } = await request(simulator, [user])+ for (const output of [+ '<tool_output name="other" sanitized="false">\n{}\n</tool_output>',+ '<tool_output name="clerum__tool_search" sanitized="false">\n{}\n</tool_output>trailing',+ ]) {+ const result = await request(simulator, [+ user,+ event.item,+ { type: 'function_call_output', call_id: event.item.call_id, output },+ ])+ expect(result.response.status).toBe(422)+ }+ expect(simulator.evidence().businessCalls).toBe(0)+ })+ it.each([83, 150, 250])(+ 'derives its answer from the selected service result for catalog %s',+ async count => {+ const simulator = createApprovedToolsUpstream()+ const result = await complete(+ simulator,+ [{ role: 'user', content: 'verification receipt' }],+ `catalog-${count}`+ )+ const evidence = simulator.evidence()+ expect(evidence).toMatchObject({+ searchCalls: 1,+ describeCalls: 1,+ businessCalls: 1,+ finalResponses: 1,+ rejected: 0,+ })+ expect(evidence.requests.map(row => row.definitionCount)).toEqual([3, 3, 3, 3])+ expect(+ evidence.requests.every(row => row.connectorDefinitionCount === 0 && !row.leakedSchema)+ ).toBe(true)+ expect(new Set(evidence.requests.map(row => row.definitionBytes)).size).toBe(1)+ expect(JSON.stringify(evidence)).not.toContain(result.businessId)+ expect(JSON.stringify(evidence)).not.toContain(result.runId)+ }+ )++ it('interleaves separate conversations without global stage or answer reuse', async () => {+ const simulator = createApprovedToolsUpstream()+ const results = await Promise.all(+ ['a', 'b'].map(run =>+ complete(simulator, [{ role: 'user', content: 'verification receipt' }], run)+ )+ )+ expect(results[0]!.businessId).not.toBe(results[1]!.businessId)+ expect(simulator.evidence().finalResponses).toBe(2)+ })++ it('recovers after an interrupted user task and returns the actual empty catalog after revocation', async () => {+ const simulator = createApprovedToolsUpstream()+ const input: Entry[] = [{ role: 'user', content: 'verification receipt' }]+ await complete(simulator, input, 'revoked')+ input.push({ role: 'user', content: 'verification receipt before cancellation' })+ const canceled = await request(simulator, input)+ input.push(canceled.event.item) // Genuine cancellation leaves no execution result.+ input.push({ role: 'user', content: 'verification receipt again' })+ const search = await request(simulator, input)+ expect(search.event.item.name).toBe(bridges[0])+ const empty = { found: 0, returned: 0, results: [] }+ input.push(search.event.item, {+ type: 'function_call_output',+ call_id: search.event.item.call_id,+ output: JSON.stringify(empty),+ })+ const denied = await request(simulator, input)+ expect(JSON.parse(denied.event.delta)).toEqual(empty)+ expect(simulator.evidence()).toMatchObject({+ businessCalls: 2,+ finalResponses: 1,+ deniedResponses: 1,+ })+ })++ it('reuses an earlier real schema for an ordinary repeated request', async () => {+ const simulator = createApprovedToolsUpstream()+ const input: Entry[] = [{ role: 'user', content: 'Show my verification receipt.' }]+ const receipt = await complete(simulator, input, 'reuse')+ const before = simulator.evidence()+ input.push({ role: 'user', content: 'Show my verification receipt again.' })+ const call = await request(simulator, input)+ expect(call.event.item.name).toBe(bridges[2])+ // Persisted JSON may reorder object keys without changing the call.+ call.event.item.arguments = JSON.stringify({ arguments: {}, name: target })+ input.push(call.event.item, {+ type: 'function_call_output',+ call_id: call.event.item.call_id,+ output: `<tool_output name="${target}" sanitized="false">\n${JSON.stringify(receipt)}\n</tool_output>`,+ })+ const final = await request(simulator, input)+ expect(JSON.parse(final.event.delta)).toEqual(receipt)+ expect(simulator.evidence().searchCalls).toBe(before.searchCalls)+ expect(simulator.evidence().describeCalls).toBe(before.describeCalls)+ expect(+ simulator+ .evidence()+ .requests.slice(before.requests.length)+ .map(row => row.stage)+ ).toEqual([bridges[2], 'final'])+ })++ it('approval denial returns the real denial and never requests another business call', async () => {+ const simulator = createApprovedToolsUpstream()+ const input: Entry[] = [{ role: 'user', content: 'verification receipt' }]+ await complete(simulator, input, 'denial')+ input.push({ role: 'user', content: 'Please read my verification receipt.' })+ const call = await request(simulator, input)+ input.push(call.event.item, {+ type: 'function_call_output',+ call_id: call.event.item.call_id,+ output: 'Error: Approval denied by user',+ })+ const final = await request(simulator, input)+ expect(final.event.delta).toContain('Approval denied by user')+ expect(simulator.evidence().businessCalls).toBe(2)+ expect(simulator.evidence().deniedResponses).toBe(1)+ input.push({ role: 'user', content: 'verification receipt please' })+ expect((await request(simulator, input)).event.item.name).toBe(bridges[0])+ })++ it('revalidates an obsolete cached target through real search after a catalog denial', async () => {+ const simulator = createApprovedToolsUpstream()+ const input: Entry[] = [{ role: 'user', content: 'verification receipt' }]+ await complete(simulator, input, 'obsolete')+ input.push({ role: 'user', content: 'verification receipt again' })+ const call = await request(simulator, input)+ input.push(call.event.item, {+ type: 'function_call_output',+ call_id: call.event.item.call_id,+ output: 'Error: Tool not found in current catalog',+ })+ const search = await request(simulator, input)+ expect(search.event.item.name).toBe(bridges[0])+ input.push(search.event.item, {+ type: 'function_call_output',+ call_id: search.event.item.call_id,+ output: JSON.stringify({ found: 0, results: [] }),+ })+ expect((await request(simulator, input)).event.delta).toContain('"found":0')+ })++ it.each(['running', 'completed'])(+ 'uses the native workflow result after %s status, never a fabricated receipt',+ async phase => {+ const simulator = createApprovedToolsUpstream()+ const workflow = 'approved-receipt-workflow'+ const nativeNames = [+ 'workflow_list',+ 'workflow_trigger',+ 'workflow_status',+ 'workflow_result',+ ]+ const definitions = [+ ...tools,+ ...nativeNames.map(name => ({ type: 'function', name, parameters: { type: 'object' } })),+ ]+ const input: Entry[] = [+ {+ role: 'user',+ content: `Run my ${workflow} workflow, check that it finishes, and show the business ID from its result artifact.`,+ },+ ]+ const businessId = randomUUID()+ const outputs = [+ {+ items: [+ { name: 'other-workflow' },+ {+ name: workflow,+ requiresInput: false,+ targets: [{ kind: 'user', label: 'Personal' }],+ },+ ],+ },+ { workflowName: workflow, phase: 'pending' },+ { name: workflow, latestRun: { phase } },+ {+ workflowName: workflow,+ artifactAvailable: true,+ result: { businessId, tool: 'workitem_read_receipt' },+ },+ ]+ for (let index = 0; index < nativeNames.length; index++) {+ const call = await request(simulator, input, definitions)+ expect(call.response.status).toBe(200)+ expect(call.event.item.name).toBe(nativeNames[index])+ if (index > 0)+ expect(JSON.parse(call.event.item.arguments)).toEqual({+ name: workflow,+ targetLabel: 'Personal',+ })+ input.push(call.event.item, {+ type: 'function_call_output',+ call_id: call.event.item.call_id,+ output: `<tool_output name="${nativeNames[index]}" sanitized="false">\n${JSON.stringify(outputs[index])}\n</tool_output>`,+ })+ }+ const final = await request(simulator, input, definitions)+ expect(JSON.parse(final.event.delta)).toEqual(outputs[3])+ expect(simulator.evidence().requests.map(row => row.stage)).toEqual([...nativeNames, 'final'])+ expect(simulator.evidence().businessCalls).toBe(0)+ }+ )++ it('rejects missing bridge definitions, incomplete results, wrong call IDs and leaked search schemas', async () => {+ const simulator = createApprovedToolsUpstream()+ const user = { role: 'user', content: 'verification receipt' }+ expect((await request(simulator, [user], tools.slice(0, 2))).response.status).toBe(422)+ const step = await request(simulator, [user])+ const call = step.event.item+ expect((await request(simulator, [user, call])).response.status).toBe(422)+ expect(+ (+ await request(simulator, [+ user,+ call,+ { type: 'function_call_output', call_id: 'wrong', output: '{}' },+ ])+ ).response.status+ ).toBe(422)+ const leaked = { found: 1, results: [{ name: target, parameters: {} }] }+ expect(+ (+ await request(simulator, [+ user,+ call,+ { type: 'function_call_output', call_id: call.call_id, output: JSON.stringify(leaked) },+ ])+ ).response.status+ ).toBe(422)+ expect(simulator.evidence().businessCalls).toBe(0)+ })++ it('accepts only the frozen catalog and completion operations without making network calls', async () => {+ const simulator = createApprovedToolsUpstream()+ const catalog = await simulator.fetchFn(+ 'https://cli-chat-proxy.grok.com/v1/models'+ )+ expect(await catalog.json()).toMatchObject({ models: [{ slug: 'gpt-5.3-grok' }] })+ for (const url of [+ 'http://cli-chat-proxy.grok.com/backend-api/grok/responses',+ 'https://example.com/',+ URL + '/other',+ ]) {+ expect((await simulator.fetchFn(url, { method: 'POST' })).status).toBe(422)+ }+ })++ it('records schema or catalog leakage without retaining the leaked content', async () => {+ const simulator = createApprovedToolsUpstream()+ await request(+ simulator,+ [{ role: 'user', content: 'verification receipt' }],+ [...tools, { type: 'function', name: target, parameters: { type: 'object' } }]+ )+ await request(simulator, [+ { role: 'user', content: 'verification receipt workitem_read_001 workitem_read_002' },+ ])+ expect(simulator.evidence().requests).toMatchObject([+ { connectorDefinitionCount: 1, leakedSchema: true },+ { connectorDefinitionCount: 0, leakedSchema: true },+ ])+ expect(JSON.stringify(simulator.evidence())).not.toContain('workitem_read_001')+ })+})diff --git a/grok-llm-proxy/test/approvedToolsUpstream.ts b/grok-llm-proxy/test/approvedToolsUpstream.tsnew file mode 100644index 000000000..608475c90--- /dev/null+++ b/grok-llm-proxy/test/approvedToolsUpstream.ts@@ -0,0 +1,390 @@+/** External model boundary for the isolated approved-tools E2E image only. */+import { randomUUID } from 'node:crypto'+import { isDeepStrictEqual } from 'node:util'++type Row = Record<string, unknown>+const COMPLETIONS = 'https://cli-chat-proxy.grok.com/v1/responses'+const CATALOG = 'https://cli-chat-proxy.grok.com/v1/models'+const BRIDGES = ['clerum__tool_search', 'clerum__tool_describe', 'clerum__tool_call']+// The deterministic external model is scoped to this fixture's read journey.+const FIXTURE_QUERY = 'verification receipt'++function record(value: unknown): Row {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ throw new Error('expected_object')+ return value as Row+}++function parse(value: unknown): Row {+ if (typeof value !== 'string') throw new Error('expected_json_text')+ return record(JSON.parse(value))+}++function textResult(value: unknown, expectedName: string): Row {+ if (typeof value === 'string' && value.startsWith('<tool_output')) {+ const wrapped =+ /^<tool_output name="([^"]+)" sanitized="(?:true|false)">\n([\s\S]*)\n<\/tool_output>$/.exec(+ value+ )+ if (!wrapped || wrapped[1] !== expectedName || wrapped[2]!.includes('</tool_output>')) {+ throw new Error('invalid_tool_output_envelope')+ }+ value = wrapped[2]+ }+ // Real tool failures can be plain sanitized text; preserve that failure as+ // data rather than inventing a successful result or retrying an approval.+ if (typeof value === 'string' && !value.trim().startsWith('{')) return { error: value }+ const result = parse(value)+ if (result.isError === true || result.is_error === true) return result+ if (Array.isArray(result.content)) {+ const blocks = result.content.map(record)+ if (blocks.length !== 1 || blocks[0]?.type !== 'text')+ throw new Error('expected_single_text_result')+ return parse(blocks[0].text)+ }+ return result+}++type Exchange = { call: Row; args: Row; result: Row }+type Decision = { stage: string; args?: Row; result?: Row }++function expectedCall(exchange: Exchange, decision: Decision): void {+ if (+ exchange.call.name !== decision.stage ||+ !isDeepStrictEqual(exchange.args, decision.args)+ ) {+ throw new Error('unexpected_fixture_call')+ }+}++function exchanges(rows: Row[]): Exchange[] {+ const calls = rows.filter(row => row.type === 'function_call')+ const outputs = rows.filter(row => row.type === 'function_call_output')+ if (calls.length > 12 || calls.length !== outputs.length)+ throw new Error('incomplete_or_repeated_calls')+ if (new Set(calls.map(call => call.call_id)).size !== calls.length)+ throw new Error('duplicate_call_id')+ return calls.map(call => {+ if (typeof call.call_id !== 'string' || typeof call.name !== 'string')+ throw new Error('invalid_call')+ const matched = outputs.filter(output => output.call_id === call.call_id)+ if (matched.length !== 1 || rows.indexOf(matched[0]!) < rows.indexOf(call))+ throw new Error('uncorrelated_result')+ const args = parse(call.arguments)+ const expectedName = call.name === BRIDGES[2] ? args.name : call.name+ if (typeof expectedName !== 'string') throw new Error('invalid_envelope_target')+ return { call, args, result: textResult(matched[0]!.output, expectedName) }+ })+}++function failed(result: Row): boolean {+ return result.isError === true || result.is_error === true || Boolean(result.error)+}++function described(exchange: Exchange): string {+ if (+ exchange.call.name !== BRIDGES[1] ||+ exchange.result.found !== true ||+ exchange.result.name !== exchange.args.name ||+ typeof exchange.args.name !== 'string'+ )+ throw new Error('description_target_mismatch')+ const schema = record(exchange.result.parameters)+ if (schema.type !== 'object' || (Array.isArray(schema.required) && schema.required.length))+ throw new Error('fixture_requires_empty_arguments')+ return exchange.args.name+}++function receipt(exchange: Exchange, candidate: string): Row {+ if (+ exchange.call.name !== BRIDGES[2] ||+ exchange.args.name !== candidate ||+ Object.keys(record(exchange.args.arguments)).length+ )+ throw new Error('invocation_target_mismatch')+ const value = exchange.result+ if (+ typeof value.businessId !== 'string' ||+ !value.businessId ||+ typeof value.runId !== 'string' ||+ typeof value.callId !== 'string' ||+ typeof value.tool !== 'string' ||+ !candidate.endsWith(`__${value.tool}`)+ )+ throw new Error('missing_business_result')+ return value+}++function reusableDescription(history: Row[]): string | undefined {+ let previousUser = history.length - 1+ while (previousUser >= 0 && history[previousUser]?.role !== 'user') previousUser--+ if (previousUser < 0) return undefined+ try {+ // A canceled or denied previous task invalidates reuse; an ordinary new+ // request must recover via discovery, not continue its interrupted call.+ const previous = exchanges(history.slice(previousUser + 1))+ const last = previous.at(-1)+ if (+ !last ||+ last.call.name !== BRIDGES[2] ||+ failed(last.result) ||+ typeof last.args.name !== 'string'+ )+ return undefined+ receipt(last, last.args.name)+ const allCalls = history.filter(row => row.type === 'function_call' && row.name === BRIDGES[1])+ for (const call of allCalls.reverse()) {+ const result = history.find(+ row => row.type === 'function_call_output' && row.call_id === call.call_id+ )+ if (!result) continue+ const candidate = described(exchanges([call, result])[0]!)+ if (candidate === last.args.name) return candidate+ }+ } catch {+ // Historical partial results are expected after genuine user cancellation.+ // They cannot supply a reusable schema, but never block the new task.+ }+ return undefined+}++function receiptDecision(current: Exchange[], known?: string): Decision {+ const last = current.at(-1)+ if (!last)+ return known+ ? { stage: BRIDGES[2]!, args: { name: known, arguments: {} } }+ : { stage: BRIDGES[0]!, args: { query: FIXTURE_QUERY, limit: 5 } }+ expectedCall(last, receiptDecision(current.slice(0, -1), known))+ if (failed(last.result)) {+ // An obsolete cached target can be rediscovered. Approval denial/cancel+ // remains terminal and must never cause an automatic business retry.+ if (+ last.call.name === BRIDGES[2] &&+ /not found|not available|unavailable|not .*catalog/i.test(JSON.stringify(last.result)) &&+ !/approval|denied|cancel|reject/i.test(JSON.stringify(last.result))+ )+ return { stage: BRIDGES[0]!, args: { query: FIXTURE_QUERY, limit: 5 } }+ return { stage: 'denied', result: last.result }+ }+ if (last.call.name === BRIDGES[0]) {+ if (last.args.query !== FIXTURE_QUERY || !Array.isArray(last.result.results))+ throw new Error('invalid_search_result')+ if (last.result.found === 0 && last.result.results.length === 0)+ return { stage: 'denied', result: last.result }+ if (last.result.results.length !== 1) throw new Error('search_must_find_one_target')+ const match = record(last.result.results[0])+ if (+ typeof match.name !== 'string' ||+ BRIDGES.includes(match.name) ||+ 'parameters' in match ||+ 'inputSchema' in match+ )+ throw new Error('invalid_search_target')+ return { stage: BRIDGES[1]!, args: { name: match.name } }+ }+ if (last.call.name === BRIDGES[1]) {+ if (last.result.found === false)+ return { stage: BRIDGES[0]!, args: { query: FIXTURE_QUERY, limit: 5 } }+ const candidate = described(last)+ const search = current.at(-2)+ if (+ !search ||+ search.call.name !== BRIDGES[0] ||+ !Array.isArray(search.result.results) ||+ record(search.result.results[0]).name !== candidate+ )+ throw new Error('description_without_search')+ return { stage: BRIDGES[2]!, args: { name: candidate, arguments: {} } }+ }+ if (last.call.name === BRIDGES[2]) {+ const prior = current.at(-2)+ const candidate = prior?.call.name === BRIDGES[1] ? described(prior) : known+ if (!candidate) throw new Error('invocation_without_schema')+ return { stage: 'final', result: receipt(last, candidate) }+ }+ throw new Error('unsupported_receipt_transition')+}++function workflowDecision(current: Exchange[], prompt: string): Decision {+ if (!current.length) return { stage: 'workflow_list', args: {} }+ expectedCall(current.at(-1)!, workflowDecision(current.slice(0, -1), prompt))+ const listed = current[0]!+ if (+ listed.call.name !== 'workflow_list' ||+ failed(listed.result) ||+ !Array.isArray(listed.result.items)+ )+ throw new Error('workflow_list_required')+ const matches = listed.result.items+ .map(record)+ .filter(item => typeof item.name === 'string' && prompt.includes(item.name))+ if (matches.length !== 1 || matches[0]!.requiresInput === true)+ throw new Error('workflow_not_uniquely_resolved')+ const selected = matches[0]!+ const args: Row = { name: selected.name }+ if (Array.isArray(selected.targets)) {+ const targets = selected.targets.map(record)+ const matching =+ targets.length === 1+ ? targets+ : targets.filter(+ target => typeof target.label === 'string' && prompt.includes(target.label)+ )+ if (matching.length !== 1 || typeof matching[0]!.label !== 'string')+ throw new Error('ambiguous_workflow_target')+ args.targetLabel = matching[0]!.label+ }+ const last = current.at(-1)!+ if (failed(last.result)) return { stage: 'denied', result: last.result }+ if (current.length === 1) return { stage: 'workflow_trigger', args }+ for (const item of current.slice(1)) {+ if (item.args.name !== selected.name) throw new Error('workflow_target_mismatch')+ }+ if (last.call.name === 'workflow_trigger' && current.length === 2) {+ if (last.result.workflowName !== selected.name) throw new Error('trigger_binding_missing')+ return { stage: 'workflow_status', args }+ }+ if (last.call.name === 'workflow_status' && current.length === 3) {+ if (last.result.name !== selected.name) throw new Error('status_binding_missing')+ const latest = last.result.latestRun ? record(last.result.latestRun) : undefined+ if (+ ['failed', 'cancelled', 'canceled'].includes(+ String(latest?.phase ?? last.result.workflowPhase)+ )+ )+ return { stage: 'denied', result: last.result }+ // workflow_result performs the real bounded artifact-readiness polling.+ return { stage: 'workflow_result', args }+ }+ if (last.call.name === 'workflow_result' && current.length === 4) {+ if (+ last.result.workflowName !== selected.name ||+ last.result.artifactAvailable !== true ||+ typeof record(last.result.result).businessId !== 'string'+ )+ throw new Error('workflow_artifact_missing')+ return { stage: 'final', result: last.result }+ }+ throw new Error('unsupported_workflow_transition')+}++function stream(event: Row): Response {+ return new Response(+ [event, { type: 'response.completed' }].map(row => `data: ${JSON.stringify(row)}\n\n`).join(''),+ {+ headers: { 'content-type': 'text/event-stream' },+ }+ )+}++export function createApprovedToolsUpstream() {+ const evidence = {+ catalogRequests: 0,+ rejected: 0,+ completions: 0,+ searchCalls: 0,+ describeCalls: 0,+ businessCalls: 0,+ finalResponses: 0,+ deniedResponses: 0,+ // Only bounded measurements, never request or result contents.+ requests: [] as Array<{+ definitionCount: number+ definitionBytes: number+ inputBytes: number+ connectorDefinitionCount: number+ leakedSchema: boolean+ stage: string+ }>,+ }++ const fetchFn: typeof fetch = async (input, init) => {+ try {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url+ if (url === CATALOG && (!init?.method || init.method === 'GET')) {+ evidence.catalogRequests+++ return Response.json({+ models: [{ slug: 'gpt-5.3-grok', display_name: 'Grok isolated tool test' }],+ })+ }+ if (url !== COMPLETIONS || init?.method !== 'POST') throw new Error('operation_denied')+ const payload = parse(init.body)+ if (payload.stream !== true || payload.store !== false)+ throw new Error('invalid_stream_contract')+ if (!Array.isArray(payload.input) || !Array.isArray(payload.tools))+ throw new Error('missing_input_or_tools')+ const history = payload.input.map(record)+ const tools = payload.tools.map(record)+ const names = new Set(tools.map(tool => tool.name))+ if (!BRIDGES.every(name => names.has(name))) throw new Error('missing_discovery_bridge')+ if (names.size !== tools.length || tools.some(tool => tool.type !== 'function'))+ throw new Error('invalid_definitions')+ let lastUser = history.length - 1+ while (lastUser >= 0 && history[lastUser]?.role !== 'user') lastUser--+ const user = history[lastUser]+ if (!user || typeof user.content !== 'string' || !user.content.trim())+ throw new Error('missing_user_request')+ const isWorkflow = /\bworkflow\b/i.test(user.content)+ if (!isWorkflow && !user.content.toLowerCase().includes(FIXTURE_QUERY))+ throw new Error('unsupported_fixture_task')+ const current = exchanges(history.slice(lastUser + 1))+ const decision = isWorkflow+ ? workflowDecision(current, user.content)+ : receiptDecision(current, reusableDescription(history.slice(0, lastUser)))+ const { stage } = decision+ if (evidence.requests.length >= 512) throw new Error('evidence_capacity_exceeded')+ evidence.completions+++ // This fixture task needs one receipt tool. Other fixture catalog names+ // anywhere in the payload reveal a catalog dump, including in messages.+ const fixtureNames = new Set(+ JSON.stringify(payload).match(/workitem_read_(?:receipt|\d{3})/g) ?? []+ )+ const connectorDefinitionCount = tools.filter(+ tool =>+ typeof tool.name === 'string' &&+ /(?:^|__)workitem_read_(?:receipt|\d{3})$/.test(tool.name)+ ).length+ evidence.requests.push({+ definitionCount: tools.length,+ definitionBytes: Buffer.byteLength(JSON.stringify(tools)),+ inputBytes: Buffer.byteLength(JSON.stringify(payload.input)),+ connectorDefinitionCount,+ leakedSchema: connectorDefinitionCount > 0 || fixtureNames.size > 1,+ stage,+ })+ if (stage === 'denied') {+ evidence.deniedResponses+++ return stream({+ type: 'response.output_text.delta',+ delta: JSON.stringify(decision.result),+ })+ }+ if (stage === 'final') {+ evidence.finalResponses+++ return stream({+ type: 'response.output_text.delta',+ delta: JSON.stringify(decision.result),+ })+ }+ if (!names.has(stage)) throw new Error('unadvertised_function')+ const args = decision.args+ if (stage === BRIDGES[0]) evidence.searchCalls+++ if (stage === BRIDGES[1]) evidence.describeCalls+++ if (stage === BRIDGES[2]) evidence.businessCalls+++ return stream({+ type: 'response.output_item.done',+ item: {+ type: 'function_call',+ id: randomUUID(),+ call_id: randomUUID(),+ name: stage,+ arguments: JSON.stringify(args),+ },+ })+ } catch {+ evidence.rejected+++ return Response.json({ error: { code: 'fixture_protocol_rejected' } }, { status: 422 })+ }+ }+ return { fetchFn, evidence: () => structuredClone(evidence) }+}diff --git a/grok-llm-proxy/test/contractFreeze.test.ts b/grok-llm-proxy/test/contractFreeze.test.tsnew file mode 100644index 000000000..07322a8a7--- /dev/null+++ b/grok-llm-proxy/test/contractFreeze.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import {+ CATALOG_ORIGIN,+ COMPLETIONS_ORIGIN,+ LIMITS,+ TRANSPORT_PROTOCOL_VERSION,+} from '@clerum/grok-provider-attempt-contract'+import {+ GROK_CATALOG_ORIGIN,+ GROK_COMPLETIONS_ORIGIN,+ GROK_TRANSPORT_PROTOCOL,+} from '../src/originPolicy.js'+import { GROK_UPSTREAM_USER_AGENT } from '../src/grokUpstreamHeaders.js'++const here = dirname(fileURLToPath(import.meta.url))+const fixturePath = join(+ here,+ '../../tests/e2e/fixtures/grok-subscription/sanitized-upstream-contract.json'+)++describe('grok-subscription contract freeze', () => {+ it('imports the origin-policy constants the proxy actually enforces', () => {+ expect(GROK_COMPLETIONS_ORIGIN).toBe(COMPLETIONS_ORIGIN)+ expect(GROK_CATALOG_ORIGIN).toBe(CATALOG_ORIGIN)+ expect(GROK_TRANSPORT_PROTOCOL).toBe(TRANSPORT_PROTOCOL_VERSION)++ const fixture = JSON.parse(readFileSync(fixturePath, 'utf8')) as {+ protocolVersion: string+ origins: Record<string, string>+ supportedOperations: string[]+ oauthScopes: string[]+ limits: Record<string, number>+ identityHeaders: { 'user-agent': string; cliImpersonation: boolean }+ forbiddenOrigins: string[]+ }++ expect(fixture.protocolVersion).toBe(GROK_TRANSPORT_PROTOCOL)+ expect(fixture.origins.completions).toBe(GROK_COMPLETIONS_ORIGIN)+ expect(fixture.origins.catalog).toBe(GROK_CATALOG_ORIGIN)+ expect(fixture.origins.oauthDevice).toBe('https://auth.x.ai/oauth2/device/code')+ expect(fixture.origins.oauthToken).toBe('https://auth.x.ai/oauth2/token')+ expect(fixture.supportedOperations).not.toContain('oauth_browser')+ expect(fixture.supportedOperations).toContain('oauth_device')+ expect(fixture.limits.maxToolCalls).toBe(LIMITS.maxToolCalls)+ expect(fixture.limits.maxToolCalls).toBe(64)+ expect(fixture.limits.maxRetriesPerAttempt).toBe(1)+ expect(fixture.identityHeaders['user-agent']).toBe(GROK_UPSTREAM_USER_AGENT)+ expect(fixture.identityHeaders.cliImpersonation).toBe(false)+ expect(fixture.oauthScopes).toEqual(+ expect.arrayContaining(['openid', 'offline_access', 'grok-cli:access', 'api:access'])+ )+ expect(fixture.forbiddenOrigins).toEqual(expect.arrayContaining(['https://api.x.ai']))+ expect(GROK_COMPLETIONS_ORIGIN).not.toContain('api.x.ai')+ expect(GROK_CATALOG_ORIGIN).not.toContain('api.x.ai')+ })+})diff --git a/grok-llm-proxy/test/controlApiClient.test.ts b/grok-llm-proxy/test/controlApiClient.test.tsnew file mode 100644index 000000000..da4bbe69b--- /dev/null+++ b/grok-llm-proxy/test/controlApiClient.test.ts@@ -0,0 +1,133 @@+import { createServer, type IncomingMessage, type Server } from 'node:http'+import { describe, expect, it } from 'vitest'+import { ControlApiClient, ControlApiClientError } from '../src/controlApiClient.js'++const LOOPBACK_V4 = ['127', '0', '0', '1'].join('.')++function listen(handler: (req: IncomingMessage, body: unknown, res: Server) => void): Promise<{+ url: string+ close: () => Promise<void>+ requests: Array<{ url: string; headers: IncomingMessage['headers']; body: unknown }>+}> {+ const requests: Array<{ url: string; headers: IncomingMessage['headers']; body: unknown }> = []+ const server = createServer((req, res) => {+ const chunks: Buffer[] = []+ req.on('data', chunk => chunks.push(Buffer.from(chunk)))+ req.on('end', () => {+ const raw = Buffer.concat(chunks).toString('utf8')+ const body = raw ? JSON.parse(raw) : {}+ requests.push({ url: String(req.url), headers: req.headers, body })+ handler(req, body, res as unknown as Server)+ if (!res.writableEnded) {+ res.statusCode = 200+ res.setHeader('content-type', 'application/json')+ res.end(+ JSON.stringify({+ accessToken: 'tok-live',+ transport: {+ protocolVersion: 'grok-subscription-transport.v1',+ completionsOrigin: 'https://cli-chat-proxy.grok.com/v1/responses',+ catalogOrigin: 'https://cli-chat-proxy.grok.com/v1/models',+ operation: 'completion_stream',+ servedModel: 'gpt-5.1',+ maxStreamDurationMs: 300000,+ },+ expiryClass: 'short_lived',+ attemptReceipt: 'a'.repeat(64),+ })+ )+ }+ })+ })+ return new Promise(resolve => {+ server.listen(0, '127.0.0.1', () => {+ const addr = server.address()+ const port = typeof addr === 'object' && addr ? addr.port : 0+ resolve({+ url: `http://${LOOPBACK_V4}:${port}`,+ requests,+ close: () =>+ new Promise(done => {+ server.close(() => done())+ }),+ })+ })+ })+}++describe('ControlApiClient', () => {+ it('redeems and finalizes with the dedicated service identity and no token cache', async () => {+ const seenTokens: string[] = []+ const server = await listen((req, body, res) => {+ if (String(req.url).endsWith('/redeem')) {+ seenTokens.push(String((body as { executionTicket: string }).executionTicket))+ }+ })+ try {+ const client = new ControlApiClient({+ baseUrl: `${server.url}/api/v1`,+ serviceName: 'grok-llm-proxy',+ serviceToken: 'dev-grok-llm-proxy-token',+ })+ const first = await client.redeem({+ executionTicket: 'ticket-1',+ requestHash: 'b'.repeat(64),+ model: 'gpt-5.1',+ operation: 'completion_stream',+ })+ const second = await client.redeem({+ executionTicket: 'ticket-2',+ requestHash: 'c'.repeat(64),+ model: 'gpt-5.1',+ operation: 'completion_stream',+ })+ expect(first.accessToken).toBe('tok-live')+ expect(second.accessToken).toBe('tok-live')+ expect(seenTokens).toEqual(['ticket-1', 'ticket-2'])+ expect(server.requests[0]?.headers['x-service-token']).toBe('grok-llm-proxy')+ expect(String(server.requests[0]?.headers.authorization)).toContain('dev-grok-llm-proxy-token')+ expect(server.requests[0]?.url).toBe('/api/v1/internal/llm/grok/provider-attempts/redeem')+ expect(server.requests.some(item => item.url === '/api/v1/internal/llm/provider-attempts/redeem')).toBe(+ false+ )++ const finalized = await client.finalize({+ attemptReceipt: 'a'.repeat(64),+ receipt: {+ schemaVersion: 'grok-attempt-receipt.v1',+ providerAttemptId: 'att-1',+ requestHash: 'b'.repeat(64),+ outcome: 'success',+ },+ })+ expect(finalized).toMatchObject({ outcome: 'success' })+ expect(server.requests.some(item => item.url?.includes('/finalize'))).toBe(true)+ } finally {+ await server.close()+ }+ })++ it('maps redeem failures to bounded codes and never retries an ambiguous attempt', async () => {+ const server = await listen((req, _body, res) => {+ ;(res as unknown as { statusCode: number; setHeader: Function; end: Function }).statusCode = 409+ ;(res as unknown as { setHeader: Function }).setHeader('content-type', 'application/json')+ ;(res as unknown as { end: Function }).end(JSON.stringify({ error: 'ticket_replayed' }))+ })+ try {+ const client = new ControlApiClient({+ baseUrl: `${server.url}/api/v1`,+ serviceName: 'grok-llm-proxy',+ serviceToken: 'dev-grok-llm-proxy-token',+ })+ await expect(+ client.redeem({+ executionTicket: 'replay',+ requestHash: 'd'.repeat(64),+ operation: 'completion_stream',+ })+ ).rejects.toMatchObject({ code: 'ticket_replayed' } satisfies Partial<ControlApiClientError>)+ } finally {+ await server.close()+ }+ })+})diff --git a/grok-llm-proxy/test/grokTransport.conformance.test.ts b/grok-llm-proxy/test/grokTransport.conformance.test.tsnew file mode 100644index 000000000..1ec32795b--- /dev/null+++ b/grok-llm-proxy/test/grokTransport.conformance.test.ts@@ -0,0 +1,902 @@+import { describe, expect, it, vi } from 'vitest'+import {+ hashGrokCompletionRequestV1,+ parseGrokCompletionRequestV1,+} from '@clerum/grok-provider-attempt-contract'+import { GrokTransportError, streamGrokCompletion } from '../src/grokTransport.js'+import type { RedeemAttemptSuccess } from '../src/controlApiClient.js'+import { GROK_COMPLETIONS_ORIGIN } from '../src/originPolicy.js'++const REQUEST = {+ schemaVersion: 'grok-completion-request.v1' as const,+ requestId: 'req-001',+ idempotencyKey: 'idem-001',+ provider: 'grok-subscription' as const,+ model: 'gpt-5.1',+ messages: [{ role: 'user' as const, content: 'hello' }],+}++const REQUEST_HASH = hashGrokCompletionRequestV1(REQUEST)++function accessTokenFor(label: string): string {+ const encoded = Buffer.from(+ JSON.stringify({+ sub: label,+ 'https://api.x.ai/auth': { grok_account_id: 'acct_live_1' },+ })+ ).toString('base64url')+ return `hdr.${encoded}.sig`+}++function redeemSuccess(overrides: Partial<RedeemAttemptSuccess> = {}): RedeemAttemptSuccess {+ return {+ accessToken: accessTokenFor('live'),+ transport: {+ protocolVersion: 'grok-subscription-transport.v1',+ completionsOrigin: GROK_COMPLETIONS_ORIGIN,+ catalogOrigin: 'https://cli-chat-proxy.grok.com/v1/models',+ operation: 'completion_stream',+ servedModel: 'gpt-5.1',+ maxStreamDurationMs: 300_000,+ },+ expiryClass: 'short_lived',+ attemptReceipt: 'a'.repeat(64),+ ...overrides,+ }+}++function sseResponse(+ frames: string[],+ status = 200,+ headers: Record<string, string> = {}+): Response {+ return new Response(frames.join(''), {+ status,+ headers: { 'content-type': 'text/event-stream', ...headers },+ })+}++describe('streamGrokCompletion', () => {+ it.each(['response.failed', 'unterminated'])(+ 'does not emit partial tool calls after %s',+ async terminal => {+ const emitted: Array<{ type: string }> = []+ const frames = [+ 'data: {"type":"response.output_item.done","item":{"type":"function_call","id":"partial","name":"lookup","arguments":"{}"}}\n\n',+ ]+ if (terminal !== 'unterminated')+ frames.push(`data: ${JSON.stringify({ type: terminal })}\n\n`)+ const pending = streamGrokCompletion({+ executionTicket: 'ticket-partial',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-partial',+ hostRef: 'research-host',+ model: REQUEST.model,+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-partial',+ },+ redeem: vi.fn(async () => redeemSuccess()),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-partial',+ outcome: 'success' as const,+ duplicate: false,+ })),+ fetchFn: vi.fn(async () => sseResponse(frames)),+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => emitted.push(frame),+ })+ if (terminal === 'unterminated') expect((await pending).outcome).toBe('unknown')+ else await expect(pending).rejects.toThrow(/upstream response failed/)+ expect(emitted).toEqual([])+ }+ )+ it.each([64, 65])(+ 'validates the complete %s-call response before emitting executable calls',+ async count => {+ const emitted: Array<{ type: string }> = []+ const finalize = vi.fn(async () => ({+ providerAttemptId: 'att-bound',+ outcome: 'success' as const,+ duplicate: false,+ }))+ const frames = Array.from(+ { length: count },+ (_, index) =>+ `data: ${JSON.stringify({+ type: 'response.output_item.done',+ item: { type: 'function_call', id: `call-${index}`, name: 'lookup', arguments: '{}' },+ })}\n\n`+ )+ frames.push('data: {"type":"response.completed"}\n\n')+ const pending = streamGrokCompletion({+ executionTicket: 'ticket-bound',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-bound',+ hostRef: 'research-host',+ model: REQUEST.model,+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-bound',+ },+ redeem: vi.fn(async () => redeemSuccess()),+ finalize,+ fetchFn: vi.fn(async () => sseResponse(frames)),+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => emitted.push(frame),+ })+ if (count === 64) {+ expect((await pending).outcome).toBe('success')+ expect(emitted.filter(frame => frame.type === 'tool_call')).toHaveLength(64)+ } else {+ await expect(pending).rejects.toThrow(/tool calls exceed 64/)+ expect(emitted.filter(frame => frame.type === 'tool_call')).toHaveLength(0)+ expect(finalize).toHaveBeenCalledWith(+ expect.objectContaining({ receipt: expect.objectContaining({ outcome: 'error' }) })+ )+ }+ }+ )+ it('validates ticket bindings before redeem and maps stream frames including tool-call data', async () => {+ const redeem = vi.fn(async () => redeemSuccess())+ const finalize = vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success' as const,+ duplicate: false,+ }))+ const frames: unknown[] = []+ const fetchFn = vi.fn(async (url: string) => {+ expect(url).toBe(GROK_COMPLETIONS_ORIGIN)+ return sseResponse([+ 'data: {"type":"response.output_text.delta","delta":"hi"}\n\n',+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","id":"call-1","name":"lookup","arguments":"{\\"q\\":\\"x\\"}"}}\n\n',+ 'data: {"type":"response.completed","response":{"usage":{"input_tokens":3,"output_tokens":2}}}\n\n',+ ])+ })++ const result = await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: '11111111-1111-4111-8111-111111111111',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem,+ finalize,+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => frames.push(frame),+ })++ expect(redeem).toHaveBeenCalledOnce()+ expect(fetchFn).toHaveBeenCalledOnce()+ expect(frames).toEqual(+ expect.arrayContaining([+ { type: 'text', text: 'hi' },+ { type: 'tool_call', id: 'call-1', name: 'lookup', arguments: { q: 'x' } },+ ])+ )+ expect(result.outcome).toBe('success')+ expect(result.usage).toEqual({ inputTokens: 3, outputTokens: 2 })+ expect(finalize).toHaveBeenCalledWith(+ expect.objectContaining({+ attemptReceipt: 'a'.repeat(64),+ receipt: expect.objectContaining({ outcome: 'success', requestHash: REQUEST_HASH }),+ })+ )+ expect(String(fetchFn.mock.calls[0]?.[1]?.headers?.['authorization'])).toContain(+ accessTokenFor('live')+ )+ expect(fetchFn.mock.calls[0]?.[1]?.headers?.['user-agent']).toBe('evenfire-grok-subscription')+ expect(fetchFn.mock.calls[0]?.[1]?.headers?.['openai-beta']).toBeUndefined()+ expect(fetchFn.mock.calls[0]?.[1]?.headers?.['x-xai-token-auth']).toBeUndefined()+ expect(String(fetchFn.mock.calls[0]?.[1]?.body)).toContain('"store":false')+ })++ it('flushes a completed event that arrives without a trailing blank line', async () => {+ const fetchFn = vi.fn(async () =>+ sseResponse([+ 'data: {"type":"response.completed","response":{"usage":{"input_tokens":1,"output_tokens":1}}}',+ ])+ )+ const result = await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-residual',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success' as const,+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ expect(result.outcome).toBe('success')+ expect(result.usage).toEqual({ inputTokens: 1, outputTokens: 1 })+ })++ it('parses CRLF-delimited SSE frames', async () => {+ const fetchFn = vi.fn(async () =>+ sseResponse([+ 'data: {"type":"response.completed","response":{"usage":{"input_tokens":4,"output_tokens":5}}}\r\n\r\n',+ ])+ )+ const result = await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-crlf',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success' as const,+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ expect(result.outcome).toBe('success')+ expect(result.usage).toEqual({ inputTokens: 4, outputTokens: 5 })+ })++ it('maps upstream 402/403 to provider_unavailable', async () => {+ const fetchFn = vi.fn(async () => new Response('paywall', { status: 403 }))+ await expect(+ streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess({ accessToken: 'opaque-token' }),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'error',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ ).rejects.toMatchObject({ code: 'provider_unavailable' })+ })++ it('rejects a mutated requestHash before redeem', async () => {+ const redeem = vi.fn()+ await expect(+ streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: 'f'.repeat(64),+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem,+ finalize: vi.fn(),+ fetchFn: vi.fn(),+ })+ ).rejects.toMatchObject({+ code: 'request_hash_mismatch',+ } satisfies Partial<GrokTransportError>)+ expect(redeem).not.toHaveBeenCalled()+ })++ it('rejects a served-model mismatch and loopback redirects', async () => {+ await expect(+ streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () =>+ redeemSuccess({ transport: { ...redeemSuccess().transport, servedModel: 'other' } }),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'error',+ duplicate: false,+ })),+ fetchFn: vi.fn(),+ })+ ).rejects.toMatchObject({ code: 'model_not_allowed' })++ const fetchFn = vi.fn(+ async () =>+ new Response(null, {+ status: 302,+ headers: { location: `https://${['127', '0', '0', '1'].join('.')}/steal` },+ })+ )+ await expect(+ streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'error',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ ).rejects.toMatchObject({ code: 'origin_denied' })+ })++ it('follows one frozen same-origin redirect then streams', async () => {+ const fetchFn = vi.fn(async () => {+ if (fetchFn.mock.calls.length === 1) {+ return new Response(null, {+ status: 307,+ headers: { location: GROK_COMPLETIONS_ORIGIN },+ })+ }+ return sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])+ })+ const result = await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ expect(result.outcome).toBe('success')+ expect(fetchFn).toHaveBeenCalledTimes(2)+ })++ it('maps upstream 401 to connection_unavailable instead of origin_denied', async () => {+ await expect(+ streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'error',+ duplicate: false,+ })),+ fetchFn: vi.fn(async () => new Response('denied', { status: 401 })),+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ ).rejects.toMatchObject({ code: 'connection_unavailable' })+ })++ it('finalizes canceled after the first frame and treats finalize 500 as idempotent retry', async () => {+ const abort = new AbortController()+ const finalize = vi+ .fn()+ .mockRejectedValueOnce(new Error('finalize 500'))+ .mockResolvedValueOnce({ providerAttemptId: 'att-1', outcome: 'canceled', duplicate: true })+ const fetchFn = vi.fn(async () => {+ const stream = new ReadableStream({+ start(controller) {+ controller.enqueue(+ new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":"x"}\n\n')+ )+ setTimeout(() => controller.close(), 20)+ },+ })+ return new Response(stream, { headers: { 'content-type': 'text/event-stream' } })+ })++ const frames: unknown[] = []+ const result = await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ signal: abort.signal,+ redeem: async () => redeemSuccess(),+ finalize,+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => {+ frames.push(frame)+ abort.abort()+ },+ })+ expect(frames[0]).toEqual({ type: 'text', text: 'x' })+ expect(result.outcome).toBe('canceled')+ expect(finalize).toHaveBeenCalledTimes(2)+ expect(finalize.mock.calls[0]?.[0]?.receipt.outcome).toBe('canceled')+ })++ it('does not reuse a redeemed access token across requests', async () => {+ const tokens: string[] = []+ const redeem = vi.fn(async (input: { executionTicket: string }) => {+ tokens.push(input.executionTicket)+ return redeemSuccess({ accessToken: accessTokenFor(input.executionTicket) })+ })+ const fetchFn = vi.fn(async () =>+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])+ )+ const ticket = {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ }+ await streamGrokCompletion({+ executionTicket: 't-a',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket,+ redeem,+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ await streamGrokCompletion({+ executionTicket: 't-b',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket,+ redeem,+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ expect(tokens).toEqual(['t-a', 't-b'])+ expect(String(fetchFn.mock.calls[0]?.[1]?.headers?.['authorization'])).toContain(+ accessTokenFor('t-a')+ )+ expect(String(fetchFn.mock.calls[1]?.[1]?.headers?.['authorization'])).toContain(+ accessTokenFor('t-b')+ )+ })++ it('does not retry after an ambiguous upstream response', async () => {+ const fetchFn = vi.fn(async () =>+ sseResponse(['data: {"type":"response.output_text.delta","delta":"partial"}\n\n'])+ )+ const result = await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'unknown',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ expect(result.outcome).toBe('unknown')+ expect(fetchFn).toHaveBeenCalledOnce()+ })++ it('maps system, tool history, and generation hints into the Responses payload', async () => {+ const request = {+ schemaVersion: 'grok-completion-request.v1' as const,+ requestId: 'req-001',+ idempotencyKey: 'idem-001',+ provider: 'grok-subscription' as const,+ model: 'gpt-5.1',+ messages: [+ { role: 'system' as const, content: 'be brief' },+ { role: 'user' as const, content: 'hello' },+ {+ role: 'assistant' as const,+ content: '',+ toolCalls: [{ id: 'call-1', name: 'echo', arguments: { x: 1 } }],+ },+ { role: 'tool' as const, content: 'ok', toolCallId: 'call-1' },+ ],+ tools: Array.from({ length: 250 }, (_, index) => ({+ name: index === 0 ? 'echo' : `approved_tool_${index}`,+ description: `Approved tool ${index}`,+ parameters: { type: 'object', properties: { x: { type: 'integer' } } },+ })),+ generation: { toolChoice: 'auto' as const },+ transportHints: { promptCacheKey: 'sess-1' },+ }+ const requestHash = hashGrokCompletionRequestV1(request)+ const fetchFn = vi.fn(async () =>+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])+ )+ await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash,+ request,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ const body = JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body)) as Record<string, unknown>+ expect(body.instructions).toBe('be brief')+ expect(body.store).toBe(false)+ expect(body.tools).toEqual(request.tools.map(tool => ({ type: 'function', ...tool })))+ expect(body.parallel_tool_calls).toBe(true)+ expect(body.tool_choice).toBe('auto')+ expect(body.prompt_cache_key).toBe('sess-1')+ expect(body.input).toEqual([+ { role: 'user', content: 'hello' },+ { type: 'function_call', call_id: 'call-1', name: 'echo', arguments: '{"x":1}' },+ { type: 'function_call_output', call_id: 'call-1', output: 'ok' },+ ])+ expect(body).not.toHaveProperty('max_output_tokens')+ expect(body).not.toHaveProperty('temperature')+ })++ it.each([+ { name: 'service.with.dots__read', mode: 'alias' },+ { name: `generated_server_${'x'.repeat(140)}__read`, mode: 'alias' },+ { name: '工具@read record', mode: 'alias' },+ { name: 'history@removed tool', mode: 'history-only' },+ { name: 'service.with.dots__read', mode: 'canonical-echo' },+ ])('roundtrips $name ($mode) without changing authorization identity', async ({ name, mode }) => {+ const request = {+ ...REQUEST,+ ...(mode === 'history-only'+ ? {}+ : { tools: [{ name, description: 'Read one record', parameters: { type: 'object' } }] }),+ messages: [+ ...REQUEST.messages,+ {+ role: 'assistant' as const,+ content: '',+ toolCalls: [{ id: 'previous', name, arguments: {} }],+ },+ { role: 'tool' as const, content: 'previous result', toolCallId: 'previous', name },+ ],+ }+ const requestHash = hashGrokCompletionRequestV1(request)+ expect(parseGrokCompletionRequestV1(request).ok).toBe(true)+ const original = structuredClone(request)+ const emitted: unknown[] = []+ const fetchFn = vi.fn(async (_url: unknown, init?: RequestInit) => {+ const body = JSON.parse(String(init?.body))+ const wireName = body.input.find(+ (item: { type?: string }) => item.type === 'function_call'+ ).name+ if (mode === 'history-only') expect(body.tools).toBeUndefined()+ else expect(body.tools[0].name).toBe(wireName)+ expect(wireName).toMatch(/^[A-Za-z0-9_-]{1,64}$/)+ expect(wireName).not.toBe(name)+ expect(body.input.find((item: { type?: string }) => item.type === 'function_call').name).toBe(+ wireName+ )+ expect(+ body.input.find((item: { type?: string }) => item.type === 'function_call_output')+ ).toEqual({+ type: 'function_call_output',+ call_id: 'previous',+ output: 'previous result',+ })+ return sseResponse([+ `data: ${JSON.stringify({+ type: 'response.output_item.done',+ item: {+ type: 'function_call',+ id: 'item-new',+ call_id: 'new-call',+ name: mode === 'canonical-echo' ? name : wireName,+ arguments: '{}',+ },+ })}\n\n`,+ 'data: {"type":"response.completed","response":{"usage":{}}}\n\n',+ ])+ })+ const result = await streamGrokCompletion({+ executionTicket: 'ticket-name-map',+ requestHash,+ request,+ ticket: {+ jti: 'name-map',+ hostRef: 'research-host',+ model: request.model,+ requestHash,+ providerAttemptId: 'att-name-map',+ },+ redeem: async () => redeemSuccess(),+ finalize: async () => ({+ providerAttemptId: 'att-name-map',+ outcome: 'success' as const,+ duplicate: false,+ }),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => emitted.push(frame),+ })+ expect(result.outcome).toBe('success')+ expect(emitted).toContainEqual({ type: 'tool_call', id: 'new-call', name, arguments: {} })+ expect(request).toEqual(original)+ expect(hashGrokCompletionRequestV1(request)).toBe(requestHash)+ })++ it('rejects an unregistered alias in a completed stream before emitting any calls', async () => {+ const emitted: unknown[] = []+ const finalize = vi.fn(async () => ({+ providerAttemptId: 'att-unknown-alias',+ outcome: 'error' as const,+ duplicate: false,+ }))+ const request = {+ ...REQUEST,+ tools: [{ name: 'known.read', description: 'Read a record', parameters: { type: 'object' } }],+ }+ const requestHash = hashGrokCompletionRequestV1(request)+ const fetchFn = vi.fn(async (_url: unknown, init?: RequestInit) => {+ const body = JSON.parse(String(init?.body))+ return sseResponse([+ ...[body.tools[0].name, '__grok_tool_unregistered'].map(+ (name, index) =>+ `data: ${JSON.stringify({+ type: 'response.output_item.done',+ item: { type: 'function_call', id: `call-${index}`, name, arguments: '{}' },+ })}\n\n`+ ),+ 'data: {"type":"response.completed"}\n\n',+ ])+ })+ await expect(+ streamGrokCompletion({+ executionTicket: 'ticket-unknown-alias',+ requestHash,+ request,+ ticket: {+ jti: 'unknown-alias',+ hostRef: 'research-host',+ model: request.model,+ requestHash,+ providerAttemptId: 'att-unknown-alias',+ },+ redeem: async () => redeemSuccess(),+ finalize,+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => emitted.push(frame),+ })+ ).rejects.toMatchObject({+ code: 'provider_unavailable',+ message: 'upstream returned an unknown tool name',+ })+ expect(fetchFn).toHaveBeenCalledOnce()+ expect(emitted).toEqual([])+ expect(finalize).toHaveBeenCalledWith(+ expect.objectContaining({+ receipt: expect.objectContaining({ outcome: 'error' }),+ })+ )+ })++ it('omits Notify-like generation fields on the Responses wire', async () => {+ const fetchFn = vi.fn(async () =>+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])+ )+ await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ const body = JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body)) as Record<string, unknown>+ expect(body.instructions).toBeUndefined()+ expect(body).not.toHaveProperty('max_output_tokens')+ expect(body).not.toHaveProperty('temperature')+ expect(body.store).toBe(false)+ expect(body.input).toEqual([{ role: 'user', content: 'hello' }])+ })++ it('keeps analysis instructions and binds max_output_tokens on the Grok wire', async () => {+ const request = {+ ...REQUEST,+ messages: [+ { role: 'system' as const, content: 'review this repository' },+ { role: 'user' as const, content: 'findings' },+ ],+ generation: { maxOutputTokens: 4096, temperature: 0.2 },+ }+ const requestHash = hashGrokCompletionRequestV1(request)+ const fetchFn = vi.fn(async () =>+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])+ )+ await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash,+ request,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ const body = JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body)) as Record<string, unknown>+ expect(body.instructions).toBe('review this repository')+ expect(body.input).toEqual([{ role: 'user', content: 'findings' }])+ expect(body.max_output_tokens).toBe(4096)+ expect(body.temperature).toBe(0.2)+ expect(body).not.toHaveProperty('text')+ expect(body).not.toHaveProperty('service_tier')+ })++ it('maps upstream 400 to invalid_request and finalizes error without usage', async () => {+ const finalize = vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'error' as const,+ duplicate: false,+ }))+ await expect(+ streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize,+ fetchFn: vi.fn(async () => new Response('bad request', { status: 400 })),+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ ).rejects.toMatchObject({ code: 'invalid_request' })+ expect(finalize).toHaveBeenCalledWith(+ expect.objectContaining({+ receipt: expect.objectContaining({ outcome: 'error' }),+ })+ )+ expect(finalize.mock.calls[0]?.[0]?.receipt?.usage).toBeUndefined()+ })++ it('emits a tool call only after argument deltas complete', async () => {+ const frames: unknown[] = []+ const fetchFn = vi.fn(async () =>+ sseResponse([+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","id":"item-1","call_id":"call-9","name":"lookup","arguments":""}}\n\n',+ 'data: {"type":"response.function_call_arguments.delta","item_id":"item-1","delta":"{\\"q\\":"}}\n\n',+ 'data: {"type":"response.function_call_arguments.delta","item_id":"item-1","delta":"\\"x\\"}"}\n\n',+ 'data: {"type":"response.function_call_arguments.done","item_id":"item-1","arguments":"{\\"q\\":\\"x\\"}"}\n\n',+ 'data: {"type":"response.completed","response":{"usage":{}}}\n\n',+ ])+ )+ await streamGrokCompletion({+ executionTicket: 'ticket-1',+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: 'jti-1',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: REQUEST_HASH,+ providerAttemptId: 'att-1',+ },+ redeem: async () => redeemSuccess(),+ finalize: vi.fn(async () => ({+ providerAttemptId: 'att-1',+ outcome: 'success',+ duplicate: false,+ })),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => frames.push(frame),+ })+ expect(frames).toEqual([+ { type: 'tool_call', id: 'call-9', name: 'lookup', arguments: { q: 'x' } },+ ])+ })+})diff --git a/grok-llm-proxy/test/grokUpstreamHeaders.test.ts b/grok-llm-proxy/test/grokUpstreamHeaders.test.tsnew file mode 100644index 000000000..561435565--- /dev/null+++ b/grok-llm-proxy/test/grokUpstreamHeaders.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest'+import { GROK_UPSTREAM_USER_AGENT, grokUpstreamHeaders } from '../src/grokUpstreamHeaders.js'++describe('grokUpstreamHeaders', () => {+ it('stamps Evenfire identity and does not impersonate the Grok CLI', () => {+ const headers = grokUpstreamHeaders('access-secret', { 'content-type': 'application/json' })+ expect(headers['user-agent']).toBe(GROK_UPSTREAM_USER_AGENT)+ expect(headers.accept).toBe('text/event-stream')+ expect(headers.authorization).toBe('Bearer access-secret')+ expect(headers['openai-beta']).toBeUndefined()+ expect(headers['x-xai-token-auth']).toBeUndefined()+ expect(headers['x-grok-client-identifier']).toBeUndefined()+ expect(JSON.stringify(headers)).not.toContain('grok-shell')+ expect(JSON.stringify(headers)).not.toMatch(/sk-|refresh-secret/i)+ })+})diff --git a/grok-llm-proxy/test/originPolicy.test.ts b/grok-llm-proxy/test/originPolicy.test.tsnew file mode 100644index 000000000..6fe55d9da--- /dev/null+++ b/grok-llm-proxy/test/originPolicy.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it } from 'vitest'+import {+ CATALOG_ORIGIN,+ COMPLETIONS_ORIGIN,+ TRANSPORT_PROTOCOL_VERSION,+} from '@clerum/grok-provider-attempt-contract'+import {+ GROK_CATALOG_ORIGIN,+ GROK_COMPLETIONS_ORIGIN,+ GROK_TRANSPORT_PROTOCOL,+ OriginDeniedError,+ assertAllowedUpstreamUrl,+ assertRedirectLocation,+ fetchFrozenOrigin,+ isBlockedAddress,+} from '../src/originPolicy.js'++const LOOPBACK_V4 = ['127', '0', '0', '1'].join('.')++describe('originPolicy', () => {+ it('enforces the Grok attempt-contract origin constants', () => {+ expect(GROK_COMPLETIONS_ORIGIN).toBe(COMPLETIONS_ORIGIN)+ expect(GROK_CATALOG_ORIGIN).toBe(CATALOG_ORIGIN)+ expect(GROK_TRANSPORT_PROTOCOL).toBe(TRANSPORT_PROTOCOL_VERSION)+ expect(GROK_COMPLETIONS_ORIGIN).toBe('https://cli-chat-proxy.grok.com/v1/responses')+ expect(GROK_CATALOG_ORIGIN).toBe('https://cli-chat-proxy.grok.com/v1/models')+ expect(GROK_CATALOG_ORIGIN).not.toContain('api.x.ai')+ })++ it('accepts only the frozen HTTPS catalog and completions URLs', () => {+ expect(assertAllowedUpstreamUrl(GROK_COMPLETIONS_ORIGIN, 'completions').href).toBe(+ GROK_COMPLETIONS_ORIGIN+ )+ expect(assertAllowedUpstreamUrl(GROK_CATALOG_ORIGIN, 'catalog').href).toBe(GROK_CATALOG_ORIGIN)+ })++ it('rejects caller-supplied, HTTP, billing, loopback, and metadata URLs', () => {+ expect(() =>+ assertAllowedUpstreamUrl('https://api.x.ai/v1/chat/completions', 'completions')+ ).toThrow(OriginDeniedError)+ expect(() => assertAllowedUpstreamUrl('http://cli-chat-proxy.grok.com/backend-api/grok/responses', 'completions')).toThrow(+ /origin_denied/+ )+ expect(() => assertAllowedUpstreamUrl(`https://${LOOPBACK_V4}/backend-api/grok/responses`, 'completions')).toThrow(+ OriginDeniedError+ )+ expect(() => assertAllowedUpstreamUrl('https://169.254.169.254/', 'catalog')).toThrow(OriginDeniedError)+ expect(isBlockedAddress('100.64.0.1')).toBe(true)+ expect(isBlockedAddress('198.18.0.1')).toBe(true)+ expect(isBlockedAddress('198.19.255.1')).toBe(true)+ expect(isBlockedAddress('64:ff9b::1')).toBe(true)+ expect(isBlockedAddress('ff02::1')).toBe(true)+ expect(() =>+ assertAllowedUpstreamUrl('https://cli-chat-proxy.grok.com/v1/responses?hijack=1', 'completions')+ ).toThrow(OriginDeniedError)+ expect(() =>+ assertAllowedUpstreamUrl('https://cli-chat-proxy.grok.com/v1/models?hijack=1', 'catalog')+ ).toThrow(OriginDeniedError)+ expect(() =>+ assertAllowedUpstreamUrl('https://api.x.ai/v1/responses', 'completions')+ ).toThrow(OriginDeniedError)+ })++ it('rejects cross-origin and private-address redirects', () => {+ expect(() =>+ assertRedirectLocation('https://evil.example/cb', new URL(GROK_COMPLETIONS_ORIGIN))+ ).toThrow(OriginDeniedError)+ expect(() =>+ assertRedirectLocation(`https://${LOOPBACK_V4}/loopback`, new URL(GROK_COMPLETIONS_ORIGIN))+ ).toThrow(OriginDeniedError)+ expect(() =>+ assertRedirectLocation('http://cli-chat-proxy.grok.com/backend-api/grok/responses', new URL(GROK_COMPLETIONS_ORIGIN))+ ).toThrow(OriginDeniedError)+ expect(+ assertRedirectLocation(+ 'https://cli-chat-proxy.grok.com/v1/responses',+ new URL(GROK_COMPLETIONS_ORIGIN)+ ).href+ ).toBe(GROK_COMPLETIONS_ORIGIN)+ })++ it('follows one frozen same-origin redirect and denies a second hop', async () => {+ let hops = 0+ const allowed = await fetchFrozenOrigin({+ url: new URL(GROK_COMPLETIONS_ORIGIN),+ init: { method: 'POST' },+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ fetchFn: (async () => {+ hops += 1+ if (hops === 1) {+ return new Response(null, {+ status: 307,+ headers: { location: GROK_COMPLETIONS_ORIGIN },+ })+ }+ return new Response('ok', { status: 200 })+ }) as unknown as typeof fetch,+ })+ expect(allowed.status).toBe(200)+ expect(hops).toBe(2)++ await expect(+ fetchFrozenOrigin({+ url: new URL(GROK_COMPLETIONS_ORIGIN),+ init: { method: 'POST' },+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ fetchFn: (async () =>+ new Response(null, {+ status: 302,+ headers: { location: GROK_COMPLETIONS_ORIGIN },+ })) as unknown as typeof fetch,+ })+ ).rejects.toBeInstanceOf(OriginDeniedError)+ })++ it('rejects DNS rebinding onto private or metadata addresses', async () => {+ const { assertResolvedUpstream } = await import('../src/originPolicy.js')+ await expect(+ assertResolvedUpstream(new URL(GROK_COMPLETIONS_ORIGIN), async () => [+ { address: '127.0.0.1', family: 4 },+ ])+ ).rejects.toBeInstanceOf(OriginDeniedError)+ await expect(+ assertResolvedUpstream(new URL(GROK_COMPLETIONS_ORIGIN), async () => [+ { address: '169.254.169.254', family: 4 },+ ])+ ).rejects.toBeInstanceOf(OriginDeniedError)+ await expect(+ assertResolvedUpstream(new URL(GROK_COMPLETIONS_ORIGIN), async () => [+ { address: '1.2.3.4', family: 4 },+ ])+ ).resolves.toBeUndefined()+ })+})diff --git a/grok-llm-proxy/test/redaction.test.ts b/grok-llm-proxy/test/redaction.test.tsnew file mode 100644index 000000000..9292b7512--- /dev/null+++ b/grok-llm-proxy/test/redaction.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest'+import { createProxyLogger, logger } from '../src/logger.js'++describe('proxy redaction', () => {+ it('strips access tokens, tickets, receipts, and authorization headers', () => {+ const messages: string[] = []+ const stream = {+ write(chunk: string) {+ messages.push(chunk)+ },+ }+ const probe = createProxyLogger(stream)+ probe.info({+ accessToken: 'sk-live-secret',+ refreshToken: 'rt-secret',+ device_code: 'device-secret',+ user_code: 'ABCD-EFGH',+ accountId: 'acct_live_secret',+ executionTicket: 'ticket-secret',+ attemptReceipt: 'receipt-secret',+ authorization: 'Bearer secret',+ headers: { authorization: 'Bearer secret' },+ event: 'grok_proxy_probe',+ })+ const joined = messages.join('\n')+ expect(joined).toContain('grok_proxy_probe')+ expect(joined).not.toContain('sk-live-secret')+ expect(joined).not.toContain('rt-secret')+ expect(joined).not.toContain('acct_live_secret')+ expect(joined).not.toContain('device-secret')+ expect(joined).not.toContain('ABCD-EFGH')+ expect(joined).not.toContain('ticket-secret')+ expect(joined).not.toContain('receipt-secret')+ expect(joined).not.toContain('Bearer secret')+ expect(logger.bindings()).toMatchObject({ svc: 'grok-llm-proxy' })+ })+})diff --git a/grok-llm-proxy/test/server.security.test.ts b/grok-llm-proxy/test/server.security.test.tsnew file mode 100644index 000000000..0e8b17263--- /dev/null+++ b/grok-llm-proxy/test/server.security.test.ts@@ -0,0 +1,284 @@+import { generateKeyPairSync } from 'node:crypto'+import jwt from 'jsonwebtoken'+import request from 'supertest'+import { describe, expect, it } from 'vitest'+import { verifyAdminPermit } from '../src/auth/adminPermitVerifier.js'+import { verifyExecutionTicket } from '../src/auth/executionTicketVerifier.js'+import { loadConfig, type GrokLlmProxyConfig } from '../src/config.js'+import { createProxyApps } from '../src/server.js'++const { privateKey, publicKey } = generateKeyPairSync('rsa', {+ modulusLength: 2048,+ publicKeyEncoding: { type: 'spki', format: 'pem' },+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+})++function config(overrides: Partial<GrokLlmProxyConfig> = {}): GrokLlmProxyConfig {+ return {+ runtimePort: 8080,+ adminPort: 8081,+ probePort: 9090,+ maxBodyBytes: 1024,+ maxStreamDurationMs: 300_000,+ maxDeadlineMs: 300_000,+ jwtIssuer: 'control-api',+ jwtPublicKey: publicKey,+ executionEnabled: true,+ controlApiBaseUrl: '',+ controlApiServiceName: 'grok-llm-proxy',+ controlApiServiceToken: '',+ ...overrides,+ }+}++function sign(payload: Record<string, unknown>, audience: string): string {+ return jwt.sign(payload, privateKey, {+ algorithm: 'RS256',+ issuer: 'control-api',+ audience,+ expiresIn: 60,+ })+}++function platformToken(overrides: Record<string, unknown> = {}): string {+ return sign(+ {+ sub: 'default/research-host',+ hostRefs: ['research-host'],+ workflowControlScopes: ['llm:grok:execute'],+ scope: 'workflow:approval:request',+ ...overrides,+ },+ 'workflow-approvals'+ )+}++function ticket(): string {+ return sign(+ {+ jti: '11111111-1111-4111-8111-111111111111',+ typ: 'grok-execution-ticket',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: 'a'.repeat(64),+ providerAttemptId: 'att-1',+ },+ 'grok-llm-proxy'+ )+}++function adminPermit(): string {+ return sign(+ { sub: 'admin-1', typ: 'grok-admin-permit', operation: 'catalog_list' },+ 'grok-llm-proxy-admin'+ )+}++describe('grok-llm-proxy security surface', () => {+ it('exposes only the frozen runtime, admin, and probe routes', async () => {+ const { runtimeApp, adminApp, probeApp } = createProxyApps(config())+ expect((await request(probeApp).get('/healthz')).status).toBe(200)+ expect((await request(probeApp).get('/readyz')).status).toBe(200)+ const metrics = await request(probeApp).get('/metrics')+ expect(metrics.status).toBe(200)+ expect(metrics.text).not.toMatch(/account|refresh|accessToken/i)+ expect((await request(runtimeApp).get('/internal/runtime/v1/grok/completions')).status).toBe(404)+ expect((await request(adminApp).get('/internal/admin/v1/grok/models')).status).toBe(404)+ })++ it('denies an admin permit on the runtime listener and a runtime ticket on admin', async () => {+ const { runtimeApp, adminApp } = createProxyApps(config())+ const runtime = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${adminPermit()}`)+ .send({ executionTicket: ticket(), requestHash: 'a'.repeat(64), request: {} })+ expect(runtime.status).toBe(403)+ expect(runtime.body.error).toBe('insufficient_scope')++ const admin = await request(adminApp)+ .post('/internal/admin/v1/grok/models')+ .set('Authorization', `Bearer ${ticket()}`)+ .send({})+ expect(admin.status).toBe(403)+ expect(admin.body.error).toBe('insufficient_scope')+ })++ it('rejects unknown fields, invalid deadlines, and incorrect content types', async () => {+ const { runtimeApp } = createProxyApps(config())+ const unknown = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${platformToken()}`)+ .send({+ executionTicket: ticket(),+ requestHash: 'a'.repeat(64),+ request: {},+ extra: true,+ })+ expect(unknown.body.error).toBe('unknown_field')++ const deadline = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${platformToken()}`)+ .send({+ executionTicket: ticket(),+ requestHash: 'a'.repeat(64),+ request: {},+ deadlineMs: 999_999,+ })+ expect(deadline.body.error).toBe('invalid_request')++ const ctype = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${platformToken()}`)+ .set('Content-Type', 'text/plain')+ .send('not-json')+ expect(ctype.status).toBe(415)+ })++ it('rejects an oversized body before invoking the completion path', async () => {+ const { runtimeApp } = createProxyApps(config({ maxBodyBytes: 32 }))+ const res = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${platformToken()}`)+ .send({+ executionTicket: ticket(),+ requestHash: 'a'.repeat(64),+ request: { pad: 'x'.repeat(200) },+ })+ expect(res.status).toBe(413)+ })++ it('rejects a platform JWT whose hostRefs do not bind the ticket hostRef', async () => {+ const { runtimeApp } = createProxyApps(config())+ const foreign = sign(+ {+ sub: 'default/other-host',+ hostRefs: ['other-host'],+ workflowControlScopes: ['llm:grok:execute'],+ scope: 'workflow:approval:request',+ },+ 'workflow-approvals'+ )+ const res = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${foreign}`)+ .send({+ executionTicket: ticket(),+ requestHash: 'a'.repeat(64),+ request: {},+ })+ expect(res.status).toBe(403)+ expect(res.body.error).toBe('host_binding_mismatch')+ })++ it('rejects a refresh JWT that otherwise carries llm:grok:execute', async () => {+ const { runtimeApp } = createProxyApps(config())+ const res = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${platformToken({ scope: 'workflow:approval:refresh' })}`)+ .send({+ executionTicket: ticket(),+ requestHash: 'a'.repeat(64),+ request: {},+ })+ expect(res.status).toBe(401)+ expect(res.body.error).toBe('Unauthorized')+ })++ it('rejects a platform JWT that omits the access-token scope', async () => {+ const { runtimeApp } = createProxyApps(config())+ const missingScope = sign(+ {+ sub: 'default/research-host',+ hostRefs: ['research-host'],+ workflowControlScopes: ['llm:grok:execute'],+ },+ 'workflow-approvals'+ )+ const res = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${missingScope}`)+ .send({+ executionTicket: ticket(),+ requestHash: 'a'.repeat(64),+ request: {},+ })+ expect(res.status).toBe(401)+ expect(res.body.error).toBe('Unauthorized')+ })++ it('rejects a platform JWT whose hostRefs is a wildcard', async () => {+ const { runtimeApp } = createProxyApps(config())+ const wildcard = sign(+ {+ sub: 'default/research-host',+ hostRefs: ['*'],+ workflowControlScopes: ['llm:grok:execute'],+ scope: 'workflow:approval:request',+ },+ 'workflow-approvals'+ )+ const res = await request(runtimeApp)+ .post('/internal/runtime/v1/grok/completions')+ .set('Authorization', `Bearer ${wildcard}`)+ .send({+ executionTicket: ticket(),+ requestHash: 'a'.repeat(64),+ request: {},+ })+ expect(res.status).toBe(401)+ })++ it('rejects execution tickets and admin permits without a numeric exp', () => {+ const cfg = config()+ const ticketNoExp = jwt.sign(+ {+ jti: '11111111-1111-4111-8111-111111111111',+ typ: 'grok-execution-ticket',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash: 'a'.repeat(64),+ providerAttemptId: 'att-1',+ },+ privateKey,+ { algorithm: 'RS256', issuer: 'control-api', audience: 'grok-llm-proxy' }+ )+ const permitNoExp = jwt.sign(+ { sub: 'admin-1', typ: 'grok-admin-permit', operation: 'catalog_list' },+ privateKey,+ { algorithm: 'RS256', issuer: 'control-api', audience: 'grok-llm-proxy-admin' }+ )+ expect(verifyExecutionTicket(ticketNoExp, cfg)).toBeNull()+ expect(verifyAdminPermit(permitNoExp, cfg)).toBeNull()+ })++ it('rejects an admin permit whose operation does not match the route', async () => {+ const { adminApp } = createProxyApps(config())+ const wrong = sign(+ { sub: 'admin-1', typ: 'grok-admin-permit', operation: 'connection_test' },+ 'grok-llm-proxy-admin'+ )+ const res = await request(adminApp)+ .post('/internal/admin/v1/grok/models')+ .set('Authorization', `Bearer ${wrong}`)+ .send({ accessToken: 'tok' })+ expect(res.status).toBe(401)+ })++ it('rejects missing, zero, and unbounded config', () => {+ expect(() => loadConfig({ GROK_LLM_PROXY_RUNTIME_PORT: '0' })).toThrow(/greater than zero/)+ expect(() =>+ loadConfig({+ GROK_LLM_PROXY_JWT_PUBLIC_KEY: publicKey,+ GROK_LLM_PROXY_MAX_BODY_BYTES: '0',+ })+ ).toThrow(/greater than zero/)+ expect(() => loadConfig({})).toThrow(/PEM-encoded public key/)+ expect(() =>+ loadConfig({+ GROK_LLM_PROXY_JWT_PUBLIC_KEY: publicKey,+ GROK_LLM_PROXY_MAX_STREAM_DURATION_MS: String(Number.MAX_SAFE_INTEGER),+ })+ ).toThrow(/bounded positive integer/)+ })+})diff --git a/grok-llm-proxy/test/toolNameMap.test.ts b/grok-llm-proxy/test/toolNameMap.test.tsnew file mode 100644index 000000000..6958ee5a1--- /dev/null+++ b/grok-llm-proxy/test/toolNameMap.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it, vi } from 'vitest'+import { createHash } from 'node:crypto'+import { ToolNameMap } from '../src/toolNameMap.js'++vi.mock('node:crypto', async importOriginal => {+ const actual = await importOriginal<typeof import('node:crypto')>()+ return { ...actual, createHash: vi.fn(actual.createHash) }+})++describe('ToolNameMap', () => {+ it('preserves compliant names and reverses opaque canonical names', () => {+ const names = [+ 'tool_A-2',+ 'x'.repeat(64),+ 'files.read',+ 'mcp:lookup',+ 'x'.repeat(129),+ 'tool name',+ '工具@read',+ ]+ const map = new ToolNameMap(names)+ for (const name of names) {+ expect(map.toWire(name)).toMatch(/^[A-Za-z0-9_-]{1,64}$/)+ expect(map.fromWire(map.toWire(name))).toBe(name)+ }+ expect(map.toWire(names[0])).toBe(names[0])+ expect(map.toWire(names[1])).toBe(names[1])+ expect(new Set(names.map(name => map.toWire(name))).size).toBe(names.length)+ })+ it('is stable across order, duplicate history, and unrelated inventory additions', () => {+ const names = ['files.read', 'history:removed', 'safe']+ const first = new ToolNameMap(names)+ const next = new ToolNameMap(['other:new', ...names.toReversed(), ...names])+ for (const name of names) expect(next.toWire(name)).toBe(first.toWire(name))+ })+ it('reserves legitimate alias-shaped canonical names and occupied suffixes', () => {+ const canonical = 'files.read'+ const base = new ToolNameMap([canonical]).toWire(canonical)+ const names = [canonical, base, `${base}_0`, `${base}_1`]+ const first = new ToolNameMap(names)+ const reversed = new ToolNameMap(names.toReversed())+ expect(first.toWire(canonical)).toBe(`${base}_2`)+ for (const name of names) {+ expect(first.fromWire(first.toWire(name))).toBe(name)+ expect(reversed.toWire(name)).toBe(first.toWire(name))+ }+ expect(first.toWire(base)).toBe(base)+ })+ it('resolves hash collisions with distinct bounded candidates', () => {+ const hash = { update: () => hash, digest: () => 'a'.repeat(64) }+ vi.mocked(createHash).mockReturnValueOnce(hash as unknown as ReturnType<typeof createHash>)+ vi.mocked(createHash).mockReturnValueOnce(hash as unknown as ReturnType<typeof createHash>)+ const map = new ToolNameMap(['a.b', 'a:b'])+ expect(map.toWire('a:b')).toBe(`${map.toWire('a.b')}_0`)+ expect(map.fromWire(map.toWire('a.b'))).toBe('a.b')+ expect(map.fromWire(map.toWire('a:b'))).toBe('a:b')+ })+ it('accepts exact registered canonical echoes', () => {+ const name = '工具@read record'+ const map = new ToolNameMap([name])+ expect(map.fromWire(name)).toBe(name)+ expect(map.fromWire(`${name} extra`)).toBeUndefined()+ })+ it('does not manufacture canonical targets from unknown aliases or unsafe names', () => {+ const map = new ToolNameMap(['files.read'])+ expect(map.fromWire('__grok_tool_unknown')).toBeUndefined()+ expect(map.fromWire('unknown.read')).toBeUndefined()+ expect(map.fromWire('ordinary_unknown')).toBe('ordinary_unknown')+ expect(() => map.toWire('missing')).toThrow('Unknown canonical tool name')+ })+})diff --git a/grok-llm-proxy/tsconfig.build.json b/grok-llm-proxy/tsconfig.build.jsonnew file mode 100644index 000000000..44b9b1ebd--- /dev/null+++ b/grok-llm-proxy/tsconfig.build.json@@ -0,0 +1,7 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": false+ },+ "exclude": ["node_modules", "dist", "test"]+}diff --git a/grok-llm-proxy/tsconfig.json b/grok-llm-proxy/tsconfig.jsonnew file mode 100644index 000000000..39c9ade7f--- /dev/null+++ b/grok-llm-proxy/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": true,+ "sourceMap": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist", "test"]+}diff --git a/grok-llm-proxy/vitest.config.ts b/grok-llm-proxy/vitest.config.tsnew file mode 100644index 000000000..642ffdf27--- /dev/null+++ b/grok-llm-proxy/vitest.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ include: ['test/**/*.test.ts'],+ pool: 'forks',+ },+})diff --git a/scripts/build-preflight.sh b/scripts/build-preflight.shindex 19064f37e..8876bbba2 100755--- a/scripts/build-preflight.sh+++ b/scripts/build-preflight.sh@@ -34,6 +34,7 @@ PACKAGES=("mcp-proxy""control-api""codex-llm-proxy"+ "grok-llm-proxy""external-rest-api""rpc-proxy""channel-reader"diff --git a/scripts/minikube/build-images.sh b/scripts/minikube/build-images.shindex fd29f75ff..0f16fed35 100755--- a/scripts/minikube/build-images.sh+++ b/scripts/minikube/build-images.sh@@ -318,6 +318,7 @@ ALL_IMAGES=("clerum/rpc-proxy:test""clerum/webhook-proxy:test""clerum/codex-llm-proxy:test"+ "clerum/grok-llm-proxy:test""clerum/webhook-gateway:test""clerum/channel-reader:test""clerum/workflow-approval-request-reader:test"@@ -347,6 +348,7 @@ KNOWN_BUILD_NAMES=(rpc-proxywebhook-proxycodex-llm-proxy+ grok-llm-proxywebhook-gatewaychannel-readerworkflow-approval-request-reader@@ -1214,6 +1216,11 @@ build_image "codex-llm-proxy" \"clerum/codex-llm-proxy:test" \"${PROJECT_DIR}/codex-llm-proxy/Dockerfile"+build_image "grok-llm-proxy" \+ "${PROJECT_DIR}" \+ "clerum/grok-llm-proxy:test" \+ "${PROJECT_DIR}/grok-llm-proxy/Dockerfile"+if [ "$ONLY_SVC" = codex-approved-tools-control-api-e2e ]; thenbuild_image codex-approved-tools-control-api-e2e "${PROJECT_DIR}" \clerum/codex-approved-tools-control-api-e2e:test \diff --git a/scripts/minikube/pre-gate-incremental.sh b/scripts/minikube/pre-gate-incremental.shindex 4acfd07a1..def390395 100755--- a/scripts/minikube/pre-gate-incremental.sh+++ b/scripts/minikube/pre-gate-incremental.sh@@ -208,6 +208,7 @@ incremental_classify_path() {profile-ui/*) incremental_add_target profile-ui profiles profile-ui ;;webhook-proxy/*) incremental_add_target webhook-proxy webhook-ingress webhook-proxy ;;codex-llm-proxy/*) incremental_add_target codex-llm-proxy control-plane codex-llm-proxy ;;+ grok-llm-proxy/*) incremental_add_target grok-llm-proxy control-plane grok-llm-proxy ;;tests/e2e/fixtures/workflow-plugin-sdk-e2e/*)incremental_add_target workflow-plugin-sdk-e2e sandbox-recipes workflow-plugin-sdk-e2e;;diff --git a/scripts/tests/test-grok-llm-proxy-deploy-contract.sh b/scripts/tests/test-grok-llm-proxy-deploy-contract.shnew file mode 100755index 000000000..3db25f242--- /dev/null+++ b/scripts/tests/test-grok-llm-proxy-deploy-contract.sh@@ -0,0 +1,165 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+FAIL=0+pass() { echo "PASS: $1"; }+fail() { echo "FAIL: $1"; FAIL=1; }++MANIFEST="$ROOT/deploy/base/control-plane/grok-llm-proxy.yaml"+KUSTOMIZE="$ROOT/deploy/base/control-plane/kustomization.yaml"+BASE_KUSTOMIZE="$ROOT/deploy/base/kustomization.yaml"+CONFIGMAPS="$ROOT/deploy/base/control-plane/configmaps.yaml"+RBAC="$ROOT/deploy/base/control-plane/rbac.yaml"+NETWORKPOLICIES="$ROOT/deploy/base/control-plane/networkpolicies.yaml"+TOKENS="$ROOT/deploy/scripts/apply-inter-service-tokens.sh"+IMAGES="$ROOT/deploy/images.json"+BUILD_IMAGES="$ROOT/scripts/minikube/build-images.sh"+WORKFLOW="$ROOT/.github/workflows/build-publish.yml"+CI_PUBLIC="$ROOT/.github/workflows/ci-public.yml"+GHCR="$ROOT/deploy/components/ghcr-images/kustomization.yaml"+MINIKUBE="$ROOT/deploy/overlays/minikube/kustomization.yaml"+SECRETS="$ROOT/deploy/base/control-plane/secrets-canary.yaml"+PREFLIGHT="$ROOT/scripts/build-preflight.sh"+INCREMENTAL="$ROOT/scripts/minikube/pre-gate-incremental.sh"++if [[ ! -f "$MANIFEST" ]]; then+ fail "missing $MANIFEST"+ exit 1+fi++python3 - "$MANIFEST" "$KUSTOMIZE" "$BASE_KUSTOMIZE" "$CONFIGMAPS" "$RBAC" "$NETWORKPOLICIES" "$TOKENS" "$IMAGES" "$BUILD_IMAGES" "$WORKFLOW" "$CI_PUBLIC" "$GHCR" "$MINIKUBE" "$SECRETS" "$PREFLIGHT" "$INCREMENTAL" <<'PY'+import json, pathlib, re, sys++(+ manifest, kustomize, base_kustomize, configmaps, rbac, networkpolicies, tokens, images,+ build_images, workflow, ci_public, ghcr, minikube, secrets, preflight, incremental,+) = map(pathlib.Path, sys.argv[1:])+errors = []++text = manifest.read_text()+for needle in (+ "kind: Deployment",+ "kind: Service",+ "kind: ServiceAccount",+ "name: grok-llm-proxy",+ "automountServiceAccountToken: false",+ "type: ClusterIP",+ "name: runtime",+ "name: admin",+ "name: metrics",+ "readOnlyRootFilesystem: true",+ "runAsNonRoot: true",+ "type: RuntimeDefault",+ "drop: [ALL]",+ "GROK_LLM_PROXY_JWT_PUBLIC_KEY",+ "GROK_LLM_PROXY_CONTROL_API_TOKEN",+ "GROK_LLM_PROXY_EXECUTION_ENABLED",+ "control-api-rpc-gateway.control-plane.svc",+):+ if needle not in text:+ errors.append(f"manifest missing {needle}")++if "kind: Role" in text or "kind: RoleBinding" in text:+ errors.append("proxy manifest must not declare Role/RoleBinding")+if "automountServiceAccountToken: true" in text:+ errors.append("proxy must not automount a service account token")+if "type: LoadBalancer" in text or "type: NodePort" in text:+ errors.append("proxy Service must stay ClusterIP")+if "DATABASE_URL" in text or "POSTGRES" in text:+ errors.append("proxy must not carry database credentials")+if "CONTROL_API_INTERNAL_SERVICE_TOKENS" in text:+ errors.append("proxy must not receive the full token map")++if "grok-llm-proxy.yaml" not in kustomize.read_text():+ errors.append("kustomization does not include grok-llm-proxy.yaml")++cm = configmaps.read_text()+if "location = /api/v1/internal/llm/grok/provider-attempts/redeem" not in cm:+ errors.append("rpc gateway missing exact Grok redeem location")+if "location = /api/v1/internal/llm/grok/provider-attempts/finalize" not in cm:+ errors.append("rpc gateway missing exact Grok finalize location")+if re.search(r"location\s+/api/v1/internal/llm/grok", cm):+ errors.append("Grok redeem/finalize paths must stay exact-match, not a prefix wildcard")+if "CONTROL_API_GROK_SUBSCRIPTION_ENABLED: 'false'" not in cm:+ errors.append("base control-api config must keep Grok subscription disabled")+if cm.count("location / {\n return 403;") < 2:+ errors.append("gateways must keep catch-all 403")++np = networkpolicies.read_text()+if "name: grok-llm-proxy-ingress" not in np or "name: grok-llm-proxy-egress" not in np:+ errors.append("networkpolicies missing grok-llm-proxy ingress/egress")+if "app: grok-llm-proxy" not in np[np.find("name: control-api-rpc-gateway"): np.find("name: grok-llm-proxy-ingress") if "name: grok-llm-proxy-ingress" in np else len(np)]:+ gateway = np[np.find("name: control-api-rpc-gateway"):]+ if "app: grok-llm-proxy" not in gateway.split("egress:", 1)[0]:+ errors.append("rpc gateway ingress must admit app: grok-llm-proxy")+if "name: grok-llm-proxy-egress" not in base_kustomize.read_text():+ errors.append("base kustomization must fill grok-llm-proxy-egress except")++token_src = tokens.read_text()+if "grok-llm-proxy=${TOKEN_GROK_LLM_PROXY}" not in token_src:+ errors.append("apply-inter-service-tokens.sh must project a dedicated grok-llm-proxy token")+if "grok-llm-proxy-secrets" not in token_src:+ errors.append("proxy must receive only its dedicated secret, not the full token map")+if "codex-llm-proxy and grok-llm-proxy tokens must be distinct" not in token_src:+ errors.append("token script must refuse equal Codex and Grok tokens")++if "name: grok-llm-proxy-secrets" not in secrets.read_text():+ errors.append("secrets-canary.yaml missing grok-llm-proxy-secrets")++manifest_json = json.loads(images.read_text())+row = next((item for item in manifest_json["images"] if item["name"] == "grok-llm-proxy"), None)+if not row:+ errors.append("images.json missing grok-llm-proxy")+else:+ paths = row.get("source_paths") or []+ if "grok-llm-proxy/**" not in paths:+ errors.append("images.json must watch grok-llm-proxy/**")+ if "packages/grok-provider-attempt-contract/**" not in paths:+ errors.append("images.json must watch packages/grok-provider-attempt-contract/**")++for consumer in ("control-api", "mcp-host", "mcp-host-slim", "mcp-host-full", "mcp-host-desktop"):+ item = next((entry for entry in manifest_json["images"] if entry["name"] == consumer), None)+ if not item:+ errors.append(f"images.json missing {consumer}")+ continue+ if "packages/grok-provider-attempt-contract/**" not in (item.get("source_paths") or []):+ errors.append(f"{consumer} source_paths must include packages/grok-provider-attempt-contract/**")++build = build_images.read_text()+if "clerum/grok-llm-proxy:test" not in build:+ errors.append("build-images.sh missing clerum/grok-llm-proxy:test")+if 'build_image "grok-llm-proxy"' not in build:+ errors.append("build-images.sh missing build_image grok-llm-proxy")++wf = workflow.read_text()+if "- image: grok-llm-proxy" not in wf:+ errors.append("build-publish.yml missing matrix image")+if "packages/grok-provider-attempt-contract/**" not in wf:+ errors.append("build-publish.yml filters must watch the Grok attempt contract")+if "- grok-llm-proxy" not in ci_public.read_text():+ errors.append("ci-public.yml missing grok-llm-proxy")+if "clerum/grok-llm-proxy" not in ghcr.read_text():+ errors.append("ghcr-images component missing rewrite")+if "clerum/grok-llm-proxy" not in minikube.read_text():+ errors.append("minikube overlay images: missing grok-llm-proxy")+if "configmaps/grok-llm-proxy-config.yaml" not in minikube.read_text():+ errors.append("minikube overlay missing grok-llm-proxy config sibling")+if '"grok-llm-proxy"' not in preflight.read_text():+ errors.append("build-preflight.sh missing grok-llm-proxy")+if "grok-llm-proxy/*" not in incremental.read_text():+ errors.append("pre-gate-incremental.sh missing grok-llm-proxy")++if errors:+ print("\n".join(errors))+ sys.exit(1)+print("ok")+PY++if [[ $? -eq 0 ]]; then+ pass "grok-llm-proxy deploy contract"+else+ fail "grok-llm-proxy deploy contract"+fi++exit "$FAIL"diff --git a/scripts/tests/test-grok-subscription-t0.sh b/scripts/tests/test-grok-subscription-t0.shnew file mode 100755index 000000000..72e1e93af--- /dev/null+++ b/scripts/tests/test-grok-subscription-t0.sh@@ -0,0 +1,118 @@+#!/usr/bin/env bash+# Wave-2 Grok subscription T0 aggregator.+# Fails when a required suite is missing, executes zero tests, reports+# skipped/todo cases, or exits non-zero.+set -u++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+FAIL=0+GROUPS_RUN=0++pass() { echo "PASS: $1"; }+fail() { echo "FAIL: $1"; FAIL=1; }++require_file() {+ local rel="$1"+ if [[ ! -f "${ROOT}/${rel}" ]]; then+ fail "missing required suite ${rel}"+ return 1+ fi+ return 0+}++strip_ansi() {+ sed $'s/\033\\[[0-9;]*m//g'+}++assert_executed_counts() {+ local name="$1"+ local log="$2"+ local normalized+ normalized="$(mktemp)"+ strip_ansi <"$log" >"$normalized"++ local vitest_passed+ vitest_passed="$(+ grep -Eo 'Tests[[:space:]]+[1-9][0-9]* passed' "$normalized" | head -n 1 || true+ )"+ local node_pass+ node_pass="$(+ grep -E 'pass[[:space:]]+[1-9][0-9]*$' "$normalized" | awk '{print $NF}' | tail -n 1 || true+ )"++ if [[ -z "${vitest_passed}" && -z "${node_pass}" ]]; then+ fail "${name}: executed zero passing tests"+ echo "----- ${name} reporter -----"+ cat "$normalized"+ rm -f "$normalized"+ return 1+ fi++ if grep -Eq '(Test Files|Tests).*[1-9][0-9]* skipped' "$normalized"; then+ fail "${name}: Vitest reported skipped tests"+ rm -f "$normalized"+ return 1+ fi+ if grep -Eiq 'no test files|no tests found' "$normalized"; then+ fail "${name}: reporter found no tests"+ rm -f "$normalized"+ return 1+ fi++ rm -f "$normalized"+ return 0+}++run_group() {+ local name="$1"+ shift+ GROUPS_RUN=$((GROUPS_RUN + 1))+ local log+ log="$(mktemp)"+ if "$@" >"$log" 2>&1; then+ if assert_executed_counts "$name" "$log"; then+ pass "$name"+ fi+ else+ fail "$name"+ echo "----- ${name} -----"+ cat "$log"+ fi+ rm -f "$log"+}++require_file packages/grok-provider-attempt-contract/index.test.cjs+require_file grok-llm-proxy/test/contractFreeze.test.ts+require_file grok-llm-proxy/test/originPolicy.test.ts+require_file control-api/test/services.grokSubscriptionOAuth.test.ts+require_file control-api/test/services.grokProviderAttemptRedemption.test.ts+require_file control-api/test/db.grokSubscriptionMigration.test.ts+require_file scripts/tests/test-grok-llm-proxy-deploy-contract.sh+require_file tests/e2e/fixtures/grok-subscription/sanitized-upstream-contract.json++run_group "grok-provider-attempt-contract" \+ bash -lc "cd '${ROOT}/packages/grok-provider-attempt-contract' && node --test index.test.cjs"++run_group "grok-llm-proxy freeze+origin" \+ bash -lc "cd '${ROOT}/grok-llm-proxy' && npx vitest run test/contractFreeze.test.ts test/originPolicy.test.ts --no-file-parallelism"++run_group "control-api grok grant/oauth/redeem" \+ bash -lc "cd '${ROOT}/control-api' && npx vitest run test/db.grokSubscriptionMigration.test.ts test/services.grokSubscriptionConnection.test.ts test/services.grokSubscriptionOAuth.test.ts test/services.grokSubscriptionCatalog.test.ts test/services.grokProviderAttemptRedemption.test.ts --no-file-parallelism"++if ! bash "${ROOT}/scripts/tests/test-grok-llm-proxy-deploy-contract.sh"; then+ fail "grok-llm-proxy deploy contract"+else+ GROUPS_RUN=$((GROUPS_RUN + 1))+ pass "grok-llm-proxy deploy contract"+fi++if [[ "$GROUPS_RUN" -lt 4 ]]; then+ fail "T0 ran too few groups (${GROUPS_RUN})"+fi++if [[ "$FAIL" -ne 0 ]]; then+ echo "FAIL: grok subscription T0"+ exit 1+fi+echo "PASS: grok subscription T0 (${GROUPS_RUN} groups)"+exit 0diff --git a/tests/e2e/fixtures/grok-subscription/sanitized-upstream-contract.json b/tests/e2e/fixtures/grok-subscription/sanitized-upstream-contract.jsonnew file mode 100644index 000000000..f8f4fb599--- /dev/null+++ b/tests/e2e/fixtures/grok-subscription/sanitized-upstream-contract.json@@ -0,0 +1,85 @@+{+ "protocolVersion": "grok-subscription-transport.v1",+ "providerId": "grok-subscription",+ "authMode": "oauth-broker",+ "modelCatalogMode": "dynamic",+ "supportedOperations": [+ "oauth_device",+ "oauth_refresh",+ "oauth_revoke",+ "oauth_reconnect",+ "catalog_list",+ "completion_stream",+ "completion_cancel",+ "connection_test"+ ],+ "origins": {+ "oauthDevice": "https://auth.x.ai/oauth2/device/code",+ "oauthToken": "https://auth.x.ai/oauth2/token",+ "oauthRevoke": "https://auth.x.ai/oauth2/revoke",+ "catalog": "https://cli-chat-proxy.grok.com/v1/models",+ "completions": "https://cli-chat-proxy.grok.com/v1/responses"+ },+ "forbiddenOrigins": [+ "https://api.x.ai",+ "https://api.x.ai/v1/chat/completions",+ "http://auth.x.ai/oauth2/token",+ "https://[::1]/",+ "https://169.254.169.254/"+ ],+ "redirectPolicy": {+ "allowHttp": false,+ "allowCrossOrigin": false,+ "allowPrivateAddresses": false,+ "sameOriginPathQuery": true,+ "oauthRedirect": "manual"+ },+ "oauthScopes": [+ "openid",+ "profile",+ "email",+ "offline_access",+ "grok-cli:access",+ "api:access",+ "conversations:read",+ "conversations:write"+ ],+ "oauthClientId": "b1a00492-073a-47ea-816f-4c329264a828",+ "identityHeaders": {+ "user-agent": "evenfire-grok-subscription",+ "cliImpersonation": false+ },+ "limits": {+ "maxRequestBodyBytes": 1048576,+ "maxMessages": 128,+ "maxToolCalls": 64,+ "maxOutputTokens": 16384,+ "maxStreamDurationMs": 300000,+ "maxDeadlineMs": 300000,+ "maxConcurrentStreams": 8,+ "maxQueuedRequests": 16,+ "maxRetriesPerAttempt": 1+ },+ "errorTaxonomy": [+ "insufficient_scope",+ "no_grant",+ "unassigned_connection",+ "model_not_allowed",+ "budget_denied",+ "connection_unavailable",+ "provider_unavailable",+ "origin_denied",+ "ticket_invalid",+ "ticket_replayed",+ "request_hash_mismatch",+ "fingerprint_in_use",+ "reauth_required",+ "disabled"+ ],+ "termsAndTestAccount": {+ "automationAuthorized": false,+ "approvedTestAccountFingerprint": "redacted:grok-subscription-pending-live-confirm",+ "evidenceHash": "sha256:grok-subscription-transport.v1-phase0-evenfire-identity-2026-09-16",+ "liveAccountConfirmation": "GROK_REAL_UPSTREAM_CONFIRM"+ }+}diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.jsonindex 3c9437eab..7a82748ab 100644--- a/tests/e2e/fixtures/package-lock.json+++ b/tests/e2e/fixtures/package-lock.json@@ -1,12 +1,12 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.78",+ "version": "1.0.79","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/e2e-test-fixtures",- "version": "1.0.78",+ "version": "1.0.79","dependencies": {"@kubernetes/client-node": "^1.0.0"},diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.jsonindex 9729e9f7e..d27887f99 100644--- a/tests/e2e/fixtures/package.json+++ b/tests/e2e/fixtures/package.json@@ -1,6 +1,6 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.78",+ "version": "1.0.79","description": "E2E test fixtures and utilities for Clerum testing","type": "module","main": "index.ts",