Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ personal wantlist ("crate").

IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`.

**Status: M4 delivered – final polish.** See the README's
**Status: Final submission ready (hand-in 27 November).** See the README's
[feature overview](README.md#what-you-can-do-in-crate) for implemented features
and the project status section for planned work.

Expand Down
154 changes: 91 additions & 63 deletions README.md

Large diffs are not rendered by default.

266 changes: 153 additions & 113 deletions docs/AI-USAGE.md

Large diffs are not rendered by default.

52 changes: 28 additions & 24 deletions docs/VM-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@ sudo /usr/bin/systemctl restart crate-api

To populate the catalog initially or import an updated MusicBrainz snapshot, run `pnpm --filter @t19/server db:import:musicbrainz`. Existing reviews and crate items are preserved.

The database and role must already exist before migrations are run. The API
runs on port 3001 and needs the repository's `schema.graphql` file at startup.
The database and role must already exist before migrations are run. By default,
the API binds to `127.0.0.1` (`HOST` default) on port `3001` (`PORT` default)
so it is only reachable locally and through the Apache `/graphql` reverse proxy,
and it needs the repository's `schema.graphql` file at startup.

### Automated deployment

Expand Down Expand Up @@ -251,15 +253,13 @@ endpoint, set `VITE_GRAPHQL_URL` in `client/.env.local`.

## Smoke suite

The smoke tests below were originally written for the sample catalog created by `db:seed`. Some expected album names, counts and genre IDs do not match the deployed MusicBrainz catalog.

**TODO (M4):** Update the smoke tests and expected results to use the MusicBrainz catalog.

Until then, the tests can be used to check API functionality, but sample-specific results should not be treated as expected values on the VM. Check each response for GraphQL `errors`.
The smoke tests below target the deployed 2,000-album MusicBrainz catalog
imported by `db:import:musicbrainz` (and remain valid if additional albums are
imported later). Check each response for GraphQL `errors`.

```bash
API=http://localhost:3001/graphql
gql() { curl -s "$API" -H 'content-type: application/json' -d "$1"; echo; }
API=http://127.0.0.1:3001/graphql
gql() { curl -fsS "$API" -H 'content-type: application/json' -d "$1"; echo; }
```

To test Apache routing as well, set `API=http://localhost/graphql` and repeat.
Expand All @@ -270,34 +270,38 @@ To test Apache routing as well, set `API=http://localhost/graphql` and repeat.
gql '{"query":"{ __typename }"}'
```

2. **Case-insensitive search.** With sample data, both `blue` and `BLUE` should
return `totalCount: 4`.
2. **Case-insensitive search.** Both `blue` and `BLUE` must return the same
non-zero `totalCount` (`66` on the clean 2,000-album MusicBrainz catalog).

```bash
gql '{"query":"{ a: searchAlbums(input:{query:\"blue\",sort:RELEVANCE},first:5){ totalCount } b: searchAlbums(input:{query:\"BLUE\",sort:RELEVANCE},first:5){ totalCount } }"}'
```

3. **Artist search.** Searching for `coltrane` should return _A Love Supreme_
and _Blue Train_, both by John Coltrane.
3. **Artist and prefix search.** Searching for `coltrane` returns _A Love
Supreme_ (John Coltrane, 1965), and `pink fl` returns _The Dark Side of the
Moon_ (1973) and _A Tree Full of Secrets_ (1999) by Pink Floyd.

```bash
gql '{"query":"{ searchAlbums(input:{query:\"coltrane\",sort:TITLE_ASC},first:5){ totalCount edges { node { title releaseYear artists { name } genres { name } } } } }"}'
gql '{"query":"{ coltrane: searchAlbums(input:{query:\"coltrane\",sort:TITLE_ASC},first:5){ totalCount edges { node { title releaseYear artists { name } genres { name } } } } pinkFloyd: searchAlbums(input:{query:\"pink fl\",sort:TITLE_ASC},first:5){ totalCount edges { node { title releaseYear artists { name } } } } }"}'
```

4. **Genre filters and facets.** With Rock (ID `4`) selected, the sample catalog
should return `totalCount: 7`. Genre facets should show Rock `7`, Pop `3`
and Electronic `2`. The `decadeFacets` counts should also reflect only albums
matching the Rock filter.
4. **Genre filters and facets.** Genre IDs depend on import order, so read the
`Rock` genre ID from `genreFacets` first, then filter by it. On the clean
2,000-album MusicBrainz catalog, `totalCount` is `229` and `decadeFacets`
reflect only Rock matches.

```bash
gql '{"query":"{ searchAlbums(input:{query:\"\",genreIds:[\"4\"],sort:TITLE_ASC},first:5){ totalCount genreFacets { genre { name } count } decadeFacets { decade count } } }"}'
ROCK_ID=$(gql '{"query":"{ searchAlbums(input:{query:\"\",sort:RELEASE_YEAR_DESC},first:1){ genreFacets { genre { id name } count } } }"}' \
| node -e 'const d = JSON.parse(require("fs").readFileSync(0,"utf8")); const g = d.data.searchAlbums.genreFacets.find(f => f.genre.name === "Rock"); console.log(g?.genre.id ?? "");')
gql "{\"query\":\"{ searchAlbums(input:{query:\\\"\\\",genreIds:[\\\"$ROCK_ID\\\"],sort:TITLE_ASC},first:5){ totalCount genreFacets { genre { name } count } decadeFacets { decade count } } }\"}"
```

5. **Pagination.** The first query should return two albums, `hasNextPage: true`
and an `endCursor`. Replace `<endCursor>` in the second query with that value;
the next page should contain different albums.
5. **Pagination.** The first query returns two albums, `hasNextPage: true`,
`totalCount: 2000` (on a clean MusicBrainz import), and an `endCursor`. Pass
that `endCursor` to the second query; the next page must return two different
albums.

```bash
gql '{"query":"{ searchAlbums(input:{query:\"\",sort:RELEASE_YEAR_DESC},first:2){ edges { node { title releaseYear } } pageInfo { hasNextPage endCursor } } }"}'
gql '{"query":"{ searchAlbums(input:{query:\"\",sort:RELEASE_YEAR_DESC},first:2,after:\"<endCursor>\"){ edges { node { title releaseYear } } pageInfo { hasNextPage endCursor } } }"}'
gql '{"query":"{ searchAlbums(input:{query:\"\",sort:RELEASE_YEAR_DESC},first:2){ totalCount edges { node { id title releaseYear } } pageInfo { hasNextPage endCursor } } }"}'
gql '{"query":"{ searchAlbums(input:{query:\"\",sort:RELEASE_YEAR_DESC},first:2,after:\"<endCursor>\"){ edges { node { id title releaseYear } } pageInfo { hasNextPage endCursor } } }"}'
```
13 changes: 7 additions & 6 deletions docs/WORKFLOW.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,13 @@ underveisinnleveringer. Issues are assigned one milestone at a time - at the
start of each milestone, not all at once up front - so we can rebalance based
on what we learned from the previous one.

| Milestone | Due | Delivers |
| --------- | ------ | ------------------------------------------------------------------ |
| M1 | 2 Oct | Spec and mockup: schema, ADRs, UI sketch, client with mock data |
| M2 | 16 Oct | Database and GraphQL backend running on the VM, client interaction |
| M3 | 30 Oct | Beta: search, paging, sorting, filtering, accessibility, bærekraft |
| M4 | 13 Nov | Finished prototype and the full test suite |
| Milestone | Due | Delivers |
| --------- | ------ | -------------------------------------------------------------------------------- |
| M1 | 2 Oct | Spec and mockup: schema, ADRs, UI sketch, client with mock data |
| M2 | 16 Oct | Database and GraphQL backend running on the VM, client interaction |
| M3 | 30 Oct | Beta: search, paging, sorting, filtering, accessibility, bærekraft |
| M4 | 13 Nov | Finished prototype and the full test suite |
| Final | 27 Nov | Final submission: polished prototype, docs, live VM, Blackboard & FeedbackFruits |

## Using AI tools

Expand Down
28 changes: 19 additions & 9 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,19 +114,29 @@ embedding UUID characters. Deriving `displayName` server-side stops the client
choosing an arbitrary name string, though it is still not an authentication
guarantee. Clearing `localStorage` resets the user's identity in the browser, but their existing reviews and crate items remain in the database.

## 6. Plain CSS, Apollo Client cache, URL as search state
## 6. Plain CSS, client-side routing, Apollo Client cache, URL as search state

**Context:** A small client that needs good accessibility, a small bundle, and
searches that survive reload and can be shared.
**Context:** A small client that needs good accessibility, a small bundle, smooth in-app transitions that preserve cached queries, manual dark-mode control compatible with a strict Content-Security-Policy, and searches that survive reload and can be shared.

**Options:** A CSS framework or component library, or plain CSS. A separate
state store such as Redux, or the Apollo cache. Search state in components, or
in the URL.
**Options:** A CSS framework or component library, or plain CSS. Full-page anchor navigation, `react-router-dom`, or a zero-dependency History API router. A separate state store such as Redux, or the Apollo cache. Search state in components, or in the URL.

**Decision:**

- **Plain CSS** for a smaller bundle and full control over focus and contrast.
- **The Apollo cache** stores data received from the server. Adding or removing an album from the crate updates its cached state, while review changes trigger a refresh of the album details.
- **Plain CSS** for a smaller bundle and full control over focus, contrast and dark/light tokens (`client/src/global.css`).
- **Zero-dependency History API SPA routing (`#131`, PR `#138`)** in `client/src/router.ts` (`useSyncExternalStore` subscribed to `popstate` + `history.pushState` / `replaceState`) and `client/src/components/Link.tsx`. Navigating between Discover (`/project2/`), Album detail (`/project2/album/:id`), and Your crate (`/project2/crate`) happens client-side without full document reloads, keeping Apollo's `InMemoryCache` warm across route changes and avoiding redundant refetches on back navigation. Pathname changes (excluding initial load and query-only or hash-only updates) move keyboard focus to `<main id="main">` (`preventScroll: true`), including after lazy `<Suspense>` routes resolve, and `RouteErrorBoundary` catches stale-chunk dynamic-import failures after deploys (reloading once per URL via a `sessionStorage` cooldown guard and falling back to an accessible manual-reload prompt if needed). Direct deep links and reloads are handled by Apache's `FallbackResource /project2/index.html` (`docs/VM-setup.md`).
- **The Apollo cache** stores data received from the server. Adding or removing an album from the crate updates its cached state, and review publish/update/delete mutations update the cached `Album` and `reviews` state directly alongside resilient album refresh recovery (`#122`, `#131`). Web Storage access (`localStorage` for user ID and theme, `sessionStorage` for back-navigation return state) degrades gracefully to in-memory fallbacks when storage throws.
- **CSP-safe manual theme toggle (`#132`)** via `ThemeToggle`, `useTheme`, and an external `/project2/theme-init.js` script (298 B) that applies any stored `light` or `dark` override to `document.documentElement.dataset.theme` before first paint—avoiding flash of unstyled theme without requiring `'unsafe-inline'` in `Content-Security-Policy`. Without an override, CSS follows `prefers-color-scheme`.
- **The URL** holds the search term, sort and filters (genres, decades, countries and `reviewed`).

**Consequences:** We write all the styling ourselves. Apollo Client manages server data, while the URL preserves search terms, filters and sorting so searches can be shared or revisited.
**Consequences:** We write all styling and lightweight routing ourselves rather than adding runtime dependencies, keeping the client bundle well below the 512 KB per-chunk CI budget. Apollo Client manages server data across routes, while the URL preserves search terms, filters and sorting so searches can be shared or revisited.

## 7. Security, privacy, and deployment tradeoffs

**Context:** Crate runs on a shared university VM (`http://it2810-19.idi.ntnu.no/project2`) behind Apache, fetches album artwork from Cover Art Archive, and uses simulated browser identities without real authentication.

**Decision & safeguards:**

- **API and PostgreSQL hardening (`#127`, `#129` — merged in PR `#136`):** The API binds to `127.0.0.1:3001` by default (`HOST`/`PORT`), enforces request body size, GraphQL query depth/complexity, input length/array caps, and rate limiting, masks unexpected internal errors and disables GraphQL introspection when `NODE_ENV=production` (configured via `crate-api.service`; see [`docs/VM-setup.md`](./VM-setup.md)), and configures PostgreSQL pool timeouts and error handlers.
- **Apache compression, caching, and security headers (`#133`):** Production deployment is configured to enable `mod_deflate` gzip compression on `/graphql` JSON responses, immutable 1-year `Cache-Control` headers on content-hashed `/project2/assets/`, `Cache-Control: no-cache` revalidation on `index.html` and `theme-init.js`, and strict `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy: no-referrer`, and `Content-Security-Policy` headers without `'unsafe-inline'` in `script-src` (see [`docs/VM-setup.md`](./VM-setup.md) for the exact Apache configuration and verification commands; not live until applied and verified in browser DevTools on `it2810-19`).
- **Cover Art Archive IP privacy tradeoff:** Album covers are loaded directly in the browser from `coverartarchive.org` (which redirects to `archive.org`) rather than mirrored on the VM. This avoids hosting third-party copyrighted artwork and keeps VM storage minimal, at the tradeoff that the visitor's browser sends its IP address directly to Cover Art Archive / Internet Archive when loading covers. Crate sends `Referrer-Policy: no-referrer` (both via `<meta name="referrer">` and Apache headers, plus `referrerPolicy="no-referrer"` on cover `<img>` elements) so internal search/filter URLs are not leaked in `Referer` headers.
- **Plain-HTTP course-VM transport tradeoff:** The NTNU course VM serves the application over plain HTTP (`http://it2810-19.idi.ntnu.no/project2`) without TLS managed by the group. Because Crate uses simulated anonymous browser UUIDs rather than real accounts, passwords, or personal data, no credentials are exposed in transit; however, plain HTTP means `X-User-Id` headers and GraphQL payloads are unencrypted on the network. Any real-world deployment with user accounts would require HTTPS/TLS termination at Apache or a reverse proxy.
14 changes: 11 additions & 3 deletions docs/data-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ with every known country represented by its credited artists. The
MusicBrainz fetch script is only used when preparing a new snapshot; the
application does not call the MusicBrainz API at runtime. Core metadata is
licensed CC0 1.0; user-contributed genre associations are CC BY-NC-SA 3.0. See
the [README](../README.md#real-album-catalog-63) for source, import and license
the [README](../README.md#real-album-catalog-63-105) for source, import and license
details.

The client also uses the optional MusicBrainz release-group ID to load artwork
Expand Down Expand Up @@ -70,10 +70,18 @@ existing reviews.
the user's personal wantlist. The schema has separate add and remove actions
so repeated requests cannot accidentally switch the album back to the wrong
state.
- A **search history entry** (`search_history`) belongs to one simulated user
and stores a trimmed, non-empty submitted search query (`PRIMARY KEY (user_id, query)`)
along with `last_searched_at` (indexed on `(user_id, last_searched_at)` for
recency lookups). Submitting an existing query refreshes its timestamp, and
`mySearchHistory` returns the 10 most recent distinct queries newest first
(empty list for anonymous requests). `recordSearch` and `clearSearchHistory`
require a valid `X-User-Id` header.

The tables exist, with unique `(user_id, album_id)` pairs for reviews and
crate items, a rating check of 1-5, and a trigger updating `review.updated_at`.
See
crate items, a rating check of 1-5, a non-empty trimmed query check on
`search_history`, cascading deletes from `app_user`, and a trigger updating
`review.updated_at`. See
[`docs/architecture.md`](./architecture.md) decision 5 for how the identity travels and what happens when it is missing.

## Search results
Expand Down
Binary file modified docs/images/album_detail_dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/album_detail_light.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/discover_desktop_dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/discover_desktop_light.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/filters.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/mobile_album_detail.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/mobile_discover.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/my_crate.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/reviews.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading