@substrate-system/cookie
    Preparing search index...

    @substrate-system/cookie

    cookie

    tests types module semantic versioning Common Changelog install size license

    Create signed cookies with an HMAC key, and verify them.

    • [x] works in Cloudflare
    • [x] works in Node

    This will stringify a JSON object in a stable format, then use an HMAC key to create a signature. The final cookie value includes a token that is the signature concatenated with the JSON you passed in, all base64 encoded.

    This conveniently includes a command to generate keys as well.

    Parsing the cookie will return the cookie as a plain object, plus a token -- the base64 encoded HMAC signature + session data.

    Parsing a session token will return the object that you passed in when creating the token, useful for embedding an ID, or any data you want to be certain has not been changed.

    Verify the signature with verifySessionString.

    Contents

    npm i -S @substrate-system/cookie
    

    These functions should all be run in a server.

    import {
    setCookie,
    createCookie,
    } from '@substrate-system/cookie'
    const { SECRET_KEY } = process.env

    const cookie = createCookie({ hello: 'world' }, SECRET_KEY)
    // => session=vTAHUs4...; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax

    // send our cookie to the client
    // create a Headers instance
    const headers = setCookie(cookie)

    // send the cookie in the response
    return new Response('hello', {
    status: 200,
    headers
    })

    In the future, the cookie gets sent back in a request.

    Assuming request is a Request object,

    import {
    parseCookie,
    verifySessionString,
    parseSession
    } from '@substrate-system/cookie'
    const { SECRET_KEY } = process.env

    export default async function onRequest (request:Request) {
    const cookies = request.headers.getSetCookie()

    if (!cookies.length) {
    // no cookie, need to login
    return new Response(null, { status: 401 })
    }

    // first parse the cookie, so we can read the session data
    const parsedCookie = parseCookie(cookies[0])

    // now verify the signature
    const isOk = await verifySessionString(parsedCookie.session, SECRET_KEY)

    if (!isOk) {
    // has cookie, signature is not valid
    return new Response(null, { status: 403 })
    }

    // parse the session,
    // get the data that we encoded
    const session = parseSession(parsedCookie.session)
    // => { hello: 'world' }

    // do something with the verified data
    }

    Create a string suitable for use as a cookie. Sign the given data with a secret key, and stringify the signature + JSON data as a base64 string.

    Note


    This will add default values for additional cookie attributes.

    session=123; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax
    

    These environment variables can be used to set the cookie attributes:

    COOKIE_HTTPONLY
    COOKIE_SECURE
    COOKIE_SAMESITE
    COOKIE_MAX_AGE_SPAN
    COOKIE_DOMAIN
    COOKIE_PATH
    import { createCookie } from '@substrate-system/cookie'

    const cookie = createCookie({ hello: 'world' }, SECRET_KEY)
    console.log(cookie)
    // => session=vTAHUs4nBS65UPy4AdnIMVdh-5MeyJoZWxsbyI6IndvcmxkIn0; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax
    async function createCookie (
    sessionData:Record<string, string>,
    secretKey:string,
    name?:string,
    env?:CookieEnv,
    ):Promise<string>

    Create or patch a Headers instance.

    import { setCookie } from '@substrate-system/cookie'

    const headers = setCookie(cookie)
    function setCookie (
    cookie:string,
    _headers?:Headers,
    ):Headers

    Parse a cookie string into a plain object.

    import { parseCookie } from '@substrate-system/cookie'

    const parsed = parseCookie('session=vTAHUs4nBS65UPy4AdnIMVdh-5MeyJoZWxsbyI6IndvcmxkIn0; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax')

    // =>
    // {
    // session: 'vTAHUs4nBS65UPy4AdnIMVdh-5MeyJoZWxsbyI6IndvcmxkIn0',
    // 'Max-Age': '604800',
    // Path: '/',
    // HttpOnly: true,
    // Secure: true,
    // SameSite: 'Lax'
    // }

    Get the cookie via request headers. An example in Cloudflare:

    import {
    parseCookie,
    verifySessionString
    } from '@substrate-system/cookie'

    export const onRequest:PagesFunction<Env> = async (ctx) => {
    const cookieHeader = ctx.request.headers.get('Cookie')

    // first get the cookie data
    const cookie = parseCookie(cookieHeader)

    // now parse and verify the token
    const { session } = cookie
    const sessionOk = verifySessionString(session, env.COOKIE_SECRET)
    if (!sessionOk) return new Response(null, { status: 403 })

    // get any data encoded in the session string
    const { id } = parseSession(session)
    }

    Parsing a cookie returns all the cookie properties as an object, one of which is session. The session is arbitrary data, base64 encoded and signed with the secret key. Parsing the session string will return whatever data was encoded originally.

    import {
    parseSession,
    parseCookie
    } from '@substrate-system/cookie'

    parsed = parseCookie('session=N6bimY9...; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax')
    const session = parseSession(parsed!.session)
    // => { hello: 'world' }

    Verify the given session token. This checks that an embedded signature is correct for the associated data.

    import {
    verifySessionString,
    parseCookie
    } from '@substrate-system/cookie'

    // ... get headers somehow ...

    const cookies = headers.getSetCookie()
    const cookie = parseCookie(cookies[0])
    const isOk = await verifySessionString(cookie.session, SECRET_KEY)
    // => true
    async function verifySessionString (
    session:string,
    key:string
    ):Promise<boolean>

    Do this serverside. Patch the given headers, removing the cookie.

    function rmCookie (headers:Headers, name?:string):void
    

    This exposes ESM and common JS via package.json exports field.

    import '@substrate-system/cookie'
    
    require('@substrate-system/cookie')
    

    Session cookies are signed using HMAC SHA256, which requires using a secret key of at least 32 bytes of length.

    This package conveniently includes a command line tool to generate keys, exposed as cookiekey. After installing this as a dependency, use it like this:

    $ npx cookiekey
    BGSzELbpBuESqmKyhtw/9zD7sHIy2hf/kSK0y0U0L60=

    Save the secret key as part of your server environment. This depends on always using the same secret key.

    This works anywhere that supports the Web Crypto API. Has been verified to work in Cloudflare and Node.