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
|
import { describe, expect, it, vi } from 'vitest';
import type { Cookies } from '@sveltejs/kit';
import {
AUTH_COOKIE_NAME,
SESSION_MAX_AGE_SECONDS,
createSession,
isValidSession,
renewSession,
verifyPassword,
} from './auth';
const TEST_PASSWORD = vi.hoisted(() => {
return 'family-password-5f2c1d7e';
});
const NOW = Temporal.Instant.fromEpochMilliseconds(1_800_000_000_000);
vi.mock('$env/dynamic/private', () => ({
env: { AUTH_PASSWORD: TEST_PASSWORD },
}));
describe('authentication', () => {
it('verifies the configured shared password', () => {
expect(verifyPassword(TEST_PASSWORD)).toBe(true);
expect(verifyPassword('wrong-password')).toBe(false);
});
it('accepts a signed session until its expiry', () => {
const session = createSession(NOW);
const almostExpired = NOW.add({
milliseconds: SESSION_MAX_AGE_SECONDS * 1000 - 1,
});
expect(isValidSession(session, almostExpired)).toBe(true);
const expired = NOW.add({ milliseconds: SESSION_MAX_AGE_SECONDS * 1000 });
expect(isValidSession(session, expired)).toBe(false);
expect(isValidSession(`${session}x`, NOW)).toBe(false);
});
it('renews a valid session with the requested cookie settings', () => {
const session = createSession(NOW);
const cookies = {
get: vi.fn(() => session),
set: vi.fn(),
} as unknown as Cookies;
expect(renewSession(cookies, true, NOW.add({ milliseconds: 1_000 }))).toBe(
true,
);
expect(cookies.set).toHaveBeenCalledWith(
AUTH_COOKIE_NAME,
expect.any(String),
expect.objectContaining({
path: '/',
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: SESSION_MAX_AGE_SECONDS,
}),
);
});
});
|