From bb8a71326a85a3d70bad36a35d300c614d8e8b7f Mon Sep 17 00:00:00 2001 From: Fuwn Date: Tue, 3 Mar 2026 08:57:37 -0800 Subject: chore(effect): add v4 cookie decode foundation and tests --- src/lib/Effect/authCookie.ts | 45 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/lib/Effect/authCookie.ts (limited to 'src/lib/Effect/authCookie.ts') diff --git a/src/lib/Effect/authCookie.ts b/src/lib/Effect/authCookie.ts new file mode 100644 index 00000000..e716f5e9 --- /dev/null +++ b/src/lib/Effect/authCookie.ts @@ -0,0 +1,45 @@ +import type { AniListAuthorisation } from "$lib/Data/AniList/identity"; +import { Effect, Result, Schema } from "effect"; + +const UserCookieSchema = Schema.Struct({ + token_type: Schema.String, + expires_in: Schema.Number, + access_token: Schema.String, + refresh_token: Schema.String, +}); + +export const decodeAuthCookieEffect = (cookie: string) => + Effect.gen(function* () { + const parsedCookie = yield* Effect.try({ + try: () => JSON.parse(cookie) as unknown, + catch: (cause) => new Error("Invalid user cookie JSON", { cause }), + }); + const decodedCookie = yield* Effect.try({ + try: () => Schema.decodeUnknownSync(UserCookieSchema)(parsedCookie), + catch: (cause) => new Error("Invalid user cookie payload", { cause }), + }); + + return { + tokenType: decodedCookie.token_type, + expiresIn: decodedCookie.expires_in, + accessToken: decodedCookie.access_token, + refreshToken: decodedCookie.refresh_token, + } as AniListAuthorisation; + }); + +export const decodeAuthCookieEither = (cookie: string) => + Result.try({ + try: () => Effect.runSync(decodeAuthCookieEffect(cookie)), + catch: (cause) => + cause instanceof Error + ? cause + : new Error("Failed to decode user cookie", { cause }), + }); + +export const decodeAuthCookieOrThrow = ( + cookie: string, +): AniListAuthorisation => { + const decoded = decodeAuthCookieEither(cookie); + + return Result.getOrThrow(decoded); +}; -- cgit v1.2.3