kitty
kitty copied to clipboard
Kitty is a collection of utilities for SvelteKit
Kitty
Kitty is a collection of utilities for SvelteKit. It includes libraries and handlers for developing secure frontend apps.
Kitty features encrypted server-side sessions, and provides mitigations against CSRF attacks for forms submitted to the server.
Installing
-
Install via NPM:
npm install @grottopress/kitty -
Set
compilerOptions.moduleResolutiontobundler,node16, ornodenextintsconfig.json:// ->> tsconfig.json { // ... "compilerOptions": { // ... "moduleResolution": "bundler", // ... } // ... }This prevents the following error:
Cannot find module '@grottopress/kitty' or its corresponding type declarations -
Set up
vite.config.jsas follows:// ->> vite.config.js // ... /** @type {import('vite').UserConfig} */ const config = { // ... optimizeDeps: { exclude: ['@grottopress/kitty'], }, ssr: { noExternal: ['@grottopress/kitty'], }, // ... } export default config
Using
Handlers
Kitty provides the following handlers:
decryptSession: Decrypts session retrieved from theCookierequest headerdisableCache: SetsCache-ControlandExpiresheaders to disable caching app-wideencryptSession: Encrypts session and sends it via theSet-Cookieresponse headerfilterRequestMethods: Forbids requests methods not listed in theALLOWED_REQUEST_METHODSenv varverifyCsrfToken: Generates and verifies CSRF tokens for requests that require them
The src/hooks.server.ts file should look similar to this:
// ->> src/hooks.server.ts
// ...
import { sequence } from '@sveltejs/kit/hooks'
import {
decryptSession,
disableCache,
encryptSession,
filterRequestMethods,
verifyCsrfToken
} from '@grottopress/kitty/server'
export const handle = sequence(
decryptSession,
filterRequestMethods,
verifyCsrfToken,
disableCache,
encryptSession
)
// ...
Add the following to the .env file:
# ->> .env
# ...
# Client
#
# Server
#
ALLOWED_REQUEST_METHODS=DELETE,GET,HEAD,PATCH,POST
SECRET_KEY=J9oyuTDuGSQhwE3lOutjUgXe4yfpWQtI # 32 bytes/chars
SESSION_KEY=_my-app-session
# ...
Update the file with your own details. Use a cryptographically-secure value for the secret key. You may run tr -cd '[:alnum:]' < /dev/random | fold -w32 | head -n1 to generate a key.
Remember to set secure permissions for this file: chmod 0600 .env.
Add types to src/app.d.ts:
declare namespace App {
// ...
interface Locals {
session: Session
// ...
}
interface PageData {
csrfHeaderKey?: string
csrfParamKey?: string
csrfToken?: string
// ...
}
interface Session {
csrfHeaderKey?: string
csrfParamKey?: string
csrfToken?: string
// ...
}
// ...
}
// ...
Session
Kitty features encrypted server-side sessions. Any value stored in the event.locals.session object is encrypted and persisted as cookies on the client via the Set-Cookie response header.
Sessions can be made available client-side via the session store by defining .load() in src/routes/+layout.server.ts as follows:
// ->> src/routes/+layout.server.ts
// ...
import type { ServerLoad } from '@sveltejs/kit'
export const load: ServerLoad = async ({ locals }) => {
const { csrfHeaderKey, csrfParamKey, csrfToken } = locals.session
return { csrfHeaderKey, csrfParamKey, csrfToken }
}
// ...
// ->> src/routes/+layout.ts
// ...
import type { Load } from '@sveltejs/kit'
export const load: Load = async ({ data }) => {
const csrfHeaderKey = data?.csrfHeaderKey
const csrfParamKey = data?.csrfParamKey
const csrfToken = data?.csrfToken
return { csrfHeaderKey, csrfParamKey, csrfToken }
}
// ...
This can then be accessed in routes (eg: data.csrfToken), or via the page store in components (eg: $page.data.csrfToken).
CSRF
Kitty provides support for generating and verifying CSRF tokens for forms submitted to the server, either via JSON or as form data.
CSRF mitigations are enforced for all requests except those with the GET, HEAD, OPTIONS, and TRACE methods.
Examples:
# ->> .env
# ...
# Skip CSRF protection for these routes (comma-separated `event.route.id`s).
# Adding a route will include all its children.
CSRF_SKIP_ROUTES=/about/team,/blog/[slug]
# ...
-
JSON:
// src/routes/some-path/+page.ts // ... import type { Load } from '@sveltejs/kit' export const load: Load = async ({ fetch }) => { return { fetch } } // ...<!-- src/routes/some-path/+page.svelte --> <script lang="ts"> export let data: App.PageData let { csrfHeaderKey, csrfToken, fetch } = data $: ({ csrfHeaderKey, csrfToken, fetch } = data) let city = '' let response: Response | undefined const onSubmit = async () => { if (!csrfHeaderKey || !csrfToken) return const headers = new Headers headers.set('Content-Type', 'application/json') headers.set(csrfHeaderKey, csrfToken) response = await fetch('/some-endpoint', { method: 'POST', headers, body: JSON.stringify({ city }) }) } </script> <h1>City</h1> <!-- ... --> <form on:submit|preventDefault={onSubmit}> <input type="text" name="city" bind:value={city} /> <button type="submit">Submit</button> </form> <!-- ... --> -
Form data:
<script lang="ts"> export let data: App.PageData let { csrfParamKey, csrfToken } = data $: ({ csrfParamKey, csrfToken } = data) let city = '' // ... </script> <h1>City</h1> <!-- ... --> <form method="POST" action="/some-endpoint"> <input type="hidden" name={csrfParamKey} value={csrfToken} /> <input type="text" name="city" bind:value={city} /> <button type="submit">Submit</button> </form> <!-- ... -->
Components
The following components are available:
-
ToggleButton<script lang="ts"> import { ToggleButton } from '@grottopress/kitty' let menu: HTMLElement | undefined let showMenu = false </script> <div> <ToggleButton bind:open={showMenu} target={menu} clickOutside> ≡ Menu </ToggleButton> {#if showMenu} <nav bind:this={menu}> <a href="/link/a">Link A</a> <a href="/link/b">Link B</a> <a href="/link/c">Link C</a> </nav> {/if} </div>The
clickOutsideprop, iftrue, enables closing a menu by clicking anywhere outside the button and its target.
Actions
Kitty comes with the following actions for use in components:
-
clickOutside<script lang="ts"> import { clickOutside } from '@grottopress/kitty' export let open: boolean const toggle = () => { open = !open } const close = () => { open = false } </script> <button type="button" use:clickOutside={close} on:click={toggle}> <slot /> </button>
Helpers
The following helpers are available:
-
.isJson(context: Request | Response): booleanimport { isJson } from '@grottopress/kitty' isJson(requestOrResponseObject).isJson()checks if the given request or response is JSON, based on itsContent-Typeheader.
Developing
After cloning this repository, copy sample.env to .env, and run npm install. You may start the development server with npm run dev, or run tests with npm run test.
Contributing
- Fork it
- Switch to the
masterbranch:git checkout master - Create your feature branch:
git checkout -b my-new-feature - Make your changes, updating changelog and documentation as appropriate.
- Commit your changes:
git commit - Push to the branch:
git push origin my-new-feature - Submit a new Pull Request against the
GrottoPress:masterbranch.