|
| 1 | +import { |
| 2 | + seal as ironSeal, |
| 3 | + unseal as ironUnseal, |
| 4 | + defaults, |
| 5 | +} from 'iron-webcrypto'; |
| 6 | + |
| 7 | +// Extract the precise Crypto type that iron-webcrypto expects |
| 8 | +type IronCrypto = Parameters<typeof ironSeal>[0]; |
| 9 | + |
| 10 | +// Cast globalThis.crypto to iron-webcrypto's expected type |
| 11 | +// Runtime-safe: DOM Crypto is fully compatible with iron-webcrypto's _Crypto |
| 12 | +const ironCrypto: IronCrypto = globalThis.crypto as unknown as IronCrypto; |
| 13 | + |
| 14 | +const VERSION_DELIMITER = '~'; |
| 15 | +const CURRENT_MAJOR_VERSION = 2; |
| 16 | + |
| 17 | +interface SealOptions { |
| 18 | + password: string; |
| 19 | + ttl?: number; |
| 20 | +} |
| 21 | + |
| 22 | +interface UnsealOptions { |
| 23 | + password: string; |
| 24 | + ttl?: number; |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Parse an iron-session seal to extract the version |
| 29 | + */ |
| 30 | +function parseSeal(seal: string): { |
| 31 | + sealWithoutVersion: string; |
| 32 | + tokenVersion: number | null; |
| 33 | +} { |
| 34 | + const [sealWithoutVersion = '', tokenVersionAsString] = |
| 35 | + seal.split(VERSION_DELIMITER); |
| 36 | + const tokenVersion = |
| 37 | + tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10); |
| 38 | + return { sealWithoutVersion, tokenVersion }; |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * Seal (encrypt) data in a format compatible with iron-session. |
| 43 | + * |
| 44 | + * @param data - The data to seal |
| 45 | + * @param options - Sealing options |
| 46 | + * @param options.password - Password for encryption (must be at least 32 characters) |
| 47 | + * @param options.ttl - Time to live in seconds (default: 0 = no expiration) |
| 48 | + * @returns The sealed string |
| 49 | + */ |
| 50 | +export async function sealData( |
| 51 | + data: unknown, |
| 52 | + { password, ttl = 0 }: SealOptions, |
| 53 | +): Promise<string> { |
| 54 | + const passwordObj = { |
| 55 | + id: '1', |
| 56 | + secret: password, |
| 57 | + }; |
| 58 | + |
| 59 | + const seal = await ironSeal(ironCrypto, data, passwordObj, { |
| 60 | + ...defaults, |
| 61 | + ttl: ttl * 1000, // Convert seconds to milliseconds |
| 62 | + }); |
| 63 | + |
| 64 | + // Add the version delimiter exactly like iron-session does |
| 65 | + return `${seal}${VERSION_DELIMITER}${CURRENT_MAJOR_VERSION}`; |
| 66 | +} |
| 67 | + |
| 68 | +/** |
| 69 | + * Unseal (decrypt) data that was sealed with iron-session or sealData. |
| 70 | + * |
| 71 | + * @param encryptedData - The sealed string to decrypt |
| 72 | + * @param options - Unsealing options |
| 73 | + * @param options.password - Password for decryption |
| 74 | + * @param options.ttl - Time to live in seconds (default: 0 = no expiration check) |
| 75 | + * @returns The unsealed data, or empty object if unsealing fails |
| 76 | + */ |
| 77 | +export async function unsealData<T = unknown>( |
| 78 | + encryptedData: string, |
| 79 | + { password, ttl = 0 }: UnsealOptions, |
| 80 | +): Promise<T> { |
| 81 | + const { sealWithoutVersion, tokenVersion } = parseSeal(encryptedData); |
| 82 | + |
| 83 | + // Format password as a map like iron-session expects |
| 84 | + const passwordMap = { 1: password }; |
| 85 | + |
| 86 | + let data: unknown; |
| 87 | + try { |
| 88 | + data = |
| 89 | + (await ironUnseal(ironCrypto, sealWithoutVersion, passwordMap, { |
| 90 | + ...defaults, |
| 91 | + ttl: ttl * 1000, |
| 92 | + })) ?? {}; |
| 93 | + } catch (error) { |
| 94 | + // Match iron-session's behavior: return empty object for known errors |
| 95 | + if ( |
| 96 | + error instanceof Error && |
| 97 | + /^(Expired seal|Bad hmac value|Cannot find password|Incorrect number of sealed components)/.test( |
| 98 | + error.message, |
| 99 | + ) |
| 100 | + ) { |
| 101 | + return {} as T; |
| 102 | + } |
| 103 | + throw error; |
| 104 | + } |
| 105 | + |
| 106 | + // Handle token version for backwards compatibility |
| 107 | + if (tokenVersion === 2) { |
| 108 | + return data as T; |
| 109 | + } else if (tokenVersion !== null) { |
| 110 | + // For older token versions, extract the persistent property |
| 111 | + const record = data as Record<string, unknown>; |
| 112 | + return (record.persistent ?? data) as T; |
| 113 | + } |
| 114 | + |
| 115 | + return data as T; |
| 116 | +} |
0 commit comments