From 4829146de80151c1b17e3b406d6601d73574ac71 Mon Sep 17 00:00:00 2001 From: Hasan Mohammad Fawzi Date: Mon, 19 Oct 2026 00:04:37 +0200 Subject: [PATCH 1/4] fix(auth): migrate sessions to HttpOnly cookies and GraphQL context --- .env.example | 2 + README.md | 6 +- apps/api/src/app.ts | 71 +++++++- apps/api/src/features/auth/authApp.test.ts | 169 ++++++++++++++---- apps/api/src/features/auth/authResolvers.ts | 34 +++- apps/api/src/features/auth/sessionCookie.ts | 16 ++ apps/api/src/generated.ts | 20 +-- apps/api/src/schema.graphql | 5 +- .../shell/SiteHeader/SiteHeader.test.tsx | 19 +- .../shell/SiteHeader/SiteHeader.tsx | 16 +- apps/web/src/features/auth/AuthPages.test.tsx | 15 +- .../src/features/auth/RequireAuth.test.tsx | 13 +- apps/web/src/features/auth/authApi.test.ts | 24 ++- apps/web/src/features/auth/authApi.ts | 15 +- apps/web/src/store.test.ts | 152 +++++----------- apps/web/src/store.ts | 29 ++- contracts/generated.ts | 92 +--------- contracts/operations.graphql | 10 +- docs/auth-improvements.md | 38 +++- e2e/auth-cookie.spec.ts | 87 +++++++++ e2e/smoke.spec.ts | 10 ++ 21 files changed, 510 insertions(+), 333 deletions(-) create mode 100644 apps/api/src/features/auth/sessionCookie.ts create mode 100644 e2e/auth-cookie.spec.ts diff --git a/.env.example b/.env.example index cdd21bf..d3d5ae9 100644 --- a/.env.example +++ b/.env.example @@ -3,3 +3,5 @@ API_HOST=127.0.0.1 API_PORT=3001 # Enable only for the documented local Apache proxy on the VM. AUTH_TRUST_PROXY=false +# false for localhost/current HTTP VM; true when HTTPS is configured. +AUTH_COOKIE_SECURE=false diff --git a/README.md b/README.md index af888c3..f197e0d 100644 --- a/README.md +++ b/README.md @@ -126,16 +126,16 @@ Ikke legg `.env`, passord, tokens eller andre hemmeligheter i Git. Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing still uses mock data. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user. -Session tokens are bearer credentials stored in localStorage to restore login after refresh or reopening the browser. They expire after seven days and are deleted server-side on successful logout. Temporary API or network errors preserve the local token for a later restoration attempt; only a confirmed invalid or expired session clears it. +Sessions use a host-only HttpOnly cookie (`t31_project2_session`, SameSite=Lax, Path=/, seven-day lifetime). GraphQL context resolves the user from the cookie. Tokens are not returned to frontend JavaScript or stored in localStorage. Logout revokes the server session and clears the cookie. Temporary API failures preserve the cookie for retry. Existing users must log in again after this migration. -Security trade-off: localStorage is readable by JavaScript on the same origin. An XSS vulnerability could steal a token and let an attacker impersonate its owner until expiry or revocation. This prototype accepts that limitation; production deployment should use HTTPS and consider Secure, HttpOnly, SameSite cookies with appropriate CSRF protection. HttpOnly cookies prevent JavaScript from reading the session credential. +Cookie-authenticated POST requests require JSON and `X-Requested-With: recipe-platform`; cross-origin CORS access is disabled. Set `AUTH_COOKIE_SECURE=true` when HTTPS is configured. Keep it false for local HTTP and the current NTNU HTTP deployment. HttpOnly reduces direct token theft through JavaScript; HTTPS is still required to protect credentials in transit. ### Protected routes Se [auth-forbedringer](docs/auth-improvements.md) for delt Zod-validering, feilkoder, genererte klientoperasjoner og rate limiting bak Apache. -`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the token. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server. +`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the cookie. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server. ## Database diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index d3c982a..3b48a0b 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -9,16 +9,81 @@ import { } from './features/auth/authResolvers.js'; import { authClientKey } from './features/auth/authRateLimit.js'; import { authService, type AuthService } from './features/auth/authService.js'; +import { + readSessionCookie, + sessionCookie, + SESSION_COOKIE, +} from './features/auth/sessionCookie.js'; export function createApp( service: AuthService = authService, trustProxy = process.env.AUTH_TRUST_PROXY === 'true', + secureCookie = process.env.AUTH_COOKIE_SECURE === 'true', ) { const authResolvers = createAuthResolvers(service); + const cookies = new WeakMap(); return createYoga<{ req?: IncomingMessage }, AuthContext>({ - context: ({ request, req }) => ({ - authClient: authClientKey(request, req?.socket.remoteAddress, trustProxy), - }), + cors: false, + graphiql: { + defaultHeaders: JSON.stringify({ 'X-Requested-With': 'recipe-platform' }), + }, + plugins: [ + { + onRequest({ request, fetchAPI, endResponse }) { + if ( + request.method === 'POST' && + (request.headers.get('x-requested-with') !== 'recipe-platform' || + request.headers.get('content-type')?.split(';')[0]?.trim() !== + 'application/json') + ) { + endResponse( + new fetchAPI.Response( + JSON.stringify({ + errors: [ + { + message: 'Request blocked.', + extensions: { code: 'FORBIDDEN' }, + }, + ], + }), + { + status: 403, + headers: { 'Content-Type': 'application/json' }, + }, + ), + ); + } + }, + onResponse({ request, response }) { + const cookie = cookies.get(request); + if (cookie) response.headers.append('Set-Cookie', cookie); + response.headers.set('Cache-Control', 'no-store'); + }, + }, + ], + context: async ({ request, req }) => { + const token = readSessionCookie(request); + const user = token ? await service.currentUser(token) : null; + if ( + !user && + request.headers.get('cookie')?.includes(SESSION_COOKIE + '=') + ) + cookies.set(request, sessionCookie(null, secureCookie)); + const context: AuthContext = { + authClient: authClientKey( + request, + req?.socket.remoteAddress, + trustProxy, + ), + user, + sessionToken: user ? token : null, + setSession: (nextToken) => { + cookies.set(request, sessionCookie(nextToken, secureCookie)); + context.sessionToken = nextToken; + }, + }; + return context; + }, schema: createSchema({ typeDefs: readFileSync( new URL('./schema.graphql', import.meta.url), diff --git a/apps/api/src/features/auth/authApp.test.ts b/apps/api/src/features/auth/authApp.test.ts index a674c71..e83ddce 100644 --- a/apps/api/src/features/auth/authApp.test.ts +++ b/apps/api/src/features/auth/authApp.test.ts @@ -1,6 +1,6 @@ // @vitest-environment node import { describe, expect, it, vi } from 'vitest'; -import { print } from 'graphql'; +import { print, parse } from 'graphql'; import { createApp } from '../../app.js'; import { createAuthService } from './authService.js'; import type { AuthRepository } from './authRepository.js'; @@ -10,19 +10,22 @@ import { SignOutDocument, RegisterDocument, } from '../../../../../contracts/generated.js'; - const token = '11111111-1111-4111-8111-111111111111'; const user = { id: '22222222-2222-4222-8222-222222222222', name: 'Hasan', email: 'hasan@example.com', }; -function setup() { +function setup(secure = false) { let active = false; + let cookie = ''; const repository: AuthRepository = { findUserByEmail: vi.fn(async () => ({ ...user, passwordHash: 'hash' })), createUser: vi.fn(async () => user), - createUserWithSession: vi.fn(async () => ({ user, sessionToken: token })), + createUserWithSession: vi.fn(async () => { + active = true; + return { user, sessionToken: token }; + }), createSession: vi.fn(async () => { active = true; return token; @@ -32,65 +35,159 @@ function setup() { active = false; }), }; - const service = createAuthService(repository, { - hash: async () => 'hash', - verify: async (_hash, password) => password === 'x', - }); - const app = createApp(service, false); + const app = createApp( + createAuthService(repository, { + hash: async () => 'hash', + verify: async (_hash, password) => password === 'x', + }), + false, + secure, + ); async function request( document: Parameters[0], - variables: Record, + variables: Record = {}, + sentCookie = cookie, + csrf = true, ) { const response = await app.fetch('http://localhost/graphql', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { + 'Content-Type': 'application/json', + ...(csrf ? { 'X-Requested-With': 'recipe-platform' } : {}), + ...(sentCookie ? { Cookie: sentCookie } : {}), + }, body: JSON.stringify({ query: print(document), variables }), }); - return (await response.json()) as { + const setCookie = response.headers.get('set-cookie'); + if (setCookie) cookie = setCookie.split(';')[0]!; + const result = (await response.json()) as { data: { - login?: { sessionToken: string }; + login?: { user: typeof user }; + register?: { user: typeof user }; currentUser?: typeof user | null; signOut?: boolean; }; errors?: { extensions: { code: string } }[]; }; + return { ...result, cookie: setCookie, status: response.status }; } - return { repository, request }; + return { + repository, + request, + expire: () => { + active = false; + }, + }; } -describe('GraphQL authentication contract', () => { - it('logs in with a short existing password, restores session and invalidates it on logout', async () => { +describe('cookie GraphQL authentication', () => { + it('sets an HttpOnly cookie, restores from context and revokes the session on logout', async () => { const { request } = setup(); const login = await request(LoginDocument, { email: user.email, password: 'x', }); expect(login.errors).toBeUndefined(); - expect(login.data.login?.sessionToken).toBe(token); - expect( - (await request(CurrentUserDocument, { sessionToken: token })).data - .currentUser, - ).toEqual(user); + expect(login.data.login).toEqual({ user }); + expect(JSON.stringify(login.data)).not.toContain(token); + expect(login.cookie).toContain('HttpOnly'); + expect(login.cookie).toContain('SameSite=Lax'); + expect(login.cookie).toContain('Path=/'); + expect(login.cookie).toContain('Max-Age=604800'); + expect(login.cookie).not.toContain('Secure'); + expect(login.cookie).not.toContain('Domain='); + expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user); + const logout = await request(SignOutDocument); + expect(logout.data.signOut).toBe(true); + expect(logout.cookie).toContain('Max-Age=0'); + expect(logout.cookie).toContain('Path=/'); expect( - (await request(SignOutDocument, { sessionToken: token })).data.signOut, - ).toBe(true); - expect( - (await request(CurrentUserDocument, { sessionToken: token })).data - .currentUser, + (await request(CurrentUserDocument, {}, 't31_project2_session=' + token)) + .data.currentUser, ).toBeNull(); }); - it('does not query the repository for malformed session IDs', async () => { + it('registration also creates a cookie without exposing the token', async () => { const { request, repository } = setup(); + vi.mocked(repository.findUserByEmail).mockResolvedValueOnce(null); + const registered = await request(RegisterDocument, { + name: user.name, + email: user.email, + password: 'secret', + }); + expect(registered.errors).toBeUndefined(); + expect(registered.data.register).toEqual({ user }); + expect(registered.cookie).toContain('HttpOnly'); + expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user); + }); + it('sets Secure when explicitly enabled for HTTPS', async () => { + const { request } = setup(true); expect( - (await request(CurrentUserDocument, { sessionToken: 'broken' })).data - .currentUser, - ).toBeNull(); - expect( - (await request(SignOutDocument, { sessionToken: 'broken' })).data.signOut, - ).toBe(false); + (await request(LoginDocument, { email: user.email, password: 'x' })) + .cookie, + ).toContain('; Secure'); + expect((await request(SignOutDocument)).cookie).toContain('; Secure'); + }); + it('treats absent, malformed and expired cookies as anonymous', async () => { + const { request, repository, expire } = setup(); + expect((await request(CurrentUserDocument)).data.currentUser).toBeNull(); + const malformed = await request( + CurrentUserDocument, + {}, + 't31_project2_session=broken', + ); + expect(malformed.data.currentUser).toBeNull(); + expect(malformed.cookie).toContain('Max-Age=0'); expect(repository.findUserBySession).not.toHaveBeenCalled(); - expect(repository.deleteSession).not.toHaveBeenCalled(); + await request(LoginDocument, { email: user.email, password: 'x' }); + expire(); + const expired = await request(CurrentUserDocument); + expect(expired.data.currentUser).toBeNull(); + expect(expired.cookie).toContain('Max-Age=0'); + }); + it('does not clear the cookie or claim success when session revocation fails', async () => { + const { request, repository } = setup(); + await request(LoginDocument, { email: user.email, password: 'x' }); + vi.mocked(repository.deleteSession).mockRejectedValueOnce( + new Error('Database offline'), + ); + const logout = await request(SignOutDocument); + expect(logout.errors).toBeDefined(); + expect(logout.cookie).toBeNull(); + expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user); + }); + it('rejects browser-simple POSTs before executing authentication', async () => { + const { request, repository } = setup(); + expect( + ( + await request( + LoginDocument, + { email: user.email, password: 'x' }, + '', + false, + ) + ).status, + ).toBe(403); + expect(repository.findUserByEmail).not.toHaveBeenCalled(); + }); + it('rejects the old token-bearing GraphQL contract', async () => { + const { request } = setup(); + expect( + ( + await request( + parse('query { currentUser(sessionToken: "old") { id } }'), + ) + ).errors, + ).toBeDefined(); + expect( + ( + await request( + parse( + 'mutation { login(email:"a@example.com",password:"x") { sessionToken } }', + ), + ) + ).errors, + ).toBeDefined(); }); - it('returns structured codes for invalid input, credentials, duplicate email and rate limits', async () => { + it('preserves structured errors and rate limiting', async () => { const { request } = setup(); expect( (await request(LoginDocument, { email: 'a@', password: 'x' })).errors?.[0] @@ -103,7 +200,7 @@ describe('GraphQL authentication contract', () => { expect( ( await request(RegisterDocument, { - name: 'Hasan', + name: user.name, email: user.email, password: 'secret', }) diff --git a/apps/api/src/features/auth/authResolvers.ts b/apps/api/src/features/auth/authResolvers.ts index 1c57c90..b973c66 100644 --- a/apps/api/src/features/auth/authResolvers.ts +++ b/apps/api/src/features/auth/authResolvers.ts @@ -1,8 +1,12 @@ import { authService, type AuthService } from './authService.js'; import { createAuthRateLimiter } from './authRateLimit.js'; +import type { PublicUser } from './authRepository.js'; export interface AuthContext { authClient: string; + user: PublicUser | null; + sessionToken: string | null; + setSession: (token: string | null) => void; } export function createAuthResolvers( @@ -11,8 +15,8 @@ export function createAuthResolvers( ) { return { Query: { - currentUser: (_parent: unknown, args: { sessionToken: string }) => - service.currentUser(args.sessionToken), + currentUser: (_parent: unknown, _args: unknown, context: AuthContext) => + context.user, }, Mutation: { @@ -26,7 +30,13 @@ export function createAuthResolvers( context: AuthContext, ) => { limiter.check('register', context.authClient); - return service.register(args.name, args.email, args.password); + return service + .register(args.name, args.email, args.password) + .then((result) => { + context.setSession(result.sessionToken); + context.user = result.user; + return { user: result.user }; + }); }, login: ( @@ -38,11 +48,23 @@ export function createAuthResolvers( context: AuthContext, ) => { limiter.check('login', context.authClient); - return service.login(args.email, args.password); + return service.login(args.email, args.password).then((result) => { + context.setSession(result.sessionToken); + context.user = result.user; + return { user: result.user }; + }); }, - signOut: (_parent: unknown, args: { sessionToken: string }) => - service.signOut(args.sessionToken), + signOut: async ( + _parent: unknown, + _args: unknown, + context: AuthContext, + ) => { + await service.signOut(context.sessionToken ?? ''); + context.setSession(null); + context.user = null; + return true; + }, }, }; } diff --git a/apps/api/src/features/auth/sessionCookie.ts b/apps/api/src/features/auth/sessionCookie.ts new file mode 100644 index 0000000..d0db972 --- /dev/null +++ b/apps/api/src/features/auth/sessionCookie.ts @@ -0,0 +1,16 @@ +import { sessionTokenSchema } from '@t31/validation'; + +export const SESSION_COOKIE = 't31_project2_session'; +export function readSessionCookie(request: Request): string | null { + const values = (request.headers.get('cookie') ?? '') + .split(';') + .map((value) => value.trim()) + .filter((value) => value.startsWith(SESSION_COOKIE + '=')); + if (values.length !== 1) return null; + const token = values[0]!.slice(SESSION_COOKIE.length + 1); + return sessionTokenSchema.safeParse(token).success ? token : null; +} +export function sessionCookie(token: string | null, secure: boolean) { + // Host-only cookie: works through local Vite and the VM's /project2/api proxy. + return `${SESSION_COOKIE}=${token ?? ''}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${token ? 604800 : 0}${secure ? '; Secure' : ''}`; +} diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index 8d4e30c..ad6d0f0 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -24,7 +24,6 @@ export type User = { export type AuthPayload = { __typename?: 'AuthPayload'; user: User; - sessionToken: Scalars['String']['output']; }; export type Query = { @@ -33,10 +32,6 @@ export type Query = { currentUser?: Maybe; }; -export type QueryCurrentUserArgs = { - sessionToken: Scalars['String']['input']; -}; - export type Mutation = { __typename?: 'Mutation'; register: AuthPayload; @@ -55,10 +50,6 @@ export type MutationLoginArgs = { password: Scalars['String']['input']; }; -export type MutationSignOutArgs = { - sessionToken: Scalars['String']['input']; -}; - export type ResolverTypeWrapper = Promise | T; export type ResolverWithResolve = { @@ -214,7 +205,6 @@ export type AuthPayloadResolvers< ResolversParentTypes['AuthPayload'] = ResolversParentTypes['AuthPayload'], > = { user?: Resolver; - sessionToken?: Resolver; }; export type QueryResolvers< @@ -226,8 +216,7 @@ export type QueryResolvers< currentUser?: Resolver< Maybe, ParentType, - ContextType, - RequireFields + ContextType >; }; @@ -248,12 +237,7 @@ export type MutationResolvers< ContextType, RequireFields >; - signOut?: Resolver< - ResolversTypes['Boolean'], - ParentType, - ContextType, - RequireFields - >; + signOut?: Resolver; }; export type Resolvers = { diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index c2cb462..436b41f 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -6,16 +6,15 @@ type User { type AuthPayload { user: User! - sessionToken: String! } type Query { health: String! - currentUser(sessionToken: String!): User + currentUser: User } type Mutation { register(name: String!, email: String!, password: String!): AuthPayload! login(email: String!, password: String!): AuthPayload! - signOut(sessionToken: String!): Boolean! + signOut: Boolean! } diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx index 37844c4..accf529 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx @@ -84,8 +84,6 @@ describe('SiteHeader authentication', () => { }); it('updates the header after signing out', async () => { - localStorage.setItem('recipe-platform-session-token', 'session-123'); - useAppStore.setState({ currentUser: authenticatedUser, }); @@ -110,8 +108,23 @@ describe('SiteHeader authentication', () => { ).toBeInTheDocument(); }); - expect(signOutUser).toHaveBeenCalledWith('session-123'); + expect(signOutUser).toHaveBeenCalledWith(); expect(useAppStore.getState().currentUser).toBeNull(); }); + it('shows a recoverable error when cookie logout fails', async () => { + useAppStore.setState({ + currentUser: authenticatedUser, + sessionStatus: 'authenticated', + }); + vi.mocked(signOutUser).mockRejectedValueOnce(new Error('Offline')); + renderHeader(); + await userEvent + .setup() + .click(screen.getByRole('button', { name: 'Sign out' })); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Unable to sign out', + ); + expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); + }); }); diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx index 6b68e13..9fa2d73 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx @@ -10,6 +10,7 @@ import { } from '../../../icons/navigation'; import { useAppStore } from '../../../store'; import Button from '../../ui/Button/Button'; +import FeedbackMessage from '../../ui/FeedbackMessage/FeedbackMessage'; import IconButton from '../../ui/IconButton/IconButton'; import './SiteHeader.css'; import LogoMark from '../../brand/LogoMark/LogoMark'; @@ -24,6 +25,7 @@ const pages = [ function SiteHeader() { const [menuOpen, setMenuOpen] = useState(false); + const [logoutError, setLogoutError] = useState(''); const navigate = useNavigate(); const currentUser = useAppStore((state) => state.currentUser); @@ -32,9 +34,14 @@ function SiteHeader() { const closeMenu = () => setMenuOpen(false); const handleSignOut = async () => { - await signOut(); - closeMenu(); - navigate('/'); + setLogoutError(''); + try { + await signOut(); + closeMenu(); + navigate('/'); + } catch { + setLogoutError('Unable to sign out. Please try again.'); + } }; return ( @@ -87,6 +94,9 @@ function SiteHeader() { ))}
+ {logoutError && ( + {logoutError} + )} {currentUser ? ( <> diff --git a/apps/web/src/features/auth/AuthPages.test.tsx b/apps/web/src/features/auth/AuthPages.test.tsx index 856ccdb..f8ca789 100644 --- a/apps/web/src/features/auth/AuthPages.test.tsx +++ b/apps/web/src/features/auth/AuthPages.test.tsx @@ -40,7 +40,6 @@ describe('authentication pages', () => { it('submits a short existing password on login', async () => { vi.mocked(loginUser).mockResolvedValue({ user: authenticatedUser, - sessionToken: 'session-123', }); const user = userEvent.setup(); renderAuthPage('/login'); @@ -93,7 +92,6 @@ describe('authentication pages', () => { it('registers a user and navigates to Explore', async () => { vi.mocked(registerUser).mockResolvedValue({ user: authenticatedUser, - sessionToken: 'session-123', }); const user = userEvent.setup(); @@ -128,15 +126,12 @@ describe('authentication pages', () => { expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); - expect(localStorage.getItem('recipe-platform-session-token')).toBe( - 'session-123', - ); + expect(localStorage.getItem('recipe-platform-session-token')).toBeNull(); }); it('logs in and navigates to Explore', async () => { vi.mocked(loginUser).mockResolvedValue({ user: authenticatedUser, - sessionToken: 'session-456', }); const user = userEvent.setup(); @@ -199,7 +194,6 @@ describe('authentication pages', () => { expect(screen.getByRole('button')).toBeEnabled(); request.mockResolvedValueOnce({ user: authenticatedUser, - sessionToken: 'retry-session', }); await user.click(screen.getByRole('button')); expect( @@ -211,10 +205,7 @@ describe('authentication pages', () => { it.each(['/login', '/register'] as const)( 'prevents duplicate submissions on %s', async (route) => { - let resolve!: (value: { - user: typeof authenticatedUser; - sessionToken: string; - }) => void; + let resolve!: (value: { user: typeof authenticatedUser }) => void; const request = vi.mocked(route === '/login' ? loginUser : registerUser); request.mockReturnValueOnce( new Promise((done) => { @@ -236,7 +227,7 @@ describe('authentication pages', () => { expect(screen.getByRole('button')).toBeDisabled(); await user.click(screen.getByRole('button')); expect(request).toHaveBeenCalledTimes(1); - resolve({ user: authenticatedUser, sessionToken: 'session-123' }); + resolve({ user: authenticatedUser }); expect( await screen.findByRole('heading', { name: 'Explore' }), ).toBeInTheDocument(); diff --git a/apps/web/src/features/auth/RequireAuth.test.tsx b/apps/web/src/features/auth/RequireAuth.test.tsx index 3422aea..a1d760b 100644 --- a/apps/web/src/features/auth/RequireAuth.test.tsx +++ b/apps/web/src/features/auth/RequireAuth.test.tsx @@ -15,7 +15,6 @@ vi.mock('./authApi', () => ({ signOutUser: vi.fn(), })); const user = { id: 'user-123', name: 'Hasan', email: 'hasan@example.com' }; -const tokenKey = 'recipe-platform-session-token'; function LocationProbe() { const location = useLocation(); return ( @@ -44,6 +43,7 @@ function pendingSession() { } beforeEach(() => { vi.resetAllMocks(); + vi.mocked(getCurrentUser).mockResolvedValue(null); localStorage.clear(); useAppStore.setState({ currentUser: null, sessionStatus: 'restoring' }); }); @@ -64,7 +64,6 @@ describe('protected routes with session restoration', () => { ])( 'waits on refresh of %s and renders after validation', async (path, title) => { - localStorage.setItem(tokenKey, 'valid-token'); const resolve = pendingSession(); renderApp(path!); expect(screen.getByText('Restoring your session...')).toHaveTextContent( @@ -85,7 +84,6 @@ describe('protected routes with session restoration', () => { }, ); it('redirects only after the API confirms expiry', async () => { - localStorage.setItem(tokenKey, 'expired-token'); const resolve = pendingSession(); renderApp('/cookbook'); expect(screen.getByTestId('location')).toHaveTextContent('/cookbook'); @@ -93,10 +91,8 @@ describe('protected routes with session restoration', () => { expect( await screen.findByRole('heading', { name: 'Log in' }), ).toBeInTheDocument(); - expect(localStorage.getItem(tokenKey)).toBeNull(); }); - it('keeps the token and protected URL during an outage and permits retry', async () => { - localStorage.setItem(tokenKey, 'valid-token'); + it('keeps the protected URL during a cookie-session outage and permits retry', async () => { vi.mocked(getCurrentUser).mockRejectedValue(new Error('Offline')); renderApp('/recipes/new'); expect(await screen.findByRole('alert')).toHaveTextContent( @@ -106,7 +102,7 @@ describe('protected routes with session restoration', () => { expect( screen.queryByRole('heading', { name: 'Add Recipe' }), ).not.toBeInTheDocument(); - expect(localStorage.getItem(tokenKey)).toBe('valid-token'); + vi.mocked(getCurrentUser).mockResolvedValue(user); await userEvent .setup() @@ -120,11 +116,9 @@ describe('protected routes with session restoration', () => { async (register) => { vi.mocked(loginUser).mockResolvedValue({ user, - sessionToken: 'new-token', }); vi.mocked(registerUser).mockResolvedValue({ user, - sessionToken: 'new-token', }); const interaction = userEvent.setup(); renderApp('/cookbook?view=saved#recipes'); @@ -152,7 +146,6 @@ describe('protected routes with session restoration', () => { }, ); it('leaves Explore public during session restoration', () => { - localStorage.setItem(tokenKey, 'valid-token'); pendingSession(); renderApp('/'); expect( diff --git a/apps/web/src/features/auth/authApi.test.ts b/apps/web/src/features/auth/authApi.test.ts index 0c3b28d..d4cacd2 100644 --- a/apps/web/src/features/auth/authApi.test.ts +++ b/apps/web/src/features/auth/authApi.test.ts @@ -1,5 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { getCurrentUser, loginUser, registerUser } from './authApi'; +import { + getCurrentUser, + loginUser, + registerUser, + signOutUser, +} from './authApi'; afterEach(() => vi.unstubAllGlobals()); const requests = [ @@ -8,6 +13,21 @@ const requests = [ ]; describe('authentication API errors', () => { + it('uses browser credentials and sends no session-token variables', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(Response.json({ data: { currentUser: null } })) + .mockResolvedValueOnce(Response.json({ data: { signOut: true } })); + vi.stubGlobal('fetch', fetch); + await getCurrentUser(); + await signOutUser(); + for (const [, options] of fetch.mock.calls) { + expect(options.credentials).toBe('same-origin'); + expect(options.headers['X-Requested-With']).toBe('recipe-platform'); + expect(JSON.parse(options.body).variables).toEqual({}); + expect(options.body).not.toContain('sessionToken'); + } + }); it.each(requests)('translates network failures', async (request) => { vi.stubGlobal( 'fetch', @@ -82,6 +102,6 @@ describe('authentication API errors', () => { }), ), ); - await expect(getCurrentUser('session-123')).rejects.toThrow(); + await expect(getCurrentUser()).rejects.toThrow(); }); }); diff --git a/apps/web/src/features/auth/authApi.ts b/apps/web/src/features/auth/authApi.ts index f644834..6e8b431 100644 --- a/apps/web/src/features/auth/authApi.ts +++ b/apps/web/src/features/auth/authApi.ts @@ -28,7 +28,11 @@ async function graphqlRequest( try { response = await fetch(GRAPHQL_URL, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + }, + credentials: 'same-origin', body: JSON.stringify({ query: print(document), variables }), }); } catch { @@ -61,10 +65,9 @@ export async function registerUser( export async function loginUser(email: string, password: string) { return (await graphqlRequest(LoginDocument, { email, password })).login; } -export async function getCurrentUser(sessionToken: string) { - return (await graphqlRequest(CurrentUserDocument, { sessionToken })) - .currentUser; +export async function getCurrentUser() { + return (await graphqlRequest(CurrentUserDocument, {})).currentUser; } -export async function signOutUser(sessionToken: string) { - return (await graphqlRequest(SignOutDocument, { sessionToken })).signOut; +export async function signOutUser() { + return (await graphqlRequest(SignOutDocument, {})).signOut; } diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 66613e6..5b5a12f 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -1,119 +1,68 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; - import { getCurrentUser, loginUser, signOutUser, } from './features/auth/authApi'; import { useAppStore } from './store'; - vi.mock('./features/auth/authApi', () => ({ loginUser: vi.fn(), registerUser: vi.fn(), getCurrentUser: vi.fn(), signOutUser: vi.fn(), })); - -const authenticatedUser = { - id: 'user-123', - name: 'Hasan', - email: 'hasan@example.com', -}; - -const SESSION_TOKEN_KEY = 'recipe-platform-session-token'; - -describe('authentication store', () => { - beforeEach(() => { - vi.clearAllMocks(); - localStorage.clear(); - - useAppStore.setState({ - search: '', - currentUser: null, - sessionStatus: 'restoring', - }); - }); - - it('restores the current user from a stored session', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - - vi.mocked(getCurrentUser).mockResolvedValue(authenticatedUser); - +const user = { id: 'user-123', name: 'Hasan', email: 'hasan@example.com' }; +const legacyKey = 'recipe-platform-session-token'; +beforeEach(() => { + vi.resetAllMocks(); + localStorage.clear(); + useAppStore.setState({ currentUser: null, sessionStatus: 'restoring' }); +}); +describe('cookie authentication store', () => { + it('restores through the browser cookie without reading a token', async () => { + localStorage.setItem(legacyKey, 'old-token'); + vi.mocked(getCurrentUser).mockResolvedValue(user); await useAppStore.getState().restoreSession(); - - expect(getCurrentUser).toHaveBeenCalledWith('session-123'); - - expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe('session-123'); + expect(getCurrentUser).toHaveBeenCalledWith(); + expect(useAppStore.getState().currentUser).toEqual(user); + expect(localStorage.getItem(legacyKey)).toBeNull(); }); - - it('removes an invalid session', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'expired-session'); - + it('becomes anonymous when the cookie is absent or expired', async () => { vi.mocked(getCurrentUser).mockResolvedValue(null); - await useAppStore.getState().restoreSession(); - - expect(useAppStore.getState().currentUser).toBeNull(); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); + expect(useAppStore.getState().sessionStatus).toBe('anonymous'); }); - - it.each(['Network error', 'API unavailable'])( - 'keeps the token after %s and restores on retry', - async (message) => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - vi.mocked(getCurrentUser).mockRejectedValueOnce(new Error(message)); - await useAppStore.getState().restoreSession(); - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe('session-123'); - expect(useAppStore.getState().currentUser).toBeNull(); - vi.mocked(getCurrentUser).mockResolvedValueOnce(authenticatedUser); - await useAppStore.getState().restoreSession(); - expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); - }, - ); - - it('signs out and removes the session', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - - useAppStore.setState({ - currentUser: authenticatedUser, - }); - + it('can retry cookie restoration after a network error', async () => { + vi.mocked(getCurrentUser).mockRejectedValueOnce(new Error('Offline')); + await useAppStore.getState().restoreSession(); + expect(useAppStore.getState().sessionStatus).toBe('error'); + vi.mocked(getCurrentUser).mockResolvedValueOnce(user); + await useAppStore.getState().restoreSession(); + expect(useAppStore.getState().currentUser).toEqual(user); + }); + it('logs in without storing session credentials', async () => { + vi.mocked(loginUser).mockResolvedValue({ user }); + await useAppStore.getState().login(user.email, 'secret'); + expect(useAppStore.getState().currentUser).toEqual(user); + expect(localStorage.length).toBe(0); + }); + it('waits for server logout before clearing authentication', async () => { + useAppStore.setState({ currentUser: user, sessionStatus: 'authenticated' }); vi.mocked(signOutUser).mockResolvedValue(true); - await useAppStore.getState().signOut(); - - expect(signOutUser).toHaveBeenCalledWith('session-123'); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); - - expect(useAppStore.getState().currentUser).toBeNull(); + expect(signOutUser).toHaveBeenCalledWith(); + expect(useAppStore.getState().sessionStatus).toBe('anonymous'); }); - - it('clears local authentication even when sign-out fails', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - - useAppStore.setState({ - currentUser: authenticatedUser, - }); - - vi.mocked(signOutUser).mockRejectedValue(new Error('Network error')); - - await expect(useAppStore.getState().signOut()).rejects.toThrow( - 'Network error', - ); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); - - expect(useAppStore.getState().currentUser).toBeNull(); + it('does not claim logout succeeded when the server is unavailable', async () => { + useAppStore.setState({ currentUser: user, sessionStatus: 'authenticated' }); + vi.mocked(signOutUser).mockRejectedValue(new Error('Offline')); + await expect(useAppStore.getState().signOut()).rejects.toThrow('Offline'); + expect(useAppStore.getState().currentUser).toEqual(user); }); it.each(['login', 'signOut'] as const)( - 'ignores restoration that finishes after %s', + 'ignores stale restoration after %s', async (action) => { - localStorage.setItem(SESSION_TOKEN_KEY, 'old-token'); - let resolve!: (value: typeof authenticatedUser | null) => void; + let resolve!: (value: typeof user | null) => void; vi.mocked(getCurrentUser).mockReturnValueOnce( new Promise((done) => { resolve = done; @@ -121,28 +70,17 @@ describe('authentication store', () => { ); const restoration = useAppStore.getState().restoreSession(); if (action === 'login') { - vi.mocked(loginUser).mockResolvedValueOnce({ - user: authenticatedUser, - sessionToken: 'new-token', - }); - await useAppStore - .getState() - .login(authenticatedUser.email, 'secret123'); + vi.mocked(loginUser).mockResolvedValueOnce({ user }); + await useAppStore.getState().login(user.email, 'secret'); resolve(null); } else { vi.mocked(signOutUser).mockResolvedValueOnce(true); await useAppStore.getState().signOut(); - resolve(authenticatedUser); + resolve(user); } await restoration; - expect(useAppStore.getState().sessionStatus).toBe( - action === 'login' ? 'authenticated' : 'anonymous', - ); expect(useAppStore.getState().currentUser).toEqual( - action === 'login' ? authenticatedUser : null, - ); - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe( - action === 'login' ? 'new-token' : null, + action === 'login' ? user : null, ); }, ); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 11a1607..6213b77 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -18,7 +18,8 @@ export type SessionStatus = | 'anonymous' | 'error'; -const SESSION_TOKEN_KEY = 'recipe-platform-session-token'; +// Remove credentials left by the old token-based client during migration. +const LEGACY_TOKEN_KEY = 'recipe-platform-session-token'; export const INITIAL_SAVED_RECIPE_IDS = recipes .filter((recipe) => recipe.isSaved) @@ -59,7 +60,7 @@ export const useAppStore = create((set) => ({ const result = await loginUser(email, password); authVersion += 1; - localStorage.setItem(SESSION_TOKEN_KEY, result.sessionToken); + localStorage.removeItem(LEGACY_TOKEN_KEY); set({ currentUser: result.user, @@ -71,7 +72,7 @@ export const useAppStore = create((set) => ({ const result = await registerUser(name, email, password); authVersion += 1; - localStorage.setItem(SESSION_TOKEN_KEY, result.sessionToken); + localStorage.removeItem(LEGACY_TOKEN_KEY); set({ currentUser: result.user, @@ -84,37 +85,27 @@ export const useAppStore = create((set) => ({ set({ currentUser: null, sessionStatus: 'restoring' }); try { - const sessionToken = localStorage.getItem(SESSION_TOKEN_KEY); - if (!sessionToken) { - set({ currentUser: null, sessionStatus: 'anonymous' }); - return; - } - - const currentUser = await getCurrentUser(sessionToken); + localStorage.removeItem(LEGACY_TOKEN_KEY); + const currentUser = await getCurrentUser(); if (version !== authVersion) return; - if (currentUser === null) { - localStorage.removeItem(SESSION_TOKEN_KEY); - } set({ currentUser, sessionStatus: currentUser ? 'authenticated' : 'anonymous', }); } catch { if (version !== authVersion) return; - // Keep the token for retry, but do not expose protected pages. + // The browser keeps the cookie for retry; protected pages remain hidden. set({ currentUser: null, sessionStatus: 'error' }); } }, signOut: async () => { - const sessionToken = localStorage.getItem(SESSION_TOKEN_KEY); + // Do not claim logout succeeded while the server session is still active. + await signOutUser(); authVersion += 1; - localStorage.removeItem(SESSION_TOKEN_KEY); + localStorage.removeItem(LEGACY_TOKEN_KEY); set({ currentUser: null, sessionStatus: 'anonymous' }); - if (sessionToken) { - await signOutUser(sessionToken); - } }, removeUserRating: (recipeId) => diff --git a/contracts/generated.ts b/contracts/generated.ts index 1b57e7e..18828d8 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -29,7 +29,6 @@ export type User = { export type AuthPayload = { __typename?: 'AuthPayload'; user: User; - sessionToken: Scalars['String']['output']; }; export type Query = { @@ -38,10 +37,6 @@ export type Query = { currentUser?: Maybe; }; -export type QueryCurrentUserArgs = { - sessionToken: Scalars['String']['input']; -}; - export type Mutation = { __typename?: 'Mutation'; register: AuthPayload; @@ -60,17 +55,11 @@ export type MutationLoginArgs = { password: Scalars['String']['input']; }; -export type MutationSignOutArgs = { - sessionToken: Scalars['String']['input']; -}; - export type HealthQueryVariables = Exact<{ [key: string]: never }>; export type HealthQuery = { health: string }; -export type SignOutMutationVariables = Exact<{ - sessionToken: string; -}>; +export type SignOutMutationVariables = Exact<{ [key: string]: never }>; export type SignOutMutation = { signOut: boolean }; @@ -81,10 +70,7 @@ export type RegisterMutationVariables = Exact<{ }>; export type RegisterMutation = { - register: { - sessionToken: string; - user: { id: string; name: string; email: string }; - }; + register: { user: { id: string; name: string; email: string } }; }; export type LoginMutationVariables = Exact<{ @@ -93,15 +79,10 @@ export type LoginMutationVariables = Exact<{ }>; export type LoginMutation = { - login: { - sessionToken: string; - user: { id: string; name: string; email: string }; - }; + login: { user: { id: string; name: string; email: string } }; }; -export type CurrentUserQueryVariables = Exact<{ - sessionToken: string; -}>; +export type CurrentUserQueryVariables = Exact<{ [key: string]: never }>; export type CurrentUserQuery = { currentUser: { id: string; name: string; email: string } | null; @@ -130,39 +111,10 @@ export const SignOutDocument = { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'SignOut' }, - variableDefinitions: [ - { - kind: 'VariableDefinition', - variable: { - kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, - }, - type: { - kind: 'NonNullType', - type: { - kind: 'NamedType', - name: { kind: 'Name', value: 'String' }, - }, - }, - }, - ], selectionSet: { kind: 'SelectionSet', selections: [ - { - kind: 'Field', - name: { kind: 'Name', value: 'signOut' }, - arguments: [ - { - kind: 'Argument', - name: { kind: 'Name', value: 'sessionToken' }, - value: { - kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, - }, - }, - ], - }, + { kind: 'Field', name: { kind: 'Name', value: 'signOut' } }, ], }, }, @@ -251,10 +203,6 @@ export const RegisterDocument = { selectionSet: { kind: 'SelectionSet', selections: [ - { - kind: 'Field', - name: { kind: 'Name', value: 'sessionToken' }, - }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, @@ -339,10 +287,6 @@ export const LoginDocument = { selectionSet: { kind: 'SelectionSet', selections: [ - { - kind: 'Field', - name: { kind: 'Name', value: 'sessionToken' }, - }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, @@ -370,38 +314,12 @@ export const CurrentUserDocument = { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'CurrentUser' }, - variableDefinitions: [ - { - kind: 'VariableDefinition', - variable: { - kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, - }, - type: { - kind: 'NonNullType', - type: { - kind: 'NamedType', - name: { kind: 'Name', value: 'String' }, - }, - }, - }, - ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'currentUser' }, - arguments: [ - { - kind: 'Argument', - name: { kind: 'Name', value: 'sessionToken' }, - value: { - kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, - }, - }, - ], selectionSet: { kind: 'SelectionSet', selections: [ diff --git a/contracts/operations.graphql b/contracts/operations.graphql index 83853e7..06ef45b 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -2,13 +2,12 @@ query Health { health } -mutation SignOut($sessionToken: String!) { - signOut(sessionToken: $sessionToken) +mutation SignOut { + signOut } mutation Register($name: String!, $email: String!, $password: String!) { register(name: $name, email: $email, password: $password) { - sessionToken user { id name @@ -19,7 +18,6 @@ mutation Register($name: String!, $email: String!, $password: String!) { mutation Login($email: String!, $password: String!) { login(email: $email, password: $password) { - sessionToken user { id name @@ -28,8 +26,8 @@ mutation Login($email: String!, $password: String!) { } } -query CurrentUser($sessionToken: String!) { - currentUser(sessionToken: $sessionToken) { +query CurrentUser { + currentUser { id name email diff --git a/docs/auth-improvements.md b/docs/auth-improvements.md index 2b053d4..2534f9b 100644 --- a/docs/auth-improvements.md +++ b/docs/auth-improvements.md @@ -1,6 +1,7 @@ # Auth-forbedringer -Dette er en avgrenset auth-endring. CRUD-arbeid og cookie-overgang er egne steg. +Dette er en avgrenset auth-endring. Cookie/context-migreringen er inkludert; +CRUD-arbeid er et eget steg. ## Delt validering @@ -14,8 +15,9 @@ Backend validerer alltid på nytt, uavhengig av hva klienten sender. - Registreringspassord er 6–128 tegn. Passord trimmes aldri. - Login krever et ikke-tomt passord, uten registreringens lengdekrav. Bekreftelsesfeltet finnes bare i frontendens registreringsskjema. -- Sesjons-ID må være en UUID før databaseoppslag eller logout-sletting. - Ugyldig ID gir `null` fra currentUser og `false` fra signOut. +- Sesjons-ID i cookien må være en UUID før databaseoppslag eller logout-sletting. + Ugyldig cookie gir `null` fra currentUser og slettes. SignOut er idempotent: + også en allerede utlogget bruker får `true` og en slettet cookie. - Sesjonsoppslag krever fortsatt `expires_at > now()`. ## Feilkoder og klientkontrakt @@ -28,8 +30,14 @@ fra backend. Uventede feil og HTML/ugyldig JSON gir en generell feilmelding. Auth-klienten bruker de genererte Register, Login, CurrentUser og SignOut- dokumentene fra `contracts/generated.ts`. Endre operasjonene i `contracts/operations.graphql` og kjør `npm run types:api` ved kontraktendringer. -Eksisterende tokenargumenter, localStorage, sesjonsgjenoppretting og beskyttede -ruter beholdes. Ingen databasemigrasjon er nødvendig. +AuthPayload returnerer bare brukerdata. `currentUser` og `signOut` har ingen +tokenargumenter. Backend setter en host-only cookie med HttpOnly, SameSite=Lax, +Path=/ og Max-Age=604800. GraphQL-context validerer cookien og henter brukeren +fra en ikke-utløpt sesjon. Ugyldig/utløpt cookie slettes; databasefeil beholder +cookien for retry. Logout tilbakekaller sesjonen før cookien slettes med samme +Path og Max-Age=0. Klienten rydder gamle localStorage-tokens og sender +`credentials: same-origin`. Eksisterende brukere må logge inn igjen. +Ingen databasemigrasjon er nødvendig. ## Enkel rate limiting @@ -68,10 +76,22 @@ rate-limit-vindu og proxy-headerhåndtering. GraphQL-testene kjører det faktisk Yoga-endepunktet med et kontrollert repository; de bruker ikke live-databasen. Frontendtestene dekker sesjonsgjenoppretting og beskyttede ruter. -HttpOnly-cookie og HTTPS gjenstår. Token i localStorage kan leses av JavaScript -på samme origin. Denne endringen fjerner ikke XSS- eller HTTP-transport-risikoen. -Det må verifiseres på VM at Apache videresender klient-IP som forventet og at -login/register/refresh/logout fungerer etter deploy. +HTTPS gjenstår. Sett `AUTH_COOKIE_SECURE=true` når HTTPS er konfigurert; behold +false for localhost og dagens NTNU HTTP-oppsett. Flagget bygger ikke på en +klientstyrt X-Forwarded-Proto-header. HttpOnly hindrer direkte lesing av cookien, +men XSS kan fortsatt utføre handlinger fra samme origin. HTTP beskytter ikke +passord eller token under overføring. + +POST krever application/json og `X-Requested-With: recipe-platform`. +`cors: false` hindrer cross-origin preflight, og en HTML-form kan ikke sette +den påkrevde headeren. GraphiQL bruker samme header. Yoga avviser GET-mutasjoner. +`Cache-Control: no-store` hindrer caching av brukeravhengige responser. + +Cookie-testene dekker login/register, context-restoration, logout, ugyldige og +utløpte sesjoner, HttpOnly/SameSite/Path/Max-Age/Secure og avvist enkel POST. +Nettlesertesten bruker ekte Yoga HTTP/cookies med en kontrollert auth-service +og sjekker document.cookie, refresh og logout. Etter deploy må samme flyt og +Apaches klient-IP-videresending verifiseres på VM. AI er brukt til implementasjon, testutforming og gjennomgang. Endringene skal vurderes i PR før sammenslåing. diff --git a/e2e/auth-cookie.spec.ts b/e2e/auth-cookie.spec.ts new file mode 100644 index 0000000..05703fb --- /dev/null +++ b/e2e/auth-cookie.spec.ts @@ -0,0 +1,87 @@ +import { createServer, type Server } from 'node:http'; +import { randomUUID } from 'node:crypto'; +import { expect, test } from '@playwright/test'; +import { createApp } from '../apps/api/src/app.js'; +import type { AuthService } from '../apps/api/src/features/auth/authService.js'; + +let server: Server; +let endpoint: string; +const sessions = new Set(); +const user = { + id: '22222222-2222-4222-8222-222222222222', + name: 'Cookie User', + email: 'cookie@example.com', +}; +test.beforeAll(async () => { + const login = async () => { + const sessionToken = randomUUID(); + sessions.add(sessionToken); + return { user, sessionToken }; + }; + const service: AuthService = { + login, + register: login, + currentUser: async (token) => (sessions.has(token) ? user : null), + signOut: async (token) => sessions.delete(token), + }; + server = createServer(createApp(service, false, false)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') + throw new Error('Missing test server address.'); + endpoint = `http://127.0.0.1:${address.port}/graphql`; +}); +test.afterAll(async () => { + if (server) + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); +}); +test('login uses an HttpOnly cookie, survives refresh and revokes logout', async ({ + page, + context, +}) => { + // Proxy to the real Yoga HTTP endpoint with a deterministic service, no live DB. + await page.route('**/project2/api/graphql', async (route) => { + const response = await route.fetch({ url: endpoint }); + await route.fulfill({ response }); + }); + await page.goto('cookbook'); + await expect(page).toHaveURL(/\/login$/); + await page.getByLabel(/^Email/).fill(user.email); + await page.getByLabel(/^Password/).fill('secret123'); + await page.getByRole('button', { name: 'Log in', exact: true }).click(); + await expect( + page.getByRole('heading', { name: 'My Cookbook' }), + ).toBeVisible(); + const cookie = (await context.cookies()).find( + (cookie) => cookie.name === 't31_project2_session', + ); + expect(cookie).toBeDefined(); + expect(cookie?.httpOnly).toBe(true); + expect(cookie?.sameSite).toBe('Lax'); + expect(cookie?.path).toBe('/'); + expect(await page.evaluate(() => document.cookie)).not.toContain( + 't31_project2_session', + ); + expect( + await page.evaluate(() => + localStorage.getItem('recipe-platform-session-token'), + ), + ).toBeNull(); + await page.reload(); + await expect( + page.getByRole('heading', { name: 'My Cookbook' }), + ).toBeVisible(); + await page.getByRole('button', { name: 'Sign out' }).click(); + await expect + .poll(async () => + (await context.cookies()).some( + (cookie) => cookie.name === 't31_project2_session', + ), + ) + .toBe(false); + expect(sessions.has(cookie!.value)).toBe(false); + await page.goto('cookbook'); + await expect(page).toHaveURL(/\/login$/); +}); diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index 2a6e477..08ba89a 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -1,5 +1,15 @@ import { expect, test } from '@playwright/test'; +// Shell tests run against a static preview, without a backend/database. +test.beforeEach(async ({ page }) => { + await page.route('**/project2/api/graphql', async (route) => { + const body = route.request().postDataJSON() as { query?: string }; + if (body.query?.includes('currentUser')) { + await route.fulfill({ json: { data: { currentUser: null } } }); + } else await route.continue(); + }); +}); + const coreRoutes = [ ['/', 'Explore'], ['/recipes/salmon-pasta', 'Creamy salmon pasta'], From ac7cc2fec8a8c743722e672068d05aaae0e07728 Mon Sep 17 00:00:00 2001 From: Hasan Mohammad Fawzi Date: Mon, 19 Oct 2026 00:37:08 +0200 Subject: [PATCH 2/4] feat(api): add recipe CRUD with cookie-based authentication --- README.md | 3 + apps/api/src/app.ts | 10 + apps/api/src/db/seed.ts | 10 + apps/api/src/db/seedData.ts | 61 + apps/api/src/features/auth/authRepository.ts | 17 +- .../src/features/recipes/recipeRepository.ts | 217 +++ .../src/features/recipes/recipeResolvers.ts | 61 + .../features/recipes/recipeValidation.test.ts | 49 + .../src/features/recipes/recipeValidation.ts | 99 ++ apps/api/src/generated.ts | 307 ++++ apps/api/src/schema.graphql | 87 ++ contracts/generated.ts | 1371 ++++++++++++++++- contracts/operations.graphql | 88 ++ docs/recipe-api.md | 120 ++ package.json | 6 +- scripts/generate-api.ts | 3 +- scripts/test-recipe-api.ts | 530 +++++++ scripts/tsconfig.json | 10 + 18 files changed, 2998 insertions(+), 51 deletions(-) create mode 100644 apps/api/src/db/seed.ts create mode 100644 apps/api/src/db/seedData.ts create mode 100644 apps/api/src/features/recipes/recipeRepository.ts create mode 100644 apps/api/src/features/recipes/recipeResolvers.ts create mode 100644 apps/api/src/features/recipes/recipeValidation.test.ts create mode 100644 apps/api/src/features/recipes/recipeValidation.ts create mode 100644 docs/recipe-api.md create mode 100644 scripts/test-recipe-api.ts create mode 100644 scripts/tsconfig.json diff --git a/README.md b/README.md index f197e0d..af57e27 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,9 @@ feilkoder, genererte klientoperasjoner og rate limiting bak Apache. ## Database +Se [Recipe API og Delivery 2-status](docs/recipe-api.md) for CRUD-kontrakter, +Bearer-autentisering, Zod-validering, seed og API-integrasjonstester. + Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen utvider autentiseringen og er klar for CRUD i neste steg. ## Nyttige kommandoer diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 3b48a0b..0cff506 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,3 +1,7 @@ +import type { Pool } from 'pg'; +import { db } from './db/client.js'; +import { createRecipeRepository } from './features/recipes/recipeRepository.js'; +import { createRecipeResolvers } from './features/recipes/recipeResolvers.js'; import { readFileSync } from 'node:fs'; import { createSchema, createYoga } from 'graphql-yoga'; @@ -19,8 +23,12 @@ export function createApp( service: AuthService = authService, trustProxy = process.env.AUTH_TRUST_PROXY === 'true', secureCookie = process.env.AUTH_COOKIE_SECURE === 'true', + database: { pool?: Pool; schema?: string } = {}, ) { const authResolvers = createAuthResolvers(service); + const recipes = createRecipeResolvers( + createRecipeRepository(database.pool ?? db, database.schema ?? 'project2'), + ); const cookies = new WeakMap(); return createYoga<{ req?: IncomingMessage }, AuthContext>({ cors: false, @@ -93,9 +101,11 @@ export function createApp( Query: { health: () => 'ok', ...authResolvers.Query, + ...recipes.Query, }, Mutation: { ...authResolvers.Mutation, + ...recipes.Mutation, }, } satisfies Resolvers, }), diff --git a/apps/api/src/db/seed.ts b/apps/api/src/db/seed.ts new file mode 100644 index 0000000..3c58e23 --- /dev/null +++ b/apps/api/src/db/seed.ts @@ -0,0 +1,10 @@ +import { db } from './client.js'; +import { seedDatabase } from './seedData.js'; +try { + await seedDatabase(db, process.env.SEED_PASSWORD); + console.log( + 'Demo data ready. Existing seed rows and passwords were not overwritten.', + ); +} finally { + await db.end(); +} diff --git a/apps/api/src/db/seedData.ts b/apps/api/src/db/seedData.ts new file mode 100644 index 0000000..42554bd --- /dev/null +++ b/apps/api/src/db/seedData.ts @@ -0,0 +1,61 @@ +import { hash } from 'argon2'; +import type { Pool } from 'pg'; + +// Explicit opt-in demo data; never run automatically during deploy. +const authorId = '11111111-1111-4111-8111-111111111111'; +export async function seedDatabase( + pool: Pool, + password: string | undefined, + schema = 'project2', +) { + if (!/^[a-z_][a-z0-9_]*$/.test(schema)) + throw new Error('Invalid database schema.'); + if (!password || password.length < 12) { + throw new Error( + 'Set SEED_PASSWORD (at least 12 characters) before running db:seed.', + ); + } + const passwordHash = await hash(password); + const client = await pool.connect(); + try { + await client.query('BEGIN'); + await client.query( + `INSERT INTO ${schema}.users (id,name,email,password_hash) + VALUES ($1,'Demo Cook','demo@example.invalid',$2) ON CONFLICT (id) DO NOTHING`, + [authorId, passwordHash], + ); + for (const [id, title, visibility] of [ + ['22222222-2222-4222-8222-222222222222', 'Demo vegetable soup', 'public'], + ['33333333-3333-4333-8333-333333333333', 'Demo private soup', 'private'], + ]) { + const inserted = await client.query( + `INSERT INTO ${schema}.recipes + (id,author_id,title,description,category,difficulty,visibility,prep_minutes,cook_minutes,servings) + VALUES ($1,$2,$3,'Simple demonstration recipe','soup','easy',$4,5,15,2) + ON CONFLICT (id) DO NOTHING RETURNING id`, + [id, authorId, title, visibility], + ); + if (!inserted.rowCount) continue; + await client.query( + `INSERT INTO ${schema}.recipe_ingredients (recipe_id,name,amount,unit,position) + VALUES ($1,'Water',500,'ml',1),($1,'Carrots',2,'',2)`, + [id], + ); + await client.query( + `INSERT INTO ${schema}.recipe_instructions (recipe_id,text,position) + VALUES ($1,'Chop the carrots.',1),($1,'Simmer in water until tender.',2)`, + [id], + ); + await client.query( + `INSERT INTO ${schema}.recipe_tags (recipe_id,tag) VALUES ($1,'demo')`, + [id], + ); + } + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } +} diff --git a/apps/api/src/features/auth/authRepository.ts b/apps/api/src/features/auth/authRepository.ts index 61f1327..18fe834 100644 --- a/apps/api/src/features/auth/authRepository.ts +++ b/apps/api/src/features/auth/authRepository.ts @@ -56,13 +56,16 @@ export interface AuthRepository { export function createAuthRepository( pool: Pool = db, executor: Pick = pool, + schema = 'project2', ): AuthRepository { + if (!/^[a-z_][a-z0-9_]*$/.test(schema)) + throw new Error('Invalid database schema.'); return { async findUserByEmail(email) { const result = await executor.query( ` SELECT id, name, email, password_hash - FROM project2.users + FROM ${schema}.users WHERE email = $1 LIMIT 1 `, @@ -86,7 +89,7 @@ export function createAuthRepository( async createUser(name, email, passwordHash) { const result = await executor.query( ` - INSERT INTO project2.users (name, email, password_hash) + INSERT INTO ${schema}.users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email `, @@ -106,7 +109,7 @@ export function createAuthRepository( const client = await pool.connect(); try { await client.query('BEGIN'); - const repository = createAuthRepository(pool, client); + const repository = createAuthRepository(pool, client, schema); const user = await repository.createUser(name, email, passwordHash); const sessionToken = await repository.createSession(user.id, expiresAt); await client.query('COMMIT'); @@ -134,7 +137,7 @@ export function createAuthRepository( async createSession(userId, expiresAt) { const result = await executor.query<{ id: string }>( ` - INSERT INTO project2.sessions (user_id, expires_at) + INSERT INTO ${schema}.sessions (user_id, expires_at) VALUES ($1, $2) RETURNING id `, @@ -155,8 +158,8 @@ export function createAuthRepository( const result = await executor.query( ` SELECT users.id, users.name, users.email - FROM project2.sessions AS sessions - JOIN project2.users AS users + FROM ${schema}.sessions AS sessions + JOIN ${schema}.users AS users ON users.id = sessions.user_id WHERE sessions.id = $1 AND sessions.expires_at > now() @@ -172,7 +175,7 @@ export function createAuthRepository( if (!sessionTokenSchema.safeParse(sessionToken).success) return; await executor.query( ` - DELETE FROM project2.sessions + DELETE FROM ${schema}.sessions WHERE id = $1 `, [sessionToken], diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts new file mode 100644 index 0000000..aaea17e --- /dev/null +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -0,0 +1,217 @@ +import { GraphQLError } from 'graphql'; +import type { Pool, PoolClient } from 'pg'; +import { db } from '../../db/client.js'; +import type { Recipe } from '../../generated.js'; +import type { RecipeInput, ListInput } from './recipeValidation.js'; + +export function createRecipeRepository(pool: Pool = db, schema = 'project2') { + if (!/^[a-z_][a-z0-9_]*$/.test(schema)) + throw new Error('Invalid database schema.'); + const t = (name: string) => `"${schema}"."${name}"`; + // One read includes ordered children and derived values; no per-recipe queries. + const select = `SELECT r.id, r.title, r.description, r.category, r.cuisine, + r.difficulty, r.visibility, r.image_url AS "imageUrl", r.source_recipe_id AS "sourceRecipeId", + r.prep_minutes AS "prepMinutes", r.cook_minutes AS "cookMinutes", r.servings, + to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "createdAt", + to_char(r.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt", + json_build_object('id',u.id,'name',u.name) AS author, + coalesce(r.author_id = $1::uuid,false) AS "isCreatedByCurrentUser", + EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved", + (SELECT count(*)::int FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount", + (SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating, + coalesce((SELECT json_agg(json_build_object('id',i.id,'name',i.name,'amount',i.amount::float,'unit',i.unit,'note',i.note) ORDER BY i.position) FROM ${t('recipe_ingredients')} i WHERE i.recipe_id=r.id),'[]') AS ingredients, + coalesce((SELECT json_agg(json_build_object('step',i.position,'text',i.text) ORDER BY i.position) FROM ${t('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions, + coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags + FROM ${t('recipes')} r JOIN ${t('users')} u ON u.id=r.author_id`; + + async function transaction(work: (client: PoolClient) => Promise) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const result = await work(client); + await client.query('COMMIT'); + return result; + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } + } + async function read( + executor: Pick, + id: string, + userId: string | null, + ) { + const result = await executor.query( + select + + ` WHERE r.id=$2 AND (r.visibility='public' OR r.author_id=$1::uuid)`, + [userId, id], + ); + return result.rows[0] ?? null; + } + async function readRequired(client: PoolClient, id: string, userId: string) { + const recipe = await read(client, id, userId); + if (!recipe) throw new Error('Recipe could not be read after writing.'); + return recipe; + } + async function owned(client: PoolClient, id: string, userId: string) { + const result = await client.query( + `SELECT id FROM ${t('recipes')} WHERE id=$1 AND author_id=$2 FOR UPDATE`, + [id, userId], + ); + if (!result.rowCount) + throw new GraphQLError('Recipe not found or not owned by you.', { + extensions: { code: 'NOT_FOUND' }, + }); + } + async function children(client: PoolClient, id: string, input: RecipeInput) { + for (const [index, ingredient] of input.ingredients.entries()) { + await client.query( + `INSERT INTO ${t('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) VALUES ($1,$2,$3,$4,$5,$6)`, + [ + id, + ingredient.name, + ingredient.amount, + ingredient.unit, + ingredient.note, + index + 1, + ], + ); + } + for (const [index, instruction] of input.instructions.entries()) + await client.query( + `INSERT INTO ${t('recipe_instructions')} (recipe_id,text,position) VALUES ($1,$2,$3)`, + [id, instruction, index + 1], + ); + for (const tag of input.tags) + await client.query( + `INSERT INTO ${t('recipe_tags')} (recipe_id,tag) VALUES ($1,$2)`, + [id, tag], + ); + } + const values = (input: RecipeInput) => [ + input.title, + input.description, + input.imageUrl, + input.category, + input.cuisine, + input.difficulty, + input.visibility, + input.prepMinutes, + input.cookMinutes, + input.servings, + ]; + return { + get: (id: string, userId: string | null) => read(pool, id, userId), + async list( + input: ListInput, + userId: string | null, + scope: 'explore' | 'all' | 'saved' | 'created' = 'explore', + ) { + const access = + scope === 'explore' + ? `r.visibility='public'` + : `(r.visibility='public' OR r.author_id=$1::uuid) AND (` + + (scope === 'created' + ? 'r.author_id=$1::uuid' + : scope === 'saved' + ? `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)` + : `r.author_id=$1::uuid OR EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`) + + ')'; + const where = ` WHERE ${access} AND ($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0) AND ($3::text IS NULL OR r.category=$3) AND ($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)`; + const args = [ + userId, + input.search, + input.category ?? null, + input.maxCookingMinutes ?? null, + ]; + // Count and rows share a snapshot, including when another request creates/deletes recipes. + return transaction(async (client) => { + await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'); + const count = await client.query<{ total: number }>( + `SELECT count(*)::int AS total, $1::uuid AS "viewerId" FROM ${t('recipes')} r` + + where, + args, + ); + const totalCount = count.rows[0]!.total; + const totalPages = Math.ceil(totalCount / input.pageSize); + const page = Math.min(input.page, Math.max(totalPages, 1)); + const rows = await client.query( + select + + where + + ' ORDER BY r.created_at DESC,r.id DESC LIMIT $5 OFFSET $6', + [...args, input.pageSize, (page - 1) * input.pageSize], + ); + return { + items: rows.rows, + totalCount, + totalPages, + page, + pageSize: input.pageSize, + }; + }); + }, + async create(input: RecipeInput, userId: string) { + return transaction(async (client) => { + const result = await client.query<{ id: string }>( + `INSERT INTO ${t('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`, + [...values(input), userId], + ); + const id = result.rows[0]!.id; + await children(client, id, input); + return readRequired(client, id, userId); + }); + }, + async update(id: string, input: RecipeInput, userId: string) { + return transaction(async (client) => { + await owned(client, id, userId); + await client.query( + `UPDATE ${t('recipes')} SET title=$1,description=$2,image_url=$3,category=$4,cuisine=$5,difficulty=$6,visibility=$7,prep_minutes=$8,cook_minutes=$9,servings=$10 WHERE id=$11`, + [...values(input), id], + ); + for (const name of [ + 'recipe_ingredients', + 'recipe_instructions', + 'recipe_tags', + ]) + await client.query(`DELETE FROM ${t(name)} WHERE recipe_id=$1`, [id]); + await children(client, id, input); + return readRequired(client, id, userId); + }); + }, + async delete(id: string, userId: string) { + return transaction(async (client) => { + await owned(client, id, userId); + await client.query(`DELETE FROM ${t('recipes')} WHERE id=$1`, [id]); + return true; + }); + }, + async save(id: string, userId: string) { + return transaction(async (client) => { + const result = await client.query( + `SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`, + [id, userId], + ); + if (!result.rowCount) + throw new GraphQLError( + 'Only public recipes by other users can be saved.', + { extensions: { code: 'FORBIDDEN' } }, + ); + await client.query( + `INSERT INTO ${t('saved_recipes')} (user_id,recipe_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`, + [userId, id], + ); + return readRequired(client, id, userId); + }); + }, + async unsave(id: string, userId: string) { + await pool.query( + `DELETE FROM ${t('saved_recipes')} WHERE user_id=$1 AND recipe_id=$2`, + [userId, id], + ); + return true; + }, + }; +} +export type RecipeRepository = ReturnType; diff --git a/apps/api/src/features/recipes/recipeResolvers.ts b/apps/api/src/features/recipes/recipeResolvers.ts new file mode 100644 index 0000000..f45e485 --- /dev/null +++ b/apps/api/src/features/recipes/recipeResolvers.ts @@ -0,0 +1,61 @@ +import { GraphQLError } from 'graphql'; +import { z } from 'zod'; +import type { AuthContext as ApiContext } from '../auth/authResolvers.js'; +import type { Resolvers } from '../../generated.js'; +import type { RecipeRepository } from './recipeRepository.js'; +import { + listInputSchema, + recipeId, + recipeInputSchema, + validate, +} from './recipeValidation.js'; + +function requireUser(context: ApiContext) { + if (!context.user) + throw new GraphQLError('Please log in.', { + extensions: { code: 'UNAUTHENTICATED' }, + }); + return context.user.id; +} +export function createRecipeResolvers(repository: RecipeRepository) { + return { + Query: { + recipes: (_parent, args, context) => + repository.list( + validate(listInputSchema, args.input ?? {}), + context.user?.id ?? null, + ), + recipe: (_parent, args, context) => + repository.get(recipeId(args.id), context.user?.id ?? null), + cookbook: (_parent, args, context) => + repository.list( + validate(listInputSchema, args.input ?? {}), + requireUser(context), + validate(z.enum(['all', 'saved', 'created']), args.scope ?? 'all'), + ), + }, + Mutation: { + createRecipe: (_parent, args, context) => { + const userId = requireUser(context); + return repository.create( + validate(recipeInputSchema, args.input), + userId, + ); + }, + updateRecipe: (_parent, args, context) => { + const userId = requireUser(context); + return repository.update( + recipeId(args.id), + validate(recipeInputSchema, args.input), + userId, + ); + }, + deleteRecipe: (_parent, args, context) => + repository.delete(recipeId(args.id), requireUser(context)), + saveRecipe: (_parent, args, context) => + repository.save(recipeId(args.id), requireUser(context)), + unsaveRecipe: (_parent, args, context) => + repository.unsave(recipeId(args.id), requireUser(context)), + }, + } satisfies Pick, 'Query' | 'Mutation'>; +} diff --git a/apps/api/src/features/recipes/recipeValidation.test.ts b/apps/api/src/features/recipes/recipeValidation.test.ts new file mode 100644 index 0000000..9825a7c --- /dev/null +++ b/apps/api/src/features/recipes/recipeValidation.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest'; +import { + listInputSchema, + recipeInputSchema, + validate, +} from './recipeValidation.js'; + +const input = { + title: ' Soup ', + description: '', + category: 'soup', + difficulty: 'easy', + visibility: 'private', + prepMinutes: 0, + cookMinutes: 10, + servings: 2, + ingredients: [{ name: ' Salt ', amount: 0.125, unit: '', note: null }], + instructions: [' Stir '], + tags: [' Quick ', 'quick'], +}; +describe('recipe validation', () => { + it('normalizes text and tags while allowing optional cuisine and image', () => { + const result = validate(recipeInputSchema, input); + expect(result.title).toBe('Soup'); + expect(result.cuisine).toBeNull(); + expect(result.imageUrl).toBeNull(); + expect(result.tags).toEqual(['quick']); + expect(result.instructions).toEqual(['Stir']); + }); + it.each([ + { ...input, category: 'Soup' }, + { ...input, servings: 1.5 }, + { ...input, ingredients: [] }, + { ...input, instructions: [' '] }, + { ...input, imageUrl: 'javascript:alert(1)' }, + { ...input, ingredients: [{ name: 'Salt', amount: 0.00001, unit: '' }] }, + { ...input, ingredients: [{ name: 'Salt', amount: Infinity, unit: '' }] }, + ])('rejects input the database or UI cannot represent', (value) => { + expect(() => validate(recipeInputSchema, value)).toThrow(); + }); + it('uses bounded pagination defaults', () => { + expect(validate(listInputSchema, {})).toMatchObject({ + page: 1, + pageSize: 6, + search: '', + }); + expect(() => validate(listInputSchema, { pageSize: 51 })).toThrow(); + }); +}); diff --git a/apps/api/src/features/recipes/recipeValidation.ts b/apps/api/src/features/recipes/recipeValidation.ts new file mode 100644 index 0000000..b98f118 --- /dev/null +++ b/apps/api/src/features/recipes/recipeValidation.ts @@ -0,0 +1,99 @@ +import { GraphQLError } from 'graphql'; +import { z } from 'zod'; + +export const categorySchema = z.enum([ + 'breakfast', + 'lunch', + 'dinner', + 'dessert', + 'soup', +]); +const optionalText = z + .string() + .trim() + .max(200) + .nullish() + .transform((value) => value || null); +export const recipeInputSchema = z.object({ + title: z.string().trim().min(1).max(160), + description: z.string().trim().max(200), + imageUrl: z + .url({ protocol: /^https?$/ }) + .max(2048) + .nullish() + .transform((value) => value ?? null), + category: categorySchema, + cuisine: optionalText, + difficulty: z.enum(['easy', 'medium', 'hard']), + visibility: z.enum(['public', 'private']), + prepMinutes: z.number().int().min(0).max(10080), + cookMinutes: z.number().int().min(0).max(10080), + servings: z.number().int().min(1).max(1000), + ingredients: z + .array( + z.object({ + name: z.string().trim().min(1).max(200), + amount: z + .number() + .positive() + .max(99999999.9999) + .refine( + (value) => Math.round(value * 10000) / 10000 === value, + 'Use at most four decimal places.', + ), + unit: z.string().trim().max(50), + note: optionalText, + }), + ) + .min(1) + .max(100), + instructions: z.array(z.string().trim().min(1).max(5000)).min(1).max(100), + tags: z + .array(z.string().trim().toLowerCase().min(1).max(50)) + .max(30) + .transform((values) => [...new Set(values)]), +}); + +export const listInputSchema = z.object({ + search: z + .string() + .trim() + .max(200) + .nullish() + .transform((value) => value ?? ''), + category: categorySchema.nullish(), + maxCookingMinutes: z.number().int().min(0).max(20160).nullish(), + page: z + .number() + .int() + .min(1) + .max(100000) + .nullish() + .transform((value) => value ?? 1), + pageSize: z + .number() + .int() + .min(1) + .max(50) + .nullish() + .transform((value) => value ?? 6), +}); +export type RecipeInput = z.output; +export type ListInput = z.output; + +export function validate(schema: z.ZodType, input: unknown): T { + const result = schema.safeParse(input); + if (!result.success) { + const issue = result.error.issues[0]!; + throw new GraphQLError( + `${issue.path.join('.') || 'input'}: ${issue.message}`, + { + extensions: { code: 'BAD_USER_INPUT' }, + }, + ); + } + return result.data; +} +export function recipeId(value: unknown) { + return validate(z.uuid(), value); +} diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index ad6d0f0..6add7b5 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -28,17 +28,59 @@ export type AuthPayload = { export type Query = { __typename?: 'Query'; + recipes: RecipePage; + recipe?: Maybe; + cookbook: RecipePage; health: Scalars['String']['output']; currentUser?: Maybe; }; +export type QueryRecipesArgs = { + input?: InputMaybe; +}; + +export type QueryRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type QueryCookbookArgs = { + input?: InputMaybe; + scope?: InputMaybe; +}; + export type Mutation = { __typename?: 'Mutation'; + createRecipe: Recipe; + updateRecipe: Recipe; + deleteRecipe: Scalars['Boolean']['output']; + saveRecipe: Recipe; + unsaveRecipe: Scalars['Boolean']['output']; register: AuthPayload; login: AuthPayload; signOut: Scalars['Boolean']['output']; }; +export type MutationCreateRecipeArgs = { + input: RecipeInput; +}; + +export type MutationUpdateRecipeArgs = { + id: Scalars['ID']['input']; + input: RecipeInput; +}; + +export type MutationDeleteRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type MutationSaveRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type MutationUnsaveRecipeArgs = { + id: Scalars['ID']['input']; +}; + export type MutationRegisterArgs = { name: Scalars['String']['input']; email: Scalars['String']['input']; @@ -50,6 +92,99 @@ export type MutationLoginArgs = { password: Scalars['String']['input']; }; +export type RecipeAuthor = { + __typename?: 'RecipeAuthor'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; +}; + +export type Ingredient = { + __typename?: 'Ingredient'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; + amount: Scalars['Float']['output']; + unit: Scalars['String']['output']; + note?: Maybe; +}; + +export type Instruction = { + __typename?: 'Instruction'; + step: Scalars['Int']['output']; + text: Scalars['String']['output']; +}; + +export type RatingSummary = { + __typename?: 'RatingSummary'; + average: Scalars['Float']['output']; + count: Scalars['Int']['output']; +}; + +export type Recipe = { + __typename?: 'Recipe'; + id: Scalars['ID']['output']; + title: Scalars['String']['output']; + description: Scalars['String']['output']; + category: Scalars['String']['output']; + cuisine?: Maybe; + difficulty: Scalars['String']['output']; + visibility: Scalars['String']['output']; + imageUrl?: Maybe; + sourceRecipeId?: Maybe; + prepMinutes: Scalars['Int']['output']; + cookMinutes: Scalars['Int']['output']; + servings: Scalars['Int']['output']; + createdAt: Scalars['String']['output']; + updatedAt: Scalars['String']['output']; + author: RecipeAuthor; + ingredients: Array; + instructions: Array; + tags: Array; + rating: RatingSummary; + saveCount: Scalars['Int']['output']; + isSaved: Scalars['Boolean']['output']; + isCreatedByCurrentUser: Scalars['Boolean']['output']; +}; + +export type RecipePage = { + __typename?: 'RecipePage'; + items: Array; + totalCount: Scalars['Int']['output']; + totalPages: Scalars['Int']['output']; + page: Scalars['Int']['output']; + pageSize: Scalars['Int']['output']; +}; + +export type RecipeListInput = { + search?: InputMaybe; + category?: InputMaybe; + maxCookingMinutes?: InputMaybe; + page?: InputMaybe; + pageSize?: InputMaybe; +}; + +export type IngredientInput = { + name: Scalars['String']['input']; + amount: Scalars['Float']['input']; + unit: Scalars['String']['input']; + note?: InputMaybe; +}; + +export type RecipeInput = { + title: Scalars['String']['input']; + description: Scalars['String']['input']; + imageUrl?: InputMaybe; + category: Scalars['String']['input']; + cuisine?: InputMaybe; + difficulty: Scalars['String']['input']; + visibility: Scalars['String']['input']; + prepMinutes: Scalars['Int']['input']; + cookMinutes: Scalars['Int']['input']; + servings: Scalars['Int']['input']; + ingredients: Array; + instructions: Array; + tags: Array; +}; + export type ResolverTypeWrapper = Promise | T; export type ResolverWithResolve = { @@ -176,6 +311,17 @@ export type ResolversTypes = { Query: ResolverTypeWrapper>; Mutation: ResolverTypeWrapper>; Boolean: ResolverTypeWrapper; + RecipeAuthor: ResolverTypeWrapper; + Ingredient: ResolverTypeWrapper; + Float: ResolverTypeWrapper; + Instruction: ResolverTypeWrapper; + Int: ResolverTypeWrapper; + RatingSummary: ResolverTypeWrapper; + Recipe: ResolverTypeWrapper; + RecipePage: ResolverTypeWrapper; + RecipeListInput: RecipeListInput; + IngredientInput: IngredientInput; + RecipeInput: RecipeInput; }; /** Mapping between all available schema types and the resolvers parents */ @@ -187,6 +333,17 @@ export type ResolversParentTypes = { Query: Record; Mutation: Record; Boolean: Scalars['Boolean']['output']; + RecipeAuthor: RecipeAuthor; + Ingredient: Ingredient; + Float: Scalars['Float']['output']; + Instruction: Instruction; + Int: Scalars['Int']['output']; + RatingSummary: RatingSummary; + Recipe: Recipe; + RecipePage: RecipePage; + RecipeListInput: RecipeListInput; + IngredientInput: IngredientInput; + RecipeInput: RecipeInput; }; export type UserResolvers< @@ -212,6 +369,24 @@ export type QueryResolvers< ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query'], > = { + recipes?: Resolver< + ResolversTypes['RecipePage'], + ParentType, + ContextType, + Partial + >; + recipe?: Resolver< + Maybe, + ParentType, + ContextType, + RequireFields + >; + cookbook?: Resolver< + ResolversTypes['RecipePage'], + ParentType, + ContextType, + Partial + >; health?: Resolver; currentUser?: Resolver< Maybe, @@ -225,6 +400,36 @@ export type MutationResolvers< ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation'], > = { + createRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + updateRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + deleteRecipe?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; + saveRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + unsaveRecipe?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; register?: Resolver< ResolversTypes['AuthPayload'], ParentType, @@ -240,9 +445,111 @@ export type MutationResolvers< signOut?: Resolver; }; +export type RecipeAuthorResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RecipeAuthor'] = ResolversParentTypes['RecipeAuthor'], +> = { + id?: Resolver; + name?: Resolver; +}; + +export type IngredientResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Ingredient'] = ResolversParentTypes['Ingredient'], +> = { + id?: Resolver; + name?: Resolver; + amount?: Resolver; + unit?: Resolver; + note?: Resolver, ParentType, ContextType>; +}; + +export type InstructionResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Instruction'] = ResolversParentTypes['Instruction'], +> = { + step?: Resolver; + text?: Resolver; +}; + +export type RatingSummaryResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RatingSummary'] = ResolversParentTypes['RatingSummary'], +> = { + average?: Resolver; + count?: Resolver; +}; + +export type RecipeResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Recipe'] = ResolversParentTypes['Recipe'], +> = { + id?: Resolver; + title?: Resolver; + description?: Resolver; + category?: Resolver; + cuisine?: Resolver, ParentType, ContextType>; + difficulty?: Resolver; + visibility?: Resolver; + imageUrl?: Resolver, ParentType, ContextType>; + sourceRecipeId?: Resolver< + Maybe, + ParentType, + ContextType + >; + prepMinutes?: Resolver; + cookMinutes?: Resolver; + servings?: Resolver; + createdAt?: Resolver; + updatedAt?: Resolver; + author?: Resolver; + ingredients?: Resolver< + Array, + ParentType, + ContextType + >; + instructions?: Resolver< + Array, + ParentType, + ContextType + >; + tags?: Resolver, ParentType, ContextType>; + rating?: Resolver; + saveCount?: Resolver; + isSaved?: Resolver; + isCreatedByCurrentUser?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType + >; +}; + +export type RecipePageResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RecipePage'] = ResolversParentTypes['RecipePage'], +> = { + items?: Resolver, ParentType, ContextType>; + totalCount?: Resolver; + totalPages?: Resolver; + page?: Resolver; + pageSize?: Resolver; +}; + export type Resolvers = { User?: UserResolvers; AuthPayload?: AuthPayloadResolvers; Query?: QueryResolvers; Mutation?: MutationResolvers; + RecipeAuthor?: RecipeAuthorResolvers; + Ingredient?: IngredientResolvers; + Instruction?: InstructionResolvers; + RatingSummary?: RatingSummaryResolvers; + Recipe?: RecipeResolvers; + RecipePage?: RecipePageResolvers; }; diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index 436b41f..790067d 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -9,12 +9,99 @@ type AuthPayload { } type Query { + recipes(input: RecipeListInput): RecipePage! + recipe(id: ID!): Recipe + cookbook(input: RecipeListInput, scope: String): RecipePage! health: String! currentUser: User } type Mutation { + createRecipe(input: RecipeInput!): Recipe! + updateRecipe(id: ID!, input: RecipeInput!): Recipe! + deleteRecipe(id: ID!): Boolean! + saveRecipe(id: ID!): Recipe! + unsaveRecipe(id: ID!): Boolean! register(name: String!, email: String!, password: String!): AuthPayload! login(email: String!, password: String!): AuthPayload! signOut: Boolean! } + +type RecipeAuthor { + id: ID! + name: String! +} +type Ingredient { + id: ID! + name: String! + amount: Float! + unit: String! + note: String +} +type Instruction { + step: Int! + text: String! +} +type RatingSummary { + average: Float! + count: Int! +} +type Recipe { + id: ID! + title: String! + description: String! + category: String! + cuisine: String + difficulty: String! + visibility: String! + imageUrl: String + sourceRecipeId: ID + prepMinutes: Int! + cookMinutes: Int! + servings: Int! + createdAt: String! + updatedAt: String! + author: RecipeAuthor! + ingredients: [Ingredient!]! + instructions: [Instruction!]! + tags: [String!]! + rating: RatingSummary! + saveCount: Int! + isSaved: Boolean! + isCreatedByCurrentUser: Boolean! +} +type RecipePage { + items: [Recipe!]! + totalCount: Int! + totalPages: Int! + page: Int! + pageSize: Int! +} +input RecipeListInput { + search: String + category: String + maxCookingMinutes: Int + page: Int + pageSize: Int +} +input IngredientInput { + name: String! + amount: Float! + unit: String! + note: String +} +input RecipeInput { + title: String! + description: String! + imageUrl: String + category: String! + cuisine: String + difficulty: String! + visibility: String! + prepMinutes: Int! + cookMinutes: Int! + servings: Int! + ingredients: [IngredientInput!]! + instructions: [String!]! + tags: [String!]! +} diff --git a/contracts/generated.ts b/contracts/generated.ts index 18828d8..1209f5b 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -8,51 +8,35 @@ export type Incremental = [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never; }; import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; -export type Maybe = T | null; -export type InputMaybe = Maybe; -/** All built-in and custom scalars, mapped to their actual values */ -export type Scalars = { - ID: { input: string; output: string }; - String: { input: string; output: string }; - Boolean: { input: boolean; output: boolean }; - Int: { input: number; output: number }; - Float: { input: number; output: number }; +export type RecipeListInput = { + search?: string | null | undefined; + category?: string | null | undefined; + maxCookingMinutes?: number | null | undefined; + page?: number | null | undefined; + pageSize?: number | null | undefined; }; -export type User = { - __typename?: 'User'; - id: Scalars['ID']['output']; - name: Scalars['String']['output']; - email: Scalars['String']['output']; -}; - -export type AuthPayload = { - __typename?: 'AuthPayload'; - user: User; -}; - -export type Query = { - __typename?: 'Query'; - health: Scalars['String']['output']; - currentUser?: Maybe; -}; - -export type Mutation = { - __typename?: 'Mutation'; - register: AuthPayload; - login: AuthPayload; - signOut: Scalars['Boolean']['output']; -}; - -export type MutationRegisterArgs = { - name: Scalars['String']['input']; - email: Scalars['String']['input']; - password: Scalars['String']['input']; +export type IngredientInput = { + name: string; + amount: number; + unit: string; + note?: string | null | undefined; }; -export type MutationLoginArgs = { - email: Scalars['String']['input']; - password: Scalars['String']['input']; +export type RecipeInput = { + title: string; + description: string; + imageUrl?: string | null | undefined; + category: string; + cuisine?: string | null | undefined; + difficulty: string; + visibility: string; + prepMinutes: number; + cookMinutes: number; + servings: number; + ingredients: Array; + instructions: Array; + tags: Array; }; export type HealthQueryVariables = Exact<{ [key: string]: never }>; @@ -88,6 +72,371 @@ export type CurrentUserQuery = { currentUser: { id: string; name: string; email: string } | null; }; +export type RecipeFieldsFragment = { + id: string; + title: string; + description: string; + category: string; + cuisine: string | null; + difficulty: string; + visibility: string; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; +}; + +export type RecipesQueryVariables = Exact<{ + input?: RecipeListInput | null | undefined; +}>; + +export type RecipesQuery = { + recipes: { + totalCount: number; + totalPages: number; + page: number; + pageSize: number; + items: Array<{ + id: string; + title: string; + description: string; + category: string; + cuisine: string | null; + difficulty: string; + visibility: string; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }>; + }; +}; + +export type RecipeQueryVariables = Exact<{ + id: string | number; +}>; + +export type RecipeQuery = { + recipe: { + id: string; + title: string; + description: string; + category: string; + cuisine: string | null; + difficulty: string; + visibility: string; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + } | null; +}; + +export type CookbookQueryVariables = Exact<{ + input?: RecipeListInput | null | undefined; + scope?: string | null | undefined; +}>; + +export type CookbookQuery = { + cookbook: { + totalCount: number; + totalPages: number; + page: number; + pageSize: number; + items: Array<{ + id: string; + title: string; + description: string; + category: string; + cuisine: string | null; + difficulty: string; + visibility: string; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }>; + }; +}; + +export type CreateRecipeMutationVariables = Exact<{ + input: RecipeInput; +}>; + +export type CreateRecipeMutation = { + createRecipe: { + id: string; + title: string; + description: string; + category: string; + cuisine: string | null; + difficulty: string; + visibility: string; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }; +}; + +export type UpdateRecipeMutationVariables = Exact<{ + id: string | number; + input: RecipeInput; +}>; + +export type UpdateRecipeMutation = { + updateRecipe: { + id: string; + title: string; + description: string; + category: string; + cuisine: string | null; + difficulty: string; + visibility: string; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }; +}; + +export type DeleteRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type DeleteRecipeMutation = { deleteRecipe: boolean }; + +export type SaveRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type SaveRecipeMutation = { + saveRecipe: { + id: string; + title: string; + description: string; + category: string; + cuisine: string | null; + difficulty: string; + visibility: string; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }; +}; + +export type UnsaveRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type UnsaveRecipeMutation = { unsaveRecipe: boolean }; + +export const RecipeFieldsFragmentDoc = { + kind: 'Document', + definitions: [ + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; export const HealthDocument = { kind: 'Document', definitions: [ @@ -334,3 +683,943 @@ export const CurrentUserDocument = { }, ], } as unknown as DocumentNode; +export const RecipesDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Recipes' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeListInput' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'recipes' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'items' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } }, + { kind: 'Field', name: { kind: 'Name', value: 'page' } }, + { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const RecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Recipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'recipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const CookbookDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Cookbook' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeListInput' }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'scope' }, + }, + type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'cookbook' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'scope' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'scope' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'items' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } }, + { kind: 'Field', name: { kind: 'Name', value: 'page' } }, + { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const CreateRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'CreateRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeInput' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'createRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + CreateRecipeMutation, + CreateRecipeMutationVariables +>; +export const UpdateRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'UpdateRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeInput' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'updateRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + UpdateRecipeMutation, + UpdateRecipeMutationVariables +>; +export const DeleteRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'DeleteRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'deleteRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + DeleteRecipeMutation, + DeleteRecipeMutationVariables +>; +export const SaveRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'SaveRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'saveRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const UnsaveRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'UnsaveRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'unsaveRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + UnsaveRecipeMutation, + UnsaveRecipeMutationVariables +>; diff --git a/contracts/operations.graphql b/contracts/operations.graphql index 06ef45b..557e796 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -33,3 +33,91 @@ query CurrentUser { email } } + +fragment RecipeFields on Recipe { + id + title + description + category + cuisine + difficulty + visibility + imageUrl + sourceRecipeId + prepMinutes + cookMinutes + servings + createdAt + updatedAt + author { + id + name + } + ingredients { + id + name + amount + unit + note + } + instructions { + step + text + } + tags + rating { + average + count + } + saveCount + isSaved + isCreatedByCurrentUser +} +query Recipes($input: RecipeListInput) { + recipes(input: $input) { + items { + ...RecipeFields + } + totalCount + totalPages + page + pageSize + } +} +query Recipe($id: ID!) { + recipe(id: $id) { + ...RecipeFields + } +} +query Cookbook($input: RecipeListInput, $scope: String) { + cookbook(input: $input, scope: $scope) { + items { + ...RecipeFields + } + totalCount + totalPages + page + pageSize + } +} +mutation CreateRecipe($input: RecipeInput!) { + createRecipe(input: $input) { + ...RecipeFields + } +} +mutation UpdateRecipe($id: ID!, $input: RecipeInput!) { + updateRecipe(id: $id, input: $input) { + ...RecipeFields + } +} +mutation DeleteRecipe($id: ID!) { + deleteRecipe(id: $id) +} +mutation SaveRecipe($id: ID!) { + saveRecipe(id: $id) { + ...RecipeFields + } +} +mutation UnsaveRecipe($id: ID!) { + unsaveRecipe(id: $id) +} diff --git a/docs/recipe-api.md b/docs/recipe-api.md new file mode 100644 index 0000000..d79e440 --- /dev/null +++ b/docs/recipe-api.md @@ -0,0 +1,120 @@ +# Recipe API – Delivery 2 + +Branch: `hasan/feat/recipe-crud-cookies`. API-et bruker eksisterende GraphQL Yoga og +PostgreSQL-oppsett, med SQL-parametre gjennom `pg`, som autentiseringen. +Zod validerer input; databasekontrollene beholdes. Ingen ny migrasjon er nødvendig. + +## Autentisering + +Branchen bygger på `hasan/fix/auth-cookie-context`. Auth og CRUD bruker samme +GraphQL-context og HttpOnly-cookie. Serveren finner brukeren fra en gyldig, +ikke-utløpt sesjon. Forfatter og cookbook-bruker kommer alltid fra context, +aldri fra klientens bruker-ID. `currentUser` returnerer bruker eller `null`. + +Frontend sender `credentials: 'same-origin'`, `Content-Type: application/json` +og `X-Requested-With: recipe-platform`, som eksisterende auth-klient. +Sesjonstoken sendes ikke som GraphQL-argument eller i responsdata, og lagres +ikke i localStorage. Logout sletter cookien og ugyldiggjør sesjonen i databasen. +Cookie har HttpOnly, SameSite=Lax og Path=/; Secure aktiveres ved HTTPS. + +## Operasjoner + +Alle operasjonene finnes i `contracts/operations.graphql`, med genererte typer og +dokumenter i `contracts/generated.ts`. Regenerer med `npm run types:api`. + +| Operasjon | Tilgang og oppførsel | +| ------------------------- | ----------------------------------------------------------------------------- | +| `recipes(input)` | Offentlige oppskrifter, også for innlogget eier. | +| `recipe(id)` | Offentlig oppskrift eller eierens private. Utilgjengelig/ukjent gir `null`. | +| `createRecipe(input)` | Krever innlogging; lagrer hele oppskriften i én transaksjon. | +| `updateRecipe(id, input)` | Bare eier; erstatter alle redigerbare felt og barn i én transaksjon. | +| `deleteRecipe(id)` | Bare eier; databasen sletter tilknyttede rader automatisk. | +| `saveRecipe(id)` | Bare innlogget bruker; offentlig oppskrift av en annen bruker; idempotent. | +| `unsaveRecipe(id)` | Fjerner bare egen lagring; idempotent, også etter at oppskriften blir privat. | +| `cookbook(input, scope)` | Krever innlogging. Scope er `all`, `saved` eller `created`. | + +Listeinput støtter `search` (tittel/beskrivelse), `category`, `maxCookingMinutes`, +`page` og `pageSize` (1–50, standard 6). Filtrering og paginering skjer i SQL. +Sortering er nyeste først med ID som stabil tie-breaker. En side utenfor området +begrenses til siste side. Tom liste har `totalPages: 0` og `page: 1`. + +Oppskriften returnerer forfatterens offentlige ID/navn, ingredienser, ordnede steg, +tagger, datoer, vurderingsoppsummering og brukeravhengige lagrings-/eierskapsflagg. +E-post og passordhash eksponeres ikke som oppskriftsforfatterdata. + +## Input og frontendkobling + +`RecipeInput` inneholder tittel, beskrivelse, kategori, difficulty, visibility, +prepMinutes, cookMinutes, servings, ingredients, instructions og tags. +`cuisine` og `imageUrl` er valgfrie. Bildet må være en HTTP(S)-URL; dette API-et +laster ikke opp bildefiler. En ingrediens har name, amount, unit og valgfri note. +Instruksjoner sendes som en liste strenger; rekkefølgen bestemmer step/position. + +Minst én ingrediens og ett steg kreves. Mengder må være positive med maksimalt +fire desimaler og passe `numeric(12,4)`. Porsjoner er heltall 1–1000, tider er +heltall 0–10080 minutter per felt, beskrivelse maksimalt 200 tegn. Tagger trimmes, +normaliseres til små bokstaver og dedupliseres. Kategori bruker databasens fem nøkler. + +Frontend må kobles separat ved de eksisterende data-grensene. Spesielt: + +- Add Recipe har nå separate felt for navn, mengde og enhet. Konverter + mengdeverdien fra formtekst til tall, og kartlegg cookingTime til cookMinutes + og eventuelt prepMinutes=0. Difficulty må få et felt eller en avtalt standard. +- Explore/Detail må bytte mock-data med de genererte operasjonene. +- Send samme cookie og forespørselshoder som auth-klienten på oppskriftsoperasjoner. +- Etter mutasjoner: refetch liste/detail/cookbook slik at lagringstilstanden er lik. +- `cuisine` er nullable; en frontend-mapper må håndtere manglende verdi. +- Bruk eksisterende pending/error/not-found-mønstre og behold formdata ved feil. + +Feilkoder: `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND` og `FORBIDDEN`. +Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller +ukjente oppskrifter gir samme feil og avslører ikke private data. + +## Lokal kontroll og seed + +Kjør fra roten, med `DATABASE_URL` i `.env`: + +```powershell +npm.cmd run db:migrate +npm.cmd run check +npm.cmd run test:db +npm.cmd run test:api +``` + +`test:api` kjører virkelige GraphQL-operasjoner mot et tilfeldig PostgreSQL-skjema. +Det bruker ekte register/login og sesjoner, tester public/private, CRUD, +save/cookbook og fremprovoserer en barnefeil for å verifisere rollback. Skjemaet +slettes i `finally`; eksisterende `project2` og migrasjonshistorikk røres ikke. +Krever CREATE SCHEMA-rettighet. Kjør bare mot en database avsatt til utvikling/test. +Integrasjonstestene er egne kommandoer, ikke del av standard CI; runneren må ha +en separat testdatabase og kjøre begge kommandoene for automatisk DB-verifisering. + +Valgfri demoseed, etter migrasjon: + +```powershell +$env:SEED_PASSWORD = '' +npm.cmd run db:seed +Remove-Item Env:SEED_PASSWORD +``` + +Seed oppretter `demo@example.invalid`, én offentlig og én privat suppe med faste +UUID-er og strukturerte barn i én transaksjon. Gjentatte kjøringer overskriver +ikke eksisterende seed-rader eller passord. Kjøres eksplisitt, aldri under deploy. +Passordet lagres som Argon2-hash. På Linux: `SEED_PASSWORD='...' npm run db:seed`. + +## Sjekk mot Delivery 2-planen + +- D2-01/03: relasjoner og migrasjoner finnes allerede; kontrakter er utvidet. +- D2-04: eksplisitt demoseed er lagt til. +- D2-05/06/08/10: API-testmønster, autentisert context, reads/visibility og create + er implementert, sammen med eierstyrt update/delete. +- D2-12: persistent Save/Unsave/Cookbook er implementert. +- D2-07/09/11/13: frontendintegrasjon gjenstår; eksisterende auth-UI virker fortsatt. +- D2-02/15/16: VM-deploy og full nettleserdemonstrasjon må kontrolleres etter + integrasjon. Bruk eksisterende Apache/systemd-oppsett og `/project2/api/graphql`. +- D2-14: ratingmutasjoner/reviews er utsatt. Avansert sortering/søk er D3. +- Editable copies og bildeopplasting er ikke inkludert. Databasens sourceRecipeId + returneres, men klienten kan ikke endre kildehenvisning via vanlig CRUD-input. + +AI er brukt til plananalyse, implementasjon og tester. Endringene skal gjennomgås +i PR og kontrolleres med prosjektets sjekker og API-/databasetestene. diff --git a/package.json b/package.json index 773ce73..0d9c093 100644 --- a/package.json +++ b/package.json @@ -28,11 +28,13 @@ "lint": "eslint . --max-warnings 0", "format": "prettier --write .", "format:check": "prettier --check .", - "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit && tsc -p apps/api/tsconfig.test.json", + "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit && tsc -p apps/api/tsconfig.test.json && tsc -p scripts/tsconfig.json", "test": "vitest run --passWithNoTests", "test:e2e": "playwright test", "check": "npm run format:check && npm run lint && npm run types:check && npm run db:check && npm run typecheck && npm test && npm run build", - "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts" + "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts", + "test:api": "tsx --env-file-if-exists=.env scripts/test-recipe-api.ts", + "db:seed": "tsx --env-file-if-exists=.env apps/api/src/db/seed.ts" }, "devDependencies": { "@eslint/js": "9.39.5", diff --git a/scripts/generate-api.ts b/scripts/generate-api.ts index 4584e61..3dffe6d 100644 --- a/scripts/generate-api.ts +++ b/scripts/generate-api.ts @@ -19,7 +19,8 @@ const targets = [ }, { filename: 'contracts/generated.ts', - plugins: [{ typescript: {} }, { operations: {} }, { typedDocument: {} }], + // typescript-operations v6 also emits the used input types. + plugins: [{ operations: {} }, { typedDocument: {} }], config: { useTypeImports: true }, }, ]; diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts new file mode 100644 index 0000000..43b1bf0 --- /dev/null +++ b/scripts/test-recipe-api.ts @@ -0,0 +1,530 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; +import { Pool } from 'pg'; +import { print } from 'graphql'; +import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; +import { createApp } from '../apps/api/src/app.js'; +import { createAuthRepository } from '../apps/api/src/features/auth/authRepository.js'; +import { createAuthService } from '../apps/api/src/features/auth/authService.js'; +import { seedDatabase } from '../apps/api/src/db/seedData.js'; +import { + RegisterDocument, + LoginDocument, + CurrentUserDocument, + SignOutDocument, + CreateRecipeDocument, + UpdateRecipeDocument, + DeleteRecipeDocument, + RecipesDocument, + RecipeDocument, + SaveRecipeDocument, + UnsaveRecipeDocument, + CookbookDocument, + type RecipeInput, +} from '../contracts/generated.js'; + +await test('recipe GraphQL API against PostgreSQL', async (t) => { + assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL in .env.'); + const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, + }); + const schema = 'api_test_' + randomUUID().replaceAll('-', ''); + const api = createApp( + createAuthService(createAuthRepository(pool, pool, schema)), + false, + false, + { pool, schema }, + ); + const input: RecipeInput = { + title: 'Test soup', + description: 'Simple soup', + category: 'soup', + cuisine: null, + difficulty: 'easy', + visibility: 'public', + prepMinutes: 5, + cookMinutes: 10, + servings: 2, + ingredients: [ + { name: 'Salt', amount: 0.125, unit: 'tsp' }, + { name: 'Water', amount: 1, unit: 'l' }, + ], + instructions: ['Boil water', 'Add salt'], + tags: [' Quick ', 'quick'], + }; + async function request( + document: TypedDocumentNode, + variables: V, + cookie?: string, + ) { + const response = await api.fetch('http://localhost/graphql', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + ...(cookie ? { Cookie: cookie } : {}), + }, + body: JSON.stringify({ query: print(document), variables }), + }); + const sessionCookie = + response.headers.get('set-cookie')?.split(';')[0] ?? ''; + const result = (await response.json()) as { + data: T; + errors?: { message: string; extensions: { code?: string } }[]; + }; + return { ...result, cookie: sessionCookie }; + } + async function ok( + document: TypedDocumentNode, + variables: V, + cookie?: string, + ) { + const result = await request(document, variables, cookie); + assert.equal(result.errors, undefined, JSON.stringify(result.errors)); + return result.data; + } + async function fails( + document: TypedDocumentNode, + variables: V, + code: string, + cookie?: string, + ) { + const result = await request(document, variables, cookie); + assert.equal( + result.errors?.[0]?.extensions.code, + code, + JSON.stringify(result), + ); + } + async function register(name: string, email: string) { + const result = await request(RegisterDocument, { + name, + email, + password: 'test-password', + }); + assert.equal(result.errors, undefined); + assert.ok(result.cookie); + assert.ok(!JSON.stringify(result.data).includes('sessionToken')); + return { ...result.data.register, cookie: result.cookie }; + } + async function loginSession(email: string, password: string) { + const result = await request(LoginDocument, { email, password }); + assert.equal(result.errors, undefined); + assert.ok(result.cookie); + return { ...result.data.login, cookie: result.cookie }; + } + try { + await pool.query(`CREATE SCHEMA "${schema}"`); + const journal = JSON.parse( + await readFile('apps/api/migrations/meta/_journal.json', 'utf8'), + ) as { entries: { tag: string }[] }; + // Exercise all real migrations; no writes to project2 or its migration history. + const client = await pool.connect(); + try { + await client.query('BEGIN'); + for (const { tag } of journal.entries) + await client.query( + (await readFile(`apps/api/migrations/${tag}.sql`, 'utf8')).replaceAll( + '"project2"', + `"${schema}"`, + ), + ); + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } + + const owner = await register('Owner', 'owner@example.com'); + const reader = await register('Reader', 'reader@example.com'); + await t.test('persistent login and authenticated context', async () => { + const login = await loginSession('owner@example.com', 'test-password'); + assert.equal( + (await ok(CurrentUserDocument, {}, login.cookie)).currentUser?.id, + owner.user.id, + ); + assert.equal((await ok(CurrentUserDocument, {})).currentUser, null); + assert.equal( + ( + await ok( + CurrentUserDocument, + {}, + 't31_project2_session=invalid-token', + ) + ).currentUser, + null, + ); + await pool.query( + `UPDATE "${schema}".sessions SET expires_at=now()-interval '1 second' WHERE id=$1`, + [login.cookie.split('=')[1]], + ); + assert.equal( + (await ok(CurrentUserDocument, {}, login.cookie)).currentUser, + null, + ); + }); + await t.test( + 'anonymous, malformed and expired sessions cannot create', + async () => { + for (const token of [ + undefined, + 't31_project2_session=invalid-token', + 't31_project2_session=' + randomUUID(), + ]) + await fails( + CreateRecipeDocument, + { input }, + 'UNAUTHENTICATED', + token, + ); + }, + ); + await t.test('Zod rejects invalid input without writing rows', async () => { + for (const invalid of [ + { ...input, title: ' ' }, + { ...input, category: 'Soup' }, + { ...input, servings: 0 }, + { ...input, ingredients: [] }, + { ...input, instructions: [] }, + { + ...input, + ingredients: [{ name: 'Salt', amount: 0.00001, unit: 'tsp' }], + }, + ]) { + await fails( + CreateRecipeDocument, + { input: invalid }, + 'BAD_USER_INPUT', + owner.cookie, + ); + } + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 0, + ); + }); + const publicRecipe = ( + await ok(CreateRecipeDocument, { input }, owner.cookie) + ).createRecipe; + const privateRecipe = ( + await ok( + CreateRecipeDocument, + { input: { ...input, title: 'Private soup', visibility: 'private' } }, + owner.cookie, + ) + ).createRecipe; + await t.test( + 'creation persists ordered content and uses authenticated author', + async () => { + assert.equal(publicRecipe.author.id, owner.user.id); + assert.equal(publicRecipe.cuisine, null); + assert.deepEqual(publicRecipe.tags, ['quick']); + const read = (await ok(RecipeDocument, { id: publicRecipe.id })) + .recipe!; + assert.equal(read.ingredients[0]?.amount, 0.125); + assert.deepEqual( + read.instructions.map((step) => step.text), + input.instructions, + ); + assert.equal(read.isCreatedByCurrentUser, false); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'public list excludes private data; private detail is owner-only', + async () => { + for (const token of [undefined, owner.cookie, reader.cookie]) { + const list = (await ok(RecipesDocument, {}, token)).recipes; + assert.deepEqual( + list.items.map((item) => item.id), + [publicRecipe.id], + ); + } + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id })).recipe, + null, + ); + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id }, reader.cookie)) + .recipe, + null, + ); + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie)) + .recipe?.id, + privateRecipe.id, + ); + assert.equal( + (await ok(RecipeDocument, { id: randomUUID() })).recipe, + null, + ); + }, + ); + await t.test('search, filters and paging run on the server', async () => { + assert.equal( + ( + await ok(RecipesDocument, { + input: { search: 'SOUP', category: 'soup', page: 99, pageSize: 1 }, + }) + ).recipes.page, + 1, + ); + assert.equal( + (await ok(RecipesDocument, { input: { search: 'missing' } })).recipes + .totalCount, + 0, + ); + assert.equal( + (await ok(RecipesDocument, { input: { maxCookingMinutes: 14 } })) + .recipes.totalCount, + 0, + ); + await fails( + RecipesDocument, + { input: { pageSize: 51 } }, + 'BAD_USER_INPUT', + ); + }); + await t.test('only the owner can update or delete', async () => { + await fails( + UpdateRecipeDocument, + { id: publicRecipe.id, input }, + 'NOT_FOUND', + reader.cookie, + ); + await fails( + DeleteRecipeDocument, + { id: publicRecipe.id }, + 'NOT_FOUND', + reader.cookie, + ); + await fails( + UpdateRecipeDocument, + { id: publicRecipe.id, input }, + 'UNAUTHENTICATED', + ); + const edited = ( + await ok( + UpdateRecipeDocument, + { + id: publicRecipe.id, + input: { + ...input, + title: 'Updated soup', + instructions: ['Serve'], + ingredients: [{ name: 'Pepper', amount: 1, unit: '' }], + }, + }, + owner.cookie, + ) + ).updateRecipe; + assert.equal(edited.title, 'Updated soup'); + assert.equal(edited.ingredients.length, 1); + assert.deepEqual(edited.instructions, [{ step: 1, text: 'Serve' }]); + }); + await t.test( + 'save is idempotent, private recipes and own recipes are blocked', + async () => { + await fails( + SaveRecipeDocument, + { id: publicRecipe.id }, + 'UNAUTHENTICATED', + ); + await fails( + SaveRecipeDocument, + { id: privateRecipe.id }, + 'FORBIDDEN', + reader.cookie, + ); + await fails( + SaveRecipeDocument, + { id: publicRecipe.id }, + 'FORBIDDEN', + owner.cookie, + ); + for (let i = 0; i < 2; i++) { + const saved = ( + await ok(SaveRecipeDocument, { id: publicRecipe.id }, reader.cookie) + ).saveRecipe; + assert.equal(saved.isSaved, true); + assert.equal(saved.saveCount, 1); + } + assert.equal( + (await ok(CookbookDocument, { scope: 'saved' }, reader.cookie)) + .cookbook.totalCount, + 1, + ); + assert.equal( + (await ok(CookbookDocument, { scope: 'created' }, owner.cookie)) + .cookbook.totalCount, + 2, + ); + await fails(CookbookDocument, {}, 'UNAUTHENTICATED'); + }, + ); + await t.test( + 'making a saved recipe private hides it from other cookbooks', + async () => { + await ok( + UpdateRecipeDocument, + { id: publicRecipe.id, input: { ...input, visibility: 'private' } }, + owner.cookie, + ); + assert.equal( + (await ok(CookbookDocument, {}, reader.cookie)).cookbook.totalCount, + 0, + ); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, reader.cookie)) + .recipe, + null, + ); + await ok(UnsaveRecipeDocument, { id: publicRecipe.id }, reader.cookie); + await ok(UnsaveRecipeDocument, { id: publicRecipe.id }, reader.cookie); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".saved_recipes`, + ) + ).rows[0].count, + 0, + ); + }, + ); + await t.test( + 'child insert failures roll back both creation and updates', + async () => { + await pool.query( + `CREATE FUNCTION "${schema}".reject_test_ingredient() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.name='fail-test' THEN RAISE EXCEPTION 'forced child failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_test BEFORE INSERT ON "${schema}".recipe_ingredients FOR EACH ROW EXECUTE FUNCTION "${schema}".reject_test_ingredient()`, + ); + const bad = { + ...input, + ingredients: [ + ...input.ingredients, + { name: 'fail-test', amount: 1, unit: '' }, + ], + }; + const failedCreate = await request( + CreateRecipeDocument, + { input: bad }, + owner.cookie, + ); + assert.ok(failedCreate.errors); + const before = ( + await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie) + ).recipe; + assert.ok( + ( + await request( + UpdateRecipeDocument, + { id: privateRecipe.id, input: bad }, + owner.cookie, + ) + ).errors, + ); + assert.deepEqual( + (await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie)) + .recipe, + before, + ); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'delete cascades; logout revokes later protected calls', + async () => { + await ok(DeleteRecipeDocument, { id: publicRecipe.id }, owner.cookie); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, owner.cookie)) + .recipe, + null, + ); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipe_ingredients WHERE recipe_id=$1`, + [publicRecipe.id], + ) + ).rows[0].count, + 0, + ); + await ok(SignOutDocument, {}, owner.cookie); + await fails( + CreateRecipeDocument, + { input }, + 'UNAUTHENTICATED', + owner.cookie, + ); + }, + ); + await t.test( + 'demo seed is repeatable and preserves existing passwords', + async () => { + await seedDatabase(pool, 'demo-test-password', schema); + const originalHash = ( + await pool.query( + `SELECT password_hash FROM "${schema}".users WHERE email='demo@example.invalid'`, + ) + ).rows[0].password_hash; + await seedDatabase(pool, 'different-demo-password', schema); + assert.equal( + ( + await pool.query( + `SELECT password_hash FROM "${schema}".users WHERE email='demo@example.invalid'`, + ) + ).rows[0].password_hash, + originalHash, + ); + const demo = await loginSession( + 'demo@example.invalid', + 'demo-test-password', + ); + const cookbook = ( + await ok(CookbookDocument, { scope: 'created' }, demo.cookie) + ).cookbook; + assert.equal(cookbook.totalCount, 2); + assert.equal( + cookbook.items.filter((recipe) => recipe.visibility === 'private') + .length, + 1, + ); + assert.ok( + cookbook.items.every( + (recipe) => + recipe.ingredients.length === 2 && + recipe.instructions.length === 2, + ), + ); + }, + ); + } finally { + try { + await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + } finally { + await pool.end(); + } + } +}); diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json new file mode 100644 index 0000000..06da1da --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"], + "noEmit": true + }, + "include": ["test-recipe-api.ts"] +} From 33c8cf26d800fcfd14f1b28118fbc0790c3e9945 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Tue, 20 Oct 2026 13:07:08 +0200 Subject: [PATCH 3/4] docs(api): add frontend quickstart for recipe CRUD --- docs/recipe-api.md | 99 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/docs/recipe-api.md b/docs/recipe-api.md index d79e440..93cac33 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -4,9 +4,106 @@ Branch: `hasan/feat/recipe-crud-cookies`. API-et bruker eksisterende GraphQL Yog PostgreSQL-oppsett, med SQL-parametre gjennom `pg`, som autentiseringen. Zod validerer input; databasekontrollene beholdes. Ingen ny migrasjon er nødvendig. +## Hurtigstart for frontend + +Alle queries og mutations sendes med HTTP POST til samme GraphQL-adresse. +Operasjonsnavnet i forespørselen bestemmer hva serveren gjør. + +| Miljø | Adresse fra frontend | +| ----------------- | --------------------------------------------------- | +| Lokal Vite-server | `/graphql` (Vite videresender til API på port 3001) | +| Deploy på VM | `/project2/api/graphql` | + +Start lokalt med `npm run dev` fra prosjektroten. PostgreSQL må kjøre, +`DATABASE_URL` må være satt i `.env`, og migrasjonene må være kjørt med +`npm run db:migrate`. + +Bruk de ferdige operasjonene i [operations.graphql](../contracts/operations.graphql) +og importer tilhørende dokumenter og typer fra +[generated.ts](../contracts/generated.ts). Ikke rediger den genererte filen. + +| Komponent/funksjon | Generert dokument | +| ------------------ | --------------------------------------------- | +| Explore | `RecipesDocument` | +| Recipe Detail | `RecipeDocument` | +| Add Recipe | `CreateRecipeDocument` | +| Edit Recipe | `UpdateRecipeDocument` | +| Slett oppskrift | `DeleteRecipeDocument` | +| Save / Unsave | `SaveRecipeDocument` / `UnsaveRecipeDocument` | +| Cookbook | `CookbookDocument` | + +Eksempelet under kan ligge i `apps/web/src/features/recipes/recipeApi.ts` når +frontend kobles til i steg 3. Det oppretter en oppskrift for innlogget bruker. +Samme URL, headere og cookie-innstilling brukes for de øvrige operasjonene. + +```ts +import { print } from 'graphql'; +import { + CreateRecipeDocument, + type CreateRecipeMutation, + type CreateRecipeMutationVariables, +} from '../../../../../contracts/generated'; + +export async function createRecipe( + input: CreateRecipeMutationVariables['input'], +) { + const url = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; + const variables: CreateRecipeMutationVariables = { input }; + const response = await fetch(url, { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + }, + body: JSON.stringify({ query: print(CreateRecipeDocument), variables }), + }); + if (!response.ok) throw new Error('Kunne ikke kontakte API-et.'); + + const result = (await response.json()) as { + data?: CreateRecipeMutation; + errors?: Array<{ message: string; extensions?: { code?: string } }>; + }; + const error = result.errors?.[0]; + if (error) { + // Komponentlaget kan bruke koden til å velge en passende feilmelding. + throw new Error(error.extensions?.code ?? 'API_ERROR'); + } + if (!result.data) throw new Error('API-et returnerte ingen data.'); + return result.data.createRecipe; +} +``` + +Et gyldig `input` for eksempelet: + +```json +{ + "title": "Enkel suppe", + "description": "En rask suppe for to.", + "category": "soup", + "difficulty": "easy", + "visibility": "private", + "prepMinutes": 5, + "cookMinutes": 10, + "servings": 2, + "ingredients": [{ "name": "Vann", "amount": 1, "unit": "l" }], + "instructions": ["Kok opp vannet."], + "tags": ["quick"] +} +``` + +`updateRecipe` krever hele samme input, i tillegg til oppskriftens `id`; +operasjonen er ikke en delvis oppdatering. Listeoperasjoner returnerer +`items`, `totalCount`, `totalPages`, `page` og `pageSize`. Cookbook bruker +`scope: "all"`, `"saved"` eller `"created"`. + +Ved frontendkobling må komponenten håndtere lasting og feil, beholde formdata +ved feil og oppdatere relevante lister etter en vellykket mutation. +Oppskriftssidene bruker fortsatt mock-data frem til steg 3. + ## Autentisering -Branchen bygger på `hasan/fix/auth-cookie-context`. Auth og CRUD bruker samme +Branchen er oppdatert med `dev`, som inkluderer auth-cookie-forbedringene. Auth og CRUD bruker samme GraphQL-context og HttpOnly-cookie. Serveren finner brukeren fra en gyldig, ikke-utløpt sesjon. Forfatter og cookbook-bruker kommer alltid fra context, aldri fra klientens bruker-ID. `currentUser` returnerer bruker eller `null`. From d913e25640223228cf67212a2d040ba556341441 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Fri, 23 Oct 2026 00:17:00 +0200 Subject: [PATCH 4/4] refactor(api): address recipe API review feedback --- .../features/recipes/recipeContract.test.ts | 74 +++++++++++++++++++ .../src/features/recipes/recipeRepository.ts | 42 +++++++---- apps/api/src/generated.ts | 51 ++++++++++--- apps/api/src/schema.graphql | 41 ++++++++-- contracts/generated.ts | 70 +++++++++++------- contracts/operations.graphql | 2 +- docs/recipe-api.md | 33 ++++++++- scripts/generate-api.ts | 4 +- scripts/test-recipe-api.ts | 12 +-- 9 files changed, 258 insertions(+), 71 deletions(-) create mode 100644 apps/api/src/features/recipes/recipeContract.test.ts diff --git a/apps/api/src/features/recipes/recipeContract.test.ts b/apps/api/src/features/recipes/recipeContract.test.ts new file mode 100644 index 0000000..6d172f0 --- /dev/null +++ b/apps/api/src/features/recipes/recipeContract.test.ts @@ -0,0 +1,74 @@ +import { readFileSync } from 'node:fs'; +import { buildSchema, graphql, isEnumType, parse, validate } from 'graphql'; +import { describe, expect, it } from 'vitest'; +import { categorySchema, recipeInputSchema } from './recipeValidation.js'; + +const schema = buildSchema( + readFileSync(new URL('../../schema.graphql', import.meta.url), 'utf8'), +); + +describe('recipe GraphQL contract', () => { + it('keeps enum values consistent with input validation', () => { + const values = (name: string) => { + const type = schema.getType(name); + if (!isEnumType(type)) throw new Error(`${name} must be an enum`); + return type.getValues().map((value) => value.name); + }; + expect(values('RecipeCategory')).toEqual(categorySchema.options); + expect(values('RecipeDifficulty')).toEqual( + recipeInputSchema.shape.difficulty.options, + ); + expect(values('RecipeVisibility')).toEqual( + recipeInputSchema.shape.visibility.options, + ); + expect(values('CookbookScope')).toEqual(['all', 'saved', 'created']); + }); + + it('accepts all shared operations against the schema', () => { + const operations = readFileSync( + new URL('../../../../../contracts/operations.graphql', import.meta.url), + 'utf8', + ); + expect(validate(schema, parse(operations))).toEqual([]); + }); + + it.each([ + ['RecipeCategory', 'Soup'], + ['RecipeDifficulty', 'expert'], + ['RecipeVisibility', 'hidden'], + ['CookbookScope', 'everyone'], + ])('rejects invalid %s variables before resolving', async (type, value) => { + const field = type === 'CookbookScope' ? 'cookbook' : 'recipes'; + const argument = + type === 'CookbookScope' + ? 'scope: $value' + : type === 'RecipeCategory' + ? 'input: { category: $value }' + : ''; + // Difficulty/visibility are mutation inputs; use their real input fields. + const source = argument + ? `query($value: ${type}) { ${field}(${argument}) { totalCount } }` + : `mutation($value: ${type}!) { + createRecipe(input: { + title: "Soup", description: "", category: soup, + difficulty: ${type === 'RecipeDifficulty' ? '$value' : 'easy'}, + visibility: ${type === 'RecipeVisibility' ? '$value' : 'public'}, + prepMinutes: 0, cookMinutes: 10, servings: 1, + ingredients: [], instructions: [], tags: [] + }) { id } + }`; + let resolved = false; + const result = await graphql({ + schema, + source, + variableValues: { value }, + rootValue: { + [argument ? field : 'createRecipe']: () => { + resolved = true; + }, + }, + }); + expect(result.errors?.[0]?.message).toContain('does not exist'); + expect(resolved).toBe(false); + }); +}); diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index aaea17e..617a052 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -1,13 +1,36 @@ import { GraphQLError } from 'graphql'; import type { Pool, PoolClient } from 'pg'; import { db } from '../../db/client.js'; -import type { Recipe } from '../../generated.js'; +import type { CookbookScope, Recipe } from '../../generated.js'; import type { RecipeInput, ListInput } from './recipeValidation.js'; export function createRecipeRepository(pool: Pool = db, schema = 'project2') { if (!/^[a-z_][a-z0-9_]*$/.test(schema)) throw new Error('Invalid database schema.'); const t = (name: string) => `"${schema}"."${name}"`; + const ownedByViewer = 'r.author_id=$1::uuid'; + const publicRecipe = "r.visibility='public'"; + const visibleToViewer = `(${publicRecipe} OR ${ownedByViewer})`; + const savedByViewer = `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`; + + function listAccessCondition(scope: 'explore' | CookbookScope) { + if (scope === 'explore') return publicRecipe; + const membership: Record = { + created: ownedByViewer, + saved: savedByViewer, + all: `(${ownedByViewer} OR ${savedByViewer})`, + }; + return `${visibleToViewer} AND (${membership[scope]})`; + } + + function listFilterConditions() { + // Keep filter parameters separate from access rules; shared by count and rows. + return [ + "($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0)", + '($3::text IS NULL OR r.category=$3)', + '($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)', + ]; + } // One read includes ordered children and derived values; no per-recipe queries. const select = `SELECT r.id, r.title, r.description, r.category, r.cuisine, r.difficulty, r.visibility, r.image_url AS "imageUrl", r.source_recipe_id AS "sourceRecipeId", @@ -44,8 +67,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { userId: string | null, ) { const result = await executor.query( - select + - ` WHERE r.id=$2 AND (r.visibility='public' OR r.author_id=$1::uuid)`, + select + ` WHERE r.id=$2 AND ${visibleToViewer}`, [userId, id], ); return result.rows[0] ?? null; @@ -107,19 +129,9 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { async list( input: ListInput, userId: string | null, - scope: 'explore' | 'all' | 'saved' | 'created' = 'explore', + scope: 'explore' | CookbookScope = 'explore', ) { - const access = - scope === 'explore' - ? `r.visibility='public'` - : `(r.visibility='public' OR r.author_id=$1::uuid) AND (` + - (scope === 'created' - ? 'r.author_id=$1::uuid' - : scope === 'saved' - ? `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)` - : `r.author_id=$1::uuid OR EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`) + - ')'; - const where = ` WHERE ${access} AND ($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0) AND ($3::text IS NULL OR r.category=$3) AND ($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)`; + const where = ` WHERE ${[listAccessCondition(scope), ...listFilterConditions()].join(' AND ')}`; const args = [ userId, input.search, diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index 6add7b5..1e42561 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -14,6 +14,19 @@ export type Scalars = { Float: { input: number; output: number }; }; +export type RecipeDifficulty = 'easy' | 'medium' | 'hard'; + +export type RecipeVisibility = 'public' | 'private'; + +export type RecipeCategory = + | 'breakfast' + | 'lunch' + | 'dinner' + | 'dessert' + | 'soup'; + +export type CookbookScope = 'all' | 'saved' | 'created'; + export type User = { __typename?: 'User'; id: Scalars['ID']['output']; @@ -45,7 +58,7 @@ export type QueryRecipeArgs = { export type QueryCookbookArgs = { input?: InputMaybe; - scope?: InputMaybe; + scope?: InputMaybe; }; export type Mutation = { @@ -124,10 +137,10 @@ export type Recipe = { id: Scalars['ID']['output']; title: Scalars['String']['output']; description: Scalars['String']['output']; - category: Scalars['String']['output']; + category: RecipeCategory; cuisine?: Maybe; - difficulty: Scalars['String']['output']; - visibility: Scalars['String']['output']; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl?: Maybe; sourceRecipeId?: Maybe; prepMinutes: Scalars['Int']['output']; @@ -156,7 +169,7 @@ export type RecipePage = { export type RecipeListInput = { search?: InputMaybe; - category?: InputMaybe; + category?: InputMaybe; maxCookingMinutes?: InputMaybe; page?: InputMaybe; pageSize?: InputMaybe; @@ -173,10 +186,10 @@ export type RecipeInput = { title: Scalars['String']['input']; description: Scalars['String']['input']; imageUrl?: InputMaybe; - category: Scalars['String']['input']; + category: RecipeCategory; cuisine?: InputMaybe; - difficulty: Scalars['String']['input']; - visibility: Scalars['String']['input']; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; prepMinutes: Scalars['Int']['input']; cookMinutes: Scalars['Int']['input']; servings: Scalars['Int']['input']; @@ -304,6 +317,10 @@ export type DirectiveResolverFn< /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { + RecipeDifficulty: RecipeDifficulty; + RecipeVisibility: RecipeVisibility; + RecipeCategory: RecipeCategory; + CookbookScope: CookbookScope; User: ResolverTypeWrapper; ID: ResolverTypeWrapper; String: ResolverTypeWrapper; @@ -492,10 +509,22 @@ export type RecipeResolvers< id?: Resolver; title?: Resolver; description?: Resolver; - category?: Resolver; + category?: Resolver< + ResolversTypes['RecipeCategory'], + ParentType, + ContextType + >; cuisine?: Resolver, ParentType, ContextType>; - difficulty?: Resolver; - visibility?: Resolver; + difficulty?: Resolver< + ResolversTypes['RecipeDifficulty'], + ParentType, + ContextType + >; + visibility?: Resolver< + ResolversTypes['RecipeVisibility'], + ParentType, + ContextType + >; imageUrl?: Resolver, ParentType, ContextType>; sourceRecipeId?: Resolver< Maybe, diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index 790067d..8825478 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -1,3 +1,28 @@ +enum RecipeDifficulty { + easy + medium + hard +} + +enum RecipeVisibility { + public + private +} + +enum RecipeCategory { + breakfast + lunch + dinner + dessert + soup +} + +enum CookbookScope { + all + saved + created +} + type User { id: ID! name: String! @@ -11,7 +36,7 @@ type AuthPayload { type Query { recipes(input: RecipeListInput): RecipePage! recipe(id: ID!): Recipe - cookbook(input: RecipeListInput, scope: String): RecipePage! + cookbook(input: RecipeListInput, scope: CookbookScope): RecipePage! health: String! currentUser: User } @@ -50,10 +75,10 @@ type Recipe { id: ID! title: String! description: String! - category: String! + category: RecipeCategory! cuisine: String - difficulty: String! - visibility: String! + difficulty: RecipeDifficulty! + visibility: RecipeVisibility! imageUrl: String sourceRecipeId: ID prepMinutes: Int! @@ -79,7 +104,7 @@ type RecipePage { } input RecipeListInput { search: String - category: String + category: RecipeCategory maxCookingMinutes: Int page: Int pageSize: Int @@ -94,10 +119,10 @@ input RecipeInput { title: String! description: String! imageUrl: String - category: String! + category: RecipeCategory! cuisine: String - difficulty: String! - visibility: String! + difficulty: RecipeDifficulty! + visibility: RecipeVisibility! prepMinutes: Int! cookMinutes: Int! servings: Int! diff --git a/contracts/generated.ts b/contracts/generated.ts index 1209f5b..25c9a17 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -8,9 +8,22 @@ export type Incremental = [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never; }; import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; +export type RecipeDifficulty = 'easy' | 'medium' | 'hard'; + +export type RecipeVisibility = 'public' | 'private'; + +export type RecipeCategory = + | 'breakfast' + | 'lunch' + | 'dinner' + | 'dessert' + | 'soup'; + +export type CookbookScope = 'all' | 'saved' | 'created'; + export type RecipeListInput = { search?: string | null | undefined; - category?: string | null | undefined; + category?: RecipeCategory | null | undefined; maxCookingMinutes?: number | null | undefined; page?: number | null | undefined; pageSize?: number | null | undefined; @@ -27,10 +40,10 @@ export type RecipeInput = { title: string; description: string; imageUrl?: string | null | undefined; - category: string; + category: RecipeCategory; cuisine?: string | null | undefined; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; prepMinutes: number; cookMinutes: number; servings: number; @@ -76,10 +89,10 @@ export type RecipeFieldsFragment = { id: string; title: string; description: string; - category: string; + category: RecipeCategory; cuisine: string | null; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl: string | null; sourceRecipeId: string | null; prepMinutes: number; @@ -117,10 +130,10 @@ export type RecipesQuery = { id: string; title: string; description: string; - category: string; + category: RecipeCategory; cuisine: string | null; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl: string | null; sourceRecipeId: string | null; prepMinutes: number; @@ -155,10 +168,10 @@ export type RecipeQuery = { id: string; title: string; description: string; - category: string; + category: RecipeCategory; cuisine: string | null; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl: string | null; sourceRecipeId: string | null; prepMinutes: number; @@ -185,7 +198,7 @@ export type RecipeQuery = { export type CookbookQueryVariables = Exact<{ input?: RecipeListInput | null | undefined; - scope?: string | null | undefined; + scope?: CookbookScope | null | undefined; }>; export type CookbookQuery = { @@ -198,10 +211,10 @@ export type CookbookQuery = { id: string; title: string; description: string; - category: string; + category: RecipeCategory; cuisine: string | null; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl: string | null; sourceRecipeId: string | null; prepMinutes: number; @@ -236,10 +249,10 @@ export type CreateRecipeMutation = { id: string; title: string; description: string; - category: string; + category: RecipeCategory; cuisine: string | null; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl: string | null; sourceRecipeId: string | null; prepMinutes: number; @@ -274,10 +287,10 @@ export type UpdateRecipeMutation = { id: string; title: string; description: string; - category: string; + category: RecipeCategory; cuisine: string | null; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl: string | null; sourceRecipeId: string | null; prepMinutes: number; @@ -317,10 +330,10 @@ export type SaveRecipeMutation = { id: string; title: string; description: string; - category: string; + category: RecipeCategory; cuisine: string | null; - difficulty: string; - visibility: string; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; imageUrl: string | null; sourceRecipeId: string | null; prepMinutes: number; @@ -982,7 +995,10 @@ export const CookbookDocument = { kind: 'Variable', name: { kind: 'Name', value: 'scope' }, }, - type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'CookbookScope' }, + }, }, ], selectionSet: { diff --git a/contracts/operations.graphql b/contracts/operations.graphql index 557e796..974ac34 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -89,7 +89,7 @@ query Recipe($id: ID!) { ...RecipeFields } } -query Cookbook($input: RecipeListInput, $scope: String) { +query Cookbook($input: RecipeListInput, $scope: CookbookScope) { cookbook(input: $input, scope: $scope) { items { ...RecipeFields diff --git a/docs/recipe-api.md b/docs/recipe-api.md index 93cac33..f1060a0 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -155,8 +155,9 @@ normaliseres til små bokstaver og dedupliseres. Kategori bruker databasens fem Frontend må kobles separat ved de eksisterende data-grensene. Spesielt: - Add Recipe har nå separate felt for navn, mengde og enhet. Konverter - mengdeverdien fra formtekst til tall, og kartlegg cookingTime til cookMinutes - og eventuelt prepMinutes=0. Difficulty må få et felt eller en avtalt standard. + mengdeverdien fra formtekst til tall. Legg til eksplisitte felt for difficulty, + prepMinutes og cookMinutes før integrasjonen; ikke gjett vanskelighetsgrad + eller fordel den eksisterende cookingTime-verdien automatisk. - Explore/Detail må bytte mock-data med de genererte operasjonene. - Send samme cookie og forespørselshoder som auth-klienten på oppskriftsoperasjoner. - Etter mutasjoner: refetch liste/detail/cookbook slik at lagringstilstanden er lik. @@ -164,9 +165,37 @@ Frontend må kobles separat ved de eksisterende data-grensene. Spesielt: - Bruk eksisterende pending/error/not-found-mønstre og behold formdata ved feil. Feilkoder: `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND` og `FORBIDDEN`. +Ugyldige enumverdier avvises av GraphQL før resolveren kjøres; klienten må også +håndtere GraphQL-valideringsfeil uten disse domenekodene. Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller ukjente oppskrifter gir samme feil og avslører ikke private data. +### Avtale for frontendintegrasjon og videre arbeid + +- GraphQL bruker RecipeDifficulty, RecipeVisibility, RecipeCategory og + CookbookScope som enums. Verdiene beholder databasens små bokstaver, for + eksempel `easy`, `public`, `soup` og `saved`. JSON-variabler sendes fortsatt + som strenger, men inline enumverdier skrives uten anførselstegn. Cookbook- + operasjoner må deklarere `$scope: CookbookScope`, ikke `$scope: String`. + Bruk de regenererte kontraktene; ingen databasemigrasjon er nødvendig. +- Søk gjelder foreløpig bare tittel/beskrivelse. Mock-søket inkluderer også + ingredienser/tagger og normaliserer bindestrek, understrek og mellomrom mer + omfattende. Beskriv det faktiske søkeomfanget i UI-et ved integrasjon. + Behold søkeinput ved datagrensen; ingrediens-/taggsøk og felles + normaliseringsregler avklares i D3 og implementeres i backend. +- Vis bare støttet sortering ved integrasjon: nyeste først. Cookbook sitt + «recently updated» er ikke det samme som opprettelsesdato. Flere sorteringer + skal implementeres i backend før LIMIT/OFFSET, med stabil tie-breaker og + tester over flere sider. Ikke sorter eller filtrer én hentet side lokalt. +- Midlertidig opprettes oppskrifter uten opplastede bilder. Skjul/deaktiver + filvalg og beskjæring med en tydelig forklaring ved integrasjon. Ikke send + lokale blob-/data-URL-er som imageUrl. Senere kan en separat opplastingstjeneste + returnere en varig HTTP(S)-URL til eksisterende CRUD-input. +- Frontendintegrasjonen gjøres i en egen branch etter API-endringene. + Separate liste-/detaljspørringer i SQL og domenefeil som oversettes til + GraphQL-feil ved resolvergrensen vurderes i senere, avgrensede endringer. + Listeoperasjonene henter foreløpig komplette oppskrifter også i databasen. + ## Lokal kontroll og seed Kjør fra roten, med `DATABASE_URL` i `.env`: diff --git a/scripts/generate-api.ts b/scripts/generate-api.ts index 3dffe6d..0084dc0 100644 --- a/scripts/generate-api.ts +++ b/scripts/generate-api.ts @@ -15,13 +15,13 @@ const targets = [ { filename: 'apps/api/src/generated.ts', plugins: [{ typescript: {} }, { resolvers: {} }], - config: { useTypeImports: true }, + config: { useTypeImports: true, enumsAsTypes: true }, }, { filename: 'contracts/generated.ts', // typescript-operations v6 also emits the used input types. plugins: [{ operations: {} }, { typedDocument: {} }], - config: { useTypeImports: true }, + config: { useTypeImports: true, enumsAsTypes: true }, }, ]; diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index 43b1bf0..d4b1712 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -187,7 +187,6 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { await t.test('Zod rejects invalid input without writing rows', async () => { for (const invalid of [ { ...input, title: ' ' }, - { ...input, category: 'Soup' }, { ...input, servings: 0 }, { ...input, ingredients: [] }, { ...input, instructions: [] }, @@ -386,10 +385,13 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { { id: publicRecipe.id, input: { ...input, visibility: 'private' } }, owner.cookie, ); - assert.equal( - (await ok(CookbookDocument, {}, reader.cookie)).cookbook.totalCount, - 0, - ); + for (const scope of ['all', 'saved', 'created'] as const) { + assert.equal( + (await ok(CookbookDocument, { scope }, reader.cookie)).cookbook + .totalCount, + 0, + ); + } assert.equal( (await ok(RecipeDocument, { id: publicRecipe.id }, reader.cookie)) .recipe,