File size: 10,196 Bytes
6c3af4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a1e948
 
 
 
 
 
 
6c3af4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cd0dd6
6c3af4e
 
 
 
2cd0dd6
 
 
 
 
 
 
 
 
 
 
 
 
6c3af4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d19ab4e
6c3af4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a1e948
d19ab4e
 
 
 
 
 
 
 
0a1e948
6c3af4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d19ab4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c3af4e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { argon2Verify } from "hash-wasm";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const mockFetch = vi.fn();
vi.stubGlobal("fetch", mockFetch);

/** Digest length in bytes, read from the trailing field of the encoded hash. */
function getDigestLength(encodedHash: string) {
  const digest = encodedHash.split("$").pop() as string;
  return atob(digest.replace(/-/g, "+").replace(/_/g, "/")).length;
}

/** Runs a validation and returns the hash that was sent to the server. */
async function getHashSentFor(accessKey: string) {
  const { validateAccessKey } = await import("./accessKey");
  mockFetch.mockResolvedValue({
    ok: true,
    json: vi.fn().mockResolvedValue({ valid: true }),
  });

  await validateAccessKey(accessKey);

  const [, requestInit] = mockFetch.mock.calls[0];
  return JSON.parse(requestInit.body).accessKeyHash as string;
}

vi.mock("./logEntries", () => ({
  addLogEntry: vi.fn(),
}));

vi.mock("@mantine/notifications", () => ({
  notifications: {
    show: vi.fn(),
  },
}));

const TIMEOUT_HOURS = 24;

/** Checks that a stored key was dropped without a call to the server. */
function expectStoredKeyDiscarded(result: unknown) {
  expect(result).toBe(false);
  expect(localStorage.getItem("accessKeyHash")).toBeNull();
  expect(mockFetch).not.toHaveBeenCalled();
}

describe("Access Key Module", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    localStorage.clear();
  });

  afterEach(() => {
    vi.restoreAllMocks();
    localStorage.clear();
  });

  describe("validateAccessKey", () => {
    it("should return valid for a valid access key", async () => {
      const { validateAccessKey } = await import("./accessKey");
      mockFetch.mockResolvedValue({
        ok: true,
        json: vi.fn().mockResolvedValue({ valid: true }),
      });

      const result = await validateAccessKey("test-key-123");
      expect(result).toBe("valid");
      expect(mockFetch).toHaveBeenCalled();
    });

    it("should return invalid for an invalid access key", async () => {
      const { validateAccessKey } = await import("./accessKey");
      mockFetch.mockResolvedValue({
        ok: true,
        json: vi.fn().mockResolvedValue({ valid: false }),
      });

      const result = await validateAccessKey("invalid-key");
      expect(result).toBe("invalid");
    });

    it("should return unreachable on network error", async () => {
      const { validateAccessKey } = await import("./accessKey");
      mockFetch.mockRejectedValue(new Error("Network error"));

      const result = await validateAccessKey("test-key");
      expect(result).toBe("unreachable");
    });

    it("should return unreachable when the server reply is not JSON", async () => {
      const { validateAccessKey } = await import("./accessKey");
      mockFetch.mockResolvedValue({
        ok: false,
        status: 502,
        json: vi.fn().mockRejectedValue(new SyntaxError("Unexpected token <")),
      });

      const result = await validateAccessKey("test-key");
      expect(result).toBe("unreachable");
    });

    it("should send a hash the server can verify against the access key", async () => {
      const hash = await getHashSentFor("test-key-123");

      // Mirrors the server-side check in validateAccessKeyServerHook.ts
      await expect(
        argon2Verify({ password: "test-key-123", hash }),
      ).resolves.toBe(true);
      await expect(
        argon2Verify({ password: "another-key", hash }),
      ).resolves.toBe(false);
    });

    it("should use a digest long enough to resist blind forgery", async () => {
      expect(getDigestLength(await getHashSentFor("test-key-123"))).toBe(32);
    });

    it("should return invalid when response is not ok", async () => {
      const { validateAccessKey } = await import("./accessKey");
      mockFetch.mockResolvedValue({
        ok: false,
        status: 401,
        json: vi.fn().mockResolvedValue({ valid: false }),
      });

      const result = await validateAccessKey("test-key");
      expect(result).toBe("invalid");
    });

    it("treats a 429 as a rate-limited refusal and stores no hash", async () => {
      const { validateAccessKey } = await import("./accessKey");
      const { notifications } = await import("@mantine/notifications");
      mockFetch.mockResolvedValue({
        ok: false,
        status: 429,
      });

      const result = await validateAccessKey("test-key");
      expect(result).toBe("rateLimited");
      expect(localStorage.getItem("accessKeyHash")).toBeNull();
      expect(notifications.show).toHaveBeenCalledWith(
        expect.objectContaining({ title: "Too many attempts" }),
      );
    });
  });

  describe("verifyStoredAccessKey", () => {
    it("should return true when stored key is valid", async () => {
      const { verifyStoredAccessKey } = await import("./accessKey");
      mockFetch.mockResolvedValue({
        ok: true,
        json: vi.fn().mockResolvedValue({ valid: true }),
      });

      localStorage.setItem(
        "accessKeyHash",
        JSON.stringify({ hash: "test-hash", timestamp: Date.now() }),
      );
      const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
      expect(result).toBe(true);
    });

    it("should return false when no key is stored", async () => {
      const { verifyStoredAccessKey } = await import("./accessKey");

      const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
      expect(result).toBe(false);
    });

    it("should return false when stored key is invalid", async () => {
      const { verifyStoredAccessKey } = await import("./accessKey");
      mockFetch.mockResolvedValue({
        ok: true,
        json: vi.fn().mockResolvedValue({ valid: false }),
      });

      localStorage.setItem(
        "accessKeyHash",
        JSON.stringify({ hash: "invalid-hash", timestamp: Date.now() }),
      );
      const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
      expect(result).toBe(false);
      expect(localStorage.getItem("accessKeyHash")).toBeNull();
    });

    it("should return false without asking the server when the timeout is zero", async () => {
      const { verifyStoredAccessKey } = await import("./accessKey");
      localStorage.setItem(
        "accessKeyHash",
        JSON.stringify({ hash: "test-hash", timestamp: Date.now() }),
      );

      const result = await verifyStoredAccessKey(0);
      expect(result).toBe(false);
      expect(mockFetch).not.toHaveBeenCalled();
    });

    it("should return false when stored key is expired", async () => {
      const { verifyStoredAccessKey } = await import("./accessKey");
      const expiredTimestamp = Date.now() - 25 * 60 * 60 * 1000;
      localStorage.setItem(
        "accessKeyHash",
        JSON.stringify({ hash: "old-hash", timestamp: expiredTimestamp }),
      );

      const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
      expectStoredKeyDiscarded(result);
    });

    it("deletes a stored value that is not JSON without asking the server", async () => {
      const { verifyStoredAccessKey } = await import("./accessKey");
      localStorage.setItem("accessKeyHash", "not-json");

      const result = await verifyStoredAccessKey(TIMEOUT_HOURS);

      expectStoredKeyDiscarded(result);
    });

    it("keeps the stored hash on a 429 instead of deleting it", async () => {
      const { verifyStoredAccessKey } = await import("./accessKey");
      mockFetch.mockResolvedValue({
        ok: false,
        status: 429,
      });

      localStorage.setItem(
        "accessKeyHash",
        JSON.stringify({ hash: "test-hash", timestamp: Date.now() }),
      );
      const result = await verifyStoredAccessKey(TIMEOUT_HOURS);

      expect(result).toBe(false);
      // A rate-limited validation must not be read as a wrong key.
      expect(localStorage.getItem("accessKeyHash")).not.toBeNull();
    });

    describe("when the server gives no verdict on the key", () => {
      const storedValue = JSON.stringify({
        hash: "test-hash",
        timestamp: Date.now(),
      });

      it.each([
        [
          "the fetch rejects",
          () => mockFetch.mockRejectedValue(new TypeError("Failed to fetch")),
        ],
        [
          "a proxy answers 502 with a page that is not JSON",
          () =>
            mockFetch.mockResolvedValue({
              ok: false,
              status: 502,
              json: vi
                .fn()
                .mockRejectedValue(new SyntaxError("Unexpected token <")),
            }),
        ],
        [
          "the SPA fallback answers 200 with the app page",
          () =>
            mockFetch.mockResolvedValue({
              ok: true,
              status: 200,
              json: vi
                .fn()
                .mockRejectedValue(new SyntaxError("Unexpected token <")),
            }),
        ],
        [
          "a proxy answers 503 with JSON that has no verdict",
          () =>
            mockFetch.mockResolvedValue({
              ok: false,
              status: 503,
              json: vi
                .fn()
                .mockResolvedValue({ error: "upstream unavailable" }),
            }),
        ],
      ])("keeps the stored hash when %s", async (_situation, answerWithIt) => {
        const { verifyStoredAccessKey } = await import("./accessKey");
        answerWithIt();
        localStorage.setItem("accessKeyHash", storedValue);

        const result = await verifyStoredAccessKey(TIMEOUT_HOURS);

        expect(result).toBe(false);
        expect(localStorage.getItem("accessKeyHash")).toBe(storedValue);
      });

      it("accepts the same hash on the next load once the server answers", async () => {
        const { verifyStoredAccessKey } = await import("./accessKey");
        localStorage.setItem("accessKeyHash", storedValue);

        mockFetch.mockRejectedValue(new TypeError("Failed to fetch"));
        await verifyStoredAccessKey(TIMEOUT_HOURS);
        mockFetch.mockResolvedValue({
          ok: true,
          json: vi.fn().mockResolvedValue({ valid: true }),
        });

        await expect(verifyStoredAccessKey(TIMEOUT_HOURS)).resolves.toBe(true);
      });
    });
  });
});