import { TestStore } from './helpers/sqlite.ts'
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { test, type TestContext } from 'node:test'
const fake: any = globalThis
fake.store = new TestStore()
const runtime = `
export const packageStorage = () => ({
sql: async(q,p)=>globalThis.store.sql(q,p),
get: async (key) => globalThis.store.get(key) ?? null,
set: async (key, value) => { globalThis.store.set(key, value) },
delete: async (key) => { globalThis.store.delete(key) },
})
export const kody = { secretList:async()=>({secrets:[{name:'audible-login',scope:'user',updated_at:'1',description:JSON.stringify({registration:'00000000-0000-4000-8000-000000000001'})}]}) }
export const credential=async()=>({name:'audible-login',scope:'user',kind:'login',hosts:['api.audible.ca','api.amazon.ca'],fetch:globalThis.fetch});
export const packageContext = {}
`
registerHooks({
resolve(specifier, context, next) {
return specifier === 'kody:runtime' ? { url: 'mock:kody-runtime', shortCircuit: true } : next(specifier, context)
},
load(url, context, next) {
return url === 'mock:kody-runtime' ? { format: 'module', shortCircuit: true, source: runtime } : next(url, context)
},
})
const { default: audibleRequest } = await import('../request.ts')
const { registerDevice } = await import('../register.ts')
const { disconnect } = await import('../disconnect.ts')
const { resolveLocale } = await import('../locales.ts')
const { startDeadline } = await import('../deadline.ts')
const unhandled: unknown[] = []
process.on('unhandledRejection', (reason) => unhandled.push(reason))
const MiB = 1024 * 1024
const CAP = 16 * MiB
const inits: RequestInit[] = []
let sent: string[] = []
let steps: Array<() => Response | Promise<Response>> = []
fake.fetch = async (url: string, init: RequestInit = {}) => {
inits.push(init)
sent.push(`${init.method ?? 'GET'} ${new URL(url).pathname}`)
return (steps.shift() ?? (() => Response.json({})))()
}
const answers = (...next: typeof steps) => {
sent = []
steps = next
}
let now = 0
const settle = async () => {
for (let turn = 0; turn < 5; turn++) await new Promise((resolve) => setImmediate(resolve))
}
const startClock = (t: TestContext) => {
t.mock.timers.enable({ apis: ['setTimeout'] })
now = 0
}
const advanceTo = async (t: TestContext, ms: number) => {
while (now < ms) {
const step = Math.min(50, ms - now)
t.mock.timers.tick(step)
now += step
await settle()
}
}
const until = (ms: number) => (ms <= now ? Promise.resolve() : new Promise<void>((resolve) => setTimeout(resolve, ms - now)))
const at = (ms: number, make: () => Response) => () => until(ms).then(make)
const never = () => new Promise<Response>(() => {})
const failsAt = (ms: number, error: Error) => () => until(ms).then(() => Promise.reject(error))
const timedBody = (parts: Array<[ms: number, bytes: Uint8Array]>, endAt: number) => {
const state = { canceled: false, pulled: 0 }
let next = 0
const stream = new ReadableStream<Uint8Array>({
async pull(controller) {
state.pulled++
const part = parts[next++]
await until(part ? part[0] : endAt)
if (state.canceled) return
if (part) controller.enqueue(part[1])
else controller.close()
},
cancel() {
state.canceled = true
},
}, { highWaterMark: 0 })
return { stream, state }
}
type Outcome<T> = { done?: 'ok' | 'error'; value?: T; error?: any }
const track = <T>(promise: Promise<T>) => {
const outcome: Outcome<T> = {}
promise.then((value) => Object.assign(outcome, { done: 'ok', value }), (error) => Object.assign(outcome, { done: 'error', error }))
return outcome
}
const ownWords = (error: any, message: string) => {
assert.ok(error instanceof Error, `not an Error: ${error}`)
assert.equal(error.message, message)
assert.equal(error.name, 'Error')
assert.equal('cause' in error, false)
assert.deepEqual(Object.keys(error), [])
for (const channel of [error.message, String(error), error.stack]) assert.doesNotMatch(channel, /SYNTHETIC|state_token/, channel)
}
const reset = () => fake.store.clear()
const LIBRARY = { path: '/1.0/library', query: { num_results: 1 } }
const LATE = 'Audible API GET /1.0/library?num_results=1 → no answer within 20 s'
const utf8 = (text: string) => new TextEncoder().encode(text)
const transportError = () => new Error('SYNTHETIC_REMOTE_TEXT at https://api.audible.ca/1.0/collections/__WISHLIST/items?state_token=SYNTHETIC_STATE_TOKEN')
test('a call whose answer never comes fails at 20 s in package words, and a late answer is canceled unread', async (t) => {
startClock(t)
reset()
const late = timedBody([[0, utf8('{"items":["SYNTHETIC_ROW"]}')]], 0)
answers(at(25_000, () => new Response(late.stream)))
const outcome = track(audibleRequest(LIBRARY))
await advanceTo(t, 19_950)
assert.equal(outcome.done, undefined, 'failed before 20 s')
await advanceTo(t, 20_000)
assert.equal(outcome.done, 'error', 'still waiting at 20 s')
ownWords(outcome.error, LATE)
await advanceTo(t, 25_100)
assert.equal(late.state.canceled, true, 'the late body was not canceled')
assert.equal(late.state.pulled, 0, 'the late body was read')
assert.deepEqual(sent, ['GET /1.0/library'])
answers(failsAt(25_000, transportError()))
now = 0
const rejected = track(audibleRequest(LIBRARY))
await advanceTo(t, 20_000)
ownWords(rejected.error, LATE)
await advanceTo(t, 25_100)
assert.deepEqual(unhandled, [])
})
test('a slow but healthy read passes: headers at 19 s, a body split inside a character that ends before 20 s', async (t) => {
startClock(t)
reset()
const bytes = utf8('{"title":"Café"}')
const split = bytes.indexOf(0xc3) + 1
const body = timedBody([[19_300, bytes.subarray(0, split)], [19_600, bytes.subarray(split)]], 19_900)
answers(at(19_000, () => new Response(body.stream)))
const outcome = track(audibleRequest(LIBRARY))
await advanceTo(t, 19_950)
assert.equal(outcome.done, 'ok', outcome.error?.message)
assert.deepEqual(outcome.value, { title: 'Café' })
})
test('the same body ending after 20 s fails at 20 s, and its read is canceled', async (t) => {
startClock(t)
reset()
const bytes = utf8('{"title":"Café"}')
const body = timedBody([[19_300, bytes.subarray(0, 5)], [19_600, bytes.subarray(5)]], 20_500)
answers(at(19_000, () => new Response(body.stream)))
const outcome = track(audibleRequest(LIBRARY))
await advanceTo(t, 20_000)
assert.equal(outcome.done, 'error', 'still waiting at 20 s')
ownWords(outcome.error, LATE)
await advanceTo(t, 20_600)
assert.equal(body.state.canceled, true)
})
test('a success body of exactly 16 MiB passes; one byte more fails in package words, whatever Content-Length says', async () => {
reset()
answers(() => new Response(`"${'x'.repeat(CAP - 2)}"`))
assert.equal(((await audibleRequest(LIBRARY)) as string).length, CAP - 2)
const OVER = 'Audible API GET /1.0/library?num_results=1 → HTTP 200 (body: over 16 MB)'
for (const headers of [{}, { 'content-length': '2' }]) {
answers(() => new Response(`"${'x'.repeat(CAP - 1)}"`, { headers }))
ownWords(await audibleRequest(LIBRARY).then(() => assert.fail('expected an error'), (error) => error), OVER)
}
})
test('an endless success body stops being pulled just past 16 MiB', async () => {
reset()
const state = { pulled: 0, canceled: false }
const CHUNK = 64 * 1024
const stream = new ReadableStream<Uint8Array>({
pull(controller) {
if (++state.pulled > (4 * CAP) / CHUNK) return controller.close()
controller.enqueue(new Uint8Array(CHUNK).fill(120))
},
cancel() {
state.canceled = true
},
}, { highWaterMark: 0 })
answers(() => new Response(stream, { headers: { 'content-length': '10' } }))
ownWords(await audibleRequest(LIBRARY).then(() => assert.fail('expected an error'), (error) => error), 'Audible API GET /1.0/library?num_results=1 → HTTP 200 (body: over 16 MB)')
assert.ok(state.pulled <= CAP / CHUNK + 2, `pulled ${state.pulled} chunks`)
assert.equal(state.canceled, true)
})
test('success bodies keep their shapes: JSON, text, and an empty body as null', async () => {
reset()
for (const [body, value] of [['{"items":[1]}', { items: [1] }], ['plain words', 'plain words'], ['', null], [null, null]] as const) {
answers(() => new Response(body))
assert.deepEqual(await audibleRequest(LIBRARY), value, String(body))
}
})
const REGISTRATION = {
authorizationCode: 'SYNTHETIC_CODE',
codeVerifier: 'SYNTHETIC_VERIFIER',
locale: resolveLocale('ca'),
serial: 'S1',
}
const registered = (expiresIn: unknown = 3600) => Response.json({ response: { success: {
tokens: { mac_dms: { adp_token: 'adp', device_private_key: 'key' }, bearer: { access_token: 'access', refresh_token: 'refresh', expires_in: expiresIn } },
extensions: { device_info: { device_serial_number: 'S1', device_type: 'D1' }, customer_info: { user_id: 'amzn1.account.X' } },
} } })
test('SECURITY: a registration whose fetch fails throws only package words and sends its code once', async () => {
answers(() => Promise.reject(transportError()))
ownWords(await registerDevice(REGISTRATION).then(() => assert.fail('expected an error'), (error) => error), 'Device registration → no answer. Start Connect again.')
assert.deepEqual(sent, ['POST /auth/register'])
answers(() => new Response(new ReadableStream({ start(controller) { controller.error(transportError()) } })))
ownWords(await registerDevice(REGISTRATION).then(() => assert.fail('expected an error'), (error) => error), 'Device registration response missing success payload.')
assert.deepEqual(sent, ['POST /auth/register'])
})
test('a registration keeps Kody\'s own bound: an answer at 100 s still connects', async (t) => {
startClock(t)
answers(at(100_000, registered))
const outcome = track(registerDevice(REGISTRATION))
await advanceTo(t, 100_050)
assert.equal(outcome.done, 'ok', outcome.error?.message)
assert.equal((outcome.value as any).serial, 'S1')
assert.deepEqual(sent, ['POST /auth/register'])
})
const REMOVE = { method: 'DELETE', path: '/1.0/collections/__WISHLIST/items', query: { asins: 'B000000001' } }
const REMOVE_LATE = 'Audible API DELETE /1.0/collections/__WISHLIST/items?asins=B000000001 → no answer within 20 s'
const collection = () => Response.json({ state_token: 'SYNTHETIC_STATE_TOKEN' })
test('SECURITY: a Wishlist remove whose DELETE never answers names the ASIN at 20 s, never the state_token', async (t) => {
startClock(t)
reset()
answers(collection, never)
const outcome = track(audibleRequest(REMOVE))
await advanceTo(t, 20_000)
assert.equal(outcome.done, 'error', 'still waiting at 20 s')
ownWords(outcome.error, REMOVE_LATE)
assert.deepEqual(sent, ['GET /1.0/collections/__WISHLIST', 'DELETE /1.0/collections/__WISHLIST/items'])
})
test('SECURITY: a Wishlist remove whose collection body is still coming at 20 s sends no DELETE', async (t) => {
startClock(t)
reset()
const body = timedBody([[19_800, utf8('{"state_token":"SYNTHETIC_')]], 30_000)
answers(at(19_500, () => new Response(body.stream)))
const outcome = track(audibleRequest(REMOVE))
await advanceTo(t, 20_000)
assert.equal(outcome.done, 'error', 'still waiting at 20 s')
ownWords(outcome.error, REMOVE_LATE)
await advanceTo(t, 21_000)
assert.deepEqual(sent, ['GET /1.0/collections/__WISHLIST'])
assert.equal(body.state.canceled, true)
})
const startElapsedClock = (t: TestContext) => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 })
now = 0
}
test('an answer that comes after 20 s, before the timer callback runs, is canceled unread', async (t) => {
startElapsedClock(t)
reset()
let deliver = (_: Response) => {}
answers(() => new Promise<Response>((resolve) => {
deliver = resolve
}))
const late = timedBody([[0, utf8('{"items":["SYNTHETIC_ROW"]}')]], 0)
const outcome = track(audibleRequest(LIBRARY))
await settle()
t.mock.timers.setTime(20_000)
deliver(new Response(late.stream))
await settle()
assert.equal(outcome.done, 'error', outcome.done && JSON.stringify(outcome.value))
ownWords(outcome.error, LATE)
assert.equal(late.state.canceled, true)
assert.equal(late.state.pulled, 0)
})
test('a budget past its cutoff starts no work, and drops a value that crosses the cutoff exactly once', async (t) => {
startElapsedClock(t)
const deadline = startDeadline(20_000, () => new Error('late'))
const drops: string[] = []
let finish = (_: string) => {}
const result = deadline.run(() => new Promise<string>((resolve) => {
finish = resolve
}), (value) => drops.push(value)).then((value) => value, (error) => error)
t.mock.timers.setTime(20_000)
finish('value')
assert.equal(((await result) as Error).message, 'late')
let starts = 0
await assert.rejects(deadline.run(async () => {
starts++
}), { message: 'late' })
assert.equal(starts, 0)
t.mock.timers.tick(1)
await settle()
assert.deepEqual(drops, ['value'])
deadline.end()
})
const BAD_EXPIRIES: unknown[] = ['SYNTHETIC_BAD_EXPIRY', 1e300, -5, 0, '', { toString: null }, true, [1800]]
test('SECURITY: a registration with an invalid expiry fails in package words; a numeric string still counts', async () => {
for (const expiresIn of BAD_EXPIRIES) {
answers(() => registered(expiresIn))
ownWords(await registerDevice(REGISTRATION).then(() => assert.fail('expected an error'), (error) => error), 'Device registration response has an invalid token expiry.')
}
answers(() => registered('1800'))
const before = Math.floor(Date.now() / 1000)
const { expiresAtSeconds } = await registerDevice(REGISTRATION)
assert.ok(expiresAtSeconds >= before + 1800 && expiresAtSeconds <= before + 1801, String(expiresAtSeconds))
})
test('each call clears its timers, on success and on failure', async () => {
const active = new Set<unknown>()
const realSet = globalThis.setTimeout
const realClear = globalThis.clearTimeout
globalThis.setTimeout = ((run: () => void, ms?: number) => {
const id = realSet(() => {
active.delete(id)
run()
}, ms)
active.add(id)
return id
}) as typeof setTimeout
globalThis.clearTimeout = ((id: Parameters<typeof clearTimeout>[0]) => {
active.delete(id)
realClear(id)
}) as typeof clearTimeout
try {
reset()
for (const step of [() => Response.json({ items: [] }), () => new Response('Not found', { status: 404 }), () => Promise.reject(transportError())]) {
answers(step)
await audibleRequest(LIBRARY).catch(() => {})
assert.equal(active.size, 0, sent.join(', '))
}
answers(collection, () => new Response(null, { status: 204 }))
await audibleRequest(REMOVE)
answers(() => new Response(null, { status: 200 }))
await disconnect()
assert.equal(active.size, 0)
} finally {
globalThis.setTimeout = realSet
globalThis.clearTimeout = realClear
}
})
test('no fetch init carries an AbortSignal: Kody\'s package-app bridge refuses a Request with one', () => {
assert.ok(inits.length > 20, `only ${inits.length} sends`)
for (const init of inits) assert.equal('signal' in init, false)
assert.deepEqual(unhandled, [])
})