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

Keep another login's turns and credentials when one signs out

Pranitca038b9b3303
diff --git a/README.md b/README.md
index 97ac003..fcc5d48 100644
--- a/README.md
+++ b/README.md
@@ -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 the running turns it funded. 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 and revokes its token. A running turn it funded stops at its next model request; another login's turns keep running. Treat the session cookie and `SESSION_SECRET` as credentials.
## License
diff --git a/lib/agent.ts b/lib/agent.ts
index 9150567..18fbc65 100644
--- a/lib/agent.ts
+++ b/lib/agent.ts
@@ -7,7 +7,6 @@ import {
dropChatCredential,
dropLoginCredentials,
readTurnCredential,
- readTurnFunding,
renewLatestCredential,
saveTrialCredential,
saveTurnCredential,
@@ -431,11 +430,12 @@ export async function deleteDesignSession(host: SessionState): Promise<boolean>
}
/**
- * 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.
+ * After sign-out has revoked this login, deletes the chat credentials it stored.
+ * A turn this login funded finds no credential at its next model request and
+ * ends with "sign in again"; nothing falls back to another login or the
+ * deployment. It cancels no turn: libfx's cancel stops whichever turn is open
+ * when it lands, which may already be another login's, so only the credentials
+ * fence this login's turns.
*/
export async function cancelUserRuntime(userId: string, loginId?: string): Promise<void> {
for (const host of registry().values()) {
@@ -443,18 +443,9 @@ 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, latestWasLogin }) => {
- const [active, stored] = await Promise.all([getActiveTurn(chatId), readSession(chatId)])
- 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(() => {})
- }))
+ for (const { chatId, turns, latest } of await dropLoginCredentials(loginId)) {
+ log(chatId, 'signout:credentials', { turns, latest })
+ }
}
export async function debugState(host: SessionState) {
diff --git a/lib/turn-credential.ts b/lib/turn-credential.ts
index a7ff3ef..4ec8b88 100644
--- a/lib/turn-credential.ts
+++ b/lib/turn-credential.ts
@@ -191,37 +191,65 @@ export async function readExecutionFunding(chatId: string, turnId?: number): Pro
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)))
+// What sign-out deletes in one chat, from what the chat held when read: the
+// credentials of the turns this login funded, and the chat's latest credential
+// if it was this login's, named by its exact sealed value. Funding records stay,
+// so a turn whose credential is gone bills nothing rather than a fallback.
+export interface SignOutCleanup { turnIds: number[]; latestSeal: string | null }
+
+export function signOutCleanup(
+ loginId: string,
+ bindings: Record<string, unknown>,
+ latestSeal: unknown,
+ latest: TurnCredential | null,
+): SignOutCleanup {
+ const turnIds = Object.entries(bindings).filter(([, value]) => fundingBinding(value)?.loginId === loginId).map(([id]) => Number(id))
+ const own = typeof latestSeal === 'string' && latest !== null && !('kind' in latest) && latest.loginId === loginId
+ return { turnIds, latestSeal: own ? latestSeal : null }
}
-// 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 }
+// Deletes the turn credentials (KEYS[2..]), and the latest credential (KEYS[1])
+// only while it still holds the sealed value the cleanup read (ARGV[1]): one
+// another login stored since then survives. Returns {turns, latest} deleted.
+export const DROP_LOGIN_CHAT = `
+local turns = 0
+for i = 2, #KEYS do turns = turns + redis.call('DEL', KEYS[i]) end
+local latest = 0
+if ARGV[1] ~= '' and redis.call('GET', KEYS[1]) == ARGV[1] then latest = redis.call('DEL', KEYS[1]) end
+return {turns, latest}
+`
+
+// A chat a sign-out cleaned: how many turn credentials it deleted, and what
+// became of the chat's latest credential.
+export interface DroppedChat { chatId: string; turns: number; latest: 'deleted' | 'replaced' | 'not-this-login' }
// Sign-out: removes every chat credential this login stored, but not one a later
-// prompt from another login of the user has since replaced.
+// prompt from another login of the user has since replaced. Cancels nothing:
+// a turn this login funded stops at its next model request.
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: DroppedChat[] = []
- await Promise.all(chats.map(async (chatId, index) => {
- const credential = await decodeCredential(values[index * 2])
+ // One round trip reads every chat's credential and funding; a second deletes,
+ // with one compare-and-delete script per chat. The seal is decoded directly:
+ // sign-out has already revoked this login.
+ const reads = redis().pipeline()
+ for (const chatId of chats) reads.get(credentialKey(chatId)).hgetall(fundingKey(chatId))
+ const values: unknown[] = chats.length ? await reads.exec() : []
+ const cleanups = await Promise.all(chats.map(async (chatId, index) => {
+ const latestSeal = 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)))
- 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 }) }
+ return { chatId, ...signOutCleanup(loginId, bindings, latestSeal, await decodeCredential(latestSeal)) }
}))
- await redis().del(...keys, loginKey(loginId))
- return dropped
+ const owned = cleanups.filter(({ turnIds, latestSeal }) => turnIds.length || latestSeal !== null)
+ const deletes = redis().pipeline()
+ for (const { chatId, turnIds, latestSeal } of owned) {
+ deletes.eval(DROP_LOGIN_CHAT, [credentialKey(chatId), ...turnIds.map(id => turnCredentialKey(chatId, id))], [latestSeal ?? ''])
+ }
+ deletes.del(loginKey(loginId))
+ const results = await deletes.exec() as unknown[]
+ return owned.map(({ chatId, latestSeal }, index): DroppedChat => {
+ const [turns, latest] = results[index] as [number, number]
+ return { chatId, turns: Number(turns), latest: latestSeal === null ? 'not-this-login' : Number(latest) ? 'deleted' : 'replaced' }
+ })
}
export async function dropChatCredential(chatId: string): Promise<void> {
diff --git a/package.json b/package.json
index 520c854..a71474c 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,8 @@
"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",
- "test:trial:integration": "node --experimental-strip-types --test tests/trial.integration.mjs"
+ "test:trial:integration": "node --experimental-strip-types --test tests/trial.integration.mjs",
+ "test:credential:integration": "node --experimental-strip-types --test tests/turn-credential.integration.mjs"
},
"dependencies": {
"@neondatabase/serverless": "^1.1.0",
diff --git a/tests/fixtures/memory-redis.mjs b/tests/fixtures/memory-redis.mjs
index 1e73624..4379d48 100644
--- a/tests/fixtures/memory-redis.mjs
+++ b/tests/fixtures/memory-redis.mjs
@@ -17,8 +17,17 @@ export function memoryRedis() {
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
+ let deleted = 0
+ for (const key of keys) deleted += Number(values.delete(key) | hashes.delete(key) | sets.delete(key))
+ return deleted
+ },
+ // The one script lib/turn-credential.ts runs, DROP_LOGIN_CHAT: delete
+ // KEYS[2..], and KEYS[1] only while it holds ARGV[1].
+ // tests/turn-credential.integration.mjs runs the real Lua against Redis.
+ eval(_script, keys, args) {
+ const turns = commands.del(...keys.slice(1))
+ const latest = args[0] !== '' && values.get(keys[0]) === args[0] ? commands.del(keys[0]) : 0
+ return [turns, latest]
},
}
const client = {
diff --git a/tests/journal.integration.mjs b/tests/journal.integration.mjs
index 74e80bc..9026066 100644
--- a/tests/journal.integration.mjs
+++ b/tests/journal.integration.mjs
@@ -303,10 +303,10 @@ 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'), [{ chatId: 'cred-laptop', latestWasLogin: true }])
+ assert.deepEqual(await credentials.dropLoginCredentials('login-laptop'), [{ chatId: 'cred-laptop', turns: 1, latest: 'deleted' }])
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 redis.hlen(`${prefix}:funding:cred-laptop`), 1, 'sign-out keeps the funding record')
assert.equal((await credentials.readTurnCredential('cred-phone'))?.accessToken, 'access-phone-secret')
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')
diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjs
index d9fe38a..b37586b 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', 'renewLatestCredential', 'readTurnCredential', 'readExecutionFunding', 'readTurnFunding', 'dropLoginCredentials', 'dropChatCredential']))
+const credentialUrl = dataUrl(forward('credentialStore', ['saveTurnCredential', 'saveTrialCredential', 'renewLatestCredential', 'readTurnCredential', 'readExecutionFunding', '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
@@ -217,7 +217,6 @@ function fixture(t, stored = { preferredModel: null, preferredEffort: null, pref
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 chatOf = (key) => key.slice(0, key.lastIndexOf(':'))
const dropped = []
@@ -226,8 +225,8 @@ function fixture(t, stored = { preferredModel: null, preferredEffort: null, pref
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 })
+ const deleted = turns.filter(([key]) => executionCredentials.delete(key)).length
+ dropped.push({ chatId, turns: deleted, latest: latestWasLogin ? 'deleted' : 'not-this-login' })
}
return dropped
},
@@ -456,7 +455,7 @@ test('cancel stops the running libfx turn, and does nothing when the chat is idl
assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [['cancel', 'wrun_9']])
})
-test('sign-out drops only this login\'s chat credentials and cancels those chats\' running turns', async (t) => {
+test('sign-out drops only this login\'s chat credentials and cancels no turn', async (t) => {
const f = fixture(t, { libfxSessionId: 'wrun_5' })
f.credentials.set('laptop-chat', credential('user-a', 'login-laptop'))
f.credentials.set('phone-chat', credential('user-a', 'login-phone'))
@@ -467,23 +466,31 @@ test('sign-out drops only this login\'s chat credentials and cancels those chats
assert.equal(laptop.gatewaySession, null)
assert.equal(phone.gatewaySession?.loginId, 'login-phone')
assert.deepEqual([...f.credentials.keys()], ['phone-chat'])
- assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [['cancel', 'wrun_5']])
+ assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [], 'its turn stops at its next model request instead')
})
-test('signing out on the phone leaves the turn the laptop funded running', async (t) => {
+test('in a trial-marked chat, each login\'s sign-out drops only its own turns\' credentials and cancels nothing', 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')
+ const free = { kind: 'trial', userId: 'user-a', loginId: 'login-laptop', expiresAt: Date.now() + 86400000 }
+ await runtime.submitPrompt(host, 'Ada', 'Free design', 'free-1', undefined, undefined, undefined, free)
+ await runtime.submitPrompt(host, 'Ada', 'Paid follow-up', 'paid-2', undefined, undefined, undefined, undefined, credential('user-a', 'login-phone', 'phone-token'))
+ assert.equal(f.stored.trialChat, true)
+ f.setActive({ id: 2 }) // the phone's paid turn is running
+
await runtime.cancelUserRuntime('user-a', 'login-laptop')
- assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [['cancel', 'wrun_6']])
+ assert.deepEqual([...f.executionCredentials.keys()], ['shared-chat:2'], 'the phone\'s turn keeps its credential')
+ assert.equal(f.credentials.get('shared-chat')?.loginId, 'login-phone')
+ await runtime.cancelUserRuntime('user-a', 'login-phone')
+ assert.deepEqual([...f.executionCredentials.keys()], [])
+ assert.equal(f.credentials.has('shared-chat'), false)
+
+ assert.deepEqual(f.calls.filter((call) => call[0] === 'cancel'), [])
+ const signOuts = console.info.mock.calls.map((call) => JSON.parse(call.arguments[0])).filter((line) => line.event === 'signout:credentials')
+ assert.deepEqual(signOuts.map(({ session, turns, latest }) => [session, turns, latest]), [
+ ['shared-chat', 1, 'not-this-login'],
+ ['shared-chat', 1, 'deleted'],
+ ])
})
test('deletion refuses a chat with a running turn and otherwise drops its records, mapping and credential', async (t) => {
diff --git a/tests/signout.test.mjs b/tests/signout.test.mjs
index 48edac1..5b5f93a 100644
--- a/tests/signout.test.mjs
+++ b/tests/signout.test.mjs
@@ -42,6 +42,16 @@ function fixture(t) {
pipeline() {
const work = []
const pipeline = {}
+ let deletes = false
+ const drop = (key) => Number(values.delete(key) | indices.delete(key) | hashes.delete(key))
+ // Sign-out's compare-and-delete script: KEYS[2..], and KEYS[1] only while
+ // it holds ARGV[1]. tests/turn-credential.integration.mjs runs the real Lua.
+ pipeline.eval = (_script, keys, args) => {
+ deletes = true
+ work.push(() => [keys.slice(1).reduce((count, key) => count + drop(key), 0), args[0] !== '' && values.get(keys[0]) === args[0] ? drop(keys[0]) : 0])
+ return pipeline
+ }
+ pipeline.del = (...keys) => { deletes = true; work.push(() => keys.reduce((count, key) => count + drop(key), 0)); return pipeline }
for (const [name, execute] of Object.entries({
set: (key, value) => values.set(key, value),
sadd: (key, value) => indices.set(key, [...(indices.get(key) ?? []), value]),
@@ -56,6 +66,7 @@ function fixture(t) {
state.commands.push('pipeline')
state.saveStarted?.resolve()
if (state.saveGate) await state.saveGate.promise
+ if (deletes && state.fail === 'delete') throw new Error('synthetic delete failure')
return work.map((execute) => execute())
}
return pipeline
diff --git a/tests/turn-credential.integration.mjs b/tests/turn-credential.integration.mjs
new file mode 100644
index 0000000..433db34
--- /dev/null
+++ b/tests/turn-credential.integration.mjs
@@ -0,0 +1,41 @@
+import assert from 'node:assert/strict'
+import { execFile, spawn } from 'node:child_process'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { promisify } from 'node:util'
+import test from 'node:test'
+import { memoryRedis, turnCredentialWith } from './fixtures/memory-redis.mjs'
+
+// Sign-out's Lua against a throwaway local Redis: the unit tests stand in for
+// it in memory, this checks the script itself.
+const run = promisify(execFile)
+
+test('sign-out deletes the latest credential only while it holds the value it read', async (t) => {
+ const { DROP_LOGIN_CHAT } = await turnCredentialWith(t, memoryRedis())
+ const dir = await mkdtemp(join(tmpdir(), 'fx0-credential-'))
+ const socket = join(dir, 'redis.sock')
+ const server = spawn('redis-server', ['--port', '0', '--unixsocket', socket, '--save', '', '--appendonly', 'no'], { stdio: 'ignore' })
+ t.after(async () => { server.kill(); await new Promise(resolve => server.once('exit', resolve)); await rm(dir, { recursive: true, force: true }) })
+ for (let i = 0; i < 100; i++) {
+ try { await run('redis-cli', ['-s', socket, 'PING']); break } catch { await new Promise(resolve => setTimeout(resolve, 10)) }
+ }
+ const redis = async (...args) => JSON.parse((await run('redis-cli', ['-s', socket, '--json', ...args])).stdout)
+ const drop = (keys, seal) => redis('EVAL', DROP_LOGIN_CHAT, String(keys.length), ...keys, seal)
+
+ await redis('SET', 'latest', 'Fe26.2**laptop')
+ await redis('SET', 'turn:1', 'Fe26.2**laptop-1')
+ await redis('SET', 'turn:3', 'Fe26.2**laptop-3')
+ assert.deepEqual(await drop(['latest', 'turn:1', 'turn:3', 'turn:9'], 'Fe26.2**laptop'), [2, 1])
+ assert.equal(await redis('EXISTS', 'latest', 'turn:1', 'turn:3'), 0)
+
+ // Another login stored the chat's latest credential after sign-out read it.
+ await redis('SET', 'latest', 'Fe26.2**phone')
+ await redis('SET', 'turn:4', 'Fe26.2**laptop-4')
+ assert.deepEqual(await drop(['latest', 'turn:4'], 'Fe26.2**laptop'), [1, 0])
+ assert.equal(await redis('GET', 'latest'), 'Fe26.2**phone')
+
+ // The latest credential was never this login's.
+ assert.deepEqual(await drop(['latest'], ''), [0, 0])
+ assert.equal(await redis('GET', 'latest'), 'Fe26.2**phone')
+})
diff --git a/tests/turn-funding.test.mjs b/tests/turn-funding.test.mjs
index 8145441..771c4e0 100644
--- a/tests/turn-funding.test.mjs
+++ b/tests/turn-funding.test.mjs
@@ -100,19 +100,61 @@ test('a paid message whose credential cannot be stored is not admitted', async (
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())
+ const store = memoryRedis()
+ const credentials = await turnCredentialWith(t, store)
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 credentials.dropLoginCredentials('laptop'), [{ chatId: 'chat', turns: 1, latest: 'not-this-login' }])
+ assert.equal(await billed(credentials, 1), 'unusable', 'no fallback to the latest credential')
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.deepEqual(Object.keys(store.hashes.get('test:funding:chat')), ['1', '2'])
+ assert.deepEqual(await credentials.dropLoginCredentials('laptop'), [], 'a repeated sign-out finds nothing')
+ assert.deepEqual(await credentials.dropLoginCredentials('phone'), [{ chatId: 'chat', turns: 1, latest: 'deleted' }])
assert.equal(await billed(credentials, 2), 'unusable')
+ assert.equal(await credentials.readTurnCredential('chat'), null)
})
+test('sign-out keeps a latest credential another login stored after it looked', async (t) => {
+ useSecret(t)
+ const store = memoryRedis()
+ const credentials = await turnCredentialWith(t, store)
+ await credentials.saveTurnCredential('chat', session('laptop', 'team_a'), 1)
+ // The phone's message lands between the laptop's sign-out reading the chat
+ // and running its delete pipeline.
+ const open = store.client.pipeline
+ store.client.pipeline = () => {
+ const pipeline = open()
+ const { eval: script, exec } = pipeline
+ let deletes = false
+ pipeline.eval = (...args) => { deletes = true; return script(...args) }
+ pipeline.exec = async () => {
+ if (deletes) await credentials.saveTurnCredential('chat', session('phone', 'team_b'), 2)
+ return exec()
+ }
+ return pipeline
+ }
+ const dropped = await credentials.dropLoginCredentials('laptop')
+ assert.equal((await credentials.readTurnCredential('chat'))?.loginId, 'phone', 'the phone\'s credential survives')
+ assert.deepEqual(dropped, [{ chatId: 'chat', turns: 1, latest: 'replaced' }])
+ assert.equal(await billed(credentials, 1), 'unusable')
+ assert.deepEqual(await billed(credentials, 2), ['phone', 'team_b', 'phone-team_b'])
+})
+
+test('sign-out cleanup names only the departing login\'s turns, and the latest credential only if it is that login\'s', async (t) => {
+ const { signOutCleanup } = await turnCredentialWith(t, memoryRedis())
+ const record = (kind, loginId) => JSON.stringify({ kind, userId: 'user-a', loginId, ...(kind === 'user' ? { teamId: 'team_a' } : {}) })
+ const bindings = { 1: record('trial', 'laptop'), 2: record('user', 'phone'), 3: record('user', 'laptop'), 4: 'not a record' }
+ const user = (loginId) => ({ userId: 'user-a', loginId, accessToken: 'token', teamId: 'team_a', expiresAt: Date.now() + HOUR })
+ assert.deepEqual(plan(signOutCleanup('laptop', bindings, 'sealed-laptop', user('laptop'))), [[1, 3], 'sealed-laptop'])
+ assert.deepEqual(plan(signOutCleanup('laptop', bindings, 'sealed-phone', user('phone'))), [[1, 3], null])
+ assert.deepEqual(plan(signOutCleanup('phone', bindings, 'sealed-laptop', user('laptop'))), [[2], null])
+ assert.deepEqual(plan(signOutCleanup('tablet', bindings, null, null)), [[], null])
+ // A seal that no longer opens, such as an expired one, names nothing to compare.
+ assert.deepEqual(plan(signOutCleanup('laptop', {}, 'expired-seal', null)), [[], null])
+})
+
+const plan = ({ turnIds, latestSeal }) => [turnIds, latestSeal]
+
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 })