Skip to content

armgit / fx0

Public Imported from GitHub
0

A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.

TypeScript

Bill every paid turn to the login and team that sent it

Pranit6266830bbcaa
diff --git a/README.md b/README.md
index 9249de5..97ac003 100644
--- a/README.md
+++ b/README.md
@@ -85,7 +85,7 @@ fx0 keeps the transcript, designs and settings in Redis. Here is one message fro
**1. Save the message before answering.** `POST /api/prompt` adds the message to the transcript in one Redis script, then hands it to libfx with its message id. libfx stores it before acknowledging, so a message that shows as sent can't be lost, and a retried request reaches the same turn.
-**2. Keep the turn's funding.** A queue delivery has no browser cookie, so the prompt route seals its funding in Redis. Paid-only chats use the sender's OAuth grant. A trial chat records each turn's funding separately: either the admitted sponsorship or its paid sender and team. Fresh SDK diagnostics and the journal's restore hook identify the executing turn after a crash. Refresh tokens stay in the cookie, and the server trial key stays out of every stored credential. Missing or expired trial funding never falls back to a customer's paid grant.
+**2. Keep the turn's funding.** A queue delivery has no browser cookie, so the prompt route seals its funding in Redis. Every message records the funding of the turn it starts: either the admitted sponsorship or its paid sender's OAuth grant and team. Fresh SDK diagnostics and the journal's restore hook identify the executing turn after a crash. Refresh tokens stay in the cookie, and the server trial key stays out of every stored credential. Missing or expired trial funding never falls back to a customer's paid grant.
**3. libfx runs the turn.** One worker holds a session at a time, and libfx fences out any other. The prompt request runs the turn first; it and each delivery to `/api/libfx` can run for 800 seconds, their `maxDuration`. libfx stops a turn 30 seconds before that limit, keeping what it has done so far, and a delivery to `/api/libfx` continues it, so a long turn spans several invocations.
@@ -109,7 +109,7 @@ You can watch this happen. Open session diagnostics from the header to see the c
- If a prompt request crashes while it runs its turn, for example by running out of memory, the turn continues about 13 minutes after the send, however early the crash came. On Vercel, libfx can't tell a crashed function from a slow one, so a crashed request still holds the session until its 800-second limit, and the prompt's backstop takes over 5 seconds later. The page keeps showing the reply as running meanwhile. A turn that only runs long isn't affected: libfx stops it 30 seconds before the limit and queues the rest at once for a delivery to `/api/libfx`.
- A text message sent while a tool runs, such as while a design is being written, waits for that tool before the model sees it. A message with images runs as its own turn, after any running turn finishes.
-- Paid-only chats use the latest stored user credential. Trial chats pin funding per turn; a later paid input cannot change an earlier free turn's funding. Token renewal keeps the original paid turn's billing team.
+- Every turn bills the login and team that sent the message that started it; a later message cannot change an earlier turn's funding. A text message that joins a running turn is billed to that turn. Token renewal from the same login keeps the turn's billing team.
- Free prompts start in a new design on Opus 5.5 Fast with low effort. Existing paid-only chats keep their own billing. The allowance is five per IP across chats and browsers, with no periodic refill; clearing cookies does not reset it. After it is used, sign in to continue with your own team.
- A design being written streams through a bounded, expiring Redis channel, so viewers on other instances can see it too. Reconnecting resumes from the full prefix; generation IDs and offsets prevent duplicated bytes. The provisional preview strips active markup and runs without scripts. Publishing or ending a turn closes its draft before it can replace the finished preview.
- Deleting a chat removes fx0's records and credential. libfx's session data expires with the World's retention.
@@ -178,7 +178,7 @@ The auth and route tests mock Vercel, AI Gateway and both databases, so check a
Generated pages run in a sandboxed iframe on an opaque origin. They can't read the app's cookies, storage or credentials, and their Content Security Policy blocks network requests (`connect-src 'none'`). It's still the browser enforcing all of this, though, not a sealed VM.
-Paid model requests carry the sender's OAuth token only to AI Gateway. Between requests it stays sealed in Redis and expires with the token. Sponsored requests require a recorded trial admission; the server key is never sent to a browser, cookie, journal or model prompt. Signing out deletes that login's stored credentials, revokes its token and cancels its running turns. Treat the session cookie and `SESSION_SECRET` as credentials.
+Paid model requests carry the sender's OAuth token only to AI Gateway. Between requests it stays sealed in Redis and expires with the token. Sponsored requests require a recorded trial admission; the server key is never sent to a browser, cookie, journal or model prompt. Signing out deletes that login's stored credentials, revokes its token and cancels the running turns it funded. Treat the session cookie and `SESSION_SECRET` as credentials.
## License
diff --git a/lib/agent.ts b/lib/agent.ts
index 166cebf..9150567 100644
--- a/lib/agent.ts
+++ b/lib/agent.ts
@@ -3,7 +3,15 @@ import { createTools, type AskQuestion, type ToolHost } from './tools'
import { assertGenerationCredential } from './gateway-session'
import { chatSession, durableAgent, runSubagent, type ChatRuntime } from './libfx-agent'
import { project } from './projector'
-import { dropChatCredential, dropLoginCredentials, readTurnCredential, saveTurnCredential, saveTrialCredential } from './turn-credential'
+import {
+ dropChatCredential,
+ dropLoginCredentials,
+ readTurnCredential,
+ readTurnFunding,
+ renewLatestCredential,
+ saveTrialCredential,
+ saveTurnCredential,
+} from './turn-credential'
import type { TrialCredential } from './trial'
import type { SessionData } from './secure-session'
import {
@@ -211,8 +219,10 @@ export async function submitPrompt(
log(host.id, 'prompt:submitted', { id: submitted.id, clientId, imageCount: images?.length ?? 0, idle: submitted.idle })
const id = submitted.id
try {
+ // Pinned before libfx sees the message: whether it starts a turn or joins
+ // the running one, no turn can run without its funding record.
if (funding) await saveTrialCredential(host.id, funding, id)
- else await saveTurnCredential(host.id, sender!, submitted.trialChat ? id : undefined)
+ else await saveTurnCredential(host.id, sender!, id)
const stored = await hydrateSession(host)
const { session } = await chatSession(agent(), host, stored?.libfxSessionId ?? null, agentInstructions(host), id, !!funding)
const input = images?.length ? [{ type: 'text' as const, text: `[${author}] ${text}` }, ...images] : `[${author}] ${text}`
@@ -235,14 +245,15 @@ export async function submitPrompt(
return { id, seq: submitted.event.seq ?? 0, trialChat: submitted.trialChat }
}
-// A token the same login renewed for the same team reaches the chat's running
-// and queued turns. Another login or team bills only from its own next prompt.
+// A token the same login renewed for the same team reaches that login's running
+// and queued turns, each billing the team its message chose. Another login or
+// team bills only from its own next prompt.
export async function renewTurnCredential(host: SessionState): Promise<void> {
const session = host.gatewaySession
if (!session) return
const stored = await readTurnCredential(host.id)
if (stored?.loginId === session.loginId && stored.teamId === session.teamId && session.expiresAt > stored.expiresAt) {
- await saveTurnCredential(host.id, session)
+ await renewLatestCredential(host.id, session)
}
}
@@ -420,10 +431,11 @@ export async function deleteDesignSession(host: SessionState): Promise<boolean>
}
/**
- * Sign-out deletes the chat credentials this login stored, then cancels those
- * chats' turns. A turn that still reaches the model finds no credential and
- * ends with "sign in again"; nothing falls back to another login or the
- * deployment.
+ * Sign-out deletes the chat credentials this login stored, then cancels the
+ * running turns this login funded. A turn another login funded keeps running
+ * on its own credential. A turn of this login that still reaches the model
+ * finds no credential and ends with "sign in again"; nothing falls back to
+ * another login or the deployment.
*/
export async function cancelUserRuntime(userId: string, loginId?: string): Promise<void> {
for (const host of registry().values()) {
@@ -432,9 +444,16 @@ export async function cancelUserRuntime(userId: string, loginId?: string): Promi
// A session without a login id never stored a chat credential.
if (!loginId) return
const chats = await dropLoginCredentials(loginId)
- await Promise.all(chats.map(async (chatId) => {
+ await Promise.all(chats.map(async ({ chatId, latestWasLogin }) => {
const [active, stored] = await Promise.all([getActiveTurn(chatId), readSession(chatId)])
- if (active && stored?.libfxSessionId) await agent().session(stored.libfxSessionId).cancel().catch(() => {})
+ if (!active || !stored?.libfxSessionId) return
+ // Only a turn this login's own message funded stops. A turn with no funding
+ // record can bill at most the chat's latest credential, so it stops when
+ // that credential was this login's.
+ const funding = await readTurnFunding(chatId, active.id)
+ const stops = funding ? funding.loginId === loginId : latestWasLogin
+ log(chatId, 'signout:turn', { turn: active.id, cancelled: stops })
+ if (stops) await agent().session(stored.libfxSessionId).cancel().catch(() => {})
}))
}
diff --git a/lib/libfx-agent.ts b/lib/libfx-agent.ts
index e17b862..84b9720 100644
--- a/lib/libfx-agent.ts
+++ b/lib/libfx-agent.ts
@@ -1,7 +1,7 @@
import { createFxAgent, createFxEngine, type FxAgent, type FxAgentHostTool, type FxEffort, type FxHostTool, type FxSession, type FxToolContext } from 'libfx'
import { createTools, type ToolHost } from './tools'
import { gatewayFetch, type GatewayError, type DesignDraftObserver } from './gateway-session'
-import { readExecutionCredential } from './turn-credential'
+import { readExecutionFunding } from './turn-credential'
// @ts-expect-error Node strip-types tests require the source extension.
import { AuthError } from './accounts.ts'
import type { SessionData } from './secure-session'
@@ -80,7 +80,8 @@ function chatFetch(
const id = await chatId()
const url = new URL(input instanceof Request ? input.url : String(input))
const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()
- if (method === 'POST' && url.pathname.endsWith('/language-model') && typeof init?.body === 'string') {
+ const modelRequest = method === 'POST' && url.pathname.endsWith('/language-model')
+ if (modelRequest && typeof init?.body === 'string') {
let step = 1
try { step = turnModelStep(JSON.parse(init.body)) } catch { /* libfx validates its own body */ }
if (step > MAX_TURN_MODEL_STEPS) {
@@ -94,11 +95,14 @@ function chatFetch(
chatGateways.set(id, gateway)
// Both reads use the same executing turn; reserving its preview adds no serial
// round trip to the credential lookup before the model request starts.
- const [credential, draft] = await Promise.all([
- readExecutionCredential(id, turn),
- turn && method === 'POST' && url.pathname.endsWith('/language-model')
- ? storedDraftObserver(id, turn).catch(() => undefined) : undefined,
+ const [funding, draft] = await Promise.all([
+ readExecutionFunding(id, turn),
+ turn && modelRequest ? storedDraftObserver(id, turn).catch(() => undefined) : undefined,
])
+ // The request fails below with "sign in again"; the log says why, with
+ // the turn and reason only, never a credential.
+ if (!funding.ok && modelRequest) log(id, 'funding:refused', { turn: turn ?? null, reason: funding.refused })
+ const credential = funding.ok ? funding.credential : null
gateway.gatewaySession = !credential ? null : 'kind' in credential ? credential : { ...credential, email: '', loginAt: 0, isLoggedIn: true }
observer = draft
}
@@ -233,7 +237,7 @@ export async function runSubagent(
signal: AbortSignal,
): Promise<string> {
const chatId = host.id
- const [credential, active] = await Promise.all([readExecutionCredential(chatId, turnId), getActiveTurn(chatId)])
+ const [funding, active] = await Promise.all([readExecutionFunding(chatId, turnId), getActiveTurn(chatId)])
// The parent turn's settings, even if the chat's were changed since it started.
const pinned = active?.id === turnId ? active.settings : undefined
const engine = await createFxEngine({
@@ -241,7 +245,7 @@ export async function runSubagent(
fetch: chatFetch(async () => chatId, () => turnId),
model: pinned
? { id: pinned.model, effort: pinned.effort as FxEffort, fast: pinned.fast }
- : chatModel(host, !!credential && 'kind' in credential),
+ : chatModel(host, funding.ok && 'kind' in funding.credential),
instructions,
tools: [
...createTools(await runtime.toolHost(chatId, turnId, signal), { allowSubagent: false }).map(tool => ({
diff --git a/lib/projector.ts b/lib/projector.ts
index b87bd7a..bb9fed5 100644
--- a/lib/projector.ts
+++ b/lib/projector.ts
@@ -14,7 +14,7 @@ import {
type TurnSettings,
} from './journal'
import { recordGeneration, recordTurn } from './history'
-import { readExecutionCredential } from './turn-credential'
+import { readExecutionFunding } from './turn-credential'
import { effectiveEffort, effectiveFast, effectiveModel, INSTANCE, log, type SessionState } from './session'
import type { StreamItem } from './events'
import { TRIAL_MODEL } from './trial-policy'
@@ -127,7 +127,8 @@ function turnSettings(host: SessionState, sponsored: boolean): TurnSettings {
}
async function startTurn(host: SessionState, id: number, input: string | undefined, startSeq: number): Promise<void> {
- const [credential] = await Promise.all([readExecutionCredential(host.id, id), readSettings(host)])
+ const [funding] = await Promise.all([readExecutionFunding(host.id, id), readSettings(host)])
+ const credential = funding.ok ? funding.credential : null
const sponsored = !!credential && 'kind' in credential
const turn: ActiveTurn = {
id,
diff --git a/lib/turn-credential.ts b/lib/turn-credential.ts
index 2e56756..a7ff3ef 100644
--- a/lib/turn-credential.ts
+++ b/lib/turn-credential.ts
@@ -7,11 +7,11 @@ import { trialEnabled, type TrialCredential } from './trial.ts'
// libfx runs a chat's turns in queue deliveries, with no user request to read a
// cookie from. So the prompt route leaves the sender's AI Gateway credential
-// here, and the agent's fetch bills every model request of that chat to it:
-// the access token and team only, sealed with SESSION_SECRET and expiring with
-// the token. The refresh token never leaves the cookie, and nothing here is
-// logged. Deleting this module, and the fetch that reads it, bills the
-// deployment instead.
+// here, pinned to the turn its message starts, and the agent's fetch bills each
+// model request to its turn's credential: the access token and team only,
+// sealed with SESSION_SECRET and expiring with the token. The refresh token
+// never leaves the cookie, and no credential is logged. Deleting this module,
+// and the fetch that reads it, bills the deployment instead.
interface UserTurnCredential {
userId: string
loginId: string
@@ -48,21 +48,38 @@ async function activeCredential<T extends TurnCredential>(credential: T | null):
return credential && !await loginRevoked(credential.loginId) ? credential : null
}
-interface FundingBinding { kind: 'trial' | 'user'; userId: string; loginId: string; teamId?: string }
+export interface FundingBinding { kind: 'trial' | 'user'; userId: string; loginId: string; teamId?: string }
-// Stores the credential that bills `chatId` from now on. A credential that has
-// already expired is not stored.
-export async function saveTurnCredential(chatId: string, session: SessionData, turnId?: number): Promise<void> {
+// Pins the sender's credential to the turn its message starts, and keeps it as
+// the chat's latest credential for token renewal. Every paid message is pinned;
+// one whose credential can't be stored is not admitted.
+export async function saveTurnCredential(chatId: string, session: SessionData, turnId: number): Promise<void> {
+ const stored = userCredential(session)
+ if (!stored) throw new Error('Sign in again to send this message')
+ await storeCredential(chatId, stored.credential, stored.ttlSeconds, turnId)
+}
+
+// A renewed token for the chat's latest credential. It reaches the turns its
+// login funded, each still billing its own team, and pins no turn. An expired
+// token is not stored.
+export async function renewLatestCredential(chatId: string, session: SessionData): Promise<void> {
+ const stored = userCredential(session)
+ if (stored) await storeCredential(chatId, stored.credential, stored.ttlSeconds)
+}
+
+function userCredential(session: SessionData): { credential: UserTurnCredential; ttlSeconds: number } | null {
const ttlSeconds = Math.floor((session.expiresAt - Date.now()) / 1000)
- if (!session.accessToken || !session.teamId || !session.loginId || ttlSeconds <= 0) return
- const credential: UserTurnCredential = {
- userId: session.userId,
- loginId: session.loginId,
- accessToken: session.accessToken,
- teamId: session.teamId,
- expiresAt: session.expiresAt,
+ if (!session.accessToken || !session.teamId || !session.loginId || ttlSeconds <= 0) return null
+ return {
+ credential: {
+ userId: session.userId,
+ loginId: session.loginId,
+ accessToken: session.accessToken,
+ teamId: session.teamId,
+ expiresAt: session.expiresAt,
+ },
+ ttlSeconds,
}
- await storeCredential(chatId, credential, ttlSeconds, turnId)
}
export async function saveTrialCredential(chatId: string, credential: TrialCredential, turnId: number): Promise<void> {
@@ -79,8 +96,8 @@ async function storeCredential(chatId: string, credential: TurnCredential, ttlSe
const sealed = await sealData(credential, { password: password(), ttl: ttlSeconds })
const pipeline = redis().pipeline()
const sponsored = 'kind' in credential
- // Latest OAuth grants still serve token renewal and old paid-only chats.
- // A sponsored admission never replaces that user's credential.
+ // The latest user credential serves token renewal, and the chats whose turns
+ // predate funding records. A sponsored admission never replaces it.
if (!sponsored) pipeline.set(credentialKey(chatId), sealed, { ex: ttlSeconds })
if (turnId !== undefined) {
const binding: FundingBinding = { kind: sponsored ? 'trial' : 'user', userId: credential.userId,
@@ -127,53 +144,81 @@ function fundingBinding(value: unknown): FundingBinding | null {
} catch { return null }
}
-// The SDK's actual executing message selects funding, including after a cold
-// restore. Redis projection timing and later submitted messages confer no billing
-// authority. Legacy fallback exists only where no explicit turn records exist.
-export async function readExecutionCredential(chatId: string, turnId?: number): Promise<TurnCredential | null> {
- // Check after selecting the credential, including old records and exact-turn
- // fallbacks. Never cache a negative revocation check across model requests.
- return activeCredential(await storedExecutionCredential(chatId, turnId))
+// Why a model request has no funding: the executing turn is unknown, it has no
+// funding record in a chat that keeps them, its credential is gone, expired or
+// no longer matches its record, or its login has signed out.
+export type FundingRefusal = 'no-turn' | 'unbound-turn' | 'unusable' | 'revoked'
+export type ExecutionFunding = { ok: true; credential: TurnCredential } | { ok: false; refused: FundingRefusal }
+
+const refuse = (refused: FundingRefusal): ExecutionFunding => ({ ok: false, refused })
+
+// What funds a turn's model request, from the chat's records alone. A turn with
+// a funding record bills that record's user, login and team, or nothing: later
+// messages and renewals can change only the token. A chat with no records at
+// all predates per-turn funding and bills its latest user credential.
+export function resolveFunding(
+ records: number,
+ turnId: number | null,
+ binding: FundingBinding | null,
+ exact: TurnCredential | null,
+ latest: TurnCredential | null,
+): ExecutionFunding {
+ if (records === 0) return latest && !('kind' in latest) ? { ok: true, credential: latest } : refuse('unusable')
+ if (turnId === null) return refuse('no-turn')
+ if (!binding) return refuse('unbound-turn')
+ const sameLogin = (credential: TurnCredential | null) =>
+ credential?.userId === binding.userId && credential.loginId === binding.loginId
+ if (binding.kind === 'trial') return exact && 'kind' in exact && sameLogin(exact) ? { ok: true, credential: exact } : refuse('unusable')
+ // Rotation may change the selected team, but this turn retains the team its
+ // admission selected. The refreshed OAuth token is usable only for that team.
+ if (latest && !('kind' in latest) && sameLogin(latest)) return { ok: true, credential: { ...latest, teamId: binding.teamId! } }
+ return exact && !('kind' in exact) && sameLogin(exact) && exact.teamId === binding.teamId
+ ? { ok: true, credential: exact } : refuse('unusable')
}
-async function storedExecutionCredential(chatId: string, turnId?: number): Promise<TurnCredential | null> {
- const validTurn = Number.isSafeInteger(turnId) && (turnId as number) > 0
+// The SDK's actual executing message selects funding, including after a cold
+// restore. Redis projection timing and later submitted messages confer no billing
+// authority. A signed-out login's credential funds nothing: the check runs after
+// selection, on every request, and is never cached.
+export async function readExecutionFunding(chatId: string, turnId?: number): Promise<ExecutionFunding> {
+ const turn = Number.isSafeInteger(turnId) && (turnId as number) > 0 ? turnId as number : null
const pipeline = redis().pipeline().hlen(fundingKey(chatId)).get(credentialKey(chatId))
- if (validTurn) pipeline.hget(fundingKey(chatId), String(turnId)).get(turnCredentialKey(chatId, turnId!))
+ if (turn !== null) pipeline.hget(fundingKey(chatId), String(turn)).get(turnCredentialKey(chatId, turn))
const values: unknown[] = await pipeline.exec()
const [count, latestSeal, bindingValue, turnSeal] = values
- const latest = await decodeCredential(latestSeal)
- if (Number(count) === 0) return latest && !('kind' in latest) ? latest : null
- if (!validTurn) return null
- const binding = fundingBinding(bindingValue)
- if (!binding) return null
- const exact = await decodeCredential(turnSeal)
- if (binding.kind === 'trial') return exact && 'kind' in exact && exact.userId === binding.userId && exact.loginId === binding.loginId ? exact : null
- if (latest && !('kind' in latest) && latest.userId === binding.userId && latest.loginId === binding.loginId) {
- // Rotation may change the selected team, but this turn retains the team its
- // admission selected. The refreshed OAuth token is usable only for that team.
- return { ...latest, teamId: binding.teamId! }
- }
- return exact && !('kind' in exact) && exact.userId === binding.userId && exact.loginId === binding.loginId && exact.teamId === binding.teamId ? exact : null
+ const [latest, exact] = await Promise.all([decodeCredential(latestSeal), decodeCredential(turnSeal)])
+ const funding = resolveFunding(Number(count), turn, fundingBinding(bindingValue), exact, latest)
+ return funding.ok && await loginRevoked(funding.credential.loginId) ? refuse('revoked') : funding
}
+// A turn's funding record. Sign-out deletes credentials, never these records.
+export async function readTurnFunding(chatId: string, turnId: number): Promise<FundingBinding | null> {
+ return fundingBinding(await redis().hget(fundingKey(chatId), String(turnId)))
+}
+
+// A chat whose credentials a sign-out dropped, and whether the chat's latest
+// credential was that login's.
+export interface DroppedChat { chatId: string; latestWasLogin: boolean }
+
// Sign-out: removes every chat credential this login stored, but not one a later
// prompt from another login of the user has since replaced.
-export async function dropLoginCredentials(loginId: string): Promise<string[]> {
+export async function dropLoginCredentials(loginId: string): Promise<DroppedChat[]> {
const chats = (await redis().smembers(loginKey(loginId))) ?? []
// One round trip reads every chat's credential and funding; a second deletes.
+ // The seal is decoded directly: sign-out has already revoked this login.
const pipeline = redis().pipeline()
for (const chatId of chats) pipeline.get(credentialKey(chatId)).hgetall(fundingKey(chatId))
const values: unknown[] = chats.length ? await pipeline.exec() : []
const keys: string[] = []
- const dropped: string[] = []
+ const dropped: DroppedChat[] = []
await Promise.all(chats.map(async (chatId, index) => {
const credential = await decodeCredential(values[index * 2])
const bindings = (values[index * 2 + 1] ?? {}) as Record<string, unknown>
const owned = Object.entries(bindings).filter(([, value]) => fundingBinding(value)?.loginId === loginId)
.map(([id]) => turnCredentialKey(chatId, Number(id)))
- if (credential && !('kind' in credential) && credential.loginId === loginId) owned.push(credentialKey(chatId))
- if (owned.length) { keys.push(...owned); dropped.push(chatId) }
+ const latestWasLogin = !!credential && !('kind' in credential) && credential.loginId === loginId
+ if (latestWasLogin) owned.push(credentialKey(chatId))
+ if (owned.length) { keys.push(...owned); dropped.push({ chatId, latestWasLogin }) }
}))
await redis().del(...keys, loginKey(loginId))
return dropped
diff --git a/package.json b/package.json
index b30dcb7..520c854 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
"typecheck": "next typegen && tsc --noEmit --incremental false",
"start": "next start",
"test:core": "node --experimental-strip-types --test tests/core.test.mjs tests/transcript.test.mjs tests/design-draft.test.mjs tests/event-delivery.test.mjs tests/event-stream.test.mjs tests/public-fetch.test.mjs tests/runtime.test.mjs",
- "test:auth": "node --experimental-strip-types --test tests/auth.test.mjs tests/auth-callback.test.mjs tests/signout.test.mjs tests/ownership.test.mjs tests/history.test.mjs tests/route-security.test.mjs tests/gateway-session.test.mjs tests/libfx-transport.test.mjs tests/libfx-agent.test.mjs tests/auth-ui.test.mjs tests/html-ui.test.mjs tests/guest-ui.test.mjs tests/guest-draft.test.mjs tests/trial.test.mjs",
+ "test:auth": "node --experimental-strip-types --test tests/auth.test.mjs tests/auth-callback.test.mjs tests/signout.test.mjs tests/ownership.test.mjs tests/history.test.mjs tests/route-security.test.mjs tests/gateway-session.test.mjs tests/libfx-transport.test.mjs tests/libfx-agent.test.mjs tests/auth-ui.test.mjs tests/html-ui.test.mjs tests/guest-ui.test.mjs tests/guest-draft.test.mjs tests/trial.test.mjs tests/turn-funding.test.mjs",
"test:journal:integration": "node --env-file-if-exists=.env.local --experimental-strip-types --test tests/journal.integration.mjs",
"test:smoke": "node tests/local-auth-smoke.mjs",
"db:migrate": "node --env-file-if-exists=.env.local scripts/migrate-database.mjs",
diff --git a/tests/fixtures/memory-redis.mjs b/tests/fixtures/memory-redis.mjs
new file mode 100644
index 0000000..1e73624
--- /dev/null
+++ b/tests/fixtures/memory-redis.mjs
@@ -0,0 +1,55 @@
+import { registerHooks } from 'node:module'
+
+// An in-memory stand-in for the Upstash commands lib/turn-credential.ts sends,
+// in pipelines and directly. Values are kept as written.
+export function memoryRedis() {
+ const values = new Map()
+ const hashes = new Map()
+ const sets = new Map()
+ const commands = {
+ set(key, value) { values.set(key, value); return 'OK' },
+ get(key) { return values.get(key) ?? null },
+ hset(key, entries) { hashes.set(key, { ...(hashes.get(key) ?? {}), ...entries }); return 1 },
+ hget(key, field) { return hashes.get(key)?.[field] ?? null },
+ hlen(key) { return Object.keys(hashes.get(key) ?? {}).length },
+ hgetall(key) { return hashes.get(key) ?? null },
+ sadd(key, member) { sets.set(key, [...new Set([...(sets.get(key) ?? []), member])]); return 1 },
+ smembers(key) { return sets.get(key) ?? [] },
+ expire() { return 1 },
+ del(...keys) {
+ for (const key of keys) { values.delete(key); hashes.delete(key); sets.delete(key) }
+ return keys.length
+ },
+ }
+ const client = {
+ pipeline() {
+ const queued = []
+ const pipeline = Object.fromEntries(Object.entries(commands).map(([name, run]) =>
+ [name, (...args) => { queued.push(() => run(...args)); return pipeline }]))
+ pipeline.exec = async () => queued.map((run) => run())
+ return pipeline
+ },
+ ...Object.fromEntries(Object.entries(commands).map(([name, run]) => [name, async (...args) => run(...args)])),
+ }
+ return { client, values, hashes, sets }
+}
+
+let loaded = null
+
+// lib/turn-credential.ts with its Redis client replaced by `store` for this
+// test. Keys carry the prefix `test:`.
+export async function turnCredentialWith(t, store) {
+ globalThis.__memoryRedis = store.client
+ t.after(() => { delete globalThis.__memoryRedis })
+ loaded ??= (async () => {
+ const hook = registerHooks({ resolve(specifier, context, next) {
+ if (context.parentURL?.includes('/lib/turn-credential.ts') && specifier === './journal.ts') {
+ const source = 'export const prefixed = key => "test:" + key; export const redis = () => globalThis.__memoryRedis'
+ return { url: `data:text/javascript,${encodeURIComponent(source)}`, shortCircuit: true }
+ }
+ return next(specifier, context)
+ } })
+ try { return await import('../../lib/turn-credential.ts') } finally { hook.deregister() }
+ })()
+ return loaded
+}
diff --git a/tests/journal.integration.mjs b/tests/journal.integration.mjs
index 2cc7588..74e80bc 100644
--- a/tests/journal.integration.mjs
+++ b/tests/journal.integration.mjs
@@ -287,8 +287,8 @@ test('journal Redis integration uses isolated durable session state', async (t)
userId: 'user-a', loginId, loginAt: 1, email: '[email protected]', accessToken, teamId: 'team_a',
expiresAt: Date.now() + 120_000, isLoggedIn: true, refreshToken: 'refresh-never-stored',
})
- await credentials.saveTurnCredential('cred-laptop', session('login-laptop', 'access-laptop-secret'))
- await credentials.saveTurnCredential('cred-phone', session('login-phone', 'access-phone-secret'))
+ await credentials.saveTurnCredential('cred-laptop', session('login-laptop', 'access-laptop-secret'), 1)
+ await credentials.saveTurnCredential('cred-phone', session('login-phone', 'access-phone-secret'), 1)
const raw = await redis.get(`${prefix}:credential:cred-laptop`)
assert.equal(typeof raw, 'string')
assert.ok(!raw.includes('access-laptop-secret') && !raw.includes('refresh-never-stored'), 'sealed, never plaintext')
@@ -303,10 +303,12 @@ test('journal Redis integration uses isolated durable session state', async (t)
assert.equal(await credentials.readTurnCredential('cred-laptop'), null, 'another secret cannot unseal it')
process.env.SESSION_SECRET = secret
- assert.deepEqual(await credentials.dropLoginCredentials('login-laptop'), ['cred-laptop'])
+ assert.deepEqual(await credentials.dropLoginCredentials('login-laptop'), [{ chatId: 'cred-laptop', latestWasLogin: true }])
assert.equal(await credentials.readTurnCredential('cred-laptop'), null)
+ assert.equal((await credentials.readExecutionFunding('cred-laptop', 1)).ok, false)
+ assert.equal((await credentials.readTurnFunding('cred-laptop', 1))?.loginId, 'login-laptop', 'sign-out keeps the funding record')
assert.equal((await credentials.readTurnCredential('cred-phone'))?.accessToken, 'access-phone-secret')
- await credentials.saveTurnCredential('cred-expired', { ...session('login-x', 'x'), expiresAt: Date.now() - 1 })
+ await assert.rejects(credentials.saveTurnCredential('cred-expired', { ...session('login-x', 'x'), expiresAt: Date.now() - 1 }, 1), /Sign in again/)
assert.equal(await credentials.readTurnCredential('cred-expired'), null, 'an expired token is never stored')
})
} finally {
diff --git a/tests/libfx-agent.test.mjs b/tests/libfx-agent.test.mjs
index 72047ed..5e97603 100644
--- a/tests/libfx-agent.test.mjs
+++ b/tests/libfx-agent.test.mjs
@@ -11,7 +11,7 @@ const fakes = {
libfx: dataUrl(forward('libfx', ['createFxAgent', 'createFxEngine'])),
'./journal': dataUrl(forward('journal', ['appendEvent', 'bindLibfxSession', 'chatOfLibfxSession', 'getActiveTurn'])),
'./draft-store': dataUrl(forward('drafts', ['storedDraftObserver','closeDraftCall'])),
- './turn-credential': dataUrl(forward('credentials', ['readTurnCredential', 'readExecutionCredential'])),
+ './turn-credential': dataUrl(forward('credentials', ['readTurnCredential', 'readExecutionFunding'])),
}
registerHooks({ resolve(specifier, context, next) {
if (context.parentURL?.includes('/lib/')) {
@@ -38,8 +38,10 @@ globalThis.__fx0Agent = {
},
credentials: {
readTurnCredential: async (chatId) => stored.get(chatId) ?? null,
- readExecutionCredential: async (chatId, turnId) => executions.has(chatId)
- ? executions.get(chatId).get(turnId) ?? null : stored.get(chatId) ?? null,
+ readExecutionFunding: async (chatId, turnId) => {
+ const credential = executions.has(chatId) ? executions.get(chatId).get(turnId) ?? null : stored.get(chatId) ?? null
+ return credential ? { ok: true, credential } : { ok: false, refused: executions.has(chatId) ? 'unbound-turn' : 'unusable' }
+ },
},
drafts: { storedDraftObserver: async () => undefined, closeDraftCall: async () => {} },
}
@@ -77,11 +79,16 @@ test('missing or expired execution funding cannot use a later paid credential',
executions.set('chat-a', new Map([[21, { ...credential('expired-token'), expiresAt: Date.now() - 1 }]]))
t.after(() => executions.clear())
const network = t.mock.method(globalThis, 'fetch', async () => Response.json({}))
+ const logged = t.mock.method(console, 'info', () => {})
for (const turnId of [21, 22]) {
agentOptions.hooks?.onEvent({ type: 'journal.restore', sessionId: 'wrun_a', data: { resumable: true, openTurnId: `m${turnId}` } })
assert.equal((await modelRequest('wrun_a')).status, 401)
}
assert.equal(network.mock.callCount(), 0)
+ // Only the refusal is logged, with its turn and reason and no credential.
+ const refusals = logged.mock.calls.map((call) => JSON.parse(call.arguments[0])).filter((line) => line.event === 'funding:refused')
+ assert.deepEqual(refusals.map(({ session, turn, reason }) => [session, turn, reason]), [['chat-a', 22, 'unbound-turn']])
+ assert.ok(!logged.mock.calls.some((call) => call.arguments[0].includes('token')))
})
test('the executing turn is captured before an asynchronous chat lookup', async (t) => {
diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjs
index 8bc8859..d9fe38a 100644
--- a/tests/runtime.test.mjs
+++ b/tests/runtime.test.mjs
@@ -17,7 +17,7 @@ const forward = (root, names) => names.map((name) =>
`export const ${name} = (...args) => globalThis.__fx0Runtime.${root}.${name}(...args)`).join('\n')
const journalUrl = dataUrl(`export class SessionCleanupError extends Error {}\nexport const QUESTION_WAIT_MS = 600000\n` + forward('journal', journalNames))
const libfxUrl = dataUrl(forward('libfx', ['createFxAgent', 'createFxEngine']))
-const credentialUrl = dataUrl(forward('credentialStore', ['saveTurnCredential', 'saveTrialCredential', 'readTurnCredential', 'readExecutionCredential', 'dropLoginCredentials', 'dropChatCredential']))
+const credentialUrl = dataUrl(forward('credentialStore', ['saveTurnCredential', 'saveTrialCredential', 'renewLatestCredential', 'readTurnCredential', 'readExecutionFunding', 'readTurnFunding', 'dropLoginCredentials', 'dropChatCredential']))
const historyUrl = dataUrl(forward('history', ['recordTurn', 'recordGeneration']))
const gatewayUrl = dataUrl(`import { AuthError } from ${JSON.stringify(new URL('../lib/accounts.ts', import.meta.url).href)}
export const RATE_LIMIT_ATTEMPTS = 3
@@ -77,6 +77,8 @@ function fixture(t, stored = { preferredModel: null, preferredEffort: null, pref
const logs = new Map()
const credentials = new Map()
const executionCredentials = new Map()
+ // `${chatId}:${turnId}` -> who funded the turn; sign-out keeps these.
+ const fundings = new Map()
let active = null
let deleting = false
let question = null
@@ -86,7 +88,7 @@ function fixture(t, stored = { preferredModel: null, preferredEffort: null, pref
let messageSeq = 0
const state = {
stored,
- calls, events, logs, credentials, executionCredentials,
+ calls, events, logs, credentials, executionCredentials, fundings,
agentOptions: null,
engineOptions: [],
sent: [],
@@ -200,13 +202,33 @@ function fixture(t, stored = { preferredModel: null, preferredEffort: null, pref
},
},
credentialStore: {
- saveTurnCredential: async (chatId, session, turnId) => { credentials.set(chatId, session); if (turnId) executionCredentials.set(`${chatId}:${turnId}`, session) },
- saveTrialCredential: async (chatId, credential, turnId) => { executionCredentials.set(`${chatId}:${turnId}`, credential) },
+ saveTurnCredential: async (chatId, session, turnId) => {
+ credentials.set(chatId, session)
+ executionCredentials.set(`${chatId}:${turnId}`, session)
+ fundings.set(`${chatId}:${turnId}`, { kind: 'user', userId: session.userId, loginId: session.loginId, teamId: session.teamId })
+ },
+ saveTrialCredential: async (chatId, credential, turnId) => {
+ executionCredentials.set(`${chatId}:${turnId}`, credential)
+ fundings.set(`${chatId}:${turnId}`, { kind: 'trial', userId: credential.userId, loginId: credential.loginId })
+ },
+ renewLatestCredential: async (chatId, session) => { credentials.set(chatId, session) },
readTurnCredential: async (chatId) => credentials.get(chatId) ?? null,
- readExecutionCredential: async (chatId, turnId) => executionCredentials.get(`${chatId}:${turnId}`) ?? credentials.get(chatId) ?? null,
+ readExecutionFunding: async (chatId, turnId) => {
+ const credential = executionCredentials.get(`${chatId}:${turnId}`) ?? credentials.get(chatId) ?? null
+ return credential ? { ok: true, credential } : { ok: false, refused: 'unusable' }
+ },
+ readTurnFunding: async (chatId, turnId) => fundings.get(`${chatId}:${turnId}`) ?? null,
dropLoginCredentials: async (loginId) => {
- const dropped = [...credentials].filter(([, value]) => value.loginId === loginId).map(([chatId]) => chatId)
- for (const chatId of dropped) credentials.delete(chatId)
+ const chatOf = (key) => key.slice(0, key.lastIndexOf(':'))
+ const dropped = []
+ for (const chatId of new Set([...credentials.keys(), ...[...fundings.keys()].map(chatOf)])) {
+ const latestWasLogin = credentials.get(chatId)?.loginId === loginId
+ const turns = [...fundings].filter(([key, funding]) => chatOf(key) === chatId && funding.loginId === loginId)
+ if (!latestWasLogin && !turns.length) continue
+ if (latestWasLogin) credentials.delete(chatId)
+ for (const [key] of turns) executionCredentials.delete(key)
+ dropped.push({ chatId, latestWasLogin })
+ }
return dropped
},
dropChatCredential: async (chatId) => { credentials.delete(chatId); calls.push(['dropCredential', chatId]) },
@@ -276,6 +298,21 @@ test('the route\'s explicit sender survives another request rebinding the host b
assert.equal(f.credentials.get('before-submit-race').loginId, sender.loginId)
})
+test('every paid message is pinned to the turn it starts, in a paid-only chat too', async (t) => {
+ const f = fixture(t)
+ const host = boundHost('paid-chat', credential('user-a', 'login-laptop', 'laptop-token'))
+ await runtime.submitPrompt(host, 'Ada', 'Long design')
+ // Another team's image prompt queues behind the running turn.
+ const phone = { ...credential('user-a', 'login-phone', 'phone-token'), teamId: 'team_b' }
+ await runtime.submitPrompt(host, 'Ada', 'Use this', undefined, [{ type: 'image', mimeType: 'image/png', data: 'cG5n' }], undefined, undefined, undefined, phone)
+ assert.notEqual(f.stored?.trialChat, true)
+ assert.deepEqual([...f.fundings], [
+ ['paid-chat:1', { kind: 'user', userId: 'user-a', loginId: 'login-laptop', teamId: 'team_a' }],
+ ['paid-chat:2', { kind: 'user', userId: 'user-a', loginId: 'login-phone', teamId: 'team_b' }],
+ ])
+ assert.equal(f.executionCredentials.get('paid-chat:1').accessToken, 'laptop-token')
+})
+
// Keep these tests sequential: each fixture owns the fake external boundaries.
test('a prompt goes to the chat\'s one libfx session with its message id, settings and context', async (t) => {
const f = fixture(t)
@@ -433,6 +470,22 @@ test('sign-out drops only this login\'s chat credentials and cancels those chats
assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [['cancel', 'wrun_5']])
})
+test('signing out on the phone leaves the turn the laptop funded running', async (t) => {
+ const f = fixture(t, { libfxSessionId: 'wrun_6' })
+ const host = boundHost('shared-chat', credential('user-a', 'login-laptop', 'laptop-token'))
+ await runtime.submitPrompt(host, 'Ada', 'Laptop turn')
+ f.setActive({ id: 1 })
+ // The phone's message joins the laptop's running turn and becomes the chat's
+ // latest credential.
+ await runtime.submitPrompt(host, 'Ada', 'Phone note', undefined, undefined, undefined, undefined, undefined, credential('user-a', 'login-phone', 'phone-token'))
+ assert.equal(sendKind(f.sent[1]), 'steer')
+ await runtime.cancelUserRuntime('user-a', 'login-phone')
+ assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [], 'the laptop funded the running turn')
+ assert.equal(host.gatewaySession?.loginId, 'login-laptop')
+ await runtime.cancelUserRuntime('user-a', 'login-laptop')
+ assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [['cancel', 'wrun_6']])
+})
+
test('deletion refuses a chat with a running turn and otherwise drops its records, mapping and credential', async (t) => {
const f = fixture(t, { libfxSessionId: 'wrun_2' })
const host = boundHost('delete-chat')
diff --git a/tests/signout.test.mjs b/tests/signout.test.mjs
index e3793a1..48edac1 100644
--- a/tests/signout.test.mjs
+++ b/tests/signout.test.mjs
@@ -20,6 +20,11 @@ registerHooks({ resolve(specifier, context, next) {
const secure = await import('../lib/secure-session.ts')
const credentials = await import('../lib/turn-credential.ts')
+// The credential a turn's model requests would bill, or null when nothing may.
+const credentialOf = async (chatId, turnId) => {
+ const funding = await credentials.readExecutionFunding(chatId, turnId)
+ return funding.ok ? funding.credential : null
+}
const { POST: signout } = await import('../app/api/auth/signout/route.ts')
const session = (loginId) => ({
@@ -125,8 +130,8 @@ test('logout waits for one durable revocation write, then returns before cleanup
assert.deepEqual(state.commands, ['set'], 'no chat enumeration, credential read or deletion on the response path')
assert.ok(state.values.has('signout-test:credential:laptop-chat'), 'cleanup has not run yet')
assert.equal(await credentials.readTurnCredential('laptop-chat'), null)
- assert.equal(await credentials.readExecutionCredential('laptop-chat', 1), null)
- assert.equal((await credentials.readExecutionCredential('phone-chat', 1)).loginId, phone.loginId)
+ assert.deepEqual(await credentials.readExecutionFunding('laptop-chat', 1), { ok: false, refused: 'revoked' })
+ assert.equal((await credentialOf('phone-chat', 1)).loginId, phone.loginId)
assert.equal(fetch.mock.callCount(), 0, 'provider revocation does not block success')
assert.equal(state.cancellations.length, 0)
assert.equal(response.headers.get('clear-site-data'), null, 'Clear-Site-Data stalls Chrome for seconds; previews revalidate instead')
@@ -135,7 +140,7 @@ test('logout waits for one durable revocation write, then returns before cleanup
assert.deepEqual(state.cancellations, [[laptop.userId, laptop.loginId]])
assert.equal(state.values.has('signout-test:credential:laptop-chat'), false)
assert.equal(fetch.mock.callCount(), 1, 'provider failure cannot restore the deleted credential')
- assert.equal(await credentials.readExecutionCredential('laptop-chat', 1), null)
+ assert.equal(await credentialOf('laptop-chat', 1), null)
})
test('pending logout hides the old grant from normal readers but still revokes it on retry', async (t) => {
@@ -166,18 +171,19 @@ test('logout retains cookies and allows retry if the durable revocation write fa
assert.deepEqual(await secure.getSessionFromRequest(incoming), {}, 'failed revocation must still hide the account on reload')
assert.equal(response.headers.get('clear-site-data'), null)
assert.equal((await response.json()).success, undefined)
- assert.equal((await credentials.readExecutionCredential('active-chat', 1)).loginId, user.loginId)
+ assert.equal((await credentialOf('active-chat', 1)).loginId, user.loginId)
assert.equal(state.after.length, 0)
assert.equal(fetch.mock.callCount(), 0)
state.fail = null
assert.equal((await signout(incoming)).status, 200)
- assert.equal(await credentials.readExecutionCredential('active-chat', 1), null)
+ assert.equal(await credentialOf('active-chat', 1), null)
})
for (const failure of ['read', 'delete']) test(`revoked credentials stay unusable when background cleanup ${failure} and OAuth fail`, async (t) => {
const state = fixture(t)
const laptop = session('a'.repeat(32)), phone = session('b'.repeat(32))
- await credentials.saveTurnCredential('legacy-chat', laptop)
+ // A chat from before per-turn funding holds only its latest credential.
+ await credentials.renewLatestCredential('legacy-chat', laptop)
await credentials.saveTurnCredential('shared-chat', laptop, 1)
await credentials.saveTurnCredential('shared-chat', phone, 2)
state.fail = failure
@@ -185,12 +191,12 @@ for (const failure of ['read', 'delete']) test(`revoked credentials stay unusabl
assert.equal((await signout(await request(laptop))).status, 200)
await assert.rejects(state.after[0](), /synthetic/)
assert.equal(await credentials.readTurnCredential('legacy-chat'), null)
- assert.equal(await credentials.readExecutionCredential('legacy-chat'), null)
- assert.equal(await credentials.readExecutionCredential('shared-chat', 1), null, 'exact-turn fallback is fenced')
- assert.equal((await credentials.readExecutionCredential('shared-chat', 2)).loginId, phone.loginId)
+ assert.equal(await credentialOf('legacy-chat'), null)
+ assert.equal(await credentialOf('shared-chat', 1), null, 'exact-turn fallback is fenced')
+ assert.equal((await credentialOf('shared-chat', 2)).loginId, phone.loginId)
assert.equal((await credentials.readTurnCredential('shared-chat')).loginId, phone.loginId)
await assert.rejects(credentials.saveTurnCredential('new-chat', laptop, 1), /Signed out/)
- await assert.rejects(credentials.saveTurnCredential('legacy-chat', { ...laptop, expiresAt: laptop.expiresAt + 3600_000 }), /Signed out/)
+ await assert.rejects(credentials.renewLatestCredential('legacy-chat', { ...laptop, expiresAt: laptop.expiresAt + 3600_000 }), /Signed out/)
})
test('a save admitted before logout cannot resurrect execution credentials after revocation', async (t) => {
@@ -205,7 +211,7 @@ test('a save admitted before logout cannot resurrect execution credentials after
await pending
assert.ok(state.values.has('signout-test:credential:late-chat'), 'the delayed write really completed')
assert.equal(await credentials.readTurnCredential('late-chat'), null)
- assert.equal(await credentials.readExecutionCredential('late-chat', 1), null)
+ assert.equal(await credentialOf('late-chat', 1), null)
})
test('execution fails closed if the revocation check is unavailable', async (t) => {
@@ -214,7 +220,7 @@ test('execution fails closed if the revocation check is unavailable', async (t)
await credentials.saveTurnCredential('active-chat', user, 1)
state.fail = 'revocation-read'
await assert.rejects(credentials.readTurnCredential('active-chat'), /revocation read failure/)
- await assert.rejects(credentials.readExecutionCredential('active-chat', 1), /revocation read failure/)
+ await assert.rejects(credentialOf('active-chat', 1), /revocation read failure/)
})
test('anonymous logout clears cookies without requiring a configured credential store', async (t) => {
diff --git a/tests/trial.test.mjs b/tests/trial.test.mjs
index 29e8402..8c4822a 100644
--- a/tests/trial.test.mjs
+++ b/tests/trial.test.mjs
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import test from 'node:test'
-import { registerHooks } from 'node:module'
+import { memoryRedis, turnCredentialWith } from './fixtures/memory-redis.mjs'
const trial = await import('../lib/trial.ts').catch(() => ({}))
@@ -24,38 +24,14 @@ test('a guest cookie proves only its random owner and never carries a Gateway cr
})
test('durable sponsored credentials survive recovery without storing the server key', async (t) => {
- const values = new Map()
- const index = new Map()
- const hashes = new Map()
- globalThis.trialCredentialRedis = {
- pipeline() {
- const commands = []
- const pipeline = {
- set(key, value) { commands.push(() => values.set(key, value)); return pipeline },
- sadd(key, value) { commands.push(() => index.set(key, [...(index.get(key) ?? []), value])); return pipeline },
- hset(key, entries) { commands.push(() => { hashes.set(key, { ...(hashes.get(key) ?? {}), ...entries }); return 1 }); return pipeline },
- hget(key, field) { commands.push(() => hashes.get(key)?.[field] ?? null); return pipeline },
- hlen(key) { commands.push(() => Object.keys(hashes.get(key) ?? {}).length); return pipeline },
- hgetall(key) { commands.push(() => hashes.get(key) ?? null); return pipeline },
- get(key) { commands.push(() => values.get(key) ?? null); return pipeline },
- expire() { commands.push(() => 1); return pipeline }, async exec() { return commands.map(work => work()) },
- }
- return pipeline
- },
- async get(key) { return values.get(key) ?? null },
- async smembers(key) { return index.get(key) ?? [] },
- async hgetall(key) { return hashes.get(key) ?? null },
- async del(...keys) { for (const key of keys) { values.delete(key); index.delete(key); hashes.delete(key) } },
+ const store = memoryRedis()
+ const { values } = store
+ const credentials = await turnCredentialWith(t, store)
+ assert.equal(typeof credentials.readExecutionFunding, 'function', 'admission-bound funding is missing')
+ const credentialOf = async (chatId, turnId) => {
+ const funding = await credentials.readExecutionFunding(chatId, turnId)
+ return funding.ok ? funding.credential : null
}
- const hook = registerHooks({ resolve(specifier, context, next) {
- if (context.parentURL?.includes('/lib/turn-credential.ts') && specifier === './journal.ts') {
- return { url: `data:text/javascript,${encodeURIComponent('export const prefixed = key => "test:" + key; export const redis = () => globalThis.trialCredentialRedis')}`, shortCircuit: true }
- }
- return next(specifier, context)
- } })
- t.after(() => { hook.deregister(); delete globalThis.trialCredentialRedis })
- const credentials = await import('../lib/turn-credential.ts')
- assert.equal(typeof credentials.readExecutionCredential, 'function', 'admission-bound funding is missing')
const previous = { secret: process.env.SESSION_SECRET, key: process.env.AI_GATEWAY_API_KEY, enabled: process.env.FX0_FREE_PROMPTS }
Object.assign(process.env, { SESSION_SECRET: 'trial-test-session-password-long-enough', AI_GATEWAY_API_KEY: 'synthetic-server-key-never-store', FX0_FREE_PROMPTS: '1' })
t.after(() => {
@@ -67,23 +43,23 @@ test('durable sponsored credentials survive recovery without storing the server
await credentials.saveTrialCredential('chat-a', proof, 1)
const raw = values.get('test:credential:chat-a:turn:1')
assert.ok(raw && !raw.includes(process.env.AI_GATEWAY_API_KEY))
- assert.deepEqual(await credentials.readExecutionCredential('chat-a', 1), proof)
- assert.equal(await credentials.readExecutionCredential('chat-a'), null, 'unknown resumed turn cannot use the latest credential')
+ assert.deepEqual(await credentialOf('chat-a', 1), proof)
+ assert.equal(await credentialOf('chat-a'), null, 'unknown resumed turn cannot use the latest credential')
const paid = { userId: 'real-user', loginId: 'paid-login', accessToken: 'synthetic-user-token', teamId: 'team_paid', expiresAt: Date.now() + 3600000 }
await credentials.saveTurnCredential('chat-a', paid, 2)
- assert.deepEqual(await credentials.readExecutionCredential('chat-a', 1), proof)
- assert.equal((await credentials.readExecutionCredential('chat-a', 2)).accessToken, paid.accessToken)
+ assert.deepEqual(await credentialOf('chat-a', 1), proof)
+ assert.equal((await credentialOf('chat-a', 2)).accessToken, paid.accessToken)
const renewed = { ...paid, accessToken: 'renewed-user-token', expiresAt: paid.expiresAt + 3600000 }
- await credentials.saveTurnCredential('chat-a', renewed)
- assert.equal((await credentials.readExecutionCredential('chat-a', 2)).accessToken, renewed.accessToken)
+ await credentials.renewLatestCredential('chat-a', renewed)
+ assert.equal((await credentialOf('chat-a', 2)).accessToken, renewed.accessToken)
values.delete('test:credential:chat-a:turn:1')
- assert.equal(await credentials.readExecutionCredential('chat-a', 1), null, 'expired sponsorship cannot fall back to a paid credential')
+ assert.equal(await credentialOf('chat-a', 1), null, 'expired sponsorship cannot fall back to a paid credential')
await credentials.saveTrialCredential('chat-a', proof, 1)
await credentials.dropLoginCredentials(proof.loginId)
- assert.equal(await credentials.readExecutionCredential('chat-a', 1), null)
- assert.equal((await credentials.readExecutionCredential('chat-a', 2)).accessToken, renewed.accessToken, 'signout of one identity keeps another login intact')
+ assert.equal(await credentialOf('chat-a', 1), null)
+ assert.equal((await credentialOf('chat-a', 2)).accessToken, renewed.accessToken, 'signout of one identity keeps another login intact')
await credentials.dropChatCredential('chat-a')
- assert.equal(await credentials.readExecutionCredential('chat-a', 2), null)
+ assert.equal(await credentialOf('chat-a', 2), null)
})
test('the picker\'s base model with fast on counts as the free-prompt model', async () => {
diff --git a/tests/turn-funding.test.mjs b/tests/turn-funding.test.mjs
new file mode 100644
index 0000000..8145441
--- /dev/null
+++ b/tests/turn-funding.test.mjs
@@ -0,0 +1,138 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { memoryRedis, turnCredentialWith } from './fixtures/memory-redis.mjs'
+
+// Every paid turn bills the login and team that sent the message starting it,
+// whatever the chat's later messages and token renewals send.
+
+const HOUR = 3_600_000
+
+function useSecret(t) {
+ const previous = process.env.SESSION_SECRET
+ process.env.SESSION_SECRET = 'turn-funding-test-session-password'
+ t.after(() => { if (previous === undefined) delete process.env.SESSION_SECRET; else process.env.SESSION_SECRET = previous })
+}
+
+function session(loginId, teamId, accessToken = `${loginId}-${teamId}`) {
+ return { userId: 'user-a', loginId, teamId, accessToken, email: '[email protected]', loginAt: 1, isLoggedIn: true, expiresAt: Date.now() + HOUR }
+}
+
+// What a turn bills: [login, team, token], or why it bills nothing.
+async function billed(credentials, turnId) {
+ const funding = await credentials.readExecutionFunding('chat', turnId)
+ return funding.ok ? [funding.credential.loginId, funding.credential.teamId, funding.credential.accessToken] : funding.refused
+}
+
+test('a paid turn keeps its sender\'s login and team when another login or team sends the next message', async (t) => {
+ useSecret(t)
+ const credentials = await turnCredentialWith(t, memoryRedis())
+ await credentials.saveTurnCredential('chat', session('laptop', 'team_a'), 1)
+ await credentials.saveTurnCredential('chat', session('phone', 'team_b'), 2)
+ assert.deepEqual(await billed(credentials, 1), ['laptop', 'team_a', 'laptop-team_a'])
+ assert.deepEqual(await billed(credentials, 2), ['phone', 'team_b', 'phone-team_b'])
+
+ // The laptop switches teams. Its new token reaches its running turn, which
+ // still bills the team its message chose.
+ await credentials.saveTurnCredential('chat', session('laptop', 'team_b', 'laptop-new'), 3)
+ assert.deepEqual(await billed(credentials, 1), ['laptop', 'team_a', 'laptop-new'])
+ assert.deepEqual(await billed(credentials, 2), ['phone', 'team_b', 'phone-team_b'])
+ assert.deepEqual(await billed(credentials, 3), ['laptop', 'team_b', 'laptop-new'])
+
+ // A renewal from the phone reaches only the phone's turn.
+ await credentials.renewLatestCredential('chat', session('phone', 'team_b', 'phone-renewed'))
+ assert.deepEqual(await billed(credentials, 1), ['laptop', 'team_a', 'laptop-team_a'])
+ assert.deepEqual(await billed(credentials, 2), ['phone', 'team_b', 'phone-renewed'])
+ assert.deepEqual(await billed(credentials, 3), ['laptop', 'team_b', 'laptop-new'])
+})
+
+test('no later message or renewal changes who pays for an earlier turn', async (t) => {
+ useSecret(t)
+ const credentials = await turnCredentialWith(t, memoryRedis())
+ let seed = 0x5eed
+ const pick = (items) => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return items[seed % items.length] }
+ for (let run = 0; run < 25; run++) {
+ globalThis.__memoryRedis = memoryRedis().client
+ const funders = new Map() // turn -> [login, team]
+ const tokens = new Map() // login -> every token it stored
+ let token = 0
+ for (let step = 0; step < 6; step++) {
+ const sent = session(pick(['laptop', 'phone', 'tablet']), pick(['team_a', 'team_b']), `token-${++token}`)
+ tokens.set(sent.loginId, [...(tokens.get(sent.loginId) ?? []), sent.accessToken])
+ if (funders.size && pick([true, false, false])) {
+ await credentials.renewLatestCredential('chat', sent)
+ } else {
+ const turnId = funders.size + 1
+ await credentials.saveTurnCredential('chat', sent, turnId)
+ funders.set(turnId, [sent.loginId, sent.teamId])
+ }
+ for (const [turnId, [loginId, teamId]] of funders) {
+ const where = `run ${run}, step ${step}, turn ${turnId}`
+ const pays = await billed(credentials, turnId)
+ assert.deepEqual(pays.slice(0, 2), [loginId, teamId], where)
+ assert.ok(tokens.get(loginId).includes(pays[2]), `${where}: a token of another login`)
+ }
+ }
+ }
+})
+
+test('a chat from before per-turn funding bills its latest credential until its first pinned message', async (t) => {
+ useSecret(t)
+ const credentials = await turnCredentialWith(t, memoryRedis())
+ // Before this change a paid message stored only the chat's latest credential.
+ await credentials.renewLatestCredential('chat', session('laptop', 'team_a'))
+ assert.deepEqual(await billed(credentials, 4), ['laptop', 'team_a', 'laptop-team_a'], 'a turn running across the deploy')
+ assert.deepEqual(await billed(credentials, undefined), ['laptop', 'team_a', 'laptop-team_a'])
+
+ await credentials.saveTurnCredential('chat', session('phone', 'team_b'), 5)
+ assert.equal(await billed(credentials, 4), 'unbound-turn', 'the old turn cannot bill the new sender')
+ assert.equal(await billed(credentials, undefined), 'no-turn')
+ assert.deepEqual(await billed(credentials, 5), ['phone', 'team_b', 'phone-team_b'])
+})
+
+test('a paid message whose credential cannot be stored is not admitted', async (t) => {
+ useSecret(t)
+ const store = memoryRedis()
+ const credentials = await turnCredentialWith(t, store)
+ await assert.rejects(credentials.saveTurnCredential('chat', { ...session('laptop', 'team_a'), expiresAt: Date.now() - 1 }, 1), /Sign in again/)
+ await assert.rejects(credentials.saveTurnCredential('chat', { ...session('laptop', 'team_a'), teamId: '' }, 1), /Sign in again/)
+ assert.equal(store.values.size + store.hashes.size, 0)
+})
+
+test('sign-out drops the departing login\'s turn credentials and keeps every funding record', async (t) => {
+ useSecret(t)
+ const credentials = await turnCredentialWith(t, memoryRedis())
+ await credentials.saveTurnCredential('chat', session('laptop', 'team_a'), 1)
+ await credentials.saveTurnCredential('chat', session('phone', 'team_b'), 2)
+ assert.deepEqual(await credentials.dropLoginCredentials('laptop'), [{ chatId: 'chat', latestWasLogin: false }])
+ assert.equal(await billed(credentials, 1), 'unusable')
+ assert.deepEqual(await billed(credentials, 2), ['phone', 'team_b', 'phone-team_b'])
+ assert.equal((await credentials.readTurnFunding('chat', 1)).loginId, 'laptop')
+ assert.equal((await credentials.readTurnFunding('chat', 2)).loginId, 'phone')
+ assert.equal(await credentials.readTurnFunding('chat', 3), null)
+ assert.deepEqual(await credentials.dropLoginCredentials('phone'), [{ chatId: 'chat', latestWasLogin: true }])
+ assert.equal(await billed(credentials, 2), 'unusable')
+})
+
+test('resolution bills a turn\'s recorded identity and team, or nothing', async (t) => {
+ const { resolveFunding } = await turnCredentialWith(t, memoryRedis())
+ const user = (loginId, teamId) => ({ userId: 'user-a', loginId, teamId, accessToken: `${loginId}-${teamId}`, expiresAt: Date.now() + HOUR })
+ const trial = (loginId) => ({ kind: 'trial', userId: 'user-a', loginId, expiresAt: Date.now() + HOUR })
+ const credentials = [null, trial('laptop'), trial('phone'), user('laptop', 'team_a'), user('laptop', 'team_b'), user('phone', 'team_a')]
+ const bindings = [null, { kind: 'trial', userId: 'user-a', loginId: 'laptop' }, { kind: 'user', userId: 'user-a', loginId: 'laptop', teamId: 'team_a' }]
+ for (const records of [0, 1]) for (const turnId of [null, 7]) for (const binding of bindings) {
+ for (const exact of credentials) for (const latest of credentials) {
+ const where = JSON.stringify({ records, turnId, binding, exact, latest })
+ const funding = resolveFunding(records, turnId, binding, exact, latest)
+ if (records === 0) {
+ assert.equal(funding.ok, !!latest && !('kind' in latest), where)
+ if (funding.ok) assert.equal(funding.credential, latest, where)
+ continue
+ }
+ if (!funding.ok) continue
+ assert.ok(turnId !== null && binding, where)
+ assert.deepEqual([funding.credential.userId, funding.credential.loginId], [binding.userId, binding.loginId], where)
+ assert.equal('kind' in funding.credential, binding.kind === 'trial', where)
+ if (binding.kind === 'user') assert.equal(funding.credential.teamId, binding.teamId, where)
+ }
+ }
+})