Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/__test__/get-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class NoErrorThrownError extends Error {}

/**
* This helper function is used to test that a function throws an error.
* The caught error is returned so that it can be inspected.
* If the function does not throw an error, a `NoErrorThrownError` is thrown.
*/
export async function getError(call: () => unknown): Promise<unknown> {
try {
await call();

throw new NoErrorThrownError();
} catch (error: unknown) {
return error;
}
}
2 changes: 1 addition & 1 deletion src/__test__/scenario.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface RequestResponsePair {
body?: any;
};
response: {
headers: Record<string, string>;
headers: Record<string, string | string[]>;
body?: any;
status: number;

Expand Down
2 changes: 2 additions & 0 deletions src/__test__/scenarios/multiple-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const multiplePages = {
headers: {},
status: 200,
body: {
status: 200,
cookies: {
"session-id": "2",
},
Expand Down Expand Up @@ -55,6 +56,7 @@ export const multiplePages = {
headers: {},
status: 200,
body: {
status: 200,
cookies: {
"session-id": "2",
},
Expand Down
19 changes: 19 additions & 0 deletions src/__test__/scenarios/signin-redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { TLSClientResponseData } from "../../kindle.js";
import { unexpectedResponse } from "./unexpected-response.js";

export function signinRedirect() {
const response = {
headers: {
Location: [
"https://www.amazon.com/ap/signin?openid.pape.max_auth_age=1209600&openid.return_to=foobar",
],
},
status: 302,
body: "{}",
cookies: {},
target:
"https://read.amazon.com/kindle-library/search?query=&libraryType=BOOKS&sortType=acquisition_desc&querySize=50",
} satisfies TLSClientResponseData;

return unexpectedResponse({ startSessionResponse: response });
}
2 changes: 2 additions & 0 deletions src/__test__/scenarios/single-book.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const singleBook = {
headers: {},
status: 200,
body: {
status: 200,
cookies: {
"session-id": "2",
},
Expand Down Expand Up @@ -54,6 +55,7 @@ export const singleBook = {
headers: {},
status: 200,
body: {
status: 200,
cookies: {
"session-id": "2",
},
Expand Down
1 change: 1 addition & 0 deletions src/__test__/scenarios/single-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const singlePages = {
headers: {},
status: 200,
body: {
status: 200,
cookies: {
"session-id": "2",
},
Expand Down
2 changes: 2 additions & 0 deletions src/__test__/scenarios/start-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export function startSession({ books }: { books?: KindleBookData[] } = {}) {
headers: {},
status: 200,
body: {
status: 200,
cookies: {
"session-id": "2",
},
Expand Down Expand Up @@ -50,6 +51,7 @@ export function startSession({ books }: { books?: KindleBookData[] } = {}) {
status: 200,
headers: {},
body: {
status: 200,
cookies: {
"session-id": faker.string.uuid(),
},
Expand Down
140 changes: 140 additions & 0 deletions src/__test__/scenarios/unexpected-response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { faker } from "@faker-js/faker";
import { TLSClientResponseData } from "../../kindle.js";
import { Scenario } from "../scenario.js";
import { sample1, sample1Details, sample1MetaData } from "./fixtures/books.js";
import { defaultRequestBody } from "./fixtures/default-request-body.js";
import { sessionToken } from "./fixtures/tokens.js";

export function unexpectedResponse({
startSessionResponse,
getBookDetailsResponse,
getBookMetaDataResponse,
getDeviceTokenResponse,
}: {
startSessionResponse?: TLSClientResponseData;
getBookDetailsResponse?: TLSClientResponseData;
getBookMetaDataResponse?: TLSClientResponseData;
getDeviceTokenResponse?: TLSClientResponseData;
}) {
return {
startSession: {
request: {
method: "post",
url: "http://localhost:8080/api/forward",
body: {
...defaultRequestBody,
requestUrl:
"https://read.amazon.com/kindle-library/search?query=&libraryType=BOOKS&sortType=acquisition_desc&querySize=50",
},
},
response: {
headers: {},
status: 200,
body: startSessionResponse ?? {
status: 200,
cookies: {
"session-id": "2",
},
body: JSON.stringify({
itemsList: [sample1],
}),
},
meta: {
response: startSessionResponse,
},
},
},
getDeviceToken: {
request: {
method: "post",
url: "http://localhost:8080/api/forward",
body: {
...defaultRequestBody,
requestUrl:
"https://read.amazon.com/service/web/register/getDeviceToken?serialNumber=bar&deviceType=bar",
headers: {
...defaultRequestBody.headers,
"x-amzn-sessionid": "2",
},
},
},
response: {
status: 200,
headers: {},
body: getDeviceTokenResponse ?? {
status: 200,
cookies: {
"session-id": faker.string.uuid(),
},
body: JSON.stringify({
clientHashId: faker.string.uuid(),
deviceName: faker.lorem.word(),
deviceSessionToken: sessionToken,
eid: faker.string.uuid(),
}),
},
},
},
getBookDetails: {
request: {
method: "post",
url: "http://localhost:8080/api/forward",
body: {
...defaultRequestBody,
requestUrl:
"https://read.amazon.com/service/mobile/reader/startReading?asin=B000FBJG4U&clientVersion=2000010",
headers: {
...defaultRequestBody.headers,
"x-amzn-sessionid": "2",
"x-adp-session-token": sessionToken,
},
},
},
response: {
headers: {},
status: 200,
body: getBookDetailsResponse ?? {
status: 200,
cookies: {
"session-id": "2",
},
body: JSON.stringify({
...sample1Details,
}),
},
meta: {
books: [sample1],
},
},
},
getBookMetaData: {
request: {
method: "post",
url: "http://localhost:8080/api/forward",
body: {
...defaultRequestBody,
requestUrl:
"https://read.amazon.com/service/metadata/lookup?asin=B000FBJG4U&metadataVersion=1",
headers: {
...defaultRequestBody.headers,
"x-amzn-sessionid": "2",
"x-adp-session-token": sessionToken,
},
},
},
response: {
headers: {},
status: 200,
body: getBookMetaDataResponse ?? {
status: 200,
cookies: {
"session-id": "2",
},
body: `(${JSON.stringify({
...sample1MetaData,
})})`,
},
},
},
} satisfies Scenario;
}
9 changes: 9 additions & 0 deletions src/book.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
KindleOwnedBookMetadataResponse,
} from "./book-metadata.js";
import { HttpClient } from "./http-client.js";
import { UnexpectedResponseError } from "./kindle.js";

export class KindleBook {
public readonly title: string;
Expand Down Expand Up @@ -45,6 +46,10 @@ export class KindleBook {
this.asin
}&clientVersion=${this.#version}`
);
if (!UnexpectedResponseError.isOk(response)) {
throw UnexpectedResponseError.unexpectedStatusCode(response);
}

const info = JSON.parse(response.body) as KindleOwnedBookMetadataResponse;

return {
Expand Down Expand Up @@ -80,6 +85,10 @@ export class KindleBook {
const info = partialDetails ?? (await this.details());
const response = await this.#client.request(info.metadataUrl);

if (!UnexpectedResponseError.isOk(response)) {
throw UnexpectedResponseError.unexpectedStatusCode(response);
}

const meta =
this.#client.parseJsonpResponse<KindleBookMetadataResponse>(response);

Expand Down
22 changes: 22 additions & 0 deletions src/errors/auth-session-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { TLSClientResponseData } from "../kindle";

export class AuthSessionError extends Error {
constructor(message: string, public response: TLSClientResponseData) {
super(message);
}

public static isSignInRedirect(response: TLSClientResponseData): boolean {
return (
response.status === 302 &&
Array.isArray(response.headers.Location) &&
response.headers.Location.length > 0 &&
response.headers.Location[0].startsWith(
"https://www.amazon.com/ap/signin"
)
);
}

static sessionExpired(resp: TLSClientResponseData) {
return new AuthSessionError("Session expired", resp);
}
}
18 changes: 18 additions & 0 deletions src/errors/unexpected-response-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { TLSClientResponseData } from "../kindle";

export class UnexpectedResponseError extends Error {
constructor(message: string, public response: TLSClientResponseData) {
super(message);
}

public static isOk(response: TLSClientResponseData): boolean {
return response.status >= 200 && response.status < 300;
}

public static unexpectedStatusCode(resp: TLSClientResponseData) {
return new UnexpectedResponseError(
`Unexpected status code: ${resp.status}`,
resp
);
}
}
9 changes: 9 additions & 0 deletions src/fetch-books.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { KindleBook, KindleBookData } from "./book.js";
import { AuthSessionError } from "./errors/auth-session-error.js";
import { UnexpectedResponseError } from "./errors/unexpected-response-error.js";
import { HttpClient } from "./http-client.js";
import { Kindle } from "./kindle.js";
import { Query, Filter } from "./query-filter.js";
Expand All @@ -18,6 +20,13 @@ export async function fetchBooks(
};

const resp = await client.request(url);

if (AuthSessionError.isSignInRedirect(resp)) {
throw AuthSessionError.sessionExpired(resp);
} else if (!UnexpectedResponseError.isOk(resp)) {
throw UnexpectedResponseError.unexpectedStatusCode(resp);
}

const newCookies = client.extractSetCookies(resp);
const sessionId = newCookies["session-id"];

Expand Down
Loading