diff --git a/src/lib/__tests__/stateCookie.test.ts b/src/lib/__tests__/stateCookie.test.ts new file mode 100644 index 0000000..1104ebb --- /dev/null +++ b/src/lib/__tests__/stateCookie.test.ts @@ -0,0 +1,36 @@ +import { describe, test, expect } from "vitest" +import { getStateCookie, setStateCookie } from "../stateCookie" + +describe("setStateCookie", () => { + test("throws errors on empty string", () => { + expect(() => setStateCookie("")) + .toThrow("state value is required") + }) + test("sets cookie with prefix app.txs", () => { + const state = setStateCookie("code_verifier_secret") + expect(document.cookie) + .toMatch(`app.txs.${state}=code_verifier_secret`) + }) + test("sets cookie with latest value", () => { + const state = setStateCookie("code_verifier_secret") + expect(document.cookie) + .toMatch(`app.txs.${state}=code_verifier_secret`) + }) + test("returns state", () => { + const state = setStateCookie("code_verifier_secret") + expect(state).toMatch(/[\w-]+/) + }) +}) + +describe("getStateCookie", () => { + test("gets cookie", () => { + const state = crypto.randomUUID() + const random = Math.random().toString(36).substring(7) + document.cookie = `app.txs.${state}=${random}` + expect(getStateCookie(state)).toBe(random) + }) + + test("gets none", () => { + expect(getStateCookie('nothere')).toBeUndefined() + }) +}) diff --git a/src/lib/stateCookie.ts b/src/lib/stateCookie.ts new file mode 100644 index 0000000..846db16 --- /dev/null +++ b/src/lib/stateCookie.ts @@ -0,0 +1,15 @@ + +import { saveCookie, getCookie } from './cookie' + +export const setStateCookie = (value: string) => { + if (!value) throw new Error('state value is required') + + const state = crypto.randomUUID() + saveCookie(`app.txs.${state}`, value, 30) + + return state +} + +export const getStateCookie = (state: string) => { + return getCookie(`app.txs.${state}`) +}