| 1 |
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 2 |
import i18n from "i18next"; |
| 3 |
import session from "./Session"; |
| 4 |
import prefs from "./Prefs"; |
| 5 |
import subscriptionManager from "./SubscriptionManager"; |
| 6 |
import accountApi from "./AccountApi"; |
| 7 |
|
| 8 |
// AccountApi.js leans on several singletons; mock them so we can drive token() and assert the |
| 9 |
// side effects of sync(), and so importing it doesn't drag in the component/Dexie/i18n trees. |
| 10 |
// (vi.mock is hoisted above the imports by vitest, so those imports receive the mocks.) |
| 11 |
vi.mock("./Session", () => ({ |
| 12 |
default: { token: vi.fn(() => "test-token"), setLastExtendedAtAsync: vi.fn(), resetAndRedirect: vi.fn() }, |
| 13 |
})); |
| 14 |
vi.mock("./SubscriptionManager", () => ({ default: { syncFromRemote: vi.fn() } })); |
| 15 |
vi.mock("./Prefs", () => ({ |
| 16 |
default: { setSound: vi.fn(), setDeleteAfter: vi.fn(), setMinPriority: vi.fn(), setDateFormat: vi.fn(), setTimeFormat: vi.fn() }, |
| 17 |
THEME: { DARK: "dark", LIGHT: "light", SYSTEM: "system" }, |
| 18 |
})); |
| 19 |
vi.mock("i18next", () => ({ default: { changeLanguage: vi.fn() } })); |
| 20 |
vi.mock("../components/routes", () => ({ default: { login: "/login" } })); |
| 21 |
|
| 22 |
let fetchMock; |
| 23 |
|
| 24 |
// fetchOrThrow treats anything other than HTTP 200 as an error, so a fake response just needs a |
| 25 |
// status and a json() method. |
| 26 |
const ok = (body = {}) => ({ status: 200, json: async () => body }); |
| 27 |
|
| 28 |
beforeEach(() => { |
| 29 |
vi.clearAllMocks(); |
| 30 |
vi.spyOn(console, "log").mockImplementation(() => {}); |
| 31 |
fetchMock = vi.fn(); |
| 32 |
vi.stubGlobal("fetch", fetchMock); |
| 33 |
session.token.mockReturnValue("test-token"); |
| 34 |
accountApi.tiers = null; // reset the billing-tiers cache between tests |
| 35 |
accountApi.listener = null; |
| 36 |
}); |
| 37 |
|
| 38 |
afterEach(() => { |
| 39 |
vi.restoreAllMocks(); |
| 40 |
vi.unstubAllGlobals(); |
| 41 |
vi.useRealTimers(); |
| 42 |
}); |
| 43 |
|
| 44 |
describe("AccountApi.login", () => { |
| 45 |
it("POSTs basic auth to the login URL and returns the token and canonical username", async () => { |
| 46 |
// The typed identifier is an email; the login endpoint returns the canonical username in one |
| 47 |
// request, so login() surfaces it (callers store it) rather than echoing what was typed. |
| 48 |
fetchMock.mockResolvedValue(ok({ token: "tk_returned", username: "phil" })); |
| 49 |
const result = await accountApi.login({ username: "[email protected]", password: "secret" }); |
| 50 |
|
| 51 |
expect(result).toEqual({ token: "tk_returned", username: "phil" }); |
| 52 |
expect(fetchMock).toHaveBeenCalledTimes(1); |
| 53 |
|
| 54 |
const [url, options] = fetchMock.mock.calls[0]; |
| 55 |
expect(url).toBe("https://ntfy.sh/v1/account/login"); |
| 56 |
expect(options.method).toBe("POST"); |
| 57 |
expect(options.headers.Authorization).toBe(`Basic ${btoa("[email protected]:secret")}`); |
| 58 |
}); |
| 59 |
|
| 60 |
it("throws when the server response has no token", async () => { |
| 61 |
fetchMock.mockResolvedValue(ok({})); |
| 62 |
await expect(accountApi.login({ username: "phil", password: "secret" })).rejects.toThrow("Cannot find token"); |
| 63 |
}); |
| 64 |
}); |
| 65 |
|
| 66 |
describe("AccountApi.create", () => { |
| 67 |
it("POSTs username/password and defaults email to an empty string", async () => { |
| 68 |
fetchMock.mockResolvedValue(ok()); |
| 69 |
await accountApi.create("phil", "pw"); |
| 70 |
expect(fetchMock).toHaveBeenCalledWith( |
| 71 |
"https://ntfy.sh/v1/account", |
| 72 |
expect.objectContaining({ method: "POST", body: JSON.stringify({ username: "phil", password: "pw", email: "" }) }), |
| 73 |
); |
| 74 |
}); |
| 75 |
}); |
| 76 |
|
| 77 |
describe("AccountApi.get", () => { |
| 78 |
it("returns the parsed account and notifies the listener", async () => { |
| 79 |
fetchMock.mockResolvedValue(ok({ username: "phil" })); |
| 80 |
const listener = vi.fn(); |
| 81 |
accountApi.registerListener(listener); |
| 82 |
|
| 83 |
const account = await accountApi.get(); |
| 84 |
|
| 85 |
expect(account).toEqual({ username: "phil" }); |
| 86 |
expect(listener).toHaveBeenCalledWith({ username: "phil" }); |
| 87 |
const [url, options] = fetchMock.mock.calls[0]; |
| 88 |
expect(url).toBe("https://ntfy.sh/v1/account"); |
| 89 |
expect(options.headers.Authorization).toBe("Bearer test-token"); |
| 90 |
}); |
| 91 |
}); |
| 92 |
|
| 93 |
describe("AccountApi.changePassword", () => { |
| 94 |
it("POSTs the current and new passwords", async () => { |
| 95 |
fetchMock.mockResolvedValue(ok()); |
| 96 |
await accountApi.changePassword("old", "new"); |
| 97 |
const [, options] = fetchMock.mock.calls[0]; |
| 98 |
expect(options.body).toBe(JSON.stringify({ password: "old", new_password: "new" })); |
| 99 |
}); |
| 100 |
}); |
| 101 |
|
| 102 |
describe("AccountApi.createToken", () => { |
| 103 |
it("converts a positive expiry into an absolute unix timestamp", async () => { |
| 104 |
vi.useFakeTimers(); |
| 105 |
vi.setSystemTime(new Date("2026-01-01T00:00:00Z")); // 1767225600 seconds |
| 106 |
fetchMock.mockResolvedValue(ok()); |
| 107 |
|
| 108 |
await accountApi.createToken("my label", 3600); |
| 109 |
|
| 110 |
const [, options] = fetchMock.mock.calls[0]; |
| 111 |
expect(JSON.parse(options.body)).toEqual({ label: "my label", expires: 1767225600 + 3600 }); |
| 112 |
}); |
| 113 |
|
| 114 |
it("sends expires=0 for a non-expiring token", async () => { |
| 115 |
fetchMock.mockResolvedValue(ok()); |
| 116 |
await accountApi.createToken("forever", 0); |
| 117 |
const [, options] = fetchMock.mock.calls[0]; |
| 118 |
expect(JSON.parse(options.body).expires).toBe(0); |
| 119 |
}); |
| 120 |
}); |
| 121 |
|
| 122 |
describe("AccountApi.deleteToken", () => { |
| 123 |
it("passes the target token in the X-Token header alongside the bearer token", async () => { |
| 124 |
fetchMock.mockResolvedValue(ok()); |
| 125 |
await accountApi.deleteToken("tk_target"); |
| 126 |
const [, options] = fetchMock.mock.calls[0]; |
| 127 |
expect(options.method).toBe("DELETE"); |
| 128 |
expect(options.headers["X-Token"]).toBe("tk_target"); |
| 129 |
expect(options.headers.Authorization).toBe("Bearer test-token"); |
| 130 |
}); |
| 131 |
}); |
| 132 |
|
| 133 |
describe("AccountApi subscriptions", () => { |
| 134 |
it("addSubscription POSTs base_url/topic and returns the parsed subscription", async () => { |
| 135 |
fetchMock.mockResolvedValue(ok({ id: "sub_1" })); |
| 136 |
const subscription = await accountApi.addSubscription("https://ntfy.sh", "mytopic"); |
| 137 |
|
| 138 |
expect(subscription).toEqual({ id: "sub_1" }); |
| 139 |
const [url, options] = fetchMock.mock.calls[0]; |
| 140 |
expect(url).toBe("https://ntfy.sh/v1/account/subscription"); |
| 141 |
expect(options.method).toBe("POST"); |
| 142 |
expect(JSON.parse(options.body)).toEqual({ base_url: "https://ntfy.sh", topic: "mytopic" }); |
| 143 |
}); |
| 144 |
|
| 145 |
it("deleteSubscription passes baseUrl/topic via headers", async () => { |
| 146 |
fetchMock.mockResolvedValue(ok()); |
| 147 |
await accountApi.deleteSubscription("https://ntfy.sh", "mytopic"); |
| 148 |
const [, options] = fetchMock.mock.calls[0]; |
| 149 |
expect(options.method).toBe("DELETE"); |
| 150 |
expect(options.headers["X-BaseURL"]).toBe("https://ntfy.sh"); |
| 151 |
expect(options.headers["X-Topic"]).toBe("mytopic"); |
| 152 |
}); |
| 153 |
}); |
| 154 |
|
| 155 |
describe("AccountApi.billingTiers", () => { |
| 156 |
it("caches the tiers and only fetches once", async () => { |
| 157 |
fetchMock.mockResolvedValue(ok([{ code: "pro" }])); |
| 158 |
const first = await accountApi.billingTiers(); |
| 159 |
const second = await accountApi.billingTiers(); |
| 160 |
|
| 161 |
expect(first).toEqual([{ code: "pro" }]); |
| 162 |
expect(second).toBe(first); |
| 163 |
expect(fetchMock).toHaveBeenCalledTimes(1); |
| 164 |
}); |
| 165 |
}); |
| 166 |
|
| 167 |
describe("AccountApi.requestPasswordReset", () => { |
| 168 |
it("POSTs the identifier without any auth header", async () => { |
| 169 |
fetchMock.mockResolvedValue(ok()); |
| 170 |
await accountApi.requestPasswordReset("phil"); |
| 171 |
const [url, options] = fetchMock.mock.calls[0]; |
| 172 |
expect(url).toBe("https://ntfy.sh/v1/account/password/reset/request"); |
| 173 |
expect(options.body).toBe(JSON.stringify({ identifier: "phil" })); |
| 174 |
expect(options.headers).toBeUndefined(); |
| 175 |
}); |
| 176 |
}); |
| 177 |
|
| 178 |
describe("AccountApi.sync", () => { |
| 179 |
it("returns null and makes no request when there is no token", async () => { |
| 180 |
session.token.mockReturnValue(null); |
| 181 |
expect(await accountApi.sync()).toBeNull(); |
| 182 |
expect(fetchMock).not.toHaveBeenCalled(); |
| 183 |
}); |
| 184 |
|
| 185 |
it("resets the session and redirects to login on an unauthorized response", async () => { |
| 186 |
fetchMock.mockResolvedValue({ status: 401, json: async () => ({}) }); |
| 187 |
const result = await accountApi.sync(); |
| 188 |
|
| 189 |
expect(result).toBeUndefined(); |
| 190 |
expect(session.resetAndRedirect).toHaveBeenCalledWith("/login"); |
| 191 |
}); |
| 192 |
|
| 193 |
it("applies language, notification prefs and subscriptions from the fetched account", async () => { |
| 194 |
fetchMock.mockResolvedValue( |
| 195 |
ok({ |
| 196 |
language: "de", |
| 197 |
date_format: "iso8601", |
| 198 |
time_format: "24h", |
| 199 |
notification: { sound: "ding", delete_after: 3600, min_priority: 3 }, |
| 200 |
subscriptions: [{ topic: "t" }], |
| 201 |
reservations: [{ topic: "t" }], |
| 202 |
}), |
| 203 |
); |
| 204 |
|
| 205 |
await accountApi.sync(); |
| 206 |
|
| 207 |
expect(i18n.changeLanguage).toHaveBeenCalledWith("de"); |
| 208 |
expect(prefs.setDateFormat).toHaveBeenCalledWith("iso8601"); |
| 209 |
expect(prefs.setTimeFormat).toHaveBeenCalledWith("24h"); |
| 210 |
expect(prefs.setSound).toHaveBeenCalledWith("ding"); |
| 211 |
expect(prefs.setDeleteAfter).toHaveBeenCalledWith(3600); |
| 212 |
expect(prefs.setMinPriority).toHaveBeenCalledWith(3); |
| 213 |
expect(subscriptionManager.syncFromRemote).toHaveBeenCalledWith([{ topic: "t" }], [{ topic: "t" }]); |
| 214 |
}); |
| 215 |
}); |