diff --git a/README.md b/README.md index 58c2bb3..a17adce 100644 --- a/README.md +++ b/README.md @@ -276,8 +276,13 @@ factor at that point, login fails. On success it logs `Logged in as (user )` and `Session saved to `. On failure it logs `Login failed: `, and the -exit status is 1. `login` is the only command that prompts, and its prompts go -to stdout. +exit status is 1. Two reasons are given in words: + +- a password the server refuses: `Login failed: incorrect email or password` +- an email with no account on the server: + `Login failed: no account with this email on the server` + +`login` is the only command that prompts, and its prompts go to stdout. #### `quak whoami` diff --git a/src/auth/login.ts b/src/auth/login.ts index fac00eb..e5e5293 100644 --- a/src/auth/login.ts +++ b/src/auth/login.ts @@ -1,5 +1,5 @@ import { SRP, SrpClient } from "fast-srp-hap"; -import type { ApiClient } from "../api/client.js"; +import { ApiError, type ApiClient } from "../api/client.js"; import { deriveKEK, deriveLoginSubkey, fromBase64 } from "../crypto/index.js"; import type { AuthorizationResponse, @@ -10,6 +10,14 @@ import type { // Ente uses the 4096-bit SRP group. Both client and server must agree. const SRP_PARAMS = SRP.params["4096"]; +// The same error, with a message that says in words what the server refused. +const withMessage = (err: ApiError, message: string): ApiError => + new ApiError(message, err.status, { + code: err.code, + requestID: err.requestID, + body: err.body, + }); + // Wrap fast-srp-hap's callback-based genKey into a Promise. const genKey = (): Promise => SRP.genKey(); @@ -63,13 +71,20 @@ const srpHandshake = async ( srpClient.setB(Buffer.from(srpB, "base64")); const srpM1 = srpClient.computeM1().toString("base64"); - const verifyResponse = await api.postJSON< - AuthorizationResponse & { srpM2: string } - >("/users/srp/verify-session", { - sessionID, - srpUserID: srpAttributes.srpUserID, - srpM1, - }); + type VerifyResponse = AuthorizationResponse & { srpM2: string }; + let verifyResponse: VerifyResponse; + try { + verifyResponse = await api.postJSON( + "/users/srp/verify-session", + { sessionID, srpUserID: srpAttributes.srpUserID, srpM1 }, + ); + } catch (err) { + // The server answers 401 when the password does not match. + if (err instanceof ApiError && err.status === 401) { + throw withMessage(err, "incorrect email or password"); + } + throw err; + } srpClient.checkM2(Buffer.from(verifyResponse.srpM2, "base64")); @@ -101,9 +116,28 @@ export const beginLogin = async ( email: string, password: string, ): Promise => { - const { attributes } = await api.getJSON<{ - attributes: SRPAttributes; - }>("/users/srp/attributes", { email }); + let attributes: SRPAttributes; + try { + ({ attributes } = await api.getJSON<{ attributes: SRPAttributes }>( + "/users/srp/attributes", + { email }, + )); + } catch (err) { + // The Ente server answers 404 with `{}` when no account has the email. + // It answers 404 with the code NOT_FOUND when the account exists but + // has no SRP attributes. A server address that points somewhere else + // answers 404 without JSON. Those two errors stay as they are. + if ( + err instanceof ApiError && + err.status === 404 && + typeof err.body === "object" && + err.body !== null && + err.code === undefined + ) { + throw withMessage(err, "no account with this email on the server"); + } + throw err; + } if (attributes.isEmailMFAEnabled) { return { kind: "emailOTP" }; diff --git a/test/auth/login.test.ts b/test/auth/login.test.ts index 177b5ed..a82d902 100644 --- a/test/auth/login.test.ts +++ b/test/auth/login.test.ts @@ -30,7 +30,7 @@ import sodium from "libsodium-wrappers-sumo"; import { SRP, SrpServer } from "fast-srp-hap"; import { beforeAll, describe, expect, it } from "vitest"; -import { ApiClient } from "../../src/api/client.js"; +import { ApiClient, ApiError } from "../../src/api/client.js"; import { init, toBase64, @@ -142,10 +142,15 @@ const buildServerFixture = async (password: string) => { * * @param fixture The server fixture from buildServerFixture * @param opts.requireTOTP If true, verify-session returns a 2FA challenge + * @param opts.unknownEmail If true, the server has no account with the email */ const buildMockFetch = ( fixture: Awaited>, - opts?: { requireTOTP?: boolean; requirePasskeyAndTOTP?: boolean }, + opts?: { + requireTOTP?: boolean; + requirePasskeyAndTOTP?: boolean; + unknownEmail?: boolean; + }, ) => { let srpServer: SrpServer; const sessionID = "test-session-id"; @@ -163,7 +168,15 @@ const buildMockFetch = ( const parsed = new URL(url); const path = parsed.pathname; + // The Ente server answers its refusals with an empty JSON object. + const refusal = (status: number) => + new Response("{}", { + status, + headers: { "content-type": "application/json" }, + }); + if (path === "/users/srp/attributes") { + if (opts?.unknownEmail) return refusal(404); return new Response( JSON.stringify({ attributes: fixture.srpAttributes }), { @@ -197,7 +210,11 @@ const buildMockFetch = ( if (path === "/users/srp/verify-session") { const body = JSON.parse(init?.body as string); - srpServer.checkM1(Buffer.from(body.srpM1, "base64")); + try { + srpServer.checkM1(Buffer.from(body.srpM1, "base64")); + } catch { + return refusal(401); + } const M2 = srpServer.computeM2(); // IMPORTANT: the museum server's EmailAuthorizationResponse @@ -365,13 +382,70 @@ describe("beginLogin via SRP", () => { } }); - it("rejects a wrong password (SRP M1 verification fails)", async () => { + it("says a wrong password is incorrect (SRP M1 verification fails)", async () => { const fixture = await buildServerFixture(TEST_PASSWORD); const api = new ApiClient({ fetch: buildMockFetch(fixture) }); + const err = await beginLogin(api, TEST_EMAIL, "wrong password").catch( + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ApiError); + expect((err as ApiError).message).toBe("incorrect email or password"); + expect((err as ApiError).status).toBe(401); + }); + + it("says the server has no account with an unknown email", async () => { + const fixture = await buildServerFixture(TEST_PASSWORD); + const api = new ApiClient({ + fetch: buildMockFetch(fixture, { unknownEmail: true }), + }); + + const err = await beginLogin(api, TEST_EMAIL, TEST_PASSWORD).catch( + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ApiError); + expect((err as ApiError).message).toBe( + "no account with this email on the server", + ); + expect((err as ApiError).status).toBe(404); + }); + + // The Ente server's answer for an account that has no SRP attributes. + it("does not call an account with no SRP attributes missing", async () => { + const api = new ApiClient({ + fetch: (async () => + new Response( + JSON.stringify({ code: "NOT_FOUND", message: "" }), + { + status: 404, + headers: { "content-type": "application/json" }, + }, + )) as typeof globalThis.fetch, + }); + + const err = await beginLogin(api, TEST_EMAIL, TEST_PASSWORD).catch( + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ApiError); + expect((err as ApiError).code).toBe("NOT_FOUND"); + expect((err as ApiError).message).not.toBe( + "no account with this email on the server", + ); + }); + + // A server address that points somewhere other than an Ente server. + it("keeps the bare status of a 404 that is not JSON", async () => { + const api = new ApiClient({ + fetch: (async () => + new Response("404 page not found", { + status: 404, + headers: { "content-type": "text/plain" }, + })) as typeof globalThis.fetch, + }); + await expect( - beginLogin(api, TEST_EMAIL, "wrong password"), - ).rejects.toThrow(); + beginLogin(api, TEST_EMAIL, TEST_PASSWORD), + ).rejects.toThrow(/^HTTP 404$/); }); });