# Protect a site with a password

`access` in `recit.config.ts` puts a password modal over every page of a Récit site: the pages, the
decks the site publishes and the stories embedded in a page. It runs in the browser alone: no
server, no serverless function, nothing to set at the host. It is a small lock on a document, not a
real protection: read the next section before you use it.

## What it stops, and what it does not

- **It stops** a passer-by who opens a link: they see the modal, not the content.
- **It does not stop** someone who really wants the content. The site is static: the text of the
  pages is in the prerendered HTML, the decks are in their JSON files, the PDF are in `dist/pdf/`,
  and the search index is in `dist/`. Viewing the source, turning JavaScript off or typing the
  address of a file is enough.
- **The password is never written in clear**, in the repository or in the published site: only its
  hash is. The hash of a short password is found by brute force: use a passphrase, several words
  long.

For a real protection, protect the site at the host, which Récit does not manage:
[Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/policies/access/),
[basic authentication in nginx](https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html), or
[Vercel deployment protection](https://vercel.com/docs/security/deployment-protection).

## Set a password

Print the hash of the password from the folder of the site. The command asks for the password twice
without showing it, and prints the hash alone:

```bash
pnpm exec recit-site hash-password
```

Paste the hash in the config:

```ts title="recit.config.ts"
import { defineConfig } from "recit/config";

export default defineConfig({
  metadata: { title: "Lorem Ipsum" },
  access: {
    password: "sha256:4f1c…:9f86d0…", // the salt and the hash, never the password
    title: "Reserved document", // the title of the modal (optional)
    message: "Enter the password you received by e-mail.", // optional
    remember: "30d", // "session" or a duration ("12h", "30d"); "30d" by default
  },
});
```

The command draws a random salt and writes it in the hash, `sha256:<salt>:<hex>`: two sites with the
same password do not share a hash, and changing the title of the site never breaks it. Piped, the
command reads one line (`echo "$PASSWORD" | recit-site hash-password`).

A hash of the older form, `sha256:<hex>` with no salt in it, keeps working: it is salted by the name
of the site, `access.salt` when set, else `metadata.title`, else `site.title`, so changing the title
changes it. `--salt` prints that form, salted by hand (`recit-site hash-password --salt "Lorem"`,
with `access.salt: "Lorem"`); `access.salt` next to a hash that carries its own salt is refused.

A password in clear is refused: `access.password` must start with `sha256:`. Do not write the
password in a comment of `recit.config.ts` either: the browser loads that file, and a source map
(when enabled with `build.sourcemap`) keeps the comments.

### From an environment variable

To keep even the hash out of the repository, name a variable that holds the password. The build
reads it (from the environment or a `.env` file of the site) and writes only its hash in the site:

```ts title="recit.config.ts"
access: {
  password: { env: "RECIT_SITE_PASSWORD" },
},
```

A missing variable stops the build. A name starting with `RECIT_PUBLIC_` is refused: those variables
are sent to the browser.

## What a visitor sees

Before the first paint, a small script of `<head>` reads the stored token and hides the site when
there is none, so the content never flashes. The modal is full screen, with the title, the message,
the password field (with a button to show it), "Remember me" and an error tied to the field. The
focus is in the field; Enter unlocks.

- A right password stores a token, the hash and an expiry: in `localStorage` for the duration of
  `remember`, or in `sessionStorage` (until the tab closes) when "Remember me" is unchecked or
  `remember` is `"session"`, which hides the box.
- A new password invalidates every token: they carry the old hash.
- **Lock**, in the header and the mobile menu, forgets the token and shows the modal again.
- The labels follow `metadata.lang` (English and French).
- Under `recit-site dev` the modal is on too; `dev: false` turns it off there.

## Search engines

A site behind `access` tells search engines to keep out: every page gets
`<meta name="robots" content="noindex, nofollow">`, over `metadata.robots`. Set
`access.indexable: true` to keep `metadata.robots` as it is. The site framework writes no
`robots.txt`, and writes a `sitemap.xml` only when `sitemap` is set: leave it out of a site that
should not be indexed.

## Encrypt the content: `mode: "encrypted"`

The default mode hides the site; it encrypts nothing. With `mode: "encrypted"`, the content is no
longer in clear in the published site:

```ts title="recit.config.ts"
access: {
  password: { env: "RECIT_SITE_PASSWORD" },
  mode: "encrypted",
},
```

At build time, Récit draws a random content key and encrypts with it (AES-256-GCM) the pages, the
local components they import, the navigation, the stories and their slides, the search index and the
exported files. It then protects that key with a key derived from the password (PBKDF2-SHA256, at
least 600 000 iterations, a random salt at each build), in `recit-access.json` next to the pages.
Every page of `dist/` is an empty shell. Without the password, viewing the source, turning
JavaScript off or typing the address of a file gives encrypted bytes only. The browser derives the
key once, in the modal, and decrypts each part of the site when it needs it, with WebCrypto.

The password must come from a variable (`{ env }`): a key cannot be derived from a hash, so a
`sha256:` password is refused. A password under 12 characters gets a warning.

### What it protects, and its limits

- **A weak password breaks offline.** `recit-access.json` is public: anyone can copy it and try
  passwords on their own machine, with no limit and without anyone seeing it. PBKDF2 slows each try
  down, but a dictionary word or eight letters still fall. Use a passphrase: four or five random
  words.
- **One password for everyone, and no revocation.** Whoever had it keeps what they downloaded.
  Changing the password takes a new build and a new deploy, and the older deploys the host keeps
  (Vercel preview URLs, for example) still open with the old one.
- **No indexing, no reading without JavaScript.** A search engine, or a browser without JavaScript,
  sees the modal only. `indexable: true` is refused, and so is the `inkeep` search, a third-party
  service that crawls the site.
- **"Remember me" keeps the key** of the current build in the browser: anyone who uses that browser
  opens the site until it expires. The box starts unchecked. The key goes to IndexedDB as a key the
  page cannot export, and Web Storage only holds the build and its expiry; a browser without
  IndexedDB keeps nothing and asks again on each page. Unchecked, the key lasts for the tab, and a
  key left behind by a closed tab is forgotten at the next visit. Each new build asks for the
  password again.
- **A secure context only.** WebCrypto exists over HTTPS and on `localhost`; over plain HTTP the
  modal says the page cannot be opened.
- **Downloads work, decrypted in the tab.** The PDF of the docs, the PDF of a published deck (its
  toolbar's "Download the deck (PDF)", or `<PdfDownload>`), a calendar's `.ics` and a roadmap's
  `.rss` are encrypted in the build, so a plain link would save encrypted bytes. Once the password
  is given, their buttons and links fetch the file through the page, which decrypts it, and save the
  decrypted copy under its own name. It lives in the tab's memory until it is saved, never in a
  cache, and a file the build encrypted that a host serves in clear is refused. Whoever downloads a
  file keeps it: the password does not follow it.

### Encrypted, and in clear

| Encrypted                                                                          | In clear                                                                                                           |
| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| the text of the pages (Markdown and MDX), and their front matter                   | the addresses of the pages (their slugs and route paths), their number and their size                              |
| the local components a page imports                                                | `recit.config.ts`: the site title, the header links, the slots                                                     |
| the navigation: the labels and the tree of the pages                               | the code of Récit and of the packages a site uses                                                                  |
| the decks, the stories and their MDX slides                                        | the images and the media (their names are hashes), the media of `public/`, and the files listed in `access.public` |
| the search index of pagefind                                                       | the stylesheets, those of the local components included (`.css` and CSS modules)                                   |
| `exports.json`, the PDFs of the docs and of the decks, the `.ics` and `.rss` feeds | `recit-access.json`: the wrapped key, the salt, the lists of the sealed files and modules                          |

A file name or a folder name is part of the address of its page: `kraxolith-secret.mdx` publishes
`/kraxolith-secret`, in clear, in the shell of the page and in the code that routes the site. Name
pages as you would name public URLs. A stylesheet stays in clear too, the `content:` of a rule or a
class name included: keep text out of CSS.

Never put anything secret in `recit.config.ts`: it stays in clear, and so does a module that it
imports (the build names those).

Files in `public/` are copied into the build like the rest of `dist/`. Its media (images, video,
fonts) stay in clear, outside the lock; its other files (an HTML page, a PDF, a JSON file) are
sealed with the content and cannot be read at their own address. Keep in `public/` only what may be
public, and put a private document in a page of the site.

To serve specific files or folders of `public/` at their own address in `mode: "encrypted"`, list
them in `access.public` (a leading `/`, relative to `basePath`; a trailing `/` covers a folder and
everything under it, otherwise a single file; `"/"` alone, `".."` and `"*"` are refused). **A listed
path is no longer protected**: it is written in clear in `dist/`, outside the lock, and anyone reads
or downloads it at its address without a password. List only what may be public. Only files of
`public/` can be listed, never a page of the site. The build stops on a path that matches no file in
`public/`, on a path it fills with content (`/pagefind/`, `/exports.json`), and on a file it
replaced or moved (a page or a status page with the same address, such as `public/index.html` or
`public/404.html`). `access.public` is refused outside `mode: "encrypted"`, even empty.

```ts title="recit.config.ts"
access: {
  mode: "encrypted",
  password: { env: "RECIT_SITE_PASSWORD" },
  public: ["/press/", "/legal.pdf"],
},
```

A page outside the site's folder (`docs.files: ["../shared/*.md"]`) is encrypted like the others:
being a page is what counts, not where it lives. So is a component that only pages import, wherever
it lives (a sibling folder, a workspace package, an example). A module that a clear part of the site
also imports stays in clear, and the build names each such module of your own code. A page that
would still land in clear fails the build.

A build that fails leaves no `dist/`: the server bundle, which renders every page in clear, is
written outside `dist/` (in `node_modules/.recit/`), and both are removed on failure. A sealed build
writes no source map, no Vite manifest, no `.md` copy of the pages, no `llms.txt` and no sitemap,
and its file names are hashes.

### Hosting, preview and dev

- The site stays static: any host serves it. A host or a custom Content Security Policy must allow
  `script-src blob:` and `img-src blob:`: the decrypted code and image previews are loaded from
  object URLs (`security.csp: "strict"` adds both automatically).
- A feed reader cannot decrypt: the `.ics` and `.rss` feeds of a sealed site cannot be subscribed
  to. A calendar's "Subscribe" menu offers only the download of the `.ics` there, decrypted.
- `recit-site preview` serves the sealed `dist/` (`localhost` is a secure context).
- `recit-site dev` encrypts nothing, since Vite serves the sources: the modal runs in the hash mode,
  computed from the same variable, with a warning. Its hash is PBKDF2 at the iterations of the
  build, with a salt drawn for each dev server, never the title: the dev bundle carries no fast hash
  of the real password. Each restart of the dev server asks for the password again. `dev: false`
  turns the modal off there.
- `recit export --to pdf --site`, and `recit export --to pdf` of a deck whose output lands in a
  sealed build, print a sealed site too: they read the same variable, refuse without it, and write
  every file encrypted. A PDF or `exports.json` is never written in clear into the build, not even
  for a moment.
- A server build (`ssr`) is refused: the server would hold the content in clear.

## Settings

| Key          | Default  | Description                                                                                                  |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------ |
| `password`   | —        | `"sha256:<salt>:<hex>"` from `recit-site hash-password`, or `{ env: "NAME" }` read at build                  |
| `salt`       | title    | the salt of an older hash `sha256:<hex>` and of `{ env }`; `metadata.title`, else `site.title`, when absent  |
| `title`      | —        | the title of the modal; "Protected document" in the language of the site                                     |
| `message`    | —        | the text under the title; "Enter the password to continue." when absent                                      |
| `remember`   | `"30d"`  | `"session"`, or a duration in minutes, hours or days (`"15m"`, `"12h"`, `"30d"`)                             |
| `dev`        | `true`   | `false` turns the modal off under `recit-site dev`                                                           |
| `indexable`  | `false`  | `true` keeps `metadata.robots` instead of `noindex, nofollow`; refused in `mode: "encrypted"`                |
| `mode`       | `"hash"` | `"hash"` hides the site; `"encrypted"` encrypts its content with a key derived from the password (`{ env }`) |
| `iterations` | 600000   | `mode: "encrypted"`: the PBKDF2 iterations, at least 600 000                                                 |
| `public`     | `[]`     | `mode: "encrypted"`: paths of `public/` (`"/press/"`, `"/legal.pdf"`) served in clear, with no protection    |

A deck built alone by `recit build`, outside a site, has no modal.
