Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@danj/audible-auth

Locked Audible gateway using one owner-provisioned Kody login.

FollowFork

Files

tokens-wire.test.ts

402 lines · 20.8 KB · TypeScript
import { TestStore } from './helpers/sqlite.ts'
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { beforeEach, test } 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()=>{if(!globalThis.loginMapped)throw new Error('missing');return {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 { default: readAccountCredits } = await import('../credits.ts')

const sent: Array<{ url: string; method: string; authorization: string | null; body: string; headers: Record<string, string> }> = []
let respond = (_url: string) => Response.json({ items: [] })
fake.fetch = async (url: string, init: RequestInit = {}) => {
	const headers = new Headers(init.headers)
	sent.push({ url, method: init.method ?? 'GET', authorization: headers.get('authorization'), body: String(init.body ?? ''), headers: Object.fromEntries(headers) })
	return respond(url)
}

beforeEach(() => connect())

test('before Connect, a call throws NotConnectedError and sends nothing', async () => {
	fake.store.clear()
	fake.loginMapped = false
	await assert.rejects(audibleRequest({ path: '/1.0/library' }), { name: 'NotConnectedError' })
	assert.deepEqual(sent, [])
})

test('a call outside the allowlist throws and sends nothing', async () => {
	await assert.rejects(audibleRequest({ path: '/1.0/account/information' }), {
		message: 'The Audible credential package does not allow GET /1.0/account/information.',
	})
	assert.deepEqual(sent, [])
})

const connect = () => { fake.store.clear(); fake.loginMapped = true }
const notAString = { message: 'The Audible credential package takes a string method and path.' }

test('a method or path that is not a string throws and sends nothing', async () => {
	connect()
	const path: any = new URL('https://api.audible.ca/1.0/library')
	const method: any = new String('GET')
	await assert.rejects(audibleRequest({ path }), notAString)
	await assert.rejects(audibleRequest({ method, path: '/1.0/library' }), notAString)
	assert.deepEqual(sent, [])
	fake.store.clear()
})


test('./credits sends only its fixed account call and returns only the summary', async () => {
	sent.length = 0
	respond = () => Response.json({
		customer_information: {
			customer_id: 'synthetic-account-id',
			credits_fulfillment_data: { credits_to_be_received: 1 },
			subscription: { subscription_details: [{ next_bill_date: '2026-11-15T07:00:00Z', next_bill_amount: { amount: 14.95, currency: 'CAD' } }] },
		},
		customer_benefits: { credit_summary: { available_credit_count: 3 } },
	})
	const summary = await readAccountCredits()
	assert.deepEqual(summary, {
		nextCharge: { date: '2026-11-15', credits: 1, cents: 1495, currency: 'CAD' },
	})
	assert.equal(JSON.stringify(summary).includes('synthetic-account-id'), false)
	assert.deepEqual(sent.map(({ url, method, authorization }) => ({ url, method, authorization })), [{
		url: 'https://api.audible.ca/1.0/account/information?response_groups=customer_benefits%2Cplan_summary%2Csubscription_details&source=Credit',
		method: 'GET',
		authorization: null,
	}])
})

const REMOVE = '/1.0/collections/__WISHLIST/items'
const COLLECTION_URL = 'https://api.audible.ca/1.0/collections/__WISHLIST'
const collection = () => Response.json({ collection_id: '__WISHLIST', state_token: 'synthetic-state-1' })
const wishlistRemove = async (answers: Array<Response | Error>, asins: string | string[] = 'B000000001') => {
	connect()
	sent.length = 0
	respond = () => {
		const next = answers.shift()!
		if (next instanceof Error) throw next
		return next
	}
	return audibleRequest({ method: 'DELETE', path: REMOVE, query: { asins } })
}
const removeFails = (answers: Array<Response | Error>, asins?: string | string[]) => wishlistRemove(answers, asins).then(() => assert.fail('expected an error'), (error) => error)

const libraryItem = { path: '/1.0/library/B000000001' }
const failure = async (call: Parameters<typeof audibleRequest>[0]) => {
	try {
		await audibleRequest(call)
	} catch (error) {
		return error as any
	}
	assert.fail('expected an AudibleApiError')
}
const TAGS = '(not-found|signature|auth|content-type|invalid)'
const ANSWER = `HTTP \\d{3}(?: \\(body: (?:json|text|empty)(?:; tags: ${TAGS}(?:, ${TAGS})*)?\\))?`
const OWNED = new RegExp(`^Audible API (?:GET|DELETE) \\S+ → ${ANSWER}$`)

test('an Audible error crosses ./request as status, call, body shape, and tags, never Audible text', async () => {
	respond = () => Response.json({ error_code: '000404', message: 'Item not found', detail: 'synthetic-detail' }, { status: 404 })
	const error = await failure(libraryItem)
	assert.equal(error.name, 'AudibleApiError')
	assert.equal(error.status, 404)
	assert.equal(error.message, 'Audible API GET /1.0/library/B000000001 → HTTP 404 (body: json; tags: not-found)')
	assert.deepEqual(Object.keys(error).sort(), ['name', 'status'])
	assert.equal(error.cause, undefined)
})

test('each error tag stands only for its fixed phrases, in a fixed order', async () => {
	const cases: Array<[body: BodyInit | null, answer: string]> = [
		[JSON.stringify({ message: 'NotFound' }), 'HTTP 400 (body: json; tags: not-found)'],
		[JSON.stringify({ error: 'not_found' }), 'HTTP 400 (body: json; tags: not-found)'],
		[JSON.stringify({ message: 'Request is not signed' }), 'HTTP 400 (body: json; tags: signature)'],
		[JSON.stringify({ message: 'Missing x-adp-signature' }), 'HTTP 400 (body: json; tags: signature)'],
		['Unauthorized', 'HTTP 400 (body: text; tags: auth)'],
		['Authentication required', 'HTTP 400 (body: text; tags: auth)'],
		[JSON.stringify({ message: 'Unsupported Media Type' }), 'HTTP 400 (body: json; tags: content-type)'],
		[JSON.stringify({ message: 'Bad Content-Type' }), 'HTTP 400 (body: json; tags: content-type)'],
		['<html>400 Bad Request</html>', 'HTTP 400 (body: text; tags: invalid)'],
		[JSON.stringify({ message: 'Malformed signed token: invalid' }), 'HTTP 400 (body: json; tags: signature, auth, invalid)'],
		[JSON.stringify({ message: 'Headphones on sale, untokenized' }), 'HTTP 400 (body: json)'],
		['[]', 'HTTP 400 (body: json)'],
		['plain words', 'HTTP 400 (body: text)'],
		[' \n ', 'HTTP 400 (body: empty)'],
		[null, 'HTTP 400 (body: empty)'],
	]
	for (const [body, answer] of cases) {
		respond = () => new Response(body, { status: 400 })
		assert.equal((await failure(libraryItem)).message, `Audible API GET /1.0/library/B000000001 → ${answer}`, String(body))
	}
})

test('only the first 4 KB of an error body count toward its tags', async () => {
	respond = () => new Response(`${'x'.repeat(4083)} not found`, { status: 404 })
	assert.equal((await failure(libraryItem)).message, 'Audible API GET /1.0/library/B000000001 → HTTP 404 (body: text; tags: not-found)')
	respond = () => new Response(`${'x'.repeat(4096)} not found`, { status: 404 })
	assert.equal((await failure(libraryItem)).message, 'Audible API GET /1.0/library/B000000001 → HTTP 404 (body: text)')
	let pulled = 0
	respond = () => new Response(new ReadableStream({ pull(controller) { pulled++; controller.enqueue(new Uint8Array(1024).fill(120)) } }), { status: 500 })
	assert.equal((await failure(libraryItem)).message, 'Audible API GET /1.0/library/B000000001 → HTTP 500 (body: text)')
	assert.ok(pulled <= 6, `pulled ${pulled} chunks of an endless body`)
})

const leaks: Array<[name: string, body: unknown, secret: string]> = [
	['short login code', { message: 'Authorization code ANDEMO12345' }, 'ANDEMO12345'],
	['echoed short header', { message: 'Authorization: Bearer shortDemoToken' }, 'shortDemoToken'],
	['token split by spaces', { message: 'Bearer Atna| SYNTHETIC012345 SYNTHETIC678901' }, 'SYNTHETIC012345'],
	['token split by Unicode spaces', { message: 'Bearer Atna|\u00a0SYNTHETIC012345\u2028SYNTHETIC678901' }, 'SYNTHETIC012345'],
	['private key split across lines', { message: '-----BEGIN PRIVATE KEY-----\nMIIEFAKEDEMO1234\nABCDFAKEDEMO5678' }, 'MIIEFAKEDEMO1234'],
	['numeric login code', { error_code: 1234567890 }, '1234567890'],
	['token split across fields', { error_code: 'SYNTHETIC012345', error: 'SYNTHETIC678901', message: 'SYNTHETIC234567' }, 'SYNTHETIC678901'],
]
const leaksNothing = (error: any, secret: string) => {
	for (const channel of [error.message, String(error), error.stack]) assert.equal(channel.includes(secret), false, `exposed: ${channel}`)
	assert.match(error.message, OWNED)
}

for (const [name, body, secret] of leaks) {
	test(`SECURITY: no ${name} reaches a failed GET's error`, async () => {
		connect()
		respond = () => Response.json(body, { status: 403 })
		leaksNothing(await failure(libraryItem), secret)
	})
	test(`SECURITY: no ${name} reaches a failed Wishlist remove's error`, async () => {
		leaksNothing(await removeFails([collection(), Response.json(body, { status: 404 })]), secret)
		leaksNothing(await removeFails([Response.json(body, { status: 404 })]), secret)
	})
}


test('a Wishlist add sends the one ASIN', async () => {
	connect()
	respond = () => Response.json({})
	sent.length = 0
	await audibleRequest({ method: 'POST', path: '/1.0/wishlist', body: { asin: 'B000000001' } })
	assert.deepEqual(sent.map(({ url, method, body }) => ({ url, method, body })), [{
		url: 'https://api.audible.ca/1.0/wishlist',
		method: 'POST',
		body: '{"asin":"B000000001"}',
	}])
})

test('a Wishlist add with another own field throws and sends nothing', async () => {
	connect()
	sent.length = 0
	await assert.rejects(audibleRequest({ method: 'POST', path: '/1.0/wishlist', body: { asin: 'B000000001', extra: 'outside-policy' } }), {
		message: 'The Audible credential package does not allow that body for POST /1.0/wishlist.',
	})
	assert.deepEqual(sent, [])
})

test('a Wishlist remove reads the state_token, then sends one DELETE for every ASIN, with x-amz-access-token and no Authorization', async () => {
	assert.equal(await wishlistRemove([collection(), new Response(null, { status: 204 })], ['B000000001', 'B000000002']), null)
	assert.deepEqual(sent.map(({ url, method, body, headers }) => ({ url, method, body, headers })), [
		{ url: COLLECTION_URL, method: 'GET', body: '', headers: { accept: 'application/json', 'user-agent': 'Audible/671 CFNetwork/1240.0.4 Darwin/20.6.0' } },
		{ url: `${COLLECTION_URL}/items?state_token=synthetic-state-1&asins=B000000001&asins=B000000002`, method: 'DELETE', body: '', headers: { accept: 'application/json', 'user-agent': 'Audible/671 CFNetwork/1240.0.4 Darwin/20.6.0' } },
	])
})

test('every other Audible call lets the login inject its header', async () => {
	connect()
	sent.length = 0
	respond = () => Response.json({})
	await audibleRequest({ path: '/1.0/wishlist' })
	await audibleRequest({ method: 'POST', path: '/1.0/wishlist', body: { asin: 'B000000001' } })
	assert.deepEqual(sent.map(({ headers }) => headers), [
		{ accept: 'application/json' },
		{ accept: 'application/json', 'content-type': 'application/json' },
	])
})

test('a Wishlist remove that fails is sent once, and its error names the ASINs but never the state_token', async () => {
	const error = await removeFails([collection(), Response.json({ message: 'Not found' }, { status: 404 })], ['B000000001', 'B000000002'])
	assert.equal(error.name, 'AudibleApiError')
	assert.equal(error.status, 404)
	assert.equal(error.message, `Audible API DELETE ${REMOVE}?asins=B000000001&asins=B000000002 → HTTP 404 (body: json; tags: not-found)`)
	for (const channel of [error.message, String(error), error.stack]) assert.equal(channel.includes('synthetic-state'), false, channel)
	assert.equal(sent.length, 2)
})

test('a Wishlist remove whose collection GET fails sends no DELETE, and its error names the GET', async () => {
	const error = await removeFails([new Response('Forbidden', { status: 403 })])
	assert.equal(error.status, 403)
	assert.equal(error.message, 'Audible API GET /1.0/collections/__WISHLIST → HTTP 403 (body: text; tags: auth)')
	assert.deepEqual(sent.map(({ method }) => method), ['GET'])
})

test('a collection answer with no usable state_token sends no DELETE and quotes nothing', async () => {
	for (const body of [{}, { state_token: '' }, { state_token: 7 }, { state_token: 'x'.repeat(4097) }, null, 'SYNTHETIC012345']) {
		const error = await removeFails([Response.json(body)])
		assert.equal(error.message, 'Audible gave no state_token for the Wishlist, so the remove was not sent.', JSON.stringify(body))
		assert.deepEqual(sent.map(({ method }) => method), ['GET'])
	}
})


test('a Wishlist remove outside its policy sends nothing', async () => {
	connect()
	sent.length = 0
	for (const call of [
		{ method: 'DELETE', path: '/1.0/wishlist/B000000001' },
		{ method: 'DELETE', path: '/1.0/collections/__ARCHIVE/items', query: { asins: 'B000000001' } },
		{ path: '/1.0/collections/__WISHLIST' },
		{ method: 'DELETE', path: REMOVE, query: { asins: 'B000000001', state_token: 'from-the-caller' } },
		{ method: 'DELETE', path: REMOVE, query: { asins: 'nope' } },
		{ method: 'DELETE', path: REMOVE, query: { asins: 'B000000001' }, body: { asin: 'B000000001' } },
	]) await assert.rejects(audibleRequest(call as any), /^Error: The Audible credential package does not allow /, JSON.stringify(call))
	assert.deepEqual(sent, [])
})

const unreadable = (status: number) => new Response(new ReadableStream({ start(controller) { controller.error(new Error('synthetic read failure SYNTHETIC012345')) } }), { status })
let stallStarted = false
const stalled = (status: number) => new Response(new ReadableStream({ pull() { stallStarted = true; return new Promise(() => {}) } }, { highWaterMark: 0 }), { status })
const keepsNoReadError = (error: any) => {
	assert.equal(error.name, 'AudibleApiError')
	assert.equal(error.cause, undefined)
	for (const channel of [error.message, String(error), error.stack]) assert.doesNotMatch(channel, /synthetic read failure|SYNTHETIC012345/)
}

test('a failed GET whose error body cannot be read keeps its status and no tags', async () => {
	connect()
	respond = () => unreadable(500)
	const error = await failure(libraryItem)
	keepsNoReadError(error)
	assert.equal(error.status, 500)
	assert.equal(error.message, 'Audible API GET /1.0/library/B000000001 → HTTP 500')
})

test('a failed call whose error body never ends reports its status after one second', { timeout: 5000 }, async (t) => {
	t.mock.timers.enable({ apis: ['setTimeout'] })
	stallStarted = false
	const outcome = removeFails([collection(), stalled(404)])
	for (let turn = 0; !stallStarted && turn < 1000; turn++) await new Promise((resolve) => setImmediate(resolve))
	assert.ok(stallStarted, 'the DELETE answer was never read')
	t.mock.timers.tick(1000)
	const error = await outcome
	keepsNoReadError(error)
	assert.equal(error.message, `Audible API DELETE ${REMOVE}?asins=B000000001 → HTTP 404`)
})

const TRANSPORT_SECRET = 'SYNTHETIC_TRANSPORT_SECRET'
const transportFailure = () => new Error(`${TRANSPORT_SECRET}: fetch failed`)
const keepsOnlyOwnWords = (error: any, message: string) => {
	assert.equal(error.name, 'Error')
	assert.equal(error.message, message)
	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|synthetic|state_token=/, channel)
}

test('SECURITY: a Wishlist remove returns null and none of the body Audible answers it with', async () => {
	let canceled = false
	const endless = new ReadableStream({ pull(controller) { controller.enqueue(new Uint8Array(1024)) }, cancel() { canceled = true } })
	for (const body of [
		() => Response.json({ state_token: 'SYNTHETIC_STATE_123', message: 'SYNTHETIC_AUDIBLE_TEXT' }),
		() => new Response('SYNTHETIC_AUDIBLE_TEXT state_token=SYNTHETIC_STATE_123', { status: 200 }),
		() => unreadable(200),
		() => new Response(endless, { status: 200 }),
	]) assert.equal(await wishlistRemove([collection(), body()]), null)
	assert.ok(canceled, 'the endless DELETE body was not canceled')
})

test('SECURITY: a failed fetch on either remove call, first send or resend, throws only package words', async () => {
	const GET = 'Audible API GET /1.0/collections/__WISHLIST → no answer'
	const DELETE = `Audible API DELETE ${REMOVE}?asins=B000000001 → no answer`
	const cases: Array<[answers: Array<Response | Error>, message: string, methods: string[]]> = [
		[[transportFailure()], GET, ['GET']],
		[[collection(), new Error(`${TRANSPORT_SECRET} at ${COLLECTION_URL}/items?state_token=synthetic-state-1`)], DELETE, ['GET', 'DELETE']],
	]
	for (const [answers, message, methods] of cases) {
		keepsOnlyOwnWords(await removeFails(answers), message)
		assert.deepEqual(sent.map(({ method }) => method), methods)
	}
})

test('SECURITY: a collection GET whose success body fails, stalls, or runs past 64 KB sends no DELETE and throws only package words', async (t) => {
	const unread = 'Audible API GET /1.0/collections/__WISHLIST → HTTP 200 (body: unreadable)'
	const large = 'Audible API GET /1.0/collections/__WISHLIST → HTTP 200 (body: over 64 KB)'
	let pulled = 0
	const endless = () => new Response(new ReadableStream({ pull(controller) { pulled++; controller.enqueue(new Uint8Array(1024).fill(120)) } }), { status: 200 })
	const cases: Array<[answers: Array<Response | Error>, message: string, methods: string[]]> = [
		[[unreadable(200)], unread, ['GET']],
		[[Response.json({ state_token: 'synthetic-state-1', padding: 'x'.repeat(65536) })], large, ['GET']],
		[[endless()], large, ['GET']],
	]
	for (const [answers, message, methods] of cases) {
		keepsOnlyOwnWords(await removeFails(answers), message)
		assert.deepEqual(sent.map(({ method }) => method), methods)
	}
	assert.ok(pulled <= 66, `pulled ${pulled} chunks of an endless body`)
	t.mock.timers.enable({ apis: ['setTimeout'] })
	stallStarted = false
	const outcome = removeFails([stalled(200)])
	for (let turn = 0; !stallStarted && turn < 1000; turn++) await new Promise((resolve) => setImmediate(resolve))
	assert.ok(stallStarted, 'the GET answer was never read')
	t.mock.timers.tick(1000)
	keepsOnlyOwnWords(await outcome, unread)
	assert.deepEqual(sent.map(({ method }) => method), ['GET'])
})

test('SECURITY: any other call whose fetch or success body fails throws only package words', async () => {
	connect()
	respond = () => { throw transportFailure() }
	keepsOnlyOwnWords(await failure(libraryItem), 'Audible API GET /1.0/library/B000000001 → no answer')
	respond = () => unreadable(200)
	keepsOnlyOwnWords(await failure(libraryItem), 'Audible API GET /1.0/library/B000000001 → HTTP 200 (body: unreadable)')
})

test('SECURITY: the sender itself refuses a call outside the policy and sends nothing', async () => {
	const { sendAudible } = await import('../send.ts')
	connect()
	sent.length = 0
	await assert.rejects(sendAudible('GET', '/1.0/orders', undefined, undefined), /does not allow GET \/1\.0\/orders/)
	await assert.rejects(sendAudible('GET', '/1.0/account/information', { response_groups: 'customer' }, undefined), /does not allow/)
	await assert.rejects(sendAudible('delete', '/1.0/collections/__WISHLIST/items', { asins: 'nope' }, undefined), /does not allow/)
	assert.deepEqual(sent, [])
})

test('SECURITY: a query changed after the sender accepts it does not reach the wire', async () => {
	const { sendAudible } = await import('../send.ts')
	const { CREDITS_CALL } = await import('../policy.ts')
	connect()
	sent.length = 0
	const query: Record<string, string> = { ...CREDITS_CALL.query }
	const pending = sendAudible(CREDITS_CALL.method, CREDITS_CALL.path, query, undefined)
	query.response_groups = 'customer'
	await pending.catch(() => {})
	const account = sent.filter((s) => s.url.includes('/1.0/account/information'))
	assert.equal(account.length, 1)
	assert.match(account[0].url, /response_groups=customer_benefits/)
	assert.ok(Object.isFrozen(CREDITS_CALL.query))
})

test('SECURITY: the sender refuses a method or path that is not a string and sends nothing', async () => {
	const { sendAudible } = await import('../send.ts')
	connect()
	sent.length = 0
	let reads = 0
	const shifty = { toString: () => (reads++ ? '/1.0/orders' : '/1.0/library') }
	await assert.rejects(sendAudible('GET', shifty as unknown as string, undefined, undefined), /string method and path/)
	await assert.rejects(sendAudible(new String('GET') as unknown as string, '/1.0/library', undefined, undefined), /string method and path/)
	assert.deepEqual(sent, [])
})