From 3a00201991bfc4256cb99432b6c752b4cceb9f84 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:16:20 +0100 Subject: [PATCH 01/26] Claim frontend task F2 (auth) in the backlog Co-Authored-By: Claude Sonnet 5.5 --- docs/BACKLOG.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index 15a1f66..a1fd25c 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -1,4 +1,10 @@ -# Backend backlog +# Backlog + +## Frontend + +- **F2 Auth** (register, login, Google sign-in, logout, route protection): claimed by `Filionus`, branch `feat/auth`, in progress. + +## Backend Findings from the first backend review, in the order we want to work through them. Status of the backend at review time: `npm test` and `npm run build` pass; API not yet tested against a real Supabase project. From b091056cfcbde81a3046bb740668f455075bf026 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:18:03 +0100 Subject: [PATCH 02/26] Add Pinia and run tests in stores, composables and middleware Pinia holds the session state (F2). pinia 3 with @pinia/nuxt 0.11 adds packages without changing any locked version. The lockfile is resolved so that npm 10 (CI) and npm 11 accept it. Co-Authored-By: Claude Sonnet 5.5 --- nuxt.config.ts | 2 +- package-lock.json | 238 ++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 + vitest.config.ts | 2 +- 4 files changed, 242 insertions(+), 2 deletions(-) diff --git a/nuxt.config.ts b/nuxt.config.ts index 0c96639..395e16e 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -3,7 +3,7 @@ import tailwindcss from '@tailwindcss/vite' export default defineNuxtConfig({ compatibilityDate: '2025-01-01', devtools: { enabled: false }, - modules: ['@nuxtjs/i18n'], + modules: ['@nuxtjs/i18n', '@pinia/nuxt'], css: ['~/assets/css/main.css'], vite: { plugins: [tailwindcss()] }, i18n: { diff --git a/package-lock.json b/package-lock.json index 1ec03ea..c1fab97 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,8 +7,10 @@ "name": "ons-couple-planner", "dependencies": { "@nuxtjs/i18n": "10.2.3", + "@pinia/nuxt": "^0.11.3", "@supabase/supabase-js": "^2.100.0", "nuxt": "^3.21.11", + "pinia": "^3.0.4", "zod": "^4.0.0" }, "devDependencies": { @@ -4574,6 +4576,128 @@ "inBundle": true, "license": "MIT" }, + "node_modules/@pinia/nuxt": { + "version": "0.11.3", + "resolved": "https://registry.npmjs.org/@pinia/nuxt/-/nuxt-0.11.3.tgz", + "integrity": "sha512-7WVNHpWx4qAEzOlnyrRC88kYrwnlR/PrThWT0XI1dSNyUAXu/KBv9oR37uCgYkZroqP5jn8DfzbkNF3BtKvE9w==", + "license": "MIT", + "dependencies": { + "@nuxt/kit": "^4.2.0" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "pinia": "^3.0.4" + } + }, + "node_modules/@pinia/nuxt/node_modules/@nuxt/kit": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@nuxt/kit/-/kit-4.7.0.tgz", + "integrity": "sha512-78NsjcazI8PQPE0H8+mx+0c4Wm1GlvM5Oxj60sCHil0TUjTMjqRVMoORgJLPyPulMhD2Ih1rEZh5TEvXkytdLA==", + "license": "MIT", + "dependencies": { + "consola": "^3.4.2", + "defu": "^6.1.7", + "destr": "^2.0.5", + "errx": "^0.2.2", + "exsolve": "^1.2.0", + "ignore": "^7.0.16", + "klona": "^2.0.6", + "microdiff": "^1.6.0", + "nostics": "^1.4.0", + "package-manager-detector": "^1.9.0", + "pathe": "^2.0.3", + "rc9": "^3.1.0", + "rou3": "^1.0.0", + "scule": "^1.3.0", + "std-env": "^4.3.0", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "unctx": "^3.0.1", + "verkit": "^0.5.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@nuxt/schema": "^3.0.0 || ^4.0.0 || ^5.0.0-0", + "confbox": ">=0.1.0", + "dotenv": "*", + "giget": ">=3.1.0", + "jiti": "^2.0.0", + "mlly": "^1.2.0", + "oxc-parser": ">=0.56.0", + "rolldown": ">=1.0.0" + }, + "peerDependenciesMeta": { + "@nuxt/schema": { + "optional": true + }, + "confbox": { + "optional": true + }, + "dotenv": { + "optional": true + }, + "giget": { + "optional": true + }, + "jiti": { + "optional": true + }, + "mlly": { + "optional": true + }, + "oxc-parser": { + "optional": true + }, + "rolldown": { + "optional": true + } + } + }, + "node_modules/@pinia/nuxt/node_modules/errx": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/errx/-/errx-0.2.2.tgz", + "integrity": "sha512-HaPN6cxm6iZ9bIbQQ5orChcw7SY5smUzM08ZMc6OtV4UQhrrc3Ms1G8Ww2n/9lXkWqiioNTssF8bCvchrSbFEQ==", + "license": "MIT" + }, + "node_modules/@pinia/nuxt/node_modules/rou3": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/rou3/-/rou3-1.0.0.tgz", + "integrity": "sha512-ySeaQkSrua+ut9g+65I7FHqOFBaY8tV0FmccXItoq0q21se32Q3u4YiW7/RqXSosWgYJaaKwRHXy3BST9PeCNQ==", + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@pinia/nuxt/node_modules/unctx": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/unctx/-/unctx-3.0.1.tgz", + "integrity": "sha512-5RAt2etv7g362RXyd33R82gm9u/kbtQlpoaOs9Bgm4E32GRMJ0xjbZyvdxUTmiuHk3V1IQb1aUNrp5IWY+JaWw==", + "license": "MIT", + "peerDependencies": { + "magic-string": ">=0.30.21", + "oxc-parser": ">=0.140.0", + "rolldown": "^1.1.5", + "unplugin": "^3.3.0" + }, + "peerDependenciesMeta": { + "magic-string": { + "optional": true + }, + "oxc-parser": { + "optional": true + }, + "rolldown": { + "optional": true + }, + "unplugin": { + "optional": true + } + } + }, "node_modules/@polka/url": { "version": "1.0.0-next.29", "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", @@ -7324,6 +7448,18 @@ "integrity": "sha512-aVf4A4hI2w70LnF7GG+7xDQUkliwiXWXFvTjkip4+b64ygDQ2sJPRSKFDHbxn8o0xu9QzPkMuuiWIXyFSE2slA==", "license": "MIT" }, + "node_modules/copy-anything": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.1.5.tgz", + "integrity": "sha512-vePst2VLTSqPglW7Q98VwFpGiGpOHTyXIo81MO5VyLecA5zMbZw/P/V1vmwD1jksa2iJpn/YkDrJ3XhTfzUyhQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -9742,6 +9878,12 @@ "node": ">= 18" } }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "license": "MIT" + }, "node_modules/mlly": { "version": "1.8.2", "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", @@ -10581,6 +10723,75 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pinia": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pinia/-/pinia-3.0.4.tgz", + "integrity": "sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^7.7.7" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "typescript": ">=4.5.0", + "vue": "^3.5.11" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/pinia/node_modules/@vue/devtools-api": { + "version": "7.7.10", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.10.tgz", + "integrity": "sha512-KxtEpUOOpFz/qOGRrAwA36QF7DqIA+FXgCYit9mk9wjbaZt0sXOFz81ElOZtKA4HbWHUdwNjZHBFsFFyp5BZiA==", + "license": "MIT", + "dependencies": { + "@vue/devtools-kit": "^7.7.10" + } + }, + "node_modules/pinia/node_modules/@vue/devtools-kit": { + "version": "7.7.10", + "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.10.tgz", + "integrity": "sha512-3WNi2Kq4tbpVbmhml7RiphmAt0279oh3fKNeWMQIrltfX8Q91b4i5PL8DtyNKdwmcsGrV4fg+erwWOmD05CLIw==", + "license": "MIT", + "dependencies": { + "@vue/devtools-shared": "^7.7.10", + "birpc": "^2.3.0", + "hookable": "^5.5.3", + "mitt": "^3.0.1", + "perfect-debounce": "^1.0.0", + "speakingurl": "^14.0.1", + "superjson": "^2.2.2" + } + }, + "node_modules/pinia/node_modules/@vue/devtools-shared": { + "version": "7.7.10", + "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.10.tgz", + "integrity": "sha512-wOPslzB8vTvpxwdaOcR2qAbwmuSP0L+rhpoC6Cf56V3Jip+HWb7PQQXOUPgBNQARpXsbQX/+mvi8kKucmBGRwQ==", + "license": "MIT", + "dependencies": { + "rfdc": "^1.4.1" + } + }, + "node_modules/pinia/node_modules/birpc": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz", + "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/pinia/node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "license": "MIT" + }, "node_modules/pkg-types": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz", @@ -11302,6 +11513,12 @@ "node": ">=0.10.0" } }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, "node_modules/rolldown": { "version": "1.2.19", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", @@ -11719,6 +11936,15 @@ "node": ">=0.10.0" } }, + "node_modules/speakingurl": { + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", + "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/srvx": { "version": "0.11.22", "resolved": "https://registry.npmjs.org/srvx/-/srvx-0.11.22.tgz", @@ -11856,6 +12082,18 @@ "postcss": "^8.5.13" } }, + "node_modules/superjson": { + "version": "2.2.7", + "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.7.tgz", + "integrity": "sha512-QK/H+tosbovdRvIuGqcWn8g3IxPZY7B8ZPowCAmWsV8bPvCk+bGMlZt90C4AxZjnzMO2WBRDacr1+0i1AOy/5g==", + "license": "MIT", + "dependencies": { + "copy-anything": "^4" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/supports-color": { "version": "10.2.2", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", diff --git a/package.json b/package.json index 246d998..4efe2e7 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,10 @@ }, "dependencies": { "@nuxtjs/i18n": "10.2.3", + "@pinia/nuxt": "^0.11.3", "@supabase/supabase-js": "^2.100.0", "nuxt": "^3.21.11", + "pinia": "^3.0.4", "zod": "^4.0.0" }, "devDependencies": { diff --git a/vitest.config.ts b/vitest.config.ts index ab14854..7145353 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' // Frontend tests live in __tests__ folders next to the code they check. // Backend tests stay in tests/. -const frontendTests = '{assets,components,i18n,layouts,pages}/**/__tests__' +const frontendTests = '{assets,components,composables,i18n,layouts,middleware,pages,stores}/**/__tests__' export default defineConfig(async () => ({ test: { From cf485d7bbe89488b758cbfdde5bdfd55507ee085 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:18:36 +0100 Subject: [PATCH 03/26] Pin language switching inside the default layout Covers the existing behaviour before the layout changes for F2. Co-Authored-By: Claude Sonnet 5.5 --- layouts/__tests__/default.nuxt.spec.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/layouts/__tests__/default.nuxt.spec.ts b/layouts/__tests__/default.nuxt.spec.ts index fa0f606..fd8a5ec 100644 --- a/layouts/__tests__/default.nuxt.spec.ts +++ b/layouts/__tests__/default.nuxt.spec.ts @@ -1,6 +1,6 @@ import { mountSuspended } from '@nuxt/test-utils/runtime' import { enableAutoUnmount } from '@vue/test-utils' -import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import DefaultLayout from '../default.vue' // The tests attach the layout to the page, so remove it again after each one. @@ -42,6 +42,18 @@ describe('default layout', () => { expect(wrapper.get('main').text()).toContain('page content') }) + test('the language switcher in the header changes the language of the layout', async () => { + const wrapper = await mountLayout() + + await wrapper.get('header a[data-locale="en"]').trigger('click') + + await vi.waitFor(() => { + expect(wrapper.get('a[href="#main"]').text()).toBe('Skip to content') + expect(wrapper.get('header a[data-locale="en"]').attributes('aria-current')).toBe('true') + expect(useRouter().currentRoute.value.path).toBe('/en') + }) + }) + test('has a header with home link and language switcher, and one main navigation', async () => { const wrapper = await mountLayout() expect(wrapper.get('header a[href="/"]').text()).toBe('Ons') From 6ba52db6a83f32e93c87efdfa823f441c6a2fc06 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:19:18 +0100 Subject: [PATCH 04/26] Add tests for the session store Covers restoring a session, sign-in, registration, Google sign-in, sign-out, token refresh and missing configuration against an in-memory Supabase Auth. Fails until the store and useSupabaseAuth exist. Co-Authored-By: Claude Sonnet 5.5 --- composables/__tests__/fake-auth.ts | 64 +++++++ composables/__tests__/reset-session.ts | 9 + stores/__tests__/session.nuxt.spec.ts | 227 +++++++++++++++++++++++++ 3 files changed, 300 insertions(+) create mode 100644 composables/__tests__/fake-auth.ts create mode 100644 composables/__tests__/reset-session.ts create mode 100644 stores/__tests__/session.nuxt.spec.ts diff --git a/composables/__tests__/fake-auth.ts b/composables/__tests__/fake-auth.ts new file mode 100644 index 0000000..eb47658 --- /dev/null +++ b/composables/__tests__/fake-auth.ts @@ -0,0 +1,64 @@ +import type { Session } from '@supabase/supabase-js' +import { vi } from 'vitest' + +// An in-memory stand-in for supabase.auth, limited to the parts the app uses. +// It lives in a __tests__ folder, so Nuxt does not auto-import it. + +type Listener = (event: string, session: Session | null) => void + +export function fakeSession(email: string, accessToken: string) { + return { + access_token: accessToken, + refresh_token: `refresh-for-${accessToken}`, + user: { id: `id-of-${email}`, email }, + } as Session +} + +export function createFakeAuth(options: { signedInAs?: string } = {}) { + let issued = 0 + // Every new session gets a new token: token-1, token-2, and so on. + function newSession(email: string) { + issued += 1 + return fakeSession(email, `token-${issued}`) + } + + let session: Session | null = options.signedInAs ? newSession(options.signedInAs) : null + const listeners = new Set() + + function change(event: string, next: Session | null) { + session = next + for (const listener of listeners) { + listener(event, next) + } + } + + function signedIn(email: string) { + change('SIGNED_IN', newSession(email)) + return { data: { session, user: session!.user }, error: null as Error | null } + } + + const auth = { + getSession: vi.fn(async () => ({ data: { session }, error: null as Error | null })), + onAuthStateChange: vi.fn((listener: Listener) => { + listeners.add(listener) + return { data: { subscription: { unsubscribe: () => listeners.delete(listener) } } } + }), + signInWithPassword: vi.fn(async (credentials: { email: string, password: string }) => signedIn(credentials.email)), + signUp: vi.fn(async (credentials: { email: string, password: string, options?: object }) => signedIn(credentials.email)), + signInWithOAuth: vi.fn(async (_request: object) => ({ data: {}, error: null as Error | null })), + signOut: vi.fn(async (_options?: object) => { + change('SIGNED_OUT', null) + return { error: null as Error | null } + }), + refreshSession: vi.fn(async () => { + change('TOKEN_REFRESHED', newSession(session?.user.email ?? 'nobody@example.org')) + return { data: { session }, error: null as Error | null } + }), + } + + return { + auth, + // A change that does not start in this tab, for example a sign-out somewhere else. + endSession: () => change('SIGNED_OUT', null), + } +} diff --git a/composables/__tests__/reset-session.ts b/composables/__tests__/reset-session.ts new file mode 100644 index 0000000..9ba7b72 --- /dev/null +++ b/composables/__tests__/reset-session.ts @@ -0,0 +1,9 @@ +import { useNuxtApp } from '#app' +import { useSessionStore } from '../../stores/session' + +// The Nuxt test app lives for a whole test file, so each test needs a fresh session store. +export function resetSession() { + const store = useSessionStore() + store.$dispose() + delete (useNuxtApp().$pinia as { state: { value: Record } }).state.value.session +} diff --git a/stores/__tests__/session.nuxt.spec.ts b/stores/__tests__/session.nuxt.spec.ts new file mode 100644 index 0000000..0e86ac4 --- /dev/null +++ b/stores/__tests__/session.nuxt.spec.ts @@ -0,0 +1,227 @@ +import { mockNuxtImport } from '@nuxt/test-utils/runtime' +import { AuthApiError, AuthRetryableFetchError } from '@supabase/supabase-js' +import { beforeEach, describe, expect, test, vi } from 'vitest' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { resetSession } from '../../composables/__tests__/reset-session' +import { useSessionStore } from '../session' + +// useSupabaseAuth is the only way to reach Supabase, so replacing it keeps tests offline. +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +let fake: ReturnType + +function start(options: Parameters[0] = {}) { + fake = createFakeAuth(options) + supabase.auth = fake.auth + resetSession() + return useSessionStore() +} + +const offline = () => new AuthRetryableFetchError('offline', 0) +const callbackPage = () => `${window.location.origin}/auth/callback` + +beforeEach(() => { + start() +}) + +describe('restoring a session', () => { + test('knows nothing before it has asked', () => { + const session = start({ signedInAs: 'ann@example.org' }) + expect(session.status).toBe('unknown') + expect(session.isSignedIn).toBe(false) + }) + + test('is signed out when nothing is stored', async () => { + const session = start() + await session.init() + expect(session.status).toBe('signedOut') + expect(session.user).toBeNull() + }) + + test('restores a stored session', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await session.init() + expect(session.status).toBe('signedIn') + expect(session.user?.email).toBe('ann@example.org') + }) + + test('asks Supabase only once, even when called twice at the same time', async () => { + const session = start() + await Promise.all([session.init(), session.init()]) + await session.init() + expect(fake.auth.getSession).toHaveBeenCalledTimes(1) + expect(fake.auth.onAuthStateChange).toHaveBeenCalledTimes(1) + }) + + test('asks again later if Supabase could not be reached', async () => { + const session = start() + fake.auth.getSession.mockResolvedValueOnce({ data: { session: null }, error: offline() }) + await session.init() + expect(session.status).toBe('signedOut') + + await session.init() + expect(fake.auth.getSession).toHaveBeenCalledTimes(2) + }) + + test('follows a sign-out that happens elsewhere', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await session.init() + fake.endSession() + expect(session.status).toBe('signedOut') + expect(session.signedOutByUser).toBe(false) + }) +}) + +describe('signing in and registering', () => { + test('signs in with email and password', async () => { + const session = start() + await session.signIn('ann@example.org', 'secret-1') + expect(fake.auth.signInWithPassword).toHaveBeenCalledWith({ email: 'ann@example.org', password: 'secret-1' }) + expect(session.status).toBe('signedIn') + }) + + test('reports why a sign-in failed, by code', async () => { + const session = start() + fake.auth.signInWithPassword.mockResolvedValueOnce({ + data: { session: null, user: null } as never, + error: new AuthApiError('Invalid login credentials', 400, 'invalid_credentials'), + }) + await expect(session.signIn('ann@example.org', 'wrong')).rejects.toMatchObject({ code: 'invalid_credentials' }) + expect(session.isSignedIn).toBe(false) + }) + + test('reports an unreachable server as a network problem', async () => { + const session = start() + fake.auth.signInWithPassword.mockResolvedValueOnce({ data: { session: null, user: null } as never, error: offline() }) + await expect(session.signIn('ann@example.org', 'secret-1')).rejects.toMatchObject({ code: 'network' }) + }) + + test('is signed in after registering when no email confirmation is needed', async () => { + const session = start() + await expect(session.register('ann@example.org', 'secret-1')).resolves.toBe('signedIn') + expect(session.status).toBe('signedIn') + }) + + test('asks for email confirmation when Supabase returns no session', async () => { + const session = start() + fake.auth.signUp.mockResolvedValueOnce({ data: { session: null, user: { id: '1' } } as never, error: null }) + + await expect(session.register('ann@example.org', 'secret-1')).resolves.toBe('confirmationRequired') + + expect(session.isSignedIn).toBe(false) + expect(fake.auth.signUp).toHaveBeenCalledWith({ + email: 'ann@example.org', + password: 'secret-1', + options: { emailRedirectTo: callbackPage() }, + }) + }) + + test('starts Google sign-in with the callback page as return address', async () => { + const session = start() + await session.signInWithGoogle() + expect(fake.auth.signInWithOAuth).toHaveBeenCalledWith({ + provider: 'google', + options: { redirectTo: callbackPage() }, + }) + }) + + test('reports a Google sign-in that cannot start', async () => { + const session = start() + fake.auth.signInWithOAuth.mockResolvedValueOnce({ + data: {}, + error: new AuthApiError('Provider is not enabled', 400, 'validation_failed'), + }) + await expect(session.signInWithGoogle()).rejects.toMatchObject({ code: 'validation_failed' }) + }) +}) + +describe('signing out', () => { + test('signs out on this device only', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await session.init() + await session.signOut() + expect(fake.auth.signOut).toHaveBeenCalledWith({ scope: 'local' }) + expect(session.status).toBe('signedOut') + expect(session.signedOutByUser).toBe(true) + }) + + test('signs out even if the server cannot be reached', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await session.init() + // Supabase removes the local session first and then reports the failed request. + fake.auth.signOut.mockResolvedValueOnce({ error: offline() }) + await session.signOut() + expect(session.status).toBe('signedOut') + }) + + test('ends a session that the backend no longer accepts', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await session.init() + await session.expire() + expect(fake.auth.signOut).toHaveBeenCalledWith({ scope: 'local' }) + expect(session.status).toBe('signedOut') + expect(session.signedOutByUser).toBe(false) + }) +}) + +describe('access token', () => { + test('returns the current token', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await expect(session.accessToken()).resolves.toBe('token-1') + }) + + test('returns nothing when signed out', async () => { + const session = start() + await expect(session.accessToken()).resolves.toBeNull() + }) + + test('refresh returns a new token', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await expect(session.refresh()).resolves.toBe('token-2') + }) + + test('refreshes that run at the same time share one request', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + const tokens = await Promise.all([session.refresh(), session.refresh()]) + expect(tokens).toEqual(['token-2', 'token-2']) + expect(fake.auth.refreshSession).toHaveBeenCalledTimes(1) + + // A later refresh is a new request. + await expect(session.refresh()).resolves.toBe('token-3') + }) + + test('refresh returns nothing when the session cannot be renewed', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await session.init() + fake.auth.refreshSession.mockResolvedValueOnce({ + data: { session: null }, + error: new AuthApiError('Invalid refresh token', 400, 'refresh_token_not_found'), + }) + await expect(session.refresh()).resolves.toBeNull() + }) + + test('refresh keeps the session when the server cannot be reached', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + await session.init() + fake.auth.refreshSession.mockResolvedValueOnce({ data: { session: null }, error: offline() }) + await expect(session.refresh()).rejects.toMatchObject({ code: 'network' }) + expect(session.status).toBe('signedIn') + }) +}) + +describe('without Supabase configuration', () => { + test('is signed out, and actions say that sign-in is unavailable', async () => { + supabase.auth = undefined + resetSession() + const session = useSessionStore() + + await session.init() + + expect(session.status).toBe('signedOut') + await expect(session.signIn('ann@example.org', 'secret-1')).rejects.toMatchObject({ code: 'unavailable' }) + await expect(session.register('ann@example.org', 'secret-1')).rejects.toMatchObject({ code: 'unavailable' }) + await expect(session.signInWithGoogle()).rejects.toMatchObject({ code: 'unavailable' }) + await expect(session.accessToken()).resolves.toBeNull() + }) +}) From c7b3395214e8fba21453cfd4ac52cfae8438ef9e Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:19:47 +0100 Subject: [PATCH 05/26] Add test for fetching a token while the server is unreachable Co-Authored-By: Claude Sonnet 5.5 --- stores/__tests__/session.nuxt.spec.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/stores/__tests__/session.nuxt.spec.ts b/stores/__tests__/session.nuxt.spec.ts index 0e86ac4..a443712 100644 --- a/stores/__tests__/session.nuxt.spec.ts +++ b/stores/__tests__/session.nuxt.spec.ts @@ -176,6 +176,13 @@ describe('access token', () => { await expect(session.accessToken()).resolves.toBeNull() }) + test('reports an unreachable server instead of looking signed out', async () => { + const session = start({ signedInAs: 'ann@example.org' }) + // An expired token cannot be renewed while offline. + fake.auth.getSession.mockResolvedValueOnce({ data: { session: null }, error: offline() }) + await expect(session.accessToken()).rejects.toMatchObject({ code: 'network' }) + }) + test('refresh returns a new token', async () => { const session = start({ signedInAs: 'ann@example.org' }) await expect(session.refresh()).resolves.toBe('token-2') From bfeb70be3b45c7bfe2170de3be620b7c57274c7e Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:20:07 +0100 Subject: [PATCH 06/26] Add the session store Holds who is signed in and wraps Supabase Auth: restore, sign in, register, Google, token refresh and sign out on this device. Failures are reported as codes so pages can translate them. Co-Authored-By: Claude Sonnet 5.5 --- composables/useSupabaseAuth.ts | 8 ++ stores/session.ts | 180 +++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+) create mode 100644 composables/useSupabaseAuth.ts create mode 100644 stores/session.ts diff --git a/composables/useSupabaseAuth.ts b/composables/useSupabaseAuth.ts new file mode 100644 index 0000000..c0928a4 --- /dev/null +++ b/composables/useSupabaseAuth.ts @@ -0,0 +1,8 @@ +import type { SupabaseClient } from '@supabase/supabase-js' + +// The one place that reaches Supabase Auth. The client comes from plugins/auth.client.ts, +// so it exists only in the browser and only when the app is configured. +export function useSupabaseAuth(): SupabaseClient['auth'] | undefined { + const supabase = useNuxtApp().$supabase as SupabaseClient | undefined + return supabase?.auth +} diff --git a/stores/session.ts b/stores/session.ts new file mode 100644 index 0000000..3801204 --- /dev/null +++ b/stores/session.ts @@ -0,0 +1,180 @@ +import { isAuthRetryableFetchError, type Session } from '@supabase/supabase-js' + +export type SessionStatus = 'unknown' | 'signedIn' | 'signedOut' + +// A failed sign-in step. Pages translate the code; text from the server is never shown. +export class AuthFailure extends Error { + constructor(readonly code: string) { + super(code) + this.name = 'AuthFailure' + } +} + +function toFailure(error: Error & { code?: string }) { + // Supabase uses this error type when the server cannot be reached. + if (isAuthRetryableFetchError(error)) { + return new AuthFailure('network') + } + return new AuthFailure(error.code ?? 'unknown') +} + +// Where Google and confirmation emails send people back to. One address for all languages, +// because Supabase only accepts return addresses that are on its allow list. +function callbackUrl() { + return new URL('/auth/callback', window.location.origin).href +} + +export const useSessionStore = defineStore('session', () => { + const auth = useSupabaseAuth() + + const status = ref('unknown') + const user = ref<{ id: string, email: string | undefined } | null>(null) + // True after somebody pressed "sign out", false when a session ended by itself. + const signedOutByUser = ref(false) + const isSignedIn = computed(() => status.value === 'signedIn') + + let loading: Promise | undefined + let refreshing: Promise | undefined + let stopListening: (() => void) | undefined + + onScopeDispose(() => stopListening?.()) + + function apply(session: Session | null) { + user.value = session ? { id: session.user.id, email: session.user.email } : null + status.value = session ? 'signedIn' : 'signedOut' + if (session) { + signedOutByUser.value = false + } + } + + function requireAuth() { + if (!auth) { + throw new AuthFailure('unavailable') + } + return auth + } + + async function load() { + if (!auth) { + apply(null) + return + } + if (!stopListening) { + // Keeps the store current, for example after a sign-out in another tab. + const { data } = auth.onAuthStateChange((_event, session) => apply(session)) + stopListening = () => data.subscription.unsubscribe() + } + const { data, error } = await auth.getSession() + apply(data.session) + if (error) { + // Forget this attempt, so that the next call asks again. + loading = undefined + } + } + + // Reads the stored session once. Safe to call from many places. + function init() { + loading ??= load() + return loading + } + + // The token for API calls. Supabase renews an expired token before returning it. + async function accessToken() { + if (!auth) { + return null + } + const { data, error } = await auth.getSession() + if (error && isAuthRetryableFetchError(error)) { + throw new AuthFailure('network') + } + return data.session?.access_token ?? null + } + + async function requestNewToken() { + const { data, error } = await requireAuth().refreshSession() + if (error && isAuthRetryableFetchError(error)) { + throw new AuthFailure('network') + } + if (error || !data.session) { + return null + } + apply(data.session) + return data.session.access_token + } + + // Calls that arrive while a refresh is running wait for that same refresh. + function refresh() { + refreshing ??= requestNewToken().finally(() => { + refreshing = undefined + }) + return refreshing + } + + async function signIn(email: string, password: string) { + const { data, error } = await requireAuth().signInWithPassword({ email, password }) + if (error) { + throw toFailure(error) + } + apply(data.session) + } + + async function register(email: string, password: string) { + const { data, error } = await requireAuth().signUp({ + email, + password, + options: { emailRedirectTo: callbackUrl() }, + }) + if (error) { + throw toFailure(error) + } + // Without a session, Supabase waits until the email address is confirmed. + if (!data.session) { + return 'confirmationRequired' as const + } + apply(data.session) + return 'signedIn' as const + } + + async function signInWithGoogle() { + const { error } = await requireAuth().signInWithOAuth({ + provider: 'google', + options: { redirectTo: callbackUrl() }, + }) + if (error) { + throw toFailure(error) + } + } + + // Signs out this device only; the same account stays signed in elsewhere. + // Supabase removes the local session even if the server cannot be reached. + async function endSession() { + await auth?.signOut({ scope: 'local' }) + apply(null) + } + + async function signOut() { + signedOutByUser.value = true + await endSession() + } + + // For a session that the backend rejects. + async function expire() { + signedOutByUser.value = false + await endSession() + } + + return { + status, + user, + isSignedIn, + signedOutByUser, + init, + accessToken, + refresh, + signIn, + register, + signInWithGoogle, + signOut, + expire, + } +}) From 7f108e3aaba28e525874c6235b513a9d3ec527a9 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:21:31 +0100 Subject: [PATCH 07/26] Add tests for route protection and client-only app pages - Signed-out visitors are sent to the login page of their language, with a safe return path. Signed-in visitors skip the sign-in pages. - A page is left when its session ends. - Only the landing page is rendered on the server. The persistence tests move their language and title checks there. - The language switcher and navigation tests now run signed in, because they visit protected pages. Co-Authored-By: Claude Sonnet 5.5 --- components/__tests__/AppNav.nuxt.spec.ts | 12 ++- .../__tests__/LanguageSwitcher.nuxt.spec.ts | 10 ++- composables/__tests__/safeRedirect.spec.ts | 45 ++++++++++ .../useLeaveWhenSignedOut.nuxt.spec.ts | 67 +++++++++++++++ i18n/__tests__/persistence.spec.ts | 46 ++++++---- middleware/__tests__/auth.nuxt.spec.ts | 85 +++++++++++++++++++ 6 files changed, 247 insertions(+), 18 deletions(-) create mode 100644 composables/__tests__/safeRedirect.spec.ts create mode 100644 composables/__tests__/useLeaveWhenSignedOut.nuxt.spec.ts create mode 100644 middleware/__tests__/auth.nuxt.spec.ts diff --git a/components/__tests__/AppNav.nuxt.spec.ts b/components/__tests__/AppNav.nuxt.spec.ts index 9f1a718..05cba94 100644 --- a/components/__tests__/AppNav.nuxt.spec.ts +++ b/components/__tests__/AppNav.nuxt.spec.ts @@ -1,10 +1,18 @@ -import { mountSuspended } from '@nuxt/test-utils/runtime' +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' import { flushPromises } from '@vue/test-utils' -import { beforeEach, describe, expect, test } from 'vitest' +import { beforeEach, describe, expect, test, vi } from 'vitest' import { RouterLink } from 'vue-router' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { resetSession } from '../../composables/__tests__/reset-session' import AppNav from '../AppNav.vue' +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +// Somebody is signed in, because some tests visit protected pages. beforeEach(async () => { + supabase.auth = createFakeAuth({ signedInAs: 'ann@example.org' }).auth + resetSession() await useNuxtApp().$i18n.setLocale('de') await useRouter().push('/') }) diff --git a/components/__tests__/LanguageSwitcher.nuxt.spec.ts b/components/__tests__/LanguageSwitcher.nuxt.spec.ts index bb58f8d..31f0740 100644 --- a/components/__tests__/LanguageSwitcher.nuxt.spec.ts +++ b/components/__tests__/LanguageSwitcher.nuxt.spec.ts @@ -1,14 +1,22 @@ -import { mountSuspended } from '@nuxt/test-utils/runtime' +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' import { beforeEach, describe, expect, test, vi } from 'vitest' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { resetSession } from '../../composables/__tests__/reset-session' import LanguageSwitcher from '../LanguageSwitcher.vue' +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + // Reads the saved language from the cookie that the server will see on the next visit. function savedLanguage() { return document.cookie.match(/(?:^|; )ons_locale=([^;]*)/)?.[1] } // Every test starts on the German home page. +// Somebody is signed in, because some tests visit protected pages. beforeEach(async () => { + supabase.auth = createFakeAuth({ signedInAs: 'ann@example.org' }).auth + resetSession() await useNuxtApp().$i18n.setLocale('de') await useRouter().push('/') }) diff --git a/composables/__tests__/safeRedirect.spec.ts b/composables/__tests__/safeRedirect.spec.ts new file mode 100644 index 0000000..5087982 --- /dev/null +++ b/composables/__tests__/safeRedirect.spec.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from 'vitest' +import { safeRedirect } from '../safeRedirect' + +// The "redirect" query parameter can be written by anybody who sends a link. +// It must never lead away from this app. +describe('safeRedirect', () => { + test.each([ + '/dashboard', + '/en/map', + '/dates?status=done#top', + ])('keeps the path %s', (path) => { + expect(safeRedirect(path, '/fallback')).toBe(path) + }) + + test.each([ + undefined, + null, + '', + ['/dates', '/map'], + 'dashboard', + 'https://evil.example', + 'javascript:alert(1)', + '//evil.example', + '/\\evil.example', + '\\/evil.example', + // Browsers drop tabs and line breaks inside addresses. + '/\t/evil.example', + '/\n/evil.example', + // Normalises to a path that starts with two slashes. + '/.//evil.example', + ])('rejects %j', (value) => { + expect(safeRedirect(value, '/fallback')).toBe('/fallback') + }) + + test.each([ + '/login', + '/en/login?redirect=/map', + '/register', + '/nl/register', + '/auth/callback?code=abc', + '/dashboard/../login', + ])('never leads back to a sign-in page: %s', (path) => { + expect(safeRedirect(path, '/fallback')).toBe('/fallback') + }) +}) diff --git a/composables/__tests__/useLeaveWhenSignedOut.nuxt.spec.ts b/composables/__tests__/useLeaveWhenSignedOut.nuxt.spec.ts new file mode 100644 index 0000000..4ce1e9a --- /dev/null +++ b/composables/__tests__/useLeaveWhenSignedOut.nuxt.spec.ts @@ -0,0 +1,67 @@ +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import { enableAutoUnmount, flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { useSessionStore } from '../../stores/session' +import { useLeaveWhenSignedOut } from '../useLeaveWhenSignedOut' +import { createFakeAuth } from './fake-auth' +import { resetSession } from './reset-session' + +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +// Stops the watchers of one test before the next one starts. +enableAutoUnmount(afterEach) + +let fake: ReturnType + +beforeEach(async () => { + fake = createFakeAuth({ signedInAs: 'ann@example.org' }) + supabase.auth = fake.auth + resetSession() + await useNuxtApp().$i18n.setLocale('de') + await useRouter().push('/') +}) + +// Any component that uses the composable; the app calls it once in app.vue. +const Host = defineComponent({ + setup() { + useLeaveWhenSignedOut() + return () => null + }, +}) + +async function openPage(path: string) { + await mountSuspended(Host, { route: path }) + await useSessionStore().init() +} + +const currentRoute = () => useRouter().currentRoute.value + +describe('useLeaveWhenSignedOut', () => { + test('leaves a protected page when the session ends elsewhere, and remembers the page', async () => { + await openPage('/map') + + fake.endSession() + + await vi.waitFor(() => expect(currentRoute().path).toBe('/login')) + expect(currentRoute().query.redirect).toBe('/map') + }) + + test('goes to a plain login page after pressing sign out', async () => { + await openPage('/en/map') + + await useSessionStore().signOut() + + await vi.waitFor(() => expect(currentRoute().path).toBe('/en/login')) + expect(currentRoute().query.redirect).toBeUndefined() + }) + + test('stays on a public page', async () => { + await openPage('/') + + fake.endSession() + await flushPromises() + + expect(currentRoute().path).toBe('/') + }) +}) diff --git a/i18n/__tests__/persistence.spec.ts b/i18n/__tests__/persistence.spec.ts index c1decd8..6614836 100644 --- a/i18n/__tests__/persistence.spec.ts +++ b/i18n/__tests__/persistence.spec.ts @@ -61,25 +61,29 @@ describe('returning visit', () => { }) test('a saved German choice stays German in a foreign-language browser', async () => { - const response = await visit('/dates', { saved: 'de', browser: 'en-GB' }) - expect(response.status).toBe(200) - expect(response.body).toContain('lang="de-DE"') + const landing = await visit('/', { saved: 'de', browser: 'en-GB' }) + expect(landing.status).toBe(200) + expect(landing.body).toContain('lang="de-DE"') + + const appPage = await visit('/dates', { saved: 'de', browser: 'en-GB' }) + expect(appPage.status).toBe(200) + expect(appPage.location).toBeNull() }) test('a language prefix in the URL wins and becomes the saved language', async () => { - const response = await visit('/en/dates', { saved: 'nl' }) + const response = await visit('/en', { saved: 'nl' }) expect(response.status).toBe(200) expect(response.body).toContain('lang="en-GB"') expect(response.cookie).toContain('ons_locale=en') }) }) -describe('server-rendered pages', () => { +describe('the landing page', () => { test.each([ - ['/map', 'de-DE', 'Karte'], - ['/en/map', 'en-GB', 'Map'], - ['/nl/map', 'nl-NL', 'Kaart'], - ])('%s is rendered in %s', async (path, language, heading) => { + ['/', 'de-DE', 'Start'], + ['/en', 'en-GB', 'Home'], + ['/nl', 'nl-NL', 'Home'], + ])('%s is rendered on the server in %s', async (path, language, heading) => { const response = await visit(path, { saved: language.slice(0, 2) }) expect(response.status).toBe(200) expect(response.body).toContain(`lang="${language}"`) @@ -87,17 +91,29 @@ describe('server-rendered pages', () => { expect(response.body).toContain(`${heading} · Ons`) }) - test.each(['/', '/dates', '/map', '/photos'])('%s exists', async (path) => { - const response = await visit(path, { saved: 'de' }) - expect(response.status).toBe(200) - }) - - test('contain no SEO link tags yet, because those need a fixed base URL (F10)', async () => { + test('contains no SEO link tags yet, because those need a fixed base URL (F10)', async () => { const response = await visit('/', { saved: 'de' }) expect(response.body).not.toMatch(/]+rel="(alternate|canonical)"/) }) }) +describe('app and sign-in pages', () => { + // Only the browser knows the session, so the server sends an empty page shell. + test.each([ + '/dashboard', + '/dates', + '/map', + '/photos', + '/en/dates', + '/login', + '/register', + ])('%s is rendered in the browser only', async (path) => { + const response = await visit(path, { saved: path.startsWith('/en/') ? 'en' : 'de' }) + expect(response.status).toBe(200) + expect(response.body).not.toContain(' { test('are never redirected to a language prefix', async () => { const response = await visit('/api/health', { saved: 'nl', browser: 'nl-NL' }) diff --git a/middleware/__tests__/auth.nuxt.spec.ts b/middleware/__tests__/auth.nuxt.spec.ts new file mode 100644 index 0000000..89cd22c --- /dev/null +++ b/middleware/__tests__/auth.nuxt.spec.ts @@ -0,0 +1,85 @@ +import { mockNuxtImport } from '@nuxt/test-utils/runtime' +import { beforeEach, describe, expect, test, vi } from 'vitest' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { resetSession } from '../../composables/__tests__/reset-session' + +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +const someone = 'ann@example.org' + +function signInAs(email: string | undefined) { + supabase.auth = createFakeAuth({ signedInAs: email }).auth + resetSession() +} + +// Navigates like a link click and returns where the app ended up. +async function visit(path: string) { + await useRouter().push(path) + return useRouter().currentRoute.value +} + +// Every test starts signed out on the German landing page. +beforeEach(async () => { + signInAs(undefined) + await useNuxtApp().$i18n.setLocale('de') + await useRouter().push('/') +}) + +describe('signed out', () => { + test.each(['/dashboard', '/dates', '/map', '/photos'])('%s leads to the login page and remembers the target', async (path) => { + const route = await visit(path) + expect(route.path).toBe('/login') + expect(route.query.redirect).toBe(path) + }) + + test.each([ + ['/en/dates', '/en/login'], + ['/nl/map', '/nl/login'], + ])('%s keeps its language: %s', async (path, login) => { + const route = await visit(path) + expect(route.path).toBe(login) + expect(route.query.redirect).toBe(path) + }) + + test('remembers the query of the target', async () => { + const route = await visit('/dates?status=done') + expect(route.query.redirect).toBe('/dates?status=done') + }) + + test.each(['/', '/en', '/login', '/en/register'])('%s is open', async (path) => { + expect((await visit(path)).path).toBe(path) + }) + + test('protects pages when Supabase is not configured', async () => { + supabase.auth = undefined + resetSession() + expect((await visit('/dashboard')).path).toBe('/login') + }) +}) + +describe('signed in', () => { + beforeEach(() => { + signInAs(someone) + }) + + test.each(['/dashboard', '/dates', '/en/map', '/nl/photos', '/'])('%s is open', async (path) => { + expect((await visit(path)).path).toBe(path) + }) + + test.each([ + ['/login', '/dashboard'], + ['/register', '/dashboard'], + ['/en/login', '/en/dashboard'], + ])('%s leads on to %s', async (path, target) => { + expect((await visit(path)).path).toBe(target) + }) + + test('the login page leads on to the remembered target', async () => { + expect((await visit('/login?redirect=/map')).path).toBe('/map') + }) + + test('the login page ignores a target outside the app', async () => { + expect((await visit('/login?redirect=https://evil.example')).path).toBe('/dashboard') + }) +}) From 8dcf6bac8a9149aaff5379bc2ccce78b96a0ab28 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:22:08 +0100 Subject: [PATCH 08/26] Protect pages and render the app in the browser (F2) - A global middleware protects every page that does not declare "public" or "guest" access, and keeps the language when it redirects. - The "redirect" query parameter only accepts paths inside the app. - Leaving a protected page happens in one place when the session ends. - routeRules render only the landing page on the server, because the session is stored in the browser. - Placeholder pages for dashboard, login and register. Co-Authored-By: Claude Sonnet 5.5 --- app.vue | 3 +++ composables/safeRedirect.ts | 20 ++++++++++++++ composables/useLeaveWhenSignedOut.ts | 17 ++++++++++++ composables/useLoginRedirect.ts | 13 +++++++++ i18n/locales/de.json | 9 +++++++ i18n/locales/en.json | 9 +++++++ i18n/locales/nl.json | 9 +++++++ middleware/auth.global.ts | 40 ++++++++++++++++++++++++++++ nuxt.config.ts | 8 ++++++ pages/dashboard.vue | 13 +++++++++ pages/index.vue | 1 + pages/login.vue | 12 +++++++++ pages/register.vue | 12 +++++++++ 13 files changed, 166 insertions(+) create mode 100644 composables/safeRedirect.ts create mode 100644 composables/useLeaveWhenSignedOut.ts create mode 100644 composables/useLoginRedirect.ts create mode 100644 middleware/auth.global.ts create mode 100644 pages/dashboard.vue create mode 100644 pages/login.vue create mode 100644 pages/register.vue diff --git a/app.vue b/app.vue index d14f9c4..6dbfd32 100644 --- a/app.vue +++ b/app.vue @@ -1,6 +1,9 @@ + + diff --git a/pages/index.vue b/pages/index.vue index fded05b..201fa80 100644 --- a/pages/index.vue +++ b/pages/index.vue @@ -1,6 +1,7 @@ diff --git a/pages/login.vue b/pages/login.vue new file mode 100644 index 0000000..3cefa7e --- /dev/null +++ b/pages/login.vue @@ -0,0 +1,12 @@ + + + diff --git a/pages/register.vue b/pages/register.vue new file mode 100644 index 0000000..86b791d --- /dev/null +++ b/pages/register.vue @@ -0,0 +1,12 @@ + + + From 16751dacd534154aa952f49170a4805dd1a9237f Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:23:40 +0100 Subject: [PATCH 09/26] Add tests for the API client and error messages Covers the bearer token, the single 401 handler (renew once, then send to the login page), concurrent requests, and the mapping from backend and Supabase codes to message keys. Fails until useApi and errorKeys exist. Co-Authored-By: Claude Sonnet 5.5 --- composables/__tests__/errorKeys.spec.ts | 60 ++++++ composables/__tests__/useApi.nuxt.spec.ts | 221 ++++++++++++++++++++++ 2 files changed, 281 insertions(+) create mode 100644 composables/__tests__/errorKeys.spec.ts create mode 100644 composables/__tests__/useApi.nuxt.spec.ts diff --git a/composables/__tests__/errorKeys.spec.ts b/composables/__tests__/errorKeys.spec.ts new file mode 100644 index 0000000..0dfa0b8 --- /dev/null +++ b/composables/__tests__/errorKeys.spec.ts @@ -0,0 +1,60 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, test } from 'vitest' +import { apiErrorCodeSchema } from '../../shared/api-errors' +import { apiErrorKey, authErrorKey } from '../errorKeys' + +const german = JSON.parse(readFileSync(new URL('../../i18n/locales/de.json', import.meta.url), 'utf8')) + +// Finds the text of a key such as "errors.api.no_space". messages.spec.ts covers en and nl. +function textFor(key: string): unknown { + return key.split('.').reduce((node, part) => node?.[part], german) +} + +// Codes from Supabase Auth, plus "network" and "unavailable" from the session store. +const authCodes = [ + 'invalid_credentials', + 'email_not_confirmed', + 'user_already_exists', + 'email_exists', + 'email_address_invalid', + 'weak_password', + 'signup_disabled', + 'email_provider_disabled', + 'provider_disabled', + 'oauth_provider_not_supported', + 'validation_failed', + 'over_request_rate_limit', + 'over_email_send_rate_limit', + 'network', + 'unavailable', +] + +describe('apiErrorKey', () => { + // The list comes from the backend contract, so a new code makes this test fail. + test.each(apiErrorCodeSchema.options)('the backend code %s has its own message', (code) => { + const key = apiErrorKey(code) + expect(key).not.toBe('errors.unexpected') + expect(textFor(key)).toBeTypeOf('string') + }) + + test.each([undefined, 'something_new', 'toString'])('%s gets the general message', (code) => { + expect(apiErrorKey(code)).toBe('errors.unexpected') + expect(textFor('errors.unexpected')).toBeTypeOf('string') + }) + + test('network problems have a message', () => { + expect(textFor('errors.network')).toBeTypeOf('string') + }) +}) + +describe('authErrorKey', () => { + test.each(authCodes)('%s has a message', (code) => { + const key = authErrorKey(code) + expect(key).not.toBe('errors.unexpected') + expect(textFor(key)).toBeTypeOf('string') + }) + + test.each([undefined, 'unknown', 'constructor'])('%s gets the general message', (code) => { + expect(authErrorKey(code)).toBe('errors.unexpected') + }) +}) diff --git a/composables/__tests__/useApi.nuxt.spec.ts b/composables/__tests__/useApi.nuxt.spec.ts new file mode 100644 index 0000000..da9558e --- /dev/null +++ b/composables/__tests__/useApi.nuxt.spec.ts @@ -0,0 +1,221 @@ +import { mockNuxtImport, registerEndpoint } from '@nuxt/test-utils/runtime' +import { AuthApiError, AuthRetryableFetchError } from '@supabase/supabase-js' +import { createError, getHeader, getQuery, readBody, setResponseStatus, type H3Event } from 'h3' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { useSessionStore } from '../../stores/session' +import { apiErrorKey } from '../errorKeys' +import { useApi } from '../useApi' +import { createFakeAuth } from './fake-auth' +import { resetSession } from './reset-session' + +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +let fake: ReturnType +// Removes the mocked endpoints of a test. +let removals: (() => void)[] = [] + +function mockEndpoint(path: string, handler: (event: H3Event) => unknown) { + const spy = vi.fn(handler) + removals.push(registerEndpoint(path, spy)) + return spy +} + +// An error response in the shape the backend sends: { data: { code } }. +function apiFailure(statusCode: number, code: string) { + return createError({ statusCode, data: { code } }) +} + +// Accepts only the given token, like a backend after the old token has expired. +function acceptOnly(token: string) { + return (event: H3Event) => { + if (getHeader(event, 'authorization') !== `Bearer ${token}`) { + throw apiFailure(401, 'unauthorized') + } + return { ok: true } + } +} + +const currentRoute = () => useRouter().currentRoute.value + +async function signedInOnMapPage() { + fake = createFakeAuth({ signedInAs: 'ann@example.org' }) + supabase.auth = fake.auth + resetSession() + await useRouter().push('/map') +} + +beforeEach(async () => { + await useNuxtApp().$i18n.setLocale('de') + await signedInOnMapPage() +}) + +afterEach(() => { + removals.forEach(remove => remove()) + removals = [] + vi.unstubAllGlobals() +}) + +describe('requests', () => { + test('send the access token and ask for JSON', async () => { + const endpoint = mockEndpoint('/api/space', event => ({ + authorization: getHeader(event, 'authorization'), + accept: getHeader(event, 'accept'), + })) + + await expect(useApi()('/api/space')).resolves.toEqual({ + authorization: 'Bearer token-1', + accept: 'application/json', + }) + expect(endpoint).toHaveBeenCalledTimes(1) + }) + + test('pass on method, body and query', async () => { + mockEndpoint('/api/dates', async event => ({ + method: event.method, + query: getQuery(event), + body: await readBody(event), + })) + + await expect(useApi()('/api/dates', { method: 'POST', query: { status: 'done' }, body: { title: 'Picnic' } })) + .resolves.toEqual({ method: 'POST', query: { status: 'done' }, body: { title: 'Picnic' } }) + }) + + test('work with an empty response', async () => { + mockEndpoint('/api/dates/1', (event) => { + setResponseStatus(event, 204) + return null + }) + + await expect(useApi()('/api/dates/1', { method: 'DELETE' })).resolves.toBeFalsy() + }) +}) + +describe('an expired token (401)', () => { + test('is renewed once, and the request is repeated', async () => { + const endpoint = mockEndpoint('/api/space', acceptOnly('token-2')) + + await expect(useApi()('/api/space')).resolves.toEqual({ ok: true }) + + expect(fake.auth.refreshSession).toHaveBeenCalledTimes(1) + expect(endpoint).toHaveBeenCalledTimes(2) + expect(useSessionStore().isSignedIn).toBe(true) + }) + + test('is renewed only once for requests that run at the same time', async () => { + mockEndpoint('/api/space', acceptOnly('token-2')) + const api = useApi() + + await Promise.all([api('/api/space'), api('/api/space'), api('/api/space')]) + + expect(fake.auth.refreshSession).toHaveBeenCalledTimes(1) + }) + + test('ends the session when the new token is rejected too', async () => { + const endpoint = mockEndpoint('/api/space', () => { + throw apiFailure(401, 'unauthorized') + }) + + await expect(useApi()('/api/space')).rejects.toMatchObject({ code: 'unauthorized', status: 401 }) + + expect(endpoint).toHaveBeenCalledTimes(2) + expect(useSessionStore().isSignedIn).toBe(false) + expect(currentRoute().path).toBe('/login') + expect(currentRoute().query.redirect).toBe('/map') + }) + + test('keeps the return page when several requests fail at the same time', async () => { + mockEndpoint('/api/space', () => { + throw apiFailure(401, 'unauthorized') + }) + const api = useApi() + + await Promise.allSettled([api('/api/space'), api('/api/space'), api('/api/space')]) + + expect(currentRoute().path).toBe('/login') + expect(currentRoute().query.redirect).toBe('/map') + }) + + test('ends the session when the token cannot be renewed', async () => { + const endpoint = mockEndpoint('/api/space', acceptOnly('token-2')) + fake.auth.refreshSession.mockResolvedValueOnce({ + data: { session: null }, + error: new AuthApiError('Invalid refresh token', 400, 'refresh_token_not_found'), + }) + + await expect(useApi()('/api/space')).rejects.toMatchObject({ code: 'unauthorized' }) + + expect(endpoint).toHaveBeenCalledTimes(1) + expect(useSessionStore().isSignedIn).toBe(false) + expect(currentRoute().path).toBe('/login') + }) + + test('keeps the session when renewing fails because the server is unreachable', async () => { + mockEndpoint('/api/space', acceptOnly('token-2')) + fake.auth.refreshSession.mockResolvedValueOnce({ + data: { session: null }, + error: new AuthRetryableFetchError('offline', 0), + }) + + await expect(useApi()('/api/space')).rejects.toMatchObject({ messageKey: 'errors.network' }) + + expect(useSessionStore().isSignedIn).toBe(true) + expect(currentRoute().path).toBe('/map') + }) +}) + +describe('without a session', () => { + test('goes to the login page without calling the API', async () => { + const endpoint = mockEndpoint('/api/space', () => ({ ok: true })) + const api = useApi() + fake.endSession() + fake.auth.getSession.mockResolvedValue({ data: { session: null }, error: null }) + + await expect(api('/api/space')).rejects.toMatchObject({ code: 'unauthorized' }) + + expect(endpoint).not.toHaveBeenCalled() + expect(currentRoute().path).toBe('/login') + }) +}) + +describe('errors', () => { + test.each([ + [400, 'invite_invalid'], + [409, 'already_paired'], + [403, 'no_space'], + [404, 'not_found'], + [400, 'validation_failed'], + [500, 'internal'], + ])('%i %s is translated through its code', async (status, code) => { + mockEndpoint('/api/space', () => { + throw apiFailure(status, code) + }) + + await expect(useApi()('/api/space')).rejects.toMatchObject({ + name: 'ApiError', + code, + status, + messageKey: apiErrorKey(code), + }) + expect(currentRoute().path).toBe('/map') + }) + + test('without a code from the backend get the general message', async () => { + // Hosting limits, for example, answer without the error envelope. + mockEndpoint('/api/photos', () => { + throw createError({ statusCode: 413 }) + }) + + await expect(useApi()('/api/photos')).rejects.toMatchObject({ + code: undefined, + status: 413, + messageKey: 'errors.unexpected', + }) + }) + + test('from an unreachable API are reported as a network problem', async () => { + vi.stubGlobal('$fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))) + + await expect(useApi()('/api/space')).rejects.toMatchObject({ messageKey: 'errors.network' }) + }) +}) From d9e8d25f406f883c3e2fec9b7a1658de3a094788 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:24:10 +0100 Subject: [PATCH 10/26] Add the API client and translated error messages (F2) useApi sends the access token to /api/*, renews it once after a 401 and otherwise ends the session and opens the login page. Backend codes and Supabase Auth codes map to messages in German, English and Dutch. Only types come from shared/, so zod stays out of the browser bundle. Co-Authored-By: Claude Sonnet 5.5 --- composables/errorKeys.ts | 48 ++++++++++++++++ composables/useApi.ts | 120 +++++++++++++++++++++++++++++++++++++++ i18n/locales/de.json | 25 ++++++++ i18n/locales/en.json | 25 ++++++++ i18n/locales/nl.json | 25 ++++++++ 5 files changed, 243 insertions(+) create mode 100644 composables/errorKeys.ts create mode 100644 composables/useApi.ts diff --git a/composables/errorKeys.ts b/composables/errorKeys.ts new file mode 100644 index 0000000..73108fe --- /dev/null +++ b/composables/errorKeys.ts @@ -0,0 +1,48 @@ +import type { ApiErrorCode } from '../shared/api-errors' + +// Maps error codes to message keys. Text sent by a server is never shown. +const unexpected = 'errors.unexpected' + +// Codes of our backend (shared/api-errors.ts). Only the type is imported, +// so the validation library behind it stays out of the browser bundle. +const apiMessages: Record = { + invite_invalid: 'errors.api.inviteInvalid', + already_paired: 'errors.api.alreadyPaired', + no_space: 'errors.api.noSpace', + not_found: 'errors.api.notFound', + validation_failed: 'errors.api.validationFailed', + unauthorized: 'errors.api.unauthorized', + internal: 'errors.api.internal', +} + +// Codes of Supabase Auth, plus "network" and "unavailable" from the session store. +const authMessages: Record = { + invalid_credentials: 'errors.auth.invalidCredentials', + email_not_confirmed: 'errors.auth.emailNotConfirmed', + user_already_exists: 'errors.auth.userExists', + email_exists: 'errors.auth.userExists', + email_address_invalid: 'errors.auth.emailInvalid', + weak_password: 'errors.auth.weakPassword', + signup_disabled: 'errors.auth.signupDisabled', + email_provider_disabled: 'errors.auth.methodDisabled', + provider_disabled: 'errors.auth.methodDisabled', + oauth_provider_not_supported: 'errors.auth.methodDisabled', + validation_failed: 'errors.auth.rejected', + over_request_rate_limit: 'errors.auth.tooManyAttempts', + over_email_send_rate_limit: 'errors.auth.tooManyAttempts', + network: 'errors.network', + unavailable: 'errors.auth.unavailable', +} + +function lookUp(messages: Record, code: string | undefined) { + // hasOwn keeps names such as "toString" from matching. + return code && Object.hasOwn(messages, code) ? messages[code]! : unexpected +} + +export function apiErrorKey(code: string | undefined) { + return lookUp(apiMessages, code) +} + +export function authErrorKey(code: string | undefined) { + return lookUp(authMessages, code) +} diff --git a/composables/useApi.ts b/composables/useApi.ts new file mode 100644 index 0000000..195dec3 --- /dev/null +++ b/composables/useApi.ts @@ -0,0 +1,120 @@ +import type { ApiErrorCode } from '../shared/api-errors' + +// A failed API call. Show it with t(error.messageKey). +export class ApiError extends Error { + readonly messageKey: string + + constructor( + // The backend code, if the response carried one. + readonly code: ApiErrorCode | undefined, + // The HTTP status, or undefined if no response arrived. + readonly status: number | undefined, + messageKey?: string, + ) { + super(code ?? `request failed with status ${status ?? 'unknown'}`) + this.name = 'ApiError' + this.messageKey = messageKey ?? apiErrorKey(code) + } +} + +export interface ApiOptions { + method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' + query?: Record + body?: Record | Blob + headers?: Record +} + +// The shape of the errors that $fetch throws. +interface FetchFailure { + status?: number + data?: { data?: { code?: ApiErrorCode } } +} + +const unauthorized = () => new ApiError('unauthorized', 401) +const networkProblem = () => new ApiError(undefined, undefined, 'errors.network') + +function toApiError(error: unknown) { + const { status, data } = error as FetchFailure + // Without a status there was no response at all. + return status ? new ApiError(data?.data?.code, status) : networkProblem() +} + +// The only way the app calls /api/*: it adds the access token and handles 401 and errors. +// const api = useApi() +// const dates = await api('/api/dates', { query: { status: 'done' } }) +export function useApi() { + const session = useSessionStore() + const router = useRouter() + const goToLogin = useLoginRedirect() + + function send(path: `/api/${string}`, options: ApiOptions, token: string) { + return $fetch(path, { + ...options, + headers: { ...options.headers, Accept: 'application/json', Authorization: `Bearer ${token}` }, + }) as Promise + } + + // The session is over: forget it and ask to sign in again. + async function leave() { + const page = router.currentRoute.value + await session.expire() + // Another request may already have sent us to the login page. + // Going there again would lose the page to return to. + if (router.currentRoute.value.meta.access !== 'guest') { + await goToLogin(page.fullPath) + } + return unauthorized() + } + + // Returns a token that differs from the rejected one, or null if there is none. + async function newerToken(rejected: string) { + // Another request may have renewed the token in the meantime. + const current = await session.accessToken() + if (current && current !== rejected) { + return current + } + return session.refresh() + } + + // Turns problems while talking to Supabase into the same error type. + async function reachable(step: Promise) { + try { + return await step + } + catch { + throw networkProblem() + } + } + + return async function api(path: `/api/${string}`, options: ApiOptions = {}): Promise { + await session.init() + const token = await reachable(session.accessToken()) + if (!token) { + throw await leave() + } + + try { + return await send(path, options, token) + } + catch (error) { + if ((error as FetchFailure).status !== 401) { + throw toApiError(error) + } + } + + // One attempt with a renewed token. + const renewed = await reachable(newerToken(token)) + if (!renewed) { + throw await leave() + } + try { + return await send(path, options, renewed) + } + catch (error) { + if ((error as FetchFailure).status === 401) { + throw await leave() + } + throw toApiError(error) + } + } +} diff --git a/i18n/locales/de.json b/i18n/locales/de.json index 3e307f6..1c63d87 100644 --- a/i18n/locales/de.json +++ b/i18n/locales/de.json @@ -42,5 +42,30 @@ "register": { "title": "Registrieren" } + }, + "errors": { + "unexpected": "Etwas ist schiefgelaufen. Bitte versuche es erneut.", + "network": "Keine Verbindung zum Server. Prüfe deine Internetverbindung und versuche es erneut.", + "api": { + "inviteInvalid": "Diese Einladung ist ungültig oder wurde schon benutzt.", + "alreadyPaired": "Du gehörst bereits zu einem gemeinsamen Bereich.", + "noSpace": "Erstelle zuerst einen gemeinsamen Bereich oder tritt einem bei.", + "notFound": "Dieser Eintrag wurde nicht gefunden.", + "validationFailed": "Bitte prüfe deine Eingaben.", + "unauthorized": "Deine Anmeldung ist abgelaufen. Bitte melde dich erneut an.", + "internal": "Der Server hat gerade ein Problem. Bitte versuche es später erneut." + }, + "auth": { + "invalidCredentials": "E-Mail-Adresse oder Passwort ist falsch.", + "emailNotConfirmed": "Bitte bestätige zuerst deine E-Mail-Adresse über den Link in unserer E-Mail.", + "userExists": "Für diese E-Mail-Adresse gibt es schon ein Konto. Melde dich stattdessen an.", + "emailInvalid": "Diese E-Mail-Adresse wird nicht akzeptiert.", + "weakPassword": "Dieses Passwort ist zu schwach. Wähle ein längeres.", + "signupDisabled": "Neue Registrierungen sind derzeit nicht möglich.", + "methodDisabled": "Diese Anmeldeart ist derzeit nicht verfügbar.", + "rejected": "Die Anmeldung wurde abgelehnt. Bitte prüfe deine Eingaben.", + "tooManyAttempts": "Zu viele Versuche. Bitte warte kurz und versuche es erneut.", + "unavailable": "Die Anmeldung ist derzeit nicht verfügbar." + } } } diff --git a/i18n/locales/en.json b/i18n/locales/en.json index 878c28f..ba5fff8 100644 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -42,5 +42,30 @@ "register": { "title": "Create account" } + }, + "errors": { + "unexpected": "Something went wrong. Please try again.", + "network": "The server cannot be reached. Check your internet connection and try again.", + "api": { + "inviteInvalid": "This invitation is invalid or has already been used.", + "alreadyPaired": "You already belong to a shared space.", + "noSpace": "Create or join a shared space first.", + "notFound": "This entry was not found.", + "validationFailed": "Please check what you entered.", + "unauthorized": "Your session has ended. Please sign in again.", + "internal": "The server has a problem right now. Please try again later." + }, + "auth": { + "invalidCredentials": "The email address or password is wrong.", + "emailNotConfirmed": "Please confirm your email address first, using the link we sent you.", + "userExists": "There is already an account for this email address. Sign in instead.", + "emailInvalid": "This email address is not accepted.", + "weakPassword": "This password is too weak. Choose a longer one.", + "signupDisabled": "New registrations are not possible at the moment.", + "methodDisabled": "This way of signing in is not available at the moment.", + "rejected": "Sign-in was rejected. Please check what you entered.", + "tooManyAttempts": "Too many attempts. Please wait a moment and try again.", + "unavailable": "Sign-in is not available at the moment." + } } } diff --git a/i18n/locales/nl.json b/i18n/locales/nl.json index 6cc9095..5cf137b 100644 --- a/i18n/locales/nl.json +++ b/i18n/locales/nl.json @@ -42,5 +42,30 @@ "register": { "title": "Account aanmaken" } + }, + "errors": { + "unexpected": "Er is iets misgegaan. Probeer het opnieuw.", + "network": "De server is niet bereikbaar. Controleer je internetverbinding en probeer het opnieuw.", + "api": { + "inviteInvalid": "Deze uitnodiging is ongeldig of al gebruikt.", + "alreadyPaired": "Je hoort al bij een gedeelde ruimte.", + "noSpace": "Maak eerst een gedeelde ruimte aan of sluit je bij een aan.", + "notFound": "Dit item is niet gevonden.", + "validationFailed": "Controleer je invoer.", + "unauthorized": "Je sessie is verlopen. Log opnieuw in.", + "internal": "De server heeft nu een probleem. Probeer het later opnieuw." + }, + "auth": { + "invalidCredentials": "Het e-mailadres of wachtwoord klopt niet.", + "emailNotConfirmed": "Bevestig eerst je e-mailadres via de link die we je hebben gestuurd.", + "userExists": "Er bestaat al een account voor dit e-mailadres. Log in plaats daarvan in.", + "emailInvalid": "Dit e-mailadres wordt niet geaccepteerd.", + "weakPassword": "Dit wachtwoord is te zwak. Kies een langer wachtwoord.", + "signupDisabled": "Nieuwe registraties zijn op dit moment niet mogelijk.", + "methodDisabled": "Deze manier van inloggen is nu niet beschikbaar.", + "rejected": "Het inloggen is geweigerd. Controleer je invoer.", + "tooManyAttempts": "Te veel pogingen. Wacht even en probeer het opnieuw.", + "unavailable": "Inloggen is op dit moment niet beschikbaar." + } } } From 1a146a516fb94c24b0bfeda2109b8dd998e2a337 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:24:25 +0100 Subject: [PATCH 11/26] Add contrast checks for error text and form field borders Fails until the danger and field colour roles exist. Co-Authored-By: Claude Sonnet 5.5 --- assets/__tests__/contrast.spec.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/assets/__tests__/contrast.spec.ts b/assets/__tests__/contrast.spec.ts index 4cc1fa5..50a9c2c 100644 --- a/assets/__tests__/contrast.spec.ts +++ b/assets/__tests__/contrast.spec.ts @@ -51,9 +51,14 @@ const pairs: [string, string, number][] = [ ['accent', 'canvas', 4.5], ['accent', 'surface', 4.5], ['on-accent', 'accent', 4.5], - // Focus rings are not text, so 3:1 is enough. + // Error messages are text. + ['danger', 'canvas', 4.5], + ['danger', 'surface', 4.5], + // Focus rings and the borders of form fields are not text, so 3:1 is enough. ['focus', 'canvas', 3], ['focus', 'surface', 3], + ['field', 'canvas', 3], + ['field', 'surface', 3], ] describe('design tokens', () => { From cdbe7b276eb0b4064fbef2e33a244e8dbb138951 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:25:40 +0100 Subject: [PATCH 12/26] Add danger and field colour tokens Co-Authored-By: Claude Sonnet 5.5 --- assets/css/main.css | 2 ++ assets/css/tokens.css | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/assets/css/main.css b/assets/css/main.css index da584a0..e8cfa6b 100644 --- a/assets/css/main.css +++ b/assets/css/main.css @@ -23,6 +23,8 @@ --color-muted: var(--ons-color-muted); --color-accent: var(--ons-color-accent); --color-on-accent: var(--ons-color-on-accent); + --color-danger: var(--ons-color-danger); + --color-field: var(--ons-color-field); --font-*: initial; --font-heading: var(--ons-font-heading); diff --git a/assets/css/tokens.css b/assets/css/tokens.css index 8b13e9b..52213c9 100644 --- a/assets/css/tokens.css +++ b/assets/css/tokens.css @@ -18,6 +18,8 @@ --palette-sand-50: #fbf7f2; --palette-sand-200: #e8ded2; --palette-sand-300: #cdbfb0; + --palette-sand-600: #8a7c6c; + --palette-ink-400: #8c8196; --palette-ink-500: #645a6b; --palette-ink-700: #4a3f55; --palette-ink-800: #2c2434; @@ -26,6 +28,8 @@ --palette-plum-700: #7a3468; --palette-blue-300: #8ec5ff; --palette-blue-700: #1c5fb8; + --palette-red-300: #ffb4ab; + --palette-red-700: #a3261d; /* 2. Colour roles: light-dark(light theme, dark theme). */ /* Page background */ @@ -44,6 +48,10 @@ --ons-color-on-accent: light-dark(var(--palette-white), var(--palette-ink-900)); /* Keyboard focus ring */ --ons-color-focus: light-dark(var(--palette-blue-700), var(--palette-blue-300)); + /* Error messages and the border of an invalid field */ + --ons-color-danger: light-dark(var(--palette-red-700), var(--palette-red-300)); + /* Border of form fields and outlined buttons */ + --ons-color-field: light-dark(var(--palette-sand-600), var(--palette-ink-400)); /* 3. Typography. System fonts until the brand typefaces are chosen. */ --ons-font-heading: ui-serif, Georgia, 'Times New Roman', serif; From cc086b56c11c887872b698480403bc1d95fae391 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:26:20 +0100 Subject: [PATCH 13/26] Add tests for the login and registration forms Covers field labels, inline errors and focus, redirect after sign-in, translated failures, the confirmation message, the Google button against a mocked client, and the password rules. The minimum password length is checked against supabase/config.toml. Co-Authored-By: Claude Sonnet 5.5 --- composables/__tests__/form-helpers.ts | 25 ++++ composables/__tests__/formRules.spec.ts | 42 ++++++ pages/__tests__/login.nuxt.spec.ts | 182 ++++++++++++++++++++++++ pages/__tests__/register.nuxt.spec.ts | 100 +++++++++++++ 4 files changed, 349 insertions(+) create mode 100644 composables/__tests__/form-helpers.ts create mode 100644 composables/__tests__/formRules.spec.ts create mode 100644 pages/__tests__/login.nuxt.spec.ts create mode 100644 pages/__tests__/register.nuxt.spec.ts diff --git a/composables/__tests__/form-helpers.ts b/composables/__tests__/form-helpers.ts new file mode 100644 index 0000000..1eba5c6 --- /dev/null +++ b/composables/__tests__/form-helpers.ts @@ -0,0 +1,25 @@ +import type { VueWrapper } from '@vue/test-utils' + +// Finds things the way a person does: by the visible label or button text. + +export function field(wrapper: VueWrapper, label: string) { + const found = wrapper.findAll('label').find(candidate => candidate.text() === label) + if (!found) { + throw new Error(`No field is labelled "${label}"`) + } + return wrapper.get(`[id="${found.attributes('for')}"]`) +} + +export function button(wrapper: VueWrapper, text: string) { + const found = wrapper.findAll('button').find(candidate => candidate.text() === text) + if (!found) { + throw new Error(`There is no button "${text}"`) + } + return found +} + +// The texts that screen readers announce for a field, taken from aria-describedby. +export function description(wrapper: VueWrapper, label: string) { + const ids = field(wrapper, label).attributes('aria-describedby')?.split(' ') ?? [] + return ids.map(id => wrapper.get(`[id="${id}"]`).text()).join(' ') +} diff --git a/composables/__tests__/formRules.spec.ts b/composables/__tests__/formRules.spec.ts new file mode 100644 index 0000000..0094d0c --- /dev/null +++ b/composables/__tests__/formRules.spec.ts @@ -0,0 +1,42 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, test } from 'vitest' +import { emailError, newPasswordError, PASSWORD_MIN_LENGTH, passwordError } from '../formRules' + +// What Supabase Auth uses when config.toml does not set minimum_password_length. +const authServerDefault = 6 + +describe('PASSWORD_MIN_LENGTH', () => { + test('matches minimum_password_length of the local Supabase configuration', () => { + const config = readFileSync(new URL('../../supabase/config.toml', import.meta.url), 'utf8') + const configured = config.match(/^\s*minimum_password_length\s*=\s*(\d+)/m)?.[1] + expect(PASSWORD_MIN_LENGTH).toBe(configured ? Number(configured) : authServerDefault) + }) +}) + +describe('emailError', () => { + test.each(['', ' '])('asks for an address when the field is %j', (value) => { + expect(emailError(value)).toBe('errors.form.emailRequired') + }) + + test.each(['ann', 'ann@', '@example.org', 'ann@example', 'ann smith@example.org'])('rejects %s', (value) => { + expect(emailError(value)).toBe('errors.form.emailInvalid') + }) + + test.each(['ann@example.org', ' ann+ons@mail.example.nl '])('accepts %j', (value) => { + expect(emailError(value)).toBeUndefined() + }) +}) + +describe('passwords', () => { + test('an existing password only has to be filled in', () => { + expect(passwordError('')).toBe('errors.form.passwordRequired') + // The server decides whether it is right, also for short old passwords. + expect(passwordError('a')).toBeUndefined() + }) + + test('a new password needs the minimum length', () => { + expect(newPasswordError('')).toBe('errors.form.passwordRequired') + expect(newPasswordError('a'.repeat(PASSWORD_MIN_LENGTH - 1))).toBe('errors.form.passwordTooShort') + expect(newPasswordError('a'.repeat(PASSWORD_MIN_LENGTH))).toBeUndefined() + }) +}) diff --git a/pages/__tests__/login.nuxt.spec.ts b/pages/__tests__/login.nuxt.spec.ts new file mode 100644 index 0000000..78d8a2d --- /dev/null +++ b/pages/__tests__/login.nuxt.spec.ts @@ -0,0 +1,182 @@ +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import { AuthApiError, AuthRetryableFetchError } from '@supabase/supabase-js' +import { enableAutoUnmount, flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { resetSession } from '../../composables/__tests__/reset-session' +import LoginPage from '../login.vue' +import { button, description, field } from '../../composables/__tests__/form-helpers' + +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +// The pages are attached to the document so that focus works. +enableAutoUnmount(afterEach) + +let fake: ReturnType + +beforeEach(async () => { + fake = createFakeAuth() + supabase.auth = fake.auth + resetSession() + await useNuxtApp().$i18n.setLocale('de') + await useRouter().push('/') +}) + +const open = (route = '/login') => mountSuspended(LoginPage, { route, attachTo: document.body }) +const currentPath = () => useRouter().currentRoute.value.path +const alertText = (wrapper: Awaited>) => wrapper.find('[role="alert"]').text() + +async function signIn(wrapper: Awaited>, email = 'ann@example.org', password = 'secret-1') { + await field(wrapper, 'E-Mail-Adresse').setValue(email) + await field(wrapper, 'Passwort').setValue(password) + await wrapper.get('form').trigger('submit') +} + +describe('login form', () => { + test('has labelled fields that password managers understand', async () => { + const wrapper = await open() + expect(field(wrapper, 'E-Mail-Adresse').attributes()).toMatchObject({ type: 'email', autocomplete: 'email' }) + expect(field(wrapper, 'Passwort').attributes()).toMatchObject({ type: 'password', autocomplete: 'current-password' }) + expect(button(wrapper, 'Anmelden').attributes('type')).toBe('submit') + }) + + test('shows errors at the empty fields and focuses the first one', async () => { + const wrapper = await open() + + await wrapper.get('form').trigger('submit') + await flushPromises() + + expect(description(wrapper, 'E-Mail-Adresse')).toBe('Bitte gib deine E-Mail-Adresse ein.') + expect(description(wrapper, 'Passwort')).toBe('Bitte gib dein Passwort ein.') + expect(field(wrapper, 'E-Mail-Adresse').attributes('aria-invalid')).toBe('true') + expect(document.activeElement).toBe(field(wrapper, 'E-Mail-Adresse').element) + expect(fake.auth.signInWithPassword).not.toHaveBeenCalled() + }) + + test('focuses the password when only that is missing', async () => { + const wrapper = await open() + await signIn(wrapper, 'ann@example.org', '') + await flushPromises() + expect(document.activeElement).toBe(field(wrapper, 'Passwort').element) + expect(field(wrapper, 'E-Mail-Adresse').attributes('aria-invalid')).toBeUndefined() + }) + + test('rejects something that is not an email address', async () => { + const wrapper = await open() + await signIn(wrapper, 'ann') + await flushPromises() + expect(description(wrapper, 'E-Mail-Adresse')).toBe('Das ist keine gültige E-Mail-Adresse.') + expect(fake.auth.signInWithPassword).not.toHaveBeenCalled() + }) + + test('signs in and opens the dashboard', async () => { + const wrapper = await open() + + await signIn(wrapper, ' ann@example.org ') + + await vi.waitFor(() => expect(currentPath()).toBe('/dashboard')) + expect(fake.auth.signInWithPassword).toHaveBeenCalledWith({ email: 'ann@example.org', password: 'secret-1' }) + }) + + test('returns to the page that asked for the sign-in', async () => { + const wrapper = await open('/login?redirect=/map') + await signIn(wrapper) + await vi.waitFor(() => expect(currentPath()).toBe('/map')) + }) + + test('does not follow a return address outside the app', async () => { + const wrapper = await open('/login?redirect=//evil.example') + await signIn(wrapper) + await vi.waitFor(() => expect(currentPath()).toBe('/dashboard')) + }) + + test('explains wrong credentials without showing server text', async () => { + fake.auth.signInWithPassword.mockResolvedValueOnce({ + data: { session: null, user: null } as never, + error: new AuthApiError('Invalid login credentials', 400, 'invalid_credentials'), + }) + const wrapper = await open() + + await signIn(wrapper) + + await vi.waitFor(() => expect(alertText(wrapper)).toBe('E-Mail-Adresse oder Passwort ist falsch.')) + expect(wrapper.text()).not.toContain('Invalid login credentials') + expect(currentPath()).toBe('/login') + expect(button(wrapper, 'Anmelden').attributes('disabled')).toBeUndefined() + }) + + test('explains that the server cannot be reached', async () => { + fake.auth.signInWithPassword.mockResolvedValueOnce({ + data: { session: null, user: null } as never, + error: new AuthRetryableFetchError('offline', 0), + }) + const wrapper = await open() + await signIn(wrapper) + await vi.waitFor(() => expect(alertText(wrapper)).toContain('Keine Verbindung zum Server.')) + }) + + test('sends only one request while waiting', async () => { + let answer: (value: never) => void = () => {} + fake.auth.signInWithPassword.mockReturnValueOnce(new Promise((resolve) => { + answer = resolve + })) + const wrapper = await open() + + await signIn(wrapper) + await wrapper.get('form').trigger('submit') + + expect(fake.auth.signInWithPassword).toHaveBeenCalledTimes(1) + expect(button(wrapper, 'Anmelden').attributes('disabled')).toBeDefined() + answer({ data: { session: null, user: null }, error: new AuthApiError('no', 400, 'invalid_credentials') } as never) + await vi.waitFor(() => expect(button(wrapper, 'Anmelden').attributes('disabled')).toBeUndefined()) + }) + + test('says so when sign-in is not configured', async () => { + supabase.auth = undefined + resetSession() + const wrapper = await open() + await signIn(wrapper) + await vi.waitFor(() => expect(alertText(wrapper)).toBe('Die Anmeldung ist derzeit nicht verfügbar.')) + }) + + test('shows messages in the active language', async () => { + const wrapper = await open('/en/login') + await wrapper.get('form').trigger('submit') + await flushPromises() + expect(description(wrapper, 'Email address')).toBe('Please enter your email address.') + }) + + test('links to registration and keeps the return address', async () => { + const wrapper = await open('/login?redirect=/map') + expect(wrapper.get('a[href^="/register"]').attributes('href')).toBe('/register?redirect=/map') + }) +}) + +describe('Google button', () => { + test('starts the Google sign-in', async () => { + const wrapper = await open() + + await button(wrapper, 'Mit Google fortfahren').trigger('click') + await flushPromises() + + expect(fake.auth.signInWithOAuth).toHaveBeenCalledWith({ + provider: 'google', + options: { redirectTo: `${window.location.origin}/auth/callback` }, + }) + // It is not the submit button, so the empty form stays quiet. + expect(wrapper.find('[aria-invalid]').exists()).toBe(false) + }) + + test('explains when Google sign-in is not available', async () => { + fake.auth.signInWithOAuth.mockResolvedValueOnce({ + data: {}, + error: new AuthApiError('Unsupported provider', 400, 'validation_failed'), + }) + const wrapper = await open() + + await button(wrapper, 'Mit Google fortfahren').trigger('click') + + await vi.waitFor(() => expect(alertText(wrapper)).toContain('Die Anmeldung wurde abgelehnt.')) + }) +}) diff --git a/pages/__tests__/register.nuxt.spec.ts b/pages/__tests__/register.nuxt.spec.ts new file mode 100644 index 0000000..47c5946 --- /dev/null +++ b/pages/__tests__/register.nuxt.spec.ts @@ -0,0 +1,100 @@ +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import { AuthApiError } from '@supabase/supabase-js' +import { enableAutoUnmount, flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { resetSession } from '../../composables/__tests__/reset-session' +import RegisterPage from '../register.vue' +import { button, description, field } from '../../composables/__tests__/form-helpers' + +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +enableAutoUnmount(afterEach) + +let fake: ReturnType + +beforeEach(async () => { + fake = createFakeAuth() + supabase.auth = fake.auth + resetSession() + await useNuxtApp().$i18n.setLocale('de') + await useRouter().push('/') +}) + +const open = (route = '/register') => mountSuspended(RegisterPage, { route, attachTo: document.body }) +const currentPath = () => useRouter().currentRoute.value.path + +async function register(wrapper: Awaited>, password = 'secret-1') { + await field(wrapper, 'E-Mail-Adresse').setValue('ann@example.org') + await field(wrapper, 'Passwort').setValue(password) + await wrapper.get('form').trigger('submit') +} + +describe('registration form', () => { + test('asks for a new password and states the minimum length beforehand', async () => { + const wrapper = await open() + expect(field(wrapper, 'Passwort').attributes('autocomplete')).toBe('new-password') + expect(description(wrapper, 'Passwort')).toBe('Mindestens 6 Zeichen.') + }) + + test('rejects a password that is too short', async () => { + const wrapper = await open() + + await register(wrapper, '12345') + await flushPromises() + + expect(description(wrapper, 'Passwort')).toContain('Das Passwort braucht mindestens 6 Zeichen.') + expect(field(wrapper, 'Passwort').attributes('aria-invalid')).toBe('true') + expect(document.activeElement).toBe(field(wrapper, 'Passwort').element) + expect(fake.auth.signUp).not.toHaveBeenCalled() + }) + + test('creates the account and opens the dashboard', async () => { + const wrapper = await open() + await register(wrapper) + await vi.waitFor(() => expect(currentPath()).toBe('/dashboard')) + expect(fake.auth.signUp).toHaveBeenCalledWith(expect.objectContaining({ + email: 'ann@example.org', + password: 'secret-1', + })) + }) + + test('returns to the page that asked for the sign-in', async () => { + const wrapper = await open('/register?redirect=/photos') + await register(wrapper) + await vi.waitFor(() => expect(currentPath()).toBe('/photos')) + }) + + test('asks to confirm the email address when Supabase requires it', async () => { + fake.auth.signUp.mockResolvedValueOnce({ data: { session: null, user: { id: '1' } } as never, error: null }) + const wrapper = await open() + + await register(wrapper) + + await vi.waitFor(() => expect(wrapper.get('[role="status"]').text()).toContain('ann@example.org')) + expect(wrapper.get('[role="status"]').text()).toContain('Bestätigungslink') + expect(wrapper.find('form').exists()).toBe(false) + expect(currentPath()).toBe('/register') + }) + + test('explains that the account already exists', async () => { + fake.auth.signUp.mockResolvedValueOnce({ + data: { session: null, user: null } as never, + error: new AuthApiError('User already registered', 422, 'user_already_exists'), + }) + const wrapper = await open() + + await register(wrapper) + + await vi.waitFor(() => expect(wrapper.get('[role="alert"]').text()).toContain('schon ein Konto')) + }) + + test('offers Google and a link back to the login page', async () => { + const wrapper = await open() + await button(wrapper, 'Mit Google fortfahren').trigger('click') + await flushPromises() + expect(fake.auth.signInWithOAuth).toHaveBeenCalled() + expect(wrapper.get('a[href="/login"]').text()).toContain('Anmelden') + }) +}) From 1e3ea7a795136e36a86f35dac80958788d6dddc2 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:27:10 +0100 Subject: [PATCH 14/26] Add accessible login and registration forms (F2) Email and password with inline errors, focus on the first invalid field, translated failures, the "confirm your email" state and a Google button. The minimum password length matches the Supabase Auth setting. Co-Authored-By: Claude Sonnet 5.5 --- assets/css/main.css | 6 ++ assets/css/tokens.css | 5 ++ components/CredentialsForm.vue | 157 +++++++++++++++++++++++++++++++++ components/FormField.vue | 56 ++++++++++++ composables/formRules.ts | 28 ++++++ i18n/locales/de.json | 17 ++++ i18n/locales/en.json | 17 ++++ i18n/locales/nl.json | 17 ++++ pages/login.vue | 1 + pages/register.vue | 1 + 10 files changed, 305 insertions(+) create mode 100644 components/CredentialsForm.vue create mode 100644 components/FormField.vue create mode 100644 composables/formRules.ts diff --git a/assets/css/main.css b/assets/css/main.css index e8cfa6b..c597b3d 100644 --- a/assets/css/main.css +++ b/assets/css/main.css @@ -67,6 +67,7 @@ --container-*: initial; --container-content: var(--ons-size-content); + --container-form: var(--ons-size-form); } /* @@ -94,6 +95,11 @@ min-height: var(--ons-size-nav); } +/* For buttons that are waiting, as in disabled:faded. */ +@utility faded { + opacity: var(--ons-opacity-disabled); +} + /* Draws the focus ring inside the element, for items that touch the screen edge. */ @utility focus-inset { &:focus-visible { diff --git a/assets/css/tokens.css b/assets/css/tokens.css index 52213c9..5530fdb 100644 --- a/assets/css/tokens.css +++ b/assets/css/tokens.css @@ -95,6 +95,11 @@ --ons-size-nav: 3.5rem; /* Widest content column */ --ons-size-content: 64rem; + /* Widest form */ + --ons-size-form: 24rem; + + /* How strongly a button fades while it is waiting */ + --ons-opacity-disabled: 0.6; } /* Hooks for a manual theme switch. Nothing sets data-theme yet. */ diff --git a/components/CredentialsForm.vue b/components/CredentialsForm.vue new file mode 100644 index 0000000..804991b --- /dev/null +++ b/components/CredentialsForm.vue @@ -0,0 +1,157 @@ + + + diff --git a/components/FormField.vue b/components/FormField.vue new file mode 100644 index 0000000..8440245 --- /dev/null +++ b/components/FormField.vue @@ -0,0 +1,56 @@ + + + diff --git a/composables/formRules.ts b/composables/formRules.ts new file mode 100644 index 0000000..fbe2402 --- /dev/null +++ b/composables/formRules.ts @@ -0,0 +1,28 @@ +// Checks that run in the browser before anything is sent. Supabase checks again. +// Each function returns a message key, or undefined if the value is fine. + +// Keep in step with minimum_password_length in supabase/config.toml. It is not set there, +// so the default of Supabase Auth applies. A test compares both. +export const PASSWORD_MIN_LENGTH = 6 + +// Something, an @, something, a dot, something; no spaces. +const emailShape = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ + +export function emailError(value: string) { + const email = value.trim() + if (!email) { + return 'errors.form.emailRequired' + } + return emailShape.test(email) ? undefined : 'errors.form.emailInvalid' +} + +// For signing in: old passwords are not measured against today's rules. +export function passwordError(value: string) { + return value ? undefined : 'errors.form.passwordRequired' +} + +// For choosing a password. +export function newPasswordError(value: string) { + return passwordError(value) + ?? (value.length < PASSWORD_MIN_LENGTH ? 'errors.form.passwordTooShort' : undefined) +} diff --git a/i18n/locales/de.json b/i18n/locales/de.json index 1c63d87..7908409 100644 --- a/i18n/locales/de.json +++ b/i18n/locales/de.json @@ -66,6 +66,23 @@ "rejected": "Die Anmeldung wurde abgelehnt. Bitte prüfe deine Eingaben.", "tooManyAttempts": "Zu viele Versuche. Bitte warte kurz und versuche es erneut.", "unavailable": "Die Anmeldung ist derzeit nicht verfügbar." + }, + "form": { + "emailRequired": "Bitte gib deine E-Mail-Adresse ein.", + "emailInvalid": "Das ist keine gültige E-Mail-Adresse.", + "passwordRequired": "Bitte gib dein Passwort ein.", + "passwordTooShort": "Das Passwort braucht mindestens {min} Zeichen." } + }, + "auth": { + "email": "E-Mail-Adresse", + "password": "Passwort", + "passwordHint": "Mindestens {min} Zeichen.", + "signIn": "Anmelden", + "createAccount": "Konto erstellen", + "google": "Mit Google fortfahren", + "noAccount": "Noch kein Konto? Registrieren", + "haveAccount": "Schon ein Konto? Anmelden", + "confirmationSent": "Fast geschafft: Wir haben einen Bestätigungslink an {email} geschickt. Öffne ihn am besten in diesem Browser." } } diff --git a/i18n/locales/en.json b/i18n/locales/en.json index ba5fff8..d79fe80 100644 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -66,6 +66,23 @@ "rejected": "Sign-in was rejected. Please check what you entered.", "tooManyAttempts": "Too many attempts. Please wait a moment and try again.", "unavailable": "Sign-in is not available at the moment." + }, + "form": { + "emailRequired": "Please enter your email address.", + "emailInvalid": "That is not a valid email address.", + "passwordRequired": "Please enter your password.", + "passwordTooShort": "The password needs at least {min} characters." } + }, + "auth": { + "email": "Email address", + "password": "Password", + "passwordHint": "At least {min} characters.", + "signIn": "Sign in", + "createAccount": "Create account", + "google": "Continue with Google", + "noAccount": "No account yet? Create one", + "haveAccount": "Already have an account? Sign in", + "confirmationSent": "Almost done: we sent a confirmation link to {email}. Open it in this browser if you can." } } diff --git a/i18n/locales/nl.json b/i18n/locales/nl.json index 5cf137b..c703b41 100644 --- a/i18n/locales/nl.json +++ b/i18n/locales/nl.json @@ -66,6 +66,23 @@ "rejected": "Het inloggen is geweigerd. Controleer je invoer.", "tooManyAttempts": "Te veel pogingen. Wacht even en probeer het opnieuw.", "unavailable": "Inloggen is op dit moment niet beschikbaar." + }, + "form": { + "emailRequired": "Vul je e-mailadres in.", + "emailInvalid": "Dit is geen geldig e-mailadres.", + "passwordRequired": "Vul je wachtwoord in.", + "passwordTooShort": "Het wachtwoord moet minstens {min} tekens hebben." } + }, + "auth": { + "email": "E-mailadres", + "password": "Wachtwoord", + "passwordHint": "Minstens {min} tekens.", + "signIn": "Inloggen", + "createAccount": "Account aanmaken", + "google": "Doorgaan met Google", + "noAccount": "Nog geen account? Maak er een aan", + "haveAccount": "Heb je al een account? Log in", + "confirmationSent": "Bijna klaar: we hebben een bevestigingslink naar {email} gestuurd. Open die het liefst in deze browser." } } diff --git a/pages/login.vue b/pages/login.vue index 3cefa7e..c5f5348 100644 --- a/pages/login.vue +++ b/pages/login.vue @@ -8,5 +8,6 @@ useHead({ title: () => t('pages.login.title') }) diff --git a/pages/register.vue b/pages/register.vue index 86b791d..0527c4b 100644 --- a/pages/register.vue +++ b/pages/register.vue @@ -8,5 +8,6 @@ useHead({ title: () => t('pages.register.title') }) From 76369495415895513f149be94ca36ce033a7f442 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:28:39 +0100 Subject: [PATCH 15/26] Add tests for the session controls and the sign-in return page - The header offers sign-in or sign-out, and the app navigation only appears when signed in. The language switcher works in both states. - The navigation starts at the dashboard. - /auth/callback exists once, without a language prefix, and explains failed returns without showing server text. Co-Authored-By: Claude Sonnet 5.5 --- components/__tests__/AppNav.nuxt.spec.ts | 8 +-- i18n/__tests__/persistence.spec.ts | 9 +++ layouts/__tests__/default.nuxt.spec.ts | 71 +++++++++++++++++++--- middleware/__tests__/auth.nuxt.spec.ts | 4 +- pages/__tests__/callback.nuxt.spec.ts | 77 ++++++++++++++++++++++++ 5 files changed, 156 insertions(+), 13 deletions(-) create mode 100644 pages/__tests__/callback.nuxt.spec.ts diff --git a/components/__tests__/AppNav.nuxt.spec.ts b/components/__tests__/AppNav.nuxt.spec.ts index 05cba94..9f3a94e 100644 --- a/components/__tests__/AppNav.nuxt.spec.ts +++ b/components/__tests__/AppNav.nuxt.spec.ts @@ -30,16 +30,16 @@ describe('AppNav', () => { test('is a labelled navigation with one link per main page', async () => { const wrapper = await mountOn('/') expect(wrapper.get('nav').attributes('aria-label')).toBe('Hauptnavigation') - expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Start', 'Dates', 'Karte', 'Fotos']) - expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/', '/dates', '/map', '/photos']) + expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Übersicht', 'Dates', 'Karte', 'Fotos']) + expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/dashboard', '/dates', '/map', '/photos']) }) test('keeps the active language in labels and links', async () => { const wrapper = await mountOn('/nl') await useNuxtApp().$i18n.setLocale('nl') await flushPromises() - expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Home', 'Dates', 'Kaart', 'Foto\'s']) - expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/nl', '/nl/dates', '/nl/map', '/nl/photos']) + expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Overzicht', 'Dates', 'Kaart', 'Foto\'s']) + expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/nl/dashboard', '/nl/dates', '/nl/map', '/nl/photos']) }) test('marks only the current page', async () => { diff --git a/i18n/__tests__/persistence.spec.ts b/i18n/__tests__/persistence.spec.ts index 6614836..055831b 100644 --- a/i18n/__tests__/persistence.spec.ts +++ b/i18n/__tests__/persistence.spec.ts @@ -114,6 +114,15 @@ describe('app and sign-in pages', () => { }) }) +describe('the sign-in return page', () => { + // Supabase only returns to addresses on its allow list, so there is just one. + test('is not redirected to a language prefix', async () => { + const response = await visit('/auth/callback?code=abc', { saved: 'en', browser: 'en-GB' }) + expect(response.status).toBe(200) + expect(response.location).toBeNull() + }) +}) + describe('API routes', () => { test('are never redirected to a language prefix', async () => { const response = await visit('/api/health', { saved: 'nl', browser: 'nl-NL' }) diff --git a/layouts/__tests__/default.nuxt.spec.ts b/layouts/__tests__/default.nuxt.spec.ts index fd8a5ec..a1624c7 100644 --- a/layouts/__tests__/default.nuxt.spec.ts +++ b/layouts/__tests__/default.nuxt.spec.ts @@ -1,25 +1,44 @@ -import { mountSuspended } from '@nuxt/test-utils/runtime' -import { enableAutoUnmount } from '@vue/test-utils' +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import { enableAutoUnmount, flushPromises } from '@vue/test-utils' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { button } from '../../composables/__tests__/form-helpers' +import { resetSession } from '../../composables/__tests__/reset-session' import DefaultLayout from '../default.vue' +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + // The tests attach the layout to the page, so remove it again after each one. enableAutoUnmount(afterEach) +let fake: ReturnType + +function signInAs(email: string | undefined) { + fake = createFakeAuth({ signedInAs: email }) + supabase.auth = fake.auth + resetSession() +} + beforeEach(async () => { + signInAs(undefined) await useNuxtApp().$i18n.setLocale('de') await useRouter().push('/') }) -function mountLayout() { - return mountSuspended(DefaultLayout, { +async function mountLayout() { + const wrapper = await mountSuspended(DefaultLayout, { route: '/', // Focus only works for elements that are part of the document. attachTo: document.body, slots: { default: () => 'page content' }, }) + await flushPromises() + return wrapper } +const mainNavigation = 'nav[aria-label="Hauptnavigation"]' + describe('default layout', () => { test('starts with a skip link to the main content', async () => { const wrapper = await mountLayout() @@ -42,7 +61,11 @@ describe('default layout', () => { expect(wrapper.get('main').text()).toContain('page content') }) - test('the language switcher in the header changes the language of the layout', async () => { + test.each([ + ['signed out', undefined], + ['signed in', 'ann@example.org'], + ])('the language switcher in the header changes the language when %s', async (_state, email) => { + signInAs(email) const wrapper = await mountLayout() await wrapper.get('header a[data-locale="en"]').trigger('click') @@ -54,10 +77,44 @@ describe('default layout', () => { }) }) - test('has a header with home link and language switcher, and one main navigation', async () => { + test('has a header with a home link and the language switcher', async () => { const wrapper = await mountLayout() expect(wrapper.get('header a[href="/"]').text()).toBe('Ons') expect(wrapper.find('header nav[aria-label="Sprache"]').exists()).toBe(true) - expect(wrapper.findAll('nav[aria-label="Hauptnavigation"]')).toHaveLength(1) + }) + + test('offers signing in, and no app navigation, to signed-out visitors', async () => { + const wrapper = await mountLayout() + expect(wrapper.get('header a[href="/login"]').text()).toBe('Anmelden') + expect(wrapper.find(mainNavigation).exists()).toBe(false) + expect(wrapper.findAll('header button')).toHaveLength(0) + }) + + test('shows one app navigation and a sign-out button when signed in', async () => { + signInAs('ann@example.org') + const wrapper = await mountLayout() + expect(wrapper.findAll(mainNavigation)).toHaveLength(1) + expect(button(wrapper, 'Abmelden').attributes('type')).toBe('button') + expect(wrapper.find('header a[href="/login"]').exists()).toBe(false) + }) + + test('signs out with the button', async () => { + signInAs('ann@example.org') + const wrapper = await mountLayout() + + await button(wrapper, 'Abmelden').trigger('click') + await flushPromises() + + expect(fake.auth.signOut).toHaveBeenCalledWith({ scope: 'local' }) + expect(wrapper.find(mainNavigation).exists()).toBe(false) + expect(wrapper.find('header a[href="/login"]').exists()).toBe(true) + }) + + test('shows neither sign-in nor sign-out while the session is still unknown', async () => { + fake.auth.getSession.mockReturnValue(new Promise(() => {})) + fake.auth.onAuthStateChange.mockReturnValue({ data: { subscription: { unsubscribe: () => true } } }) + const wrapper = await mountLayout() + expect(wrapper.find('header a[href="/login"]').exists()).toBe(false) + expect(wrapper.findAll('header button')).toHaveLength(0) }) }) diff --git a/middleware/__tests__/auth.nuxt.spec.ts b/middleware/__tests__/auth.nuxt.spec.ts index 89cd22c..dceb480 100644 --- a/middleware/__tests__/auth.nuxt.spec.ts +++ b/middleware/__tests__/auth.nuxt.spec.ts @@ -47,7 +47,7 @@ describe('signed out', () => { expect(route.query.redirect).toBe('/dates?status=done') }) - test.each(['/', '/en', '/login', '/en/register'])('%s is open', async (path) => { + test.each(['/', '/en', '/login', '/en/register', '/auth/callback'])('%s is open', async (path) => { expect((await visit(path)).path).toBe(path) }) @@ -63,7 +63,7 @@ describe('signed in', () => { signInAs(someone) }) - test.each(['/dashboard', '/dates', '/en/map', '/nl/photos', '/'])('%s is open', async (path) => { + test.each(['/dashboard', '/dates', '/en/map', '/nl/photos', '/', '/auth/callback'])('%s is open', async (path) => { expect((await visit(path)).path).toBe(path) }) diff --git a/pages/__tests__/callback.nuxt.spec.ts b/pages/__tests__/callback.nuxt.spec.ts new file mode 100644 index 0000000..2e64ca0 --- /dev/null +++ b/pages/__tests__/callback.nuxt.spec.ts @@ -0,0 +1,77 @@ +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import { enableAutoUnmount, flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { resetSession } from '../../composables/__tests__/reset-session' +import CallbackPage from '../auth/callback.vue' + +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +enableAutoUnmount(afterEach) + +function signInAs(email: string | undefined) { + supabase.auth = createFakeAuth({ signedInAs: email }).auth + resetSession() +} + +beforeEach(async () => { + signInAs(undefined) + await useNuxtApp().$i18n.setLocale('de') + await useRouter().push('/') +}) + +// The page Google and confirmation emails come back to. +async function comeBack(address = '/auth/callback?code=abc') { + const wrapper = await mountSuspended(CallbackPage, { route: address }) + await flushPromises() + return wrapper +} + +const currentPath = () => useRouter().currentRoute.value.path + +describe('auth callback page', () => { + test('has one address for all languages', () => { + const paths = useRouter().getRoutes().map(route => route.path).filter(path => path.endsWith('/auth/callback')) + expect(paths).toEqual(['/auth/callback']) + }) + + test('opens the dashboard once Supabase has a session', async () => { + signInAs('ann@example.org') + await comeBack() + await vi.waitFor(() => expect(currentPath()).toBe('/dashboard')) + }) + + test('opens the dashboard in the active language', async () => { + signInAs('ann@example.org') + await useNuxtApp().$i18n.setLocale('en') + await comeBack() + await vi.waitFor(() => expect(currentPath()).toBe('/en/dashboard')) + }) + + test('asks to sign in when there is no session, for example on another device', async () => { + const wrapper = await comeBack() + expect(wrapper.get('[role="alert"]').text()).toContain('nicht automatisch anmelden') + expect(wrapper.get('a[href="/login"]').text()).toBe('Zur Anmeldung') + }) + + test.each([ + '/auth/callback?error=access_denied&error_description=Secret+details', + '/auth/callback#error=access_denied&error_description=Secret+details', + ])('explains a rejected sign-in without showing server text: %s', async (address) => { + const wrapper = await comeBack(address) + expect(wrapper.get('[role="alert"]').text()).toContain('abgebrochen oder abgelehnt') + expect(wrapper.text()).not.toContain('Secret') + }) + + test('says that it is working while Supabase has not answered', async () => { + const fake = createFakeAuth() + fake.auth.getSession.mockReturnValue(new Promise(() => {})) + supabase.auth = fake.auth + resetSession() + + const wrapper = await comeBack() + + expect(wrapper.get('[role="status"]').text()).toContain('Anmeldung wird abgeschlossen') + }) +}) From 445189080fb06c76406ddf00f787ec23ccfa54c3 Mon Sep 17 00:00:00 2001 From: Filionus Date: Thu, 26 Nov 2026 12:29:18 +0100 Subject: [PATCH 16/26] Add sign-out, the signed-in header and the sign-in return page (F2) The header offers sign-in or sign-out and the app navigation appears only when signed in. /auth/callback receives Google sign-ins and confirmation links under one address and explains failures in the chosen language. Co-Authored-By: Claude Sonnet 5.5 --- components/AppNav.vue | 2 +- components/SessionControls.vue | 26 ++++++++++++++ i18n/locales/de.json | 14 ++++++-- i18n/locales/en.json | 14 ++++++-- i18n/locales/nl.json | 14 ++++++-- layouts/default.vue | 16 +++++++-- pages/auth/callback.vue | 65 ++++++++++++++++++++++++++++++++++ 7 files changed, 141 insertions(+), 10 deletions(-) create mode 100644 components/SessionControls.vue create mode 100644 pages/auth/callback.vue diff --git a/components/AppNav.vue b/components/AppNav.vue index 570eb60..94b443b 100644 --- a/components/AppNav.vue +++ b/components/AppNav.vue @@ -4,7 +4,7 @@ const { t } = useI18n() // The main pages. To plug in a new one, add its file in pages/ and one entry here. const items = [ - { to: '/', label: 'nav.home' }, + { to: '/dashboard', label: 'nav.dashboard' }, { to: '/dates', label: 'nav.dates' }, { to: '/map', label: 'nav.map' }, { to: '/photos', label: 'nav.photos' }, diff --git a/components/SessionControls.vue b/components/SessionControls.vue new file mode 100644 index 0000000..d1015d6 --- /dev/null +++ b/components/SessionControls.vue @@ -0,0 +1,26 @@ + + + diff --git a/i18n/locales/de.json b/i18n/locales/de.json index 7908409..7c16bee 100644 --- a/i18n/locales/de.json +++ b/i18n/locales/de.json @@ -4,7 +4,7 @@ }, "nav": { "label": "Hauptnavigation", - "home": "Start", + "dashboard": "Übersicht", "dates": "Dates", "map": "Karte", "photos": "Fotos" @@ -41,6 +41,9 @@ }, "register": { "title": "Registrieren" + }, + "callback": { + "title": "Anmeldung" } }, "errors": { @@ -83,6 +86,13 @@ "google": "Mit Google fortfahren", "noAccount": "Noch kein Konto? Registrieren", "haveAccount": "Schon ein Konto? Anmelden", - "confirmationSent": "Fast geschafft: Wir haben einen Bestätigungslink an {email} geschickt. Öffne ihn am besten in diesem Browser." + "confirmationSent": "Fast geschafft: Wir haben einen Bestätigungslink an {email} geschickt. Öffne ihn am besten in diesem Browser.", + "signOut": "Abmelden", + "callback": { + "working": "Anmeldung wird abgeschlossen …", + "rejected": "Die Anmeldung wurde abgebrochen oder abgelehnt.", + "incomplete": "Wir konnten dich nicht automatisch anmelden. Wenn du gerade deine E-Mail-Adresse bestätigt hast, melde dich jetzt einfach an.", + "toLogin": "Zur Anmeldung" + } } } diff --git a/i18n/locales/en.json b/i18n/locales/en.json index d79fe80..cd16991 100644 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -4,7 +4,7 @@ }, "nav": { "label": "Main navigation", - "home": "Home", + "dashboard": "Overview", "dates": "Dates", "map": "Map", "photos": "Photos" @@ -41,6 +41,9 @@ }, "register": { "title": "Create account" + }, + "callback": { + "title": "Signing in" } }, "errors": { @@ -83,6 +86,13 @@ "google": "Continue with Google", "noAccount": "No account yet? Create one", "haveAccount": "Already have an account? Sign in", - "confirmationSent": "Almost done: we sent a confirmation link to {email}. Open it in this browser if you can." + "confirmationSent": "Almost done: we sent a confirmation link to {email}. Open it in this browser if you can.", + "signOut": "Sign out", + "callback": { + "working": "Finishing your sign-in …", + "rejected": "The sign-in was cancelled or rejected.", + "incomplete": "We could not sign you in automatically. If you have just confirmed your email address, simply sign in now.", + "toLogin": "Go to sign-in" + } } } diff --git a/i18n/locales/nl.json b/i18n/locales/nl.json index c703b41..b7d031b 100644 --- a/i18n/locales/nl.json +++ b/i18n/locales/nl.json @@ -4,7 +4,7 @@ }, "nav": { "label": "Hoofdnavigatie", - "home": "Home", + "dashboard": "Overzicht", "dates": "Dates", "map": "Kaart", "photos": "Foto's" @@ -41,6 +41,9 @@ }, "register": { "title": "Account aanmaken" + }, + "callback": { + "title": "Inloggen" } }, "errors": { @@ -83,6 +86,13 @@ "google": "Doorgaan met Google", "noAccount": "Nog geen account? Maak er een aan", "haveAccount": "Heb je al een account? Log in", - "confirmationSent": "Bijna klaar: we hebben een bevestigingslink naar {email} gestuurd. Open die het liefst in deze browser." + "confirmationSent": "Bijna klaar: we hebben een bevestigingslink naar {email} gestuurd. Open die het liefst in deze browser.", + "signOut": "Uitloggen", + "callback": { + "working": "Het inloggen wordt afgerond …", + "rejected": "Het inloggen is geannuleerd of geweigerd.", + "incomplete": "We konden je niet automatisch inloggen. Heb je net je e-mailadres bevestigd? Log dan nu gewoon in.", + "toLogin": "Naar inloggen" + } } } diff --git a/layouts/default.vue b/layouts/default.vue index ccd52f7..233f33b 100644 --- a/layouts/default.vue +++ b/layouts/default.vue @@ -1,5 +1,10 @@