sveltekit-auth-example 5.5.0 → 5.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/README.md +12 -12
  3. package/db_create.sh +13 -0
  4. package/db_create.sql +15 -376
  5. package/db_schema.sql +369 -0
  6. package/package.json +5 -2
  7. package/src/app.d.ts +22 -1
  8. package/src/hooks.server.ts +47 -12
  9. package/src/lib/app-state.svelte.ts +8 -0
  10. package/src/lib/auth-redirect.ts +4 -0
  11. package/src/lib/focus.ts +8 -0
  12. package/src/lib/google.ts +17 -0
  13. package/src/lib/server/db.ts +9 -0
  14. package/src/lib/server/email/index.ts +1 -0
  15. package/src/lib/server/email/mfa-code.ts +22 -0
  16. package/src/lib/server/email/password-reset.ts +6 -0
  17. package/src/lib/server/email/verify-email.ts +6 -0
  18. package/src/lib/server/sendgrid.ts +9 -0
  19. package/src/routes/+layout.server.ts +10 -1
  20. package/src/routes/+layout.svelte +103 -28
  21. package/src/routes/admin/+page.server.ts +8 -0
  22. package/src/routes/api/v1/user/+server.ts +20 -0
  23. package/src/routes/auth/[slug]/+server.ts +9 -2
  24. package/src/routes/auth/forgot/+server.ts +10 -0
  25. package/src/routes/auth/google/+server.ts +35 -4
  26. package/src/routes/auth/login/+server.ts +67 -10
  27. package/src/routes/auth/logout/+server.ts +10 -0
  28. package/src/routes/auth/mfa/+server.ts +75 -0
  29. package/src/routes/auth/register/+server.ts +21 -1
  30. package/src/routes/auth/reset/+server.ts +15 -0
  31. package/src/routes/auth/reset/[token]/+page.svelte +16 -8
  32. package/src/routes/auth/reset/[token]/+page.ts +8 -0
  33. package/src/routes/auth/verify/[token]/+server.ts +12 -1
  34. package/src/routes/forgot/+page.svelte +13 -8
  35. package/src/routes/layout.css +3 -3
  36. package/src/routes/login/+page.server.ts +8 -0
  37. package/src/routes/login/+page.svelte +222 -77
  38. package/src/routes/profile/+page.server.ts +9 -0
  39. package/src/routes/profile/+page.svelte +32 -12
  40. package/src/routes/register/+page.server.ts +8 -1
  41. package/src/routes/register/+page.svelte +160 -122
  42. package/src/routes/teachers/+page.server.ts +9 -0
  43. package/src/service-worker.ts +17 -1
package/db_schema.sql ADDED
@@ -0,0 +1,369 @@
1
+ -- Run via db_create.sh or:
2
+ -- $ psql -d auth -f db_schema.sql
3
+ -- Required for password hashing
4
+ CREATE EXTENSION IF NOT EXISTS pgcrypto;
5
+
6
+ -- Required to generate UUIDs for sessions
7
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
8
+
9
+ -- Required for case-insensitive text (email_address domain)
10
+ CREATE EXTENSION IF NOT EXISTS citext;
11
+
12
+ -- Using hard-coded roles (often this would be a table)
13
+ CREATE TYPE public.roles AS ENUM('student', 'teacher', 'admin');
14
+
15
+ ALTER TYPE public.roles OWNER TO auth;
16
+
17
+ -- Domains
18
+ CREATE DOMAIN public.email_address AS citext CHECK (
19
+ length(VALUE) <= 254
20
+ AND VALUE = btrim(VALUE)
21
+ AND VALUE ~* '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$'
22
+ );
23
+
24
+ COMMENT ON DOMAIN public.email_address IS 'RFC-compliant email address (case-insensitive, max 254 chars)';
25
+
26
+ CREATE DOMAIN public.persons_name AS text CHECK (length(VALUE) <= 20) NOT NULL;
27
+
28
+ COMMENT ON DOMAIN public.persons_name IS 'Person first or last name (max 20 characters)';
29
+
30
+ CREATE DOMAIN public.phone_number AS text CHECK (
31
+ VALUE IS NULL
32
+ OR length(VALUE) <= 50
33
+ );
34
+
35
+ COMMENT ON DOMAIN public.phone_number IS 'Phone number (max 50 characters)';
36
+
37
+ CREATE TABLE IF NOT EXISTS public.users (
38
+ id integer NOT NULL GENERATED ALWAYS AS IDENTITY (
39
+ INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1
40
+ ),
41
+ role roles NOT NULL DEFAULT 'student'::roles,
42
+ email email_address NOT NULL,
43
+ password character varying(80) COLLATE pg_catalog."default",
44
+ first_name persons_name,
45
+ last_name persons_name,
46
+ opt_out boolean NOT NULL DEFAULT false,
47
+ email_verified boolean NOT NULL DEFAULT false,
48
+ phone phone_number,
49
+ CONSTRAINT users_pkey PRIMARY KEY (id),
50
+ CONSTRAINT users_email_unique UNIQUE (email)
51
+ ) TABLESPACE pg_default;
52
+
53
+ ALTER TABLE public.users OWNER TO auth;
54
+
55
+ CREATE INDEX users_first_name_index ON public.users USING btree (
56
+ first_name COLLATE pg_catalog."default" ASC NULLS LAST
57
+ ) TABLESPACE pg_default;
58
+
59
+ CREATE INDEX users_last_name_index ON public.users USING btree (
60
+ last_name COLLATE pg_catalog."default" ASC NULLS LAST
61
+ ) TABLESPACE pg_default;
62
+
63
+ CREATE INDEX users_password ON public.users USING btree (
64
+ password COLLATE pg_catalog."default" ASC NULLS LAST
65
+ ) TABLESPACE pg_default;
66
+
67
+ CREATE TABLE IF NOT EXISTS public.sessions (
68
+ id uuid NOT NULL DEFAULT uuid_generate_v4 (),
69
+ user_id integer NOT NULL,
70
+ expires timestamptz NOT NULL DEFAULT (CURRENT_TIMESTAMP + INTERVAL '2 hours'),
71
+ CONSTRAINT sessions_pkey PRIMARY KEY (id),
72
+ CONSTRAINT sessions_user_fkey FOREIGN KEY (user_id) REFERENCES public.users (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE,
73
+ CONSTRAINT sessions_one_per_user UNIQUE (user_id)
74
+ ) TABLESPACE pg_default;
75
+
76
+ ALTER TABLE public.sessions OWNER TO auth;
77
+
78
+ CREATE OR REPLACE FUNCTION public.authenticate (input json, OUT response json) RETURNS json LANGUAGE 'plpgsql' COST 100 VOLATILE PARALLEL UNSAFE AS $BODY$
79
+ DECLARE
80
+ input_email text := trim(input->>'email');
81
+ input_password text := input->>'password';
82
+ v_user users%ROWTYPE;
83
+ BEGIN
84
+ IF input_email IS NULL OR input_password IS NULL THEN
85
+ response := json_build_object('statusCode', 400, 'status', 'Please provide an email address and password to authenticate.', 'user', NULL, 'sessionId', NULL);
86
+ RETURN;
87
+ END IF;
88
+
89
+ SELECT * INTO v_user FROM users
90
+ WHERE email = input_email AND password = crypt(input_password, password) LIMIT 1;
91
+
92
+ IF NOT FOUND THEN
93
+ response := json_build_object('statusCode', 401, 'status', 'Invalid username/password combination.', 'user', NULL, 'sessionId', NULL);
94
+ ELSIF NOT v_user.email_verified THEN
95
+ response := json_build_object('statusCode', 403, 'status', 'Please verify your email address before logging in.', 'user', NULL, 'sessionId', NULL);
96
+ ELSE
97
+ response := json_build_object(
98
+ 'statusCode', 200,
99
+ 'status', 'Login successful.',
100
+ 'user', json_build_object('id', v_user.id, 'role', v_user.role, 'email', input_email, 'firstName', v_user.first_name, 'lastName', v_user.last_name, 'phone', v_user.phone, 'optOut', v_user.opt_out),
101
+ 'sessionId', create_session(v_user.id)
102
+ );
103
+ END IF;
104
+ END;
105
+ $BODY$;
106
+
107
+ ALTER FUNCTION public.authenticate (json) OWNER TO auth;
108
+
109
+ CREATE OR REPLACE FUNCTION public.create_session (input_user_id integer) RETURNS uuid LANGUAGE 'sql' COST 100 VOLATILE PARALLEL UNSAFE AS $BODY$
110
+ -- Remove expired sessions (index-friendly cleanup)
111
+ DELETE FROM sessions WHERE expires < CURRENT_TIMESTAMP;
112
+ -- Remove any existing session(s) for this user
113
+ DELETE FROM sessions WHERE user_id = input_user_id;
114
+ -- Create the new session
115
+ INSERT INTO sessions(user_id) VALUES (input_user_id) RETURNING sessions.id;
116
+ $BODY$;
117
+
118
+ ALTER FUNCTION public.create_session (integer) OWNER TO auth;
119
+
120
+ CREATE OR REPLACE FUNCTION public.get_session (input_session_id uuid) RETURNS json LANGUAGE 'sql' AS $BODY$
121
+ SELECT json_build_object(
122
+ 'id', sessions.user_id,
123
+ 'role', users.role,
124
+ 'email', users.email,
125
+ 'firstName', users.first_name,
126
+ 'lastName', users.last_name,
127
+ 'phone', users.phone,
128
+ 'optOut', users.opt_out,
129
+ 'expires', sessions.expires
130
+ ) AS user
131
+ FROM sessions
132
+ INNER JOIN users ON sessions.user_id = users.id
133
+ WHERE sessions.id = input_session_id AND expires > CURRENT_TIMESTAMP LIMIT 1;
134
+ $BODY$;
135
+
136
+ ALTER FUNCTION public.get_session (uuid) OWNER TO auth;
137
+
138
+ -- Like get_session but also bumps the expiry (sliding sessions).
139
+ -- Returns NULL if the session is expired or does not exist.
140
+ CREATE OR REPLACE FUNCTION public.get_and_update_session (input_session_id uuid) RETURNS json LANGUAGE 'plpgsql' AS $BODY$
141
+ DECLARE
142
+ result json;
143
+ BEGIN
144
+ UPDATE sessions
145
+ SET expires = CURRENT_TIMESTAMP + INTERVAL '2 hours'
146
+ WHERE id = input_session_id AND expires > CURRENT_TIMESTAMP;
147
+
148
+ IF NOT FOUND THEN
149
+ RETURN NULL;
150
+ END IF;
151
+
152
+ SELECT json_build_object(
153
+ 'id', sessions.user_id,
154
+ 'role', users.role,
155
+ 'email', users.email,
156
+ 'firstName', users.first_name,
157
+ 'lastName', users.last_name,
158
+ 'phone', users.phone,
159
+ 'optOut', users.opt_out,
160
+ 'expires', sessions.expires
161
+ ) INTO result
162
+ FROM sessions
163
+ INNER JOIN users ON sessions.user_id = users.id
164
+ WHERE sessions.id = input_session_id;
165
+
166
+ RETURN result;
167
+ END;
168
+ $BODY$;
169
+
170
+ ALTER FUNCTION public.get_and_update_session (uuid) OWNER TO auth;
171
+
172
+ CREATE OR REPLACE FUNCTION public.verify_email_and_create_session (input_id integer) RETURNS uuid LANGUAGE 'plpgsql' COST 100 VOLATILE PARALLEL UNSAFE AS $BODY$
173
+ DECLARE
174
+ session_id uuid;
175
+ BEGIN
176
+ UPDATE users SET email_verified = true WHERE id = input_id;
177
+ SELECT create_session(input_id) INTO session_id;
178
+ RETURN session_id;
179
+ END;
180
+ $BODY$;
181
+
182
+ ALTER FUNCTION public.verify_email_and_create_session (integer) OWNER TO auth;
183
+
184
+ CREATE OR REPLACE FUNCTION public.register (input json, OUT user_session json) RETURNS json LANGUAGE 'plpgsql' COST 100 VOLATILE PARALLEL UNSAFE AS $BODY$
185
+ DECLARE
186
+ input_email text := trim(input->>'email');
187
+ input_first_name text := trim(input->>'firstName');
188
+ input_last_name text := trim(input->>'lastName');
189
+ input_phone text := trim(input->>'phone');
190
+ input_password text := input->>'password';
191
+ BEGIN
192
+ PERFORM id FROM users WHERE email = input_email;
193
+ IF NOT FOUND THEN
194
+ INSERT INTO users(role, password, email, first_name, last_name, phone)
195
+ VALUES('student', crypt(input_password, gen_salt('bf', 12)), input_email, input_first_name, input_last_name, input_phone)
196
+ RETURNING
197
+ json_build_object(
198
+ 'sessionId', create_session(users.id),
199
+ 'user', json_build_object('id', users.id, 'role', 'student', 'email', input_email, 'firstName', input_first_name, 'lastName', input_last_name, 'phone', input_phone, 'optOut', users.opt_out)
200
+ ) INTO user_session;
201
+ ELSE -- user is registering account that already exists so set sessionId and user to null so client can let them know
202
+ SELECT authenticate(input) INTO user_session;
203
+ END IF;
204
+ END;
205
+ $BODY$;
206
+
207
+ ALTER FUNCTION public.register (json) OWNER TO auth;
208
+
209
+ CREATE OR REPLACE FUNCTION public.start_gmail_user_session (input json, OUT user_session json) RETURNS json LANGUAGE 'plpgsql' COST 100 VOLATILE PARALLEL UNSAFE AS $BODY$
210
+ DECLARE
211
+ input_email varchar(80) := LOWER(TRIM((input->>'email')::varchar));
212
+ input_first_name varchar(20) := TRIM((input->>'firstName')::varchar);
213
+ input_last_name varchar(20) := TRIM((input->>'lastName')::varchar);
214
+ BEGIN
215
+ -- Google verifies email ownership; mark user as verified on every sign-in
216
+ UPDATE users SET email_verified = true WHERE email = input_email;
217
+ SELECT json_build_object('id', create_session(users.id), 'user', json_build_object('id', users.id, 'role', users.role, 'email', input_email, 'firstName', users.first_name, 'lastName', users.last_name, 'phone', users.phone)) INTO user_session FROM users WHERE email = input_email;
218
+ IF NOT FOUND THEN
219
+ INSERT INTO users(role, email, first_name, last_name, email_verified)
220
+ VALUES('student', input_email, input_first_name, input_last_name, true)
221
+ RETURNING
222
+ json_build_object(
223
+ 'id', create_session(users.id),
224
+ 'user', json_build_object('id', users.id, 'role', 'student', 'email', input_email, 'firstName', input_first_name, 'lastName', input_last_name, 'phone', null)
225
+ ) INTO user_session;
226
+ END IF;
227
+ END;
228
+ $BODY$;
229
+
230
+ ALTER FUNCTION public.start_gmail_user_session (json) OWNER TO auth;
231
+
232
+ CREATE PROCEDURE public.delete_session (input_id integer) LANGUAGE sql AS $$
233
+ DELETE FROM sessions WHERE user_id = input_id;
234
+ $$;
235
+
236
+ CREATE OR REPLACE PROCEDURE public.delete_user (input_id integer) LANGUAGE sql AS $$
237
+ DELETE FROM users WHERE id = input_id;
238
+ $$;
239
+
240
+ ALTER PROCEDURE public.delete_user (integer) OWNER TO auth;
241
+
242
+ CREATE OR REPLACE PROCEDURE public.reset_password (IN input_id integer, IN input_password text) LANGUAGE plpgsql AS $procedure$
243
+ BEGIN
244
+ UPDATE users SET password = crypt(input_password, gen_salt('bf', 12)) WHERE id = input_id;
245
+ END;
246
+ $procedure$;
247
+
248
+ ALTER PROCEDURE public.reset_password (integer, text) OWNER TO auth;
249
+
250
+ CREATE OR REPLACE PROCEDURE public.upsert_user (input json) LANGUAGE plpgsql AS $BODY$
251
+ DECLARE
252
+ input_id integer := COALESCE((input->>'id')::integer, 0);
253
+ input_role roles := COALESCE((input->>'role')::roles, 'student');
254
+ input_email varchar(80) := LOWER(TRIM((input->>'email')::varchar));
255
+ input_password varchar(80) := COALESCE((input->>'password')::varchar, '');
256
+ input_first_name varchar(20) := TRIM((input->>'firstName')::varchar);
257
+ input_last_name varchar(20) := TRIM((input->>'lastName')::varchar);
258
+ input_phone varchar(23) := TRIM((input->>'phone')::varchar);
259
+ BEGIN
260
+ IF input_id = 0 THEN
261
+ INSERT INTO users (role, email, password, first_name, last_name, phone, email_verified)
262
+ VALUES (
263
+ input_role, input_email, crypt(input_password, gen_salt('bf', 12)),
264
+ input_first_name, input_last_name, input_phone, true
265
+ );
266
+ ELSE
267
+ UPDATE users SET
268
+ role = input_role,
269
+ email = input_email,
270
+ email_verified = true,
271
+ password = CASE WHEN input_password = ''
272
+ THEN password -- leave as is (we are updating fields other than the password)
273
+ ELSE crypt(input_password, gen_salt('bf', 12))
274
+ END,
275
+ first_name = input_first_name,
276
+ last_name = input_last_name,
277
+ phone = input_phone
278
+ WHERE id = input_id;
279
+ END IF;
280
+ END;
281
+ $BODY$;
282
+
283
+ ALTER PROCEDURE public.upsert_user (json) OWNER TO auth;
284
+
285
+ CREATE OR REPLACE PROCEDURE public.update_user (input_id integer, input json) LANGUAGE plpgsql AS $BODY$
286
+ DECLARE
287
+ input_email varchar(80) := LOWER(TRIM((input->>'email')::varchar));
288
+ input_password varchar(80) := COALESCE((input->>'password')::varchar, '');
289
+ input_first_name varchar(20) := TRIM((input->>'firstName')::varchar);
290
+ input_last_name varchar(20) := TRIM((input->>'lastName')::varchar);
291
+ input_phone varchar(23) := TRIM((input->>'phone')::varchar);
292
+ BEGIN
293
+ UPDATE users SET
294
+ email = input_email,
295
+ password = CASE WHEN input_password = ''
296
+ THEN password -- leave as is (we are updating fields other than the password)
297
+ ELSE crypt(input_password, gen_salt('bf', 12))
298
+ END,
299
+ first_name = input_first_name,
300
+ last_name = input_last_name,
301
+ phone = input_phone
302
+ WHERE id = input_id;
303
+ END;
304
+ $BODY$;
305
+
306
+ ALTER PROCEDURE public.update_user (integer, json) OWNER TO auth;
307
+
308
+ -- MFA codes table (one pending code per user, replaced on each new login attempt)
309
+ CREATE TABLE IF NOT EXISTS public.mfa_codes (
310
+ user_id integer NOT NULL,
311
+ code varchar(6) NOT NULL,
312
+ expires timestamptz NOT NULL DEFAULT (CURRENT_TIMESTAMP + INTERVAL '10 minutes'),
313
+ CONSTRAINT mfa_codes_pkey PRIMARY KEY (user_id),
314
+ CONSTRAINT mfa_codes_user_fkey FOREIGN KEY (user_id) REFERENCES public.users (id) ON DELETE CASCADE
315
+ ) TABLESPACE pg_default;
316
+
317
+ ALTER TABLE public.mfa_codes OWNER TO auth;
318
+
319
+ -- Generate and store a fresh 6-digit MFA code for a user, returning the code
320
+ CREATE OR REPLACE FUNCTION public.create_mfa_code (input_user_id integer) RETURNS varchar LANGUAGE plpgsql AS $BODY$
321
+ DECLARE
322
+ v_code varchar(6) := lpad(floor(random() * 1000000)::integer::text, 6, '0');
323
+ BEGIN
324
+ DELETE FROM mfa_codes WHERE expires < CURRENT_TIMESTAMP;
325
+ INSERT INTO mfa_codes(user_id, code)
326
+ VALUES (input_user_id, v_code)
327
+ ON CONFLICT (user_id) DO UPDATE
328
+ SET code = EXCLUDED.code,
329
+ expires = CURRENT_TIMESTAMP + INTERVAL '10 minutes';
330
+ RETURN v_code;
331
+ END;
332
+ $BODY$;
333
+
334
+ ALTER FUNCTION public.create_mfa_code (integer) OWNER TO auth;
335
+
336
+ -- Verify an MFA code for a given email address.
337
+ -- Returns the user_id on success (and deletes the code), or NULL on failure.
338
+ CREATE OR REPLACE FUNCTION public.verify_mfa_code (input_email text, input_code text) RETURNS integer LANGUAGE plpgsql AS $BODY$
339
+ DECLARE
340
+ v_user_id integer;
341
+ BEGIN
342
+ SELECT mfa_codes.user_id INTO v_user_id
343
+ FROM mfa_codes
344
+ INNER JOIN users ON mfa_codes.user_id = users.id
345
+ WHERE users.email = input_email
346
+ AND mfa_codes.code = input_code
347
+ AND mfa_codes.expires > CURRENT_TIMESTAMP;
348
+
349
+ IF FOUND THEN
350
+ DELETE FROM mfa_codes WHERE user_id = v_user_id;
351
+ END IF;
352
+
353
+ RETURN v_user_id;
354
+ END;
355
+ $BODY$;
356
+
357
+ ALTER FUNCTION public.verify_mfa_code (text, text) OWNER TO auth;
358
+
359
+ CALL public.upsert_user (
360
+ '{"id":0, "role":"admin", "email":"admin@example.com", "password":"admin123", "firstName":"Jane", "lastName":"Doe", "phone":"412-555-1212"}'::json
361
+ );
362
+
363
+ CALL public.upsert_user (
364
+ '{"id":0, "role":"teacher", "email":"teacher@example.com", "password":"teacher123", "firstName":"John", "lastName":"Doe", "phone":"724-555-1212"}'::json
365
+ );
366
+
367
+ CALL public.upsert_user (
368
+ '{"id":0, "role":"student", "email":"student@example.com", "password":"student123", "firstName":"Justin", "lastName":"Case", "phone":"814-555-1212"}'::json
369
+ );
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sveltekit-auth-example",
3
3
  "description": "SvelteKit Authentication Example",
4
- "version": "5.5.0",
4
+ "version": "5.6.1",
5
5
  "author": "Nate Stuyvesant",
6
6
  "license": "https://github.com/nstuyvesant/sveltekit-auth-example/blob/master/LICENSE",
7
7
  "repository": {
@@ -28,7 +28,10 @@
28
28
  "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
29
29
  "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
30
30
  "lint": "prettier --check . && eslint .",
31
- "format": "prettier --write ."
31
+ "format": "prettier --write .",
32
+ "coverage": "vitest run --coverage",
33
+ "test:e2e": "playwright test",
34
+ "test:unit": "vitest"
32
35
  },
33
36
  "engines": {
34
37
  "node": "^24.14.0"
package/src/app.d.ts CHANGED
@@ -4,42 +4,60 @@
4
4
  // for information about these interfaces
5
5
  // and what to do when importing types
6
6
  declare namespace App {
7
+ /** Per-request server-side locals populated by `hooks.server.ts`. */
7
8
  interface Locals {
9
+ /** The authenticated user, or `undefined` when no valid session exists. */
8
10
  user: User | undefined
9
11
  }
10
12
 
11
13
  // interface Platform {}
12
14
 
15
+ /** Private environment variables (server-side only). */
13
16
  interface PrivateEnv {
14
17
  // $env/static/private
18
+ /** PostgreSQL connection string. */
15
19
  DATABASE_URL: string
20
+ /** Public-facing domain used to construct email links (e.g. `https://example.com`). */
16
21
  DOMAIN: string
22
+ /** Secret key used to sign and verify JWTs. */
17
23
  JWT_SECRET: string
24
+ /** SendGrid API key. */
18
25
  SENDGRID_KEY: string
26
+ /** Default sender email address for outgoing mail. */
19
27
  SENDGRID_SENDER: string
20
28
  }
21
29
 
30
+ /** Public environment variables (safe to expose to the client). */
22
31
  interface PublicEnv {
23
32
  // $env/static/public
33
+ /** Google OAuth 2.0 client ID for Google Sign-In. */
24
34
  PUBLIC_GOOGLE_CLIENT_ID: string
25
35
  }
26
36
  }
27
37
 
38
+ /** Result returned by the `authenticate` and `register` SQL functions. */
28
39
  interface AuthenticationResult {
40
+ /** HTTP status code to use when the operation fails. */
29
41
  statusCode: NumericRange<400, 599>
42
+ /** Human-readable status message. */
30
43
  status: string
44
+ /** The authenticated or registered user, if successful. */
31
45
  user: User
46
+ /** The newly created session ID. */
32
47
  sessionId: string
33
48
  }
34
49
 
50
+ /** Raw login credentials submitted by the user. */
35
51
  interface Credentials {
36
52
  email: string
37
53
  password: string
38
54
  }
39
55
 
56
+ /** Persistent properties stored in the database for a user account. */
40
57
  interface UserProperties {
41
58
  id: number
42
- expires?: string // ISO-8601 datetime
59
+ /** ISO-8601 datetime at which the current session expires. */
60
+ expires?: string
43
61
  role: 'student' | 'teacher' | 'admin'
44
62
  password?: string
45
63
  firstName?: string
@@ -48,9 +66,12 @@ interface UserProperties {
48
66
  phone?: string
49
67
  }
50
68
 
69
+ /** A user record, or `undefined`/`null` when unauthenticated. */
51
70
  type User = UserProperties | undefined | null
52
71
 
72
+ /** A database session paired with its associated user. */
53
73
  interface UserSession {
74
+ /** UUID session identifier stored in the `session` cookie. */
54
75
  id: string
55
76
  user: User
56
77
  }
@@ -2,13 +2,28 @@ import type { Handle, RequestEvent } from '@sveltejs/kit'
2
2
  import { error } from '@sveltejs/kit'
3
3
  import { query } from '$lib/server/db'
4
4
 
5
- // In-memory IP-based rate limiter for sensitive auth endpoints.
6
- // For multi-instance deployments, replace with a shared store like Redis.
5
+ /**
6
+ * In-memory IP-based rate limiter for sensitive auth endpoints.
7
+ * @remarks For multi-instance deployments, replace with a shared store like Redis.
8
+ */
7
9
  const ipRateLimit = new Map<string, { count: number; resetAt: number }>()
10
+ /** Duration of each rate-limit window in milliseconds (15 minutes). */
8
11
  const RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000 // 15 minutes
12
+ /** Maximum number of requests allowed per IP within {@link RATE_LIMIT_WINDOW_MS}. */
9
13
  const RATE_LIMIT_MAX_REQUESTS = 20
10
- const RATE_LIMITED_PATHS = new Set(['/auth/login', '/auth/register', '/auth/forgot'])
14
+ /** Set of path prefixes that are subject to IP-based rate limiting. */
15
+ const RATE_LIMITED_PATHS = new Set(['/auth/login', '/auth/register', '/auth/forgot', '/auth/mfa'])
11
16
 
17
+ /**
18
+ * Checks whether the given IP address is within its rate-limit allowance.
19
+ *
20
+ * Starts a new window if none exists or the previous one has expired. Once
21
+ * {@link RATE_LIMIT_MAX_REQUESTS} is reached within the window, subsequent
22
+ * calls return `false` until the window resets.
23
+ *
24
+ * @param ip - The client IP address to check.
25
+ * @returns `true` if the request is allowed, `false` if the limit is exceeded.
26
+ */
12
27
  function checkRateLimit(ip: string): boolean {
13
28
  const now = Date.now()
14
29
  const entry = ipRateLimit.get(ip)
@@ -21,15 +36,26 @@ function checkRateLimit(ip: string): boolean {
21
36
  return true
22
37
  }
23
38
 
24
- // Periodically clean up expired entries to prevent unbounded memory growth
25
- setInterval(() => {
26
- const now = Date.now()
27
- for (const [key, value] of ipRateLimit) {
28
- if (now > value.resetAt) ipRateLimit.delete(key)
29
- }
30
- }, 60 * 60 * 1000)
39
+ /** Periodically removes expired entries from {@link ipRateLimit} to prevent unbounded memory growth. */
40
+ setInterval(
41
+ () => {
42
+ const now = Date.now()
43
+ for (const [key, value] of ipRateLimit) {
44
+ if (now > value.resetAt) ipRateLimit.delete(key)
45
+ }
46
+ },
47
+ 60 * 60 * 1000
48
+ )
31
49
 
32
- // Attach authorization to each server request (role may have changed)
50
+ /**
51
+ * Looks up the session in the database and attaches the associated user to
52
+ * `event.locals`. Also updates the session's last-active timestamp.
53
+ *
54
+ * Sets `event.locals.user` to `undefined` if the session is not found.
55
+ *
56
+ * @param sessionId - The session UUID read from the request cookie.
57
+ * @param event - The SvelteKit request event to attach the user to.
58
+ */
33
59
  async function attachUserToRequestEvent(sessionId: string, event: RequestEvent) {
34
60
  const result = await query(
35
61
  'SELECT get_and_update_session($1::uuid)',
@@ -39,7 +65,16 @@ async function attachUserToRequestEvent(sessionId: string, event: RequestEvent)
39
65
  event.locals.user = result.rows[0]?.get_and_update_session // undefined if not found
40
66
  }
41
67
 
42
- // Invoked for each endpoint called and initially for SSR router
68
+ /**
69
+ * SvelteKit server hook — invoked for every request before the endpoint or
70
+ * page load function runs.
71
+ *
72
+ * Responsibilities:
73
+ * - Short-circuits static asset requests (`/_app/`) immediately.
74
+ * - Enforces IP-based rate limiting on sensitive auth paths.
75
+ * - Resolves the session cookie to a user and populates `event.locals.user`.
76
+ * - Deletes a stale session cookie when no matching session is found.
77
+ */
43
78
  export const handle = (async ({ event, resolve }) => {
44
79
  const { cookies, url } = event
45
80
 
@@ -1,9 +1,17 @@
1
+ /** Represents a toast notification shown to the user. */
1
2
  interface Toast {
3
+ /** Short heading displayed at the top of the toast. */
2
4
  title: string
5
+ /** Main message content of the toast. */
3
6
  body: string
7
+ /** Whether the toast is currently visible. */
4
8
  isOpen: boolean
5
9
  }
6
10
 
11
+ /**
12
+ * Reactive singleton holding global application state.
13
+ * Access via the exported {@link appState} instance.
14
+ */
7
15
  class AppState {
8
16
  /** Currently logged-in user, undefined when not authenticated */
9
17
  user = $state<User | undefined>(undefined)
@@ -4,6 +4,10 @@ import { page } from '$app/state'
4
4
  /**
5
5
  * Redirect the user to the appropriate page after a successful login,
6
6
  * respecting an optional ?referrer= query parameter.
7
+ *
8
+ * @param user - The authenticated user. Redirects to a role-based default route
9
+ * (`/teachers`, `/admin`, or `/`) unless a valid same-origin `referrer` query
10
+ * parameter is present, in which case that path is used instead.
7
11
  */
8
12
  export function redirectAfterLogin(user: User): void {
9
13
  if (!user) return
package/src/lib/focus.ts CHANGED
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Focuses the first invalid input element within a form.
3
+ *
4
+ * Iterates through the form's elements in DOM order and calls `focus()` on the
5
+ * first `HTMLInputElement` that fails constraint validation, then stops.
6
+ *
7
+ * @param form - The form element to search for invalid inputs.
8
+ */
1
9
  export const focusOnFirstError = (form: HTMLFormElement) => {
2
10
  for (const field of form.elements) {
3
11
  if (field instanceof HTMLInputElement && !field.checkValidity()) {
package/src/lib/google.ts CHANGED
@@ -2,6 +2,13 @@ import { PUBLIC_GOOGLE_CLIENT_ID } from '$env/static/public'
2
2
  import { appState } from '$lib/app-state.svelte'
3
3
  import { redirectAfterLogin } from '$lib/auth-redirect'
4
4
 
5
+ /**
6
+ * Renders the Google Sign-In button inside the element with id `googleButton`.
7
+ *
8
+ * Reads the element's width (falling back to its parent's width, then 400px)
9
+ * and passes it to the Google Identity Services SDK so the button scales
10
+ * correctly within its container.
11
+ */
5
12
  export function renderGoogleButton() {
6
13
  const btn = document.getElementById('googleButton')
7
14
  if (btn) {
@@ -15,6 +22,16 @@ export function renderGoogleButton() {
15
22
  }
16
23
  }
17
24
 
25
+ /**
26
+ * Initializes the Google Identity Services SDK (once per session) and
27
+ * registers a callback that handles the credential response after the user
28
+ * signs in with Google.
29
+ *
30
+ * On a successful sign-in the callback:
31
+ * 1. POSTs the Google credential token to `/auth/google`.
32
+ * 2. Updates {@link appState.user} with the returned user.
33
+ * 3. Redirects the user via {@link redirectAfterLogin}.
34
+ */
18
35
  export function initializeGoogleAccounts() {
19
36
  if (!appState.googleInitialized) {
20
37
  google.accounts.id.initialize({
@@ -30,6 +30,15 @@ pool.on('error', (err: Error) => {
30
30
  console.error('Unexpected error on idle client', err)
31
31
  })
32
32
 
33
+ /**
34
+ * Executes a parameterized SQL query using the connection pool.
35
+ *
36
+ * @template T - The expected row type, extending QueryResultRow.
37
+ * @param sql - The SQL query string with optional $1, $2, ... placeholders.
38
+ * @param params - Optional positional parameter values to bind to the query.
39
+ * @param name - Optional name for the query to use a prepared statement.
40
+ * @returns A promise resolving to the typed QueryResult.
41
+ */
33
42
  queryFn = <T extends QueryResultRow>(
34
43
  sql: string,
35
44
  params?: (string | number | boolean | object | null)[],
@@ -1,2 +1,3 @@
1
1
  export { sendPasswordResetEmail } from './password-reset'
2
2
  export { sendVerificationEmail } from './verify-email'
3
+ export { sendMfaCodeEmail } from './mfa-code'
@@ -0,0 +1,22 @@
1
+ import { SENDGRID_SENDER } from '$env/static/private'
2
+ import { sendMessage } from '$lib/server/sendgrid'
3
+
4
+ /**
5
+ * Sends a multi-factor authentication (MFA) verification code email to the user.
6
+ *
7
+ * @param toEmail - The recipient's email address.
8
+ * @param code - The one-time verification code to include in the email.
9
+ */
10
+ export const sendMfaCodeEmail = async (toEmail: string, code: string) => {
11
+ await sendMessage({
12
+ to: { email: toEmail },
13
+ from: SENDGRID_SENDER,
14
+ subject: 'Your login verification code',
15
+ categories: ['account'],
16
+ html: `
17
+ <p>Your verification code is:</p>
18
+ <p style="font-size: 2em; font-weight: bold; letter-spacing: 0.25em;">${code}</p>
19
+ <p>This code expires in 10 minutes. If you did not attempt to log in, you can safely ignore this email.</p>
20
+ `
21
+ })
22
+ }