UNPKG

@analog-tools/auth

Version:
1 lines 264 kB
{"version":3,"file":"index.cjs","names":["i","a","o","s","c","l","d","f","p","m","h","decodeBase64URL","jwk.isJWK","jwk.isSecretJWK","invalidKeyInput","jwk.isPrivateJWK","jwk.isPublicJWK","b64u","#jwks","#cached","#url","#timeoutDuration","#cooldownDuration","#cacheMaxAge","#headers","#customFetch","#cache","#jwksTimestamp","#local","#pendingFetch"],"sources":["../logger/index.js","../inject/index.js","../../../packages/auth/src/server/services/session.service.ts","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/buffer_utils.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/base64.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/util/base64url.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/crypto_key.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/invalid_key_input.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/util/errors.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/is_key_like.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/helpers.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/type_checks.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/signing.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/jwk_to_key.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/normalize_key.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/key/import.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/validate_crit.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/validate_algorithms.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/check_key_type.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jws/flattened/verify.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jws/compact/verify.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/jwt_claims_set.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwt/verify.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwks/local.js","../../.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwks/remote.js","../../../packages/auth/src/server/utils/pkce.ts","../../../packages/auth/src/server/services/oauth-authentication.service.ts","../../../packages/auth/src/server/routes/authenticated.ts","../../../packages/auth/src/server/utils/sanitizeRedirectUrl.ts","../../../packages/auth/src/server/routes/callback.ts","../../.pnpm/uncrypto@0.1.3/node_modules/uncrypto/dist/crypto.web.mjs","../../../packages/auth/src/server/routes/login.ts","../../../packages/auth/src/server/routes/logout.ts","../../../packages/auth/src/server/routes/protected-data.ts","../../../packages/auth/src/server/utils/timing-safe-equal.ts","../../../packages/auth/src/server/routes/refresh-tokens.ts","../../../packages/auth/src/server/routes/user.ts","../../../packages/auth/src/server/functions/registerRoutes.ts","../../../packages/auth/src/server/utils/getLastPathSegment.ts","../../../packages/auth/src/server/functions/handleAuthRoute.ts","../../../packages/auth/src/server/functions/checkAuthentication.ts","../../../packages/auth/src/server/functions/useAnalogAuthMiddleware.ts","../../../packages/auth/src/server/functions/useAnalogAuth.ts"],"sourcesContent":["import { defineEventHandler as e } from \"h3\";\n//#region src/lib/logger.types.ts\nvar t = /* @__PURE__ */ function(e) {\n\treturn e.SkyBlue = \"\\x1B[94m\", e.OceanBlue = \"\\x1B[34m\", e.MidnightBlue = \"\\x1B[38;5;17m\", e.SkyBlueBg = \"\\x1B[104m\", e.OceanBlueBg = \"\\x1B[44m\", e.MidnightBlueBg = \"\\x1B[48;5;17m\", e.MintGreen = \"\\x1B[92m\", e.ForestGreen = \"\\x1B[32m\", e.EmeraldGreen = \"\\x1B[38;5;28m\", e.MintGreenBg = \"\\x1B[102m\", e.ForestGreenBg = \"\\x1B[42m\", e.EmeraldGreenBg = \"\\x1B[48;5;28m\", e.LemonYellow = \"\\x1B[93m\", e.SunflowerYellow = \"\\x1B[33m\", e.GoldYellow = \"\\x1B[38;5;220m\", e.LemonYellowBg = \"\\x1B[103m\", e.SunflowerYellowBg = \"\\x1B[43m\", e.GoldYellowBg = \"\\x1B[48;5;220m\", e.RoseRed = \"\\x1B[91m\", e.FireRed = \"\\x1B[31m\", e.BurgundyRed = \"\\x1B[38;5;88m\", e.RoseRedBg = \"\\x1B[101m\", e.FireRedBg = \"\\x1B[41m\", e.BurgundyRedBg = \"\\x1B[48;5;88m\", e.LavenderPurple = \"\\x1B[95m\", e.RoyalPurple = \"\\x1B[38;5;93m\", e.DeepPurple = \"\\x1B[38;5;54m\", e.LavenderPurpleBg = \"\\x1B[105m\", e.RoyalPurpleBg = \"\\x1B[48;5;93m\", e.DeepPurpleBg = \"\\x1B[48;5;54m\", e.PeachOrange = \"\\x1B[38;5;215m\", e.TangerineOrange = \"\\x1B[38;5;208m\", e.AmberOrange = \"\\x1B[38;5;214m\", e.PeachOrangeBg = \"\\x1B[48;5;215m\", e.TangerineOrangeBg = \"\\x1B[48;5;208m\", e.AmberOrangeBg = \"\\x1B[48;5;214m\", e.SilverGray = \"\\x1B[37m\", e.SlateGray = \"\\x1B[90m\", e.CharcoalGray = \"\\x1B[38;5;238m\", e.SilverGrayBg = \"\\x1B[47m\", e.SlateGrayBg = \"\\x1B[100m\", e.CharcoalGrayBg = \"\\x1B[48;5;238m\", e.PureBlack = \"\\x1B[30m\", e.PureWhite = \"\\x1B[97m\", e.PureBlackBg = \"\\x1B[40m\", e.PureWhiteBg = \"\\x1B[107m\", e.Cyan = \"\\x1B[36m\", e.Reset = \"\\x1B[0m\", e.Bold = \"\\x1B[1m\", e.Dim = \"\\x1B[2m\", e.Underline = \"\\x1B[4m\", e.Blink = \"\\x1B[5m\", e.Reverse = \"\\x1B[7m\", e.Hidden = \"\\x1B[8m\", e;\n}({}), n = /* @__PURE__ */ function(e) {\n\treturn e[e.trace = 0] = \"trace\", e[e.debug = 1] = \"debug\", e[e.info = 2] = \"info\", e[e.warn = 3] = \"warn\", e[e.error = 4] = \"error\", e[e.fatal = 5] = \"fatal\", e[e.silent = 6] = \"silent\", e;\n}({});\nfunction r(e) {\n\treturn [\n\t\t\"trace\",\n\t\t\"debug\",\n\t\t\"info\",\n\t\t\"warn\",\n\t\t\"error\",\n\t\t\"fatal\",\n\t\t\"silent\"\n\t].includes(e);\n}\n//#endregion\n//#region src/lib/error-serialization/error-serializer.ts\nvar i = class e {\n\tstatic {\n\t\tthis.DEFAULT_MAX_DEPTH = 10;\n\t}\n\tstatic {\n\t\tthis.CIRCULAR_REF_PLACEHOLDER = \"[Circular Reference]\";\n\t}\n\tstatic {\n\t\tthis.MAX_DEPTH_PLACEHOLDER = \"[Max Depth Reached]\";\n\t}\n\tstatic {\n\t\tthis.UNABLE_TO_SERIALIZE = \"[Unable to serialize]\";\n\t}\n\tstatic {\n\t\tthis.serializationCache = /* @__PURE__ */ new Map();\n\t}\n\tstatic {\n\t\tthis.MAX_CACHE_SIZE = 100;\n\t}\n\tstatic getCacheKey(e, t, n, r) {\n\t\tif (!e.stack) return null;\n\t\tlet i = e.stack.split(\"\\n\")[0] || \"\";\n\t\treturn `${e.name}:${e.message}:${i}:${t}:${n}:${r}`;\n\t}\n\tstatic addToCache(e, t) {\n\t\tif (this.serializationCache.size >= this.MAX_CACHE_SIZE) {\n\t\t\tlet e = this.serializationCache.keys().next().value;\n\t\t\te && this.serializationCache.delete(e);\n\t\t}\n\t\tthis.serializationCache.set(e, t);\n\t}\n\tstatic serialize(t, n = {}) {\n\t\tlet { includeStack: r = !0, maxDepth: i = e.DEFAULT_MAX_DEPTH, includeNonEnumerable: a = !1 } = n;\n\t\tif (t instanceof Error) {\n\t\t\tlet e = this.getCacheKey(t, r, i, a);\n\t\t\tif (e) {\n\t\t\t\tlet t = this.serializationCache.get(e);\n\t\t\t\tif (t) return t;\n\t\t\t}\n\t\t\tlet n = this.serializeError(t, r, i, a, /* @__PURE__ */ new WeakSet());\n\t\t\treturn e && this.addToCache(e, n), n;\n\t\t}\n\t\tif (typeof t == \"string\") return t;\n\t\tlet o = this.safeStringify(t, i, /* @__PURE__ */ new WeakSet());\n\t\tif (typeof o == \"string\") return o;\n\t\ttry {\n\t\t\treturn JSON.stringify(o, null, 2);\n\t\t} catch {\n\t\t\treturn String(o);\n\t\t}\n\t}\n\tstatic serializeError(e, t, n, r, i = /* @__PURE__ */ new WeakSet()) {\n\t\tif (i.has(e)) return {\n\t\t\tmessage: e.message,\n\t\t\tname: e.name,\n\t\t\t[Symbol.for(\"circular\")]: this.CIRCULAR_REF_PLACEHOLDER\n\t\t};\n\t\ti.add(e);\n\t\tlet a = {\n\t\t\tmessage: e.message,\n\t\t\tname: e.name\n\t\t};\n\t\treturn t && e.stack && (a.stack = e.stack), \"cause\" in e && e.cause !== void 0 && (e.cause instanceof Error ? a.cause = this.serializeError(e.cause, t, n - 1, r, i) : a.cause = this.safeStringify(e.cause, n - 1, i)), Object.keys(e).forEach((t) => {\n\t\t\tif (!(t in a)) try {\n\t\t\t\tlet r = e;\n\t\t\t\ta[t] = this.safeStringify(r[t], n - 1, i);\n\t\t\t} catch {\n\t\t\t\ta[t] = this.UNABLE_TO_SERIALIZE;\n\t\t\t}\n\t\t}), r && Object.getOwnPropertyNames(e).forEach((t) => {\n\t\t\tif (!(t in a) && t !== \"stack\" && t !== \"message\" && t !== \"name\") try {\n\t\t\t\tlet r = Object.getOwnPropertyDescriptor(e, t);\n\t\t\t\tif (r && r.enumerable === !1) {\n\t\t\t\t\tlet r = e;\n\t\t\t\t\ta[t] = this.safeStringify(r[t], n - 1, i);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\ta[t] = this.UNABLE_TO_SERIALIZE;\n\t\t\t}\n\t\t}), a;\n\t}\n\tstatic safeStringify(e, t, n = /* @__PURE__ */ new WeakSet()) {\n\t\tif (t <= 0) return this.MAX_DEPTH_PLACEHOLDER;\n\t\tif (typeof e != \"object\" || !e) return e;\n\t\tif (n.has(e)) return this.CIRCULAR_REF_PLACEHOLDER;\n\t\tn.add(e);\n\t\ttry {\n\t\t\tif (Array.isArray(e)) {\n\t\t\t\tlet r = e.map((e) => this.safeStringify(e, t - 1, n));\n\t\t\t\treturn n.delete(e), r;\n\t\t\t}\n\t\t\tlet r = {};\n\t\t\tfor (let [i, a] of Object.entries(e)) try {\n\t\t\t\tr[i] = this.safeStringify(a, t - 1, n);\n\t\t\t} catch {\n\t\t\t\tr[i] = this.UNABLE_TO_SERIALIZE;\n\t\t\t}\n\t\t\treturn n.delete(e), r;\n\t\t} catch {\n\t\t\treturn n.delete(e), this.UNABLE_TO_SERIALIZE;\n\t\t}\n\t}\n}, a = {\n\thighlight: {\n\t\tcolor: t.LemonYellow,\n\t\tbold: !0\n\t},\n\taccent: { color: t.SkyBlue },\n\tattention: {\n\t\tcolor: t.RoyalPurple,\n\t\tbold: !0\n\t},\n\tsuccess: { color: t.ForestGreen },\n\twarning: { color: t.TangerineOrange },\n\terror: { color: t.FireRed },\n\tinfo: { color: t.OceanBlue },\n\tdebug: { color: t.SlateGray }\n}, o = {\n\tsuccess: \"✅\",\n\twarning: \"⚠️\",\n\terror: \"❌\",\n\tinfo: \"ℹ️\",\n\tdebug: \"🐞\"\n}, s = {\n\ttrace: t.SlateGray,\n\tdebug: t.Cyan,\n\tinfo: t.ForestGreen,\n\twarn: t.SunflowerYellow,\n\terror: t.FireRed,\n\tfatal: t.FireRed,\n\tsilent: t.Reset\n}, c = class {\n\tresolveStyle(e, t = \"test\", n) {\n\t\treturn this.applyStyle(e, t, n);\n\t}\n\tstatic {\n\t\tthis.INJECTABLE = !0;\n\t}\n\tconstructor(e = {}) {\n\t\tthis.styleCache = /* @__PURE__ */ new Map();\n\t\tlet t = process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\";\n\t\tthis.useColors = e.useColors === void 0 ? !t : e.useColors, this.globalStyles = {\n\t\t\t...a,\n\t\t\t...e.styles\n\t\t}, this.globalIcons = {\n\t\t\t...o,\n\t\t\t...e.icons\n\t\t};\n\t}\n\tsetUseColors(e) {\n\t\tthis.useColors = e;\n\t}\n\tgetUseColors() {\n\t\treturn this.useColors;\n\t}\n\tupdateStyleConfig(e, t) {\n\t\tthis.globalStyles = {\n\t\t\t...this.globalStyles,\n\t\t\t...e\n\t\t}, this.globalIcons = {\n\t\t\t...this.globalIcons,\n\t\t\t...t\n\t\t};\n\t}\n\tformatMessage(e, n, r, i, a) {\n\t\tlet o = i ? `[${r}:${i}]` : `[${r}]`;\n\t\tif (this.useColors) {\n\t\t\tlet r = this.getColorForLevel(e);\n\t\t\treturn a && (r = a), `${r}${o} ${n}${t.Reset}`;\n\t\t} else return `${o} ${n}`;\n\t}\n\tformatMessageWithMetadata(e, t, n, r, i) {\n\t\tlet a = t, o = this.getColorForLevel(e);\n\t\tif (r?.style) {\n\t\t\tlet e = this.applyStyle(r.style, n, i);\n\t\t\te && (o = e);\n\t\t}\n\t\treturn r?.icon && (a = `${this.resolveIcon(r.icon, n, i)} ${t}`), this.formatMessage(e, a, n, i, o);\n\t}\n\tparseMetadataParameter(e, t = []) {\n\t\tif (e && typeof e == \"object\" && !Array.isArray(e) && (\"style\" in e || \"icon\" in e)) return {\n\t\t\tmetadata: e,\n\t\t\trestData: t\n\t\t};\n\t\tlet n = e === void 0 ? t : [e, ...t];\n\t\tif (n.length > 0) {\n\t\t\tlet e = n[n.length - 1];\n\t\t\tif (e && typeof e == \"object\" && !Array.isArray(e) && (\"style\" in e || \"icon\" in e)) return {\n\t\t\t\tmetadata: e,\n\t\t\t\trestData: n.slice(0, -1)\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tmetadata: void 0,\n\t\t\trestData: n\n\t\t};\n\t}\n\tgetColorForLevel(e) {\n\t\tlet r = s[n[e]];\n\t\treturn e === n.fatal ? `${t.Bold}${r}` : r || t.Reset;\n\t}\n\tapplyStyle(e, t, n) {\n\t\tlet r = this.getStyleCacheValue(e);\n\t\tif (r !== void 0) return r;\n\t\tif (typeof e == \"string\") {\n\t\t\tlet r = this.getSemanticStyleColor(e, t, n);\n\t\t\treturn this.setStyleCache(e, r), r;\n\t\t}\n\t\tif (typeof e == \"object\" && \"color\" in e) {\n\t\t\tif (!this.isValidColor(e.color)) {\n\t\t\t\tthis.setStyleCache(e, void 0), this.logWarning(\"Invalid color provided. Only predefined ColorEnum values are allowed.\", t, n);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet r = this.constructStyleCode(e);\n\t\t\treturn this.setStyleCache(e, r), r;\n\t\t}\n\t\tthis.setStyleCache(e, void 0), this.logWarning(\"Unknown style configuration provided. Only semantic style names or valid ColorEnum objects are allowed.\", t, n);\n\t}\n\tisValidColor(e) {\n\t\treturn Object.values(t).includes(e);\n\t}\n\tisValidIcon(e) {\n\t\treturn this.isEmojiIcon(e);\n\t}\n\tgetStyleCacheValue(e) {\n\t\treturn this.styleCache.has(e) ? this.styleCache.get(e) : void 0;\n\t}\n\tsetStyleCache(e, t) {\n\t\tthis.styleCache.set(e, t);\n\t}\n\tlogWarning(e, t, n) {\n\t\tlet r = n ? `${t}:${n}` : t;\n\t\tconsole.warn(`[${r}] ${e}`);\n\t}\n\tconstructStyleCode(e) {\n\t\tlet n = e.color.toString();\n\t\treturn e.bold && (n += t.Bold), e.underline && (n += t.Underline), n;\n\t}\n\tgetSemanticStyleColor(e, n, r) {\n\t\tif (this.styleCache.has(e)) return this.styleCache.get(e);\n\t\tlet i = this.globalStyles[e];\n\t\tif (i) {\n\t\t\tlet n = i.color.toString();\n\t\t\treturn i.bold && (n += t.Bold), i.underline && (n += t.Underline), this.styleCache.set(e, n), n;\n\t\t}\n\t\tlet a = r ? `${n}:${r}` : n;\n\t\tconsole.warn(`[${a}] Unknown semantic style: ${e}. Falling back to default.`), this.styleCache.set(e, void 0);\n\t}\n\tgetStyleCache() {\n\t\treturn this.styleCache;\n\t}\n\tresolveIcon(e, t, n) {\n\t\tif (this.isValidIcon(e)) return e;\n\t\tlet r = [\n\t\t\t\"success\",\n\t\t\t\"warning\",\n\t\t\t\"error\",\n\t\t\t\"info\",\n\t\t\t\"debug\"\n\t\t], i = r.find((t) => t === e);\n\t\treturn i && this.globalIcons[i] ? this.globalIcons[i] : (r.includes(e) ? this.logWarning(`Unknown icon: ${e}. Expected a valid emoji or semantic icon name.`, t, n) : this.logWarning(`Invalid icon: ${e}. Expected a valid emoji or semantic icon name.`, t, n), e);\n\t}\n\tisEmojiIcon(e) {\n\t\treturn (/* @__PURE__ */ \"✅.⚠️.❌.ℹ️.🐞.⭐️.🚀.🔥.✔️.✖️.❓.🔒.🔓.⏳.🕒.⬆️.⬇️.➡️.⬅️.📁.📄.👤.👥.✏️.➕.➖.🔔.⚡️.🎁.🐛.🌟.❤️.👀.⚙️.🔧.🔨.🔑.🎉.📝.🚨.📅.💡.🔍.🔗.🔖.📌.📎.✉️.📞.🌍.☁️.🌈.🌙.☀️.❄️.✨.🎵.📷.🎥.🎤.🔊.🔋.🗑️.💰.💳.🎂.🏅.🏆.👑.🛸.🛡️.🛑.▶️.⏸️.⏺️.⏪.⏩.🔁.🔀.🎲.🎈.🍪.☕️.🍵.🍺.🍷.🍕.🍔.🍟.🍎.🍌.🍒.🍋.🥕.🌽.🥦.🥚.🧀.🍞.🍰.🍦.🍫.🍿.🥓.🍤.🐟.🦀.🐙.🐋.🐬.🐧.🐸.🐢.🐍.🐉.🦄.🐱.🐶.🐭.🐰.🐻.🐼.🐨.🐯.🦁.🐒.🐘.🐎.🐄.🐖.🐑.🐔.🦆.🦢.🦉.🦅.🦜.🦚.🦩.🦋.🐝.🐜.🐞.🕷️.🦂.🐌.🪱.🐛.🦗.🦟.🪰.🪳.🪲\".split(\".\")).includes(e);\n\t}\n}, l = class extends Error {\n\tconstructor(e) {\n\t\tsuper(e), this.name = \"LoggerError\";\n\t}\n}, u = class extends Error {\n\tconstructor(e) {\n\t\tsuper(e), this.name = \"LoggerContextError\";\n\t}\n}, d = {\n\tenabled: !1,\n\twindowMs: 5e3,\n\tflushOnCritical: !0\n}, f = [n.error, n.fatal], p = class {\n\tconstructor(e, t, n) {\n\t\tthis.config = e, this.formatter = t, this.loggerName = n, this.entries = /* @__PURE__ */ new Map();\n\t}\n\taddMessage(e, t, n = \"\") {\n\t\tif (!this.config.enabled || this.config.flushOnCritical && f.includes(e)) return !0;\n\t\tlet r = this.generateFingerprint(t, e, n), i = this.entries.get(r);\n\t\treturn i ? i.count++ : this.entries.set(r, {\n\t\t\tmessage: t,\n\t\t\tlevel: e,\n\t\t\tcontext: n,\n\t\t\tfirstSeen: Date.now(),\n\t\t\tcount: 1\n\t\t}), this.scheduleFlush(), !1;\n\t}\n\tflush() {\n\t\tif (this.entries.size !== 0) {\n\t\t\tthis.flushTimer &&= (clearTimeout(this.flushTimer), void 0);\n\t\t\tfor (let e of this.entries.values()) this.outputMessage(e);\n\t\t\tthis.entries.clear();\n\t\t}\n\t}\n\tdestroy() {\n\t\tthis.flushTimer &&= (clearTimeout(this.flushTimer), void 0), this.entries.clear();\n\t}\n\tgenerateFingerprint(e, t, n) {\n\t\treturn `${t}:${n}:${e}`;\n\t}\n\tscheduleFlush() {\n\t\tthis.flushTimer ||= setTimeout(() => {\n\t\t\tthis.flush();\n\t\t}, this.config.windowMs);\n\t}\n\toutputMessage(e) {\n\t\tlet t = e.message;\n\t\te.count > 1 && (t = `${t} (×${e.count})`);\n\t\tlet r = this.formatter.format({\n\t\t\tlevel: e.level,\n\t\t\tmessage: t,\n\t\t\tlogger: this.loggerName,\n\t\t\ttimestamp: new Date(e.firstSeen),\n\t\t\tcontext: e.context || void 0\n\t\t});\n\t\tswitch (e.level) {\n\t\t\tcase n.trace:\n\t\t\t\tconsole.trace(r);\n\t\t\t\tbreak;\n\t\t\tcase n.debug:\n\t\t\t\tconsole.debug(r);\n\t\t\t\tbreak;\n\t\t\tcase n.info:\n\t\t\t\tconsole.info(r);\n\t\t\t\tbreak;\n\t\t\tcase n.warn:\n\t\t\t\tconsole.warn(r);\n\t\t\t\tbreak;\n\t\t\tcase n.error:\n\t\t\t\tconsole.error(r);\n\t\t\t\tbreak;\n\t\t\tcase n.fatal:\n\t\t\t\tconsole.error(r);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}, m = class {\n\tconstructor(e) {\n\t\tthis.styleEngine = e;\n\t}\n\tformat(e) {\n\t\treturn e.styling ? this.styleEngine.formatMessageWithMetadata(e.level, e.message, e.logger, e.styling, e.context) : this.styleEngine.formatMessage(e.level, e.message, e.logger, e.context);\n\t}\n\tisSelfContained() {\n\t\treturn !1;\n\t}\n}, h = class {\n\tconstructor(e) {\n\t\tthis.prettyPrint = e?.prettyPrint ?? !1;\n\t}\n\tformat(e) {\n\t\ttry {\n\t\t\tlet t = {\n\t\t\t\ttimestamp: e.timestamp.toISOString(),\n\t\t\t\tlevel: this.getLevelName(e.level),\n\t\t\t\tlogger: e.logger,\n\t\t\t\tmessage: e.message\n\t\t\t};\n\t\t\treturn e.context && (t.context = e.context), e.correlationId && (t.correlationId = e.correlationId), e.metadata && Object.keys(e.metadata).length > 0 && (t.metadata = e.metadata), e.error && (t.error = i.serialize(e.error)), JSON.stringify(t, null, this.prettyPrint ? 2 : 0);\n\t\t} catch (t) {\n\t\t\treturn console.error(\"JsonFormatter: Failed to serialize log entry to JSON.\", {\n\t\t\t\terror: t,\n\t\t\t\tentry: e\n\t\t\t}), `${e.level} [${e.logger}] ${e.message} (formatting error)`;\n\t\t}\n\t}\n\tisSelfContained() {\n\t\treturn !0;\n\t}\n\tgetLevelName(e) {\n\t\tswitch (e) {\n\t\t\tcase n.trace: return \"trace\";\n\t\t\tcase n.debug: return \"debug\";\n\t\t\tcase n.info: return \"info\";\n\t\t\tcase n.warn: return \"warn\";\n\t\t\tcase n.error: return \"error\";\n\t\t\tcase n.fatal: return \"fatal\";\n\t\t\tdefault: return \"info\";\n\t\t}\n\t}\n}, g = class {\n\tconstructor(e) {\n\t\tthis.formatterFn = e;\n\t}\n\tformat(e) {\n\t\treturn this.formatterFn(e);\n\t}\n\tisSelfContained() {\n\t\treturn !0;\n\t}\n}, _ = class {\n\tstatic createConsole(e) {\n\t\treturn new m(new c({ useColors: e?.useColors }));\n\t}\n\tstatic createJson(e) {\n\t\treturn new h(e);\n\t}\n\tstatic createCustom(e) {\n\t\treturn new g(e);\n\t}\n}, v = {\n\tenabled: !0,\n\tstrategy: \"mask\",\n\tmaxDepth: 10\n}, y = [\n\t/password/i,\n\t/token/i,\n\t/secret/i,\n\t/apikey|api_key|api-key/i,\n\t/authorization/i,\n\t/credential/i,\n\t/private/i\n], b = [\n\t{\n\t\tpattern: /\\beyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}(?!\\w)/g,\n\t\treplacement: \"[TOKEN]\"\n\t},\n\t{\n\t\tpattern: /\\bBearer\\s+[A-Za-z0-9._~+/-]{8,}=*(?!\\w)/gi,\n\t\treplacement: \"Bearer [TOKEN]\"\n\t},\n\t{\n\t\tpattern: /\\b(?:sk_live|sk_test|pk_live|pk_test|ghp|gho|github_pat|xox[baprs]|ya29)[_.-][A-Za-z0-9_.-]{10,}(?!\\w)/g,\n\t\treplacement: \"[TOKEN]\"\n\t},\n\t{\n\t\tpattern: /(token|api_?key|secret|auth_?token)\\s*[:=]\\s*[A-Za-z0-9._~+/-]{10,}=*/gi,\n\t\treplacement: \"$1: [TOKEN]\"\n\t},\n\t{\n\t\tpattern: /\\b(?!(.)\\1{10})[A-Za-z0-9+/]{16,}={1,2}(?!\\w)/g,\n\t\treplacement: \"[TOKEN]\"\n\t},\n\t{\n\t\tpattern: /(?<![A-Za-z0-9+/])(?!(.)\\1{10})(?=[A-Za-z0-9+/]*[+/])(?=[A-Za-z0-9+/]*(?:\\+|[0-9]))[A-Za-z0-9+/]{16,}(?!\\w)/g,\n\t\treplacement: \"[TOKEN]\"\n\t},\n\t{\n\t\tpattern: /\\b(?!(.)\\1{10})(?=[A-Za-z0-9+/]*[0-9])(?=[A-Za-z0-9+/]*[A-Za-z])[A-Za-z0-9+/]{20,}={0,2}(?!\\w)/g,\n\t\treplacement: \"[TOKEN]\"\n\t},\n\t{\n\t\tpattern: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n\t\treplacement: \"[CARD]\"\n\t},\n\t{\n\t\tpattern: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b/g,\n\t\treplacement: \"[EMAIL]\"\n\t},\n\t{\n\t\tpattern: /\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/g,\n\t\treplacement: \"[IP]\"\n\t},\n\t{\n\t\tpattern: /\\b\\d{3}-\\d{2}-\\d{4}\\b/g,\n\t\treplacement: \"[SSN]\"\n\t}\n];\n//#endregion\n//#region src/lib/sanitization/sanitizer.ts\nfunction x(e) {\n\treturn e.replace(/\\r\\n|\\r|\\n/g, \"\\\\n\").replace(/\\t/g, \"\\\\t\").replace(/[\\x00-\\x1f\\x7f-\\x9f]/g, \"\");\n}\nfunction S(e, t) {\n\tlet n = 0;\n\tfor (let t = 0; t < e.length; t++) {\n\t\tlet r = e.charCodeAt(t);\n\t\tn = (n << 5) - n + r, n &= n;\n\t}\n\treturn Math.abs(n).toString(16).substring(0, t);\n}\nfunction C(e, t) {\n\tswitch (t.strategy) {\n\t\tcase \"mask\": return e.replace(t.pattern, t.replacement);\n\t\tcase \"remove\": return e.replace(t.pattern, \"\");\n\t\tcase \"hash\": return e.replace(t.pattern, (e) => `[HASH:${S(e, t.hashLength)}]`);\n\t\tcase \"custom\": return t.customHandler ? e.replace(t.pattern, t.customHandler) : e.replace(t.pattern, t.replacement);\n\t\tdefault: return e.replace(t.pattern, t.replacement);\n\t}\n}\nfunction w(e, t) {\n\tlet n = e;\n\tfor (let e of t) n = C(n, e);\n\treturn n;\n}\nfunction T(e) {\n\treturn y.some((t) => t.test(e));\n}\nfunction E(e, t, n = 0, r = /* @__PURE__ */ new WeakSet()) {\n\tif (!t.enabled || n > t.maxDepth || e == null) return e;\n\tif (typeof e == \"string\") {\n\t\tlet n = w(e, t.rules);\n\t\treturn n = x(n), n;\n\t}\n\tif (Array.isArray(e)) return r.has(e) ? \"[Circular Reference]\" : (r.add(e), e.map((e) => E(e, t, n + 1, r)));\n\tif (typeof e == \"object\") {\n\t\tif (r.has(e)) return \"[Circular Reference]\";\n\t\tr.add(e);\n\t\tlet i = {};\n\t\tfor (let [a, o] of Object.entries(e)) T(a) && typeof o == \"string\" ? i[a] = \"[REDACTED]\" : i[a] = E(o, t, n + 1, r);\n\t\treturn i;\n\t}\n\treturn e;\n}\nfunction D(e, t) {\n\treturn e.map((e) => ({\n\t\tpattern: e.pattern,\n\t\tstrategy: e.strategy ?? t,\n\t\treplacement: e.replacement ?? \"[REDACTED]\",\n\t\thashLength: e.hashLength ?? 8,\n\t\tcustomHandler: e.customHandler\n\t}));\n}\nfunction O(e) {\n\tlet t = e?.enabled ?? v.enabled, n = e?.strategy ?? v.strategy, r = e?.maxDepth ?? v.maxDepth, i;\n\treturn i = e?.rules ? e.rules : [...b, ...e?.customRules ?? []], {\n\t\tenabled: t,\n\t\trules: D(i, n),\n\t\tmaxDepth: r\n\t};\n}\nfunction k(e, t) {\n\tif (!t.enabled) return e;\n\tlet n = w(e, t.rules);\n\treturn n = x(n), n;\n}\n//#endregion\n//#region ../../node_modules/@analog-tools/inject/index.js\nvar A = class {\n\tstatic {\n\t\tthis.contexts = /* @__PURE__ */ new Map();\n\t}\n\tstatic {\n\t\tthis.defaultScope = \"default\";\n\t}\n\tstatic getRegistry(e = this.defaultScope) {\n\t\tthis.contexts.has(e) || this.contexts.set(e, new I());\n\t\tlet t = this.contexts.get(e);\n\t\tif (!t) throw Error(`Failed to create registry for scope '${e}'`);\n\t\treturn t;\n\t}\n\tstatic createScope(e) {\n\t\tif (this.contexts.has(e)) throw Error(`Scope '${e}' already exists`);\n\t\tlet t = new I();\n\t\treturn this.contexts.set(e, t), t;\n\t}\n\tstatic destroyScope(e) {\n\t\tlet t = this.contexts.get(e);\n\t\tt && (t.destroy(), this.contexts.delete(e));\n\t}\n\tstatic async destroyScopeAsync(e) {\n\t\tlet t = this.contexts.get(e);\n\t\tt && (await t.destroyAsync(), this.contexts.delete(e));\n\t}\n\tstatic async clearAllAsync() {\n\t\tlet e = [], t = Array.from(this.contexts.entries());\n\t\tfor (let [n, r] of t) try {\n\t\t\tawait r.destroyAsync();\n\t\t} catch (t) {\n\t\t\tt instanceof B ? e.push(...t.failures) : t instanceof Error && e.push({\n\t\t\t\tserviceName: `scope:${n}`,\n\t\t\t\terror: t\n\t\t\t});\n\t\t}\n\t\tif (this.contexts.clear(), e.length > 0) throw new B(e);\n\t}\n\tstatic setDefaultScope(e) {\n\t\tthis.defaultScope = e;\n\t}\n\tstatic getActiveScopes() {\n\t\treturn Array.from(this.contexts.keys());\n\t}\n\tstatic clearAll() {\n\t\tlet e = Array.from(this.contexts.values());\n\t\tfor (let t of e) t.destroy();\n\t\tthis.contexts.clear();\n\t}\n}, j = Symbol.for(\"@analog-tools/inject:SERVICE_TOKEN\");\nfunction M(e) {\n\treturn Symbol(e || \"ServiceToken\");\n}\nvar N = class {\n\tstatic {\n\t\tthis.tokens = /* @__PURE__ */ new WeakMap();\n\t}\n\tstatic getToken(e) {\n\t\tif (!this.tokens.has(e)) {\n\t\t\tlet t = M(e.name);\n\t\t\tthis.tokens.set(e, t);\n\t\t}\n\t\tlet t = this.tokens.get(e);\n\t\tif (!t) throw Error(`Failed to get token for service ${e.name}`);\n\t\treturn t;\n\t}\n\tstatic setToken(e, t) {\n\t\tthis.tokens.set(e, t);\n\t}\n};\nfunction P(e) {\n\treturn (t) => {\n\t\tlet n = e || N.getToken(t);\n\t\treturn N.setToken(t, n), t.INJECTABLE = !0, t[j] = n, t;\n\t};\n}\nfunction F() {\n\treturn A.getRegistry();\n}\nvar I = class {\n\tconstructor() {\n\t\tthis.serviceMap = /* @__PURE__ */ new Map(), this.initializingServices = /* @__PURE__ */ new Set(), this.initializationPromises = /* @__PURE__ */ new Map(), this.serviceNames = /* @__PURE__ */ new Map(), this.initializedServices = /* @__PURE__ */ new Set(), this.destroyed = !1;\n\t}\n\tgetServiceKey(e) {\n\t\tlet t = e[j];\n\t\tif (!t) throw new z(e.name);\n\t\treturn this.serviceNames.set(t, e.name), t;\n\t}\n\tgetServiceName(e) {\n\t\treturn this.serviceNames.get(e) ?? \"Unknown\";\n\t}\n\tregister(e, ...t) {\n\t\tlet n = this.getServiceKey(e);\n\t\tif (this.initializingServices.has(n)) throw new R([e.name]);\n\t\tif (!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) {\n\t\t\tthis.initializingServices.add(n);\n\t\t\ttry {\n\t\t\t\tlet r = t.length === 0 ? new e() : new e(...t);\n\t\t\t\tthis.serviceMap.set(n, r);\n\t\t\t} finally {\n\t\t\t\tthis.initializingServices.delete(n);\n\t\t\t}\n\t\t}\n\t}\n\tregisterAsUndefined(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\tthis.serviceMap.set(t, void 0);\n\t}\n\tregisterCustomServiceInstance(e, t) {\n\t\tlet n = this.getServiceKey(e);\n\t\tthis.serviceNames.set(n, e.name), this.serviceMap.set(n, t);\n\t}\n\tgetService(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\treturn this.serviceMap.has(t) || this.register(e), this.serviceMap.get(t);\n\t}\n\thasService(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\treturn this.serviceMap.has(t);\n\t}\n\tasync ensureAsyncInitialized(e, t) {\n\t\tif (this.initializedServices.has(t)) return;\n\t\tif (this.initializationPromises.has(t)) {\n\t\t\tlet e = this.initializationPromises.get(t);\n\t\t\tif (e) {\n\t\t\t\tawait e;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tlet n = e;\n\t\tif (typeof n.initializeAsync != \"function\") {\n\t\t\tthis.initializedServices.add(t);\n\t\t\tlet e = Promise.resolve();\n\t\t\treturn this.initializationPromises.set(t, e), e;\n\t\t}\n\t\tlet r = n.initializeAsync().then(() => {\n\t\t\tthis.initializedServices.add(t);\n\t\t}).catch((e) => {\n\t\t\tthrow this.initializationPromises.delete(t), e;\n\t\t});\n\t\tthis.initializationPromises.set(t, r), await r;\n\t}\n\tasync getServiceAsync(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\tthis.serviceMap.has(t) || this.register(e);\n\t\tlet n = this.serviceMap.get(t);\n\t\treturn n !== void 0 && await this.ensureAsyncInitialized(n, t), n;\n\t}\n\tasync registerAsync(e, ...t) {\n\t\tlet n = this.getServiceKey(e);\n\t\t(!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) && this.register(e, ...t);\n\t\tlet r = this.serviceMap.get(n);\n\t\tawait this.ensureAsyncInitialized(r, n);\n\t}\n\tasync destroyAsync() {\n\t\tif (this.destroyed) return;\n\t\tthis.destroyed = !0;\n\t\tlet e = Array.from(this.initializationPromises.values());\n\t\te.length > 0 && await Promise.allSettled(e);\n\t\tlet t = [], n = Array.from(this.serviceMap.entries());\n\t\tfor (let [e, r] of n) {\n\t\t\tif (!this.initializedServices.has(e) || r === void 0) continue;\n\t\t\tlet n = r;\n\t\t\tif (typeof n.onDestroy == \"function\") try {\n\t\t\t\tawait n.onDestroy();\n\t\t\t} catch (n) {\n\t\t\t\tt.push({\n\t\t\t\t\tserviceName: this.getServiceName(e),\n\t\t\t\t\terror: n\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (this.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear(), t.length > 0) throw new B(t);\n\t}\n\tdestroy() {\n\t\tthis.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear();\n\t}\n}, L = class extends Error {\n\tconstructor(e, t, n) {\n\t\tsuper(e), this.token = t, this.name = \"InjectionError\", n && (this.cause = n);\n\t}\n}, R = class extends L {\n\tconstructor(e) {\n\t\tsuper(`Circular dependency detected: ${e.join(\" -> \")}`), this.name = \"CircularDependencyError\";\n\t}\n}, z = class extends L {\n\tconstructor(e) {\n\t\tsuper(`Service '${e}' is missing SERVICE_TOKEN. Add @Injectable() decorator to the class. See: packages/inject/docs/migrations/symbol-tokens.md`, e), this.name = \"MissingServiceTokenError\";\n\t}\n}, B = class extends L {\n\tconstructor(e) {\n\t\tlet t = e.map((e) => `${e.serviceName}: ${e.error.message}`).join(\"; \");\n\t\tsuper(`Failed to destroy ${e.length} service(s): ${t}`), this.failures = e, this.name = \"AggregateDestructionError\";\n\t}\n\tgetErrors() {\n\t\treturn this.failures.map((e) => e.error);\n\t}\n\thasFailure(e) {\n\t\treturn this.failures.some((t) => t.serviceName === e);\n\t}\n};\nfunction V(e, t = {}) {\n\tlet { required: n = !0 } = t;\n\ttry {\n\t\tlet t = F().getService(e);\n\t\tif (t == null) {\n\t\t\tif (n) throw new L(`Service '${e.name}' not found in registry and is required`, e.name);\n\t\t\treturn;\n\t\t}\n\t\treturn t;\n\t} catch (t) {\n\t\tthrow t instanceof L ? t : new L(`Failed to inject service '${e.name}'`, e.name, t);\n\t}\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.139.0/helpers/esm/decorateMetadata.js\nfunction H(e, t) {\n\tif (typeof Reflect == \"object\" && typeof Reflect.metadata == \"function\") return Reflect.metadata(e, t);\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.139.0/helpers/esm/decorate.js\nfunction U(e, t, n, r) {\n\tvar i = arguments.length, a = i < 3 ? t : r === null ? r = Object.getOwnPropertyDescriptor(t, n) : r, o;\n\tif (typeof Reflect == \"object\" && typeof Reflect.decorate == \"function\") a = Reflect.decorate(e, t, n, r);\n\telse for (var s = e.length - 1; s >= 0; s--) (o = e[s]) && (a = (i < 3 ? o(a) : i > 3 ? o(t, n, a) : o(t, n)) || a);\n\treturn i > 3 && a && Object.defineProperty(t, n, a), a;\n}\n//#endregion\n//#region src/lib/logger.service.ts\nvar W, G = W = class {\n\tconstructor(e = {}, t, r, i) {\n\t\tif (this.config = e, this.childLoggers = {}, this.disabledContexts = [], this.activeGroups = [], i) this.parentLogger = i, this.name = i.name, this.context = r, this.logLevel = i.getLogLevel(), this.styleEngine = i.styleEngine, this.formatter = i.formatter, this.correlationId = i.correlationId, this.sanitizer = i.sanitizer;\n\t\telse {\n\t\t\tif (typeof e.level == \"string\" && !Object.keys(n).includes(e.level)) throw new l(`Invalid log level: ${e.level}`);\n\t\t\tif (this.logLevel = this.castLoglevel(e.level || process.env.LOG_LEVEL || \"info\"), this.name = e.name || \"analog-tools\", this.correlationId = e.correlationId, this.setDisabledContexts(e.disabledContexts ?? process.env.LOG_DISABLED_CONTEXTS?.split(\",\") ?? []), this.styleEngine = t || new c({\n\t\t\t\tuseColors: e.useColors,\n\t\t\t\tstyles: {\n\t\t\t\t\t...a,\n\t\t\t\t\t...e.styles\n\t\t\t\t},\n\t\t\t\ticons: {\n\t\t\t\t\t...o,\n\t\t\t\t\t...e.icons\n\t\t\t\t}\n\t\t\t}), this.formatter = e.formatter || _.createConsole({ useColors: this.styleEngine.getUseColors() }), e.deduplication?.enabled) {\n\t\t\t\tlet t = {\n\t\t\t\t\tenabled: !0,\n\t\t\t\t\twindowMs: e.deduplication.windowMs ?? d.windowMs,\n\t\t\t\t\tflushOnCritical: e.deduplication.flushOnCritical ?? d.flushOnCritical\n\t\t\t\t};\n\t\t\t\tthis.deduplicator = new p(t, this.formatter, this.name);\n\t\t\t}\n\t\t\tthis.sanitizer = O(e.sanitization);\n\t\t}\n\t}\n\tresolveMessage(e) {\n\t\tif (typeof e == \"function\") try {\n\t\t\treturn e();\n\t\t} catch (e) {\n\t\t\treturn console.error(\"Logger: Message evaluation failed:\", e), `[Message evaluation failed: ${e}]`;\n\t\t}\n\t\treturn e;\n\t}\n\tisContextEnabled() {\n\t\treturn !this.context || !(this.parentLogger || this).disabledContexts.includes(this.context);\n\t}\n\tsetDisabledContexts(e) {\n\t\tthis.disabledContexts = e;\n\t}\n\tgetLogLevel() {\n\t\treturn this.logLevel;\n\t}\n\tgetDisabledContexts() {\n\t\treturn (this.parentLogger || this).disabledContexts || [];\n\t}\n\tsetUseColors(e) {\n\t\t(this.parentLogger || this).styleEngine.setUseColors(e);\n\t}\n\tgetUseColors() {\n\t\treturn (this.parentLogger || this).styleEngine.getUseColors();\n\t}\n\tsetCorrelationId(e) {\n\t\tthis.correlationId = e;\n\t}\n\tgetCorrelationId() {\n\t\treturn this.correlationId;\n\t}\n\tclearCorrelationId() {\n\t\tthis.correlationId = void 0;\n\t}\n\tforContext(e) {\n\t\treturn this.childLoggers[e] || (this.childLoggers[e] = new W({}, void 0, e, this)), this.childLoggers[e];\n\t}\n\tgroup(e) {\n\t\tif (!this.isContextEnabled()) return;\n\t\t(this.parentLogger?.activeGroups || this.activeGroups).push(e);\n\t\tlet t = this.formatter.format({\n\t\t\tlevel: n.info,\n\t\t\tmessage: `Group: ${e}`,\n\t\t\tlogger: this.name,\n\t\t\tcontext: this.context,\n\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\tcorrelationId: this.getCorrelationId()\n\t\t});\n\t\tconsole.group(`${t} ▼`);\n\t}\n\tgroupEnd(e) {\n\t\tif (!this.isContextEnabled()) return;\n\t\tlet t = this.parentLogger?.activeGroups || this.activeGroups;\n\t\tif (e) {\n\t\t\tlet n = t.lastIndexOf(e);\n\t\t\tif (n !== -1) {\n\t\t\t\tlet e = t.splice(n);\n\t\t\t\tfor (let t = 0; t < e.length; t++) console.groupEnd(), console.log(\"\");\n\t\t\t}\n\t\t} else t.length > 0 && (t.pop(), console.groupEnd(), console.log(\"\"));\n\t}\n\ttrace(e, t, ...r) {\n\t\tthis.doLog(n.trace, e, t, ...r);\n\t}\n\tdebug(e, t, ...r) {\n\t\tthis.doLog(n.debug, e, t, ...r);\n\t}\n\tinfo(e, t, ...r) {\n\t\tthis.doLog(n.info, e, t, ...r);\n\t}\n\twarn(e, t, ...r) {\n\t\tthis.doLog(n.warn, e, t, ...r);\n\t}\n\terror(e, t, r, ...i) {\n\t\tif (!this.isContextEnabled() || this.logLevel > n.error) return;\n\t\tlet { message: a, serializedError: o, rawError: s, context: c, data: l } = this.parseErrorParameters(e, t, r, i), u = k(a, this.sanitizer), d = c ? E(c, this.sanitizer) : void 0, f = l || [], p, m = f;\n\t\tif (f.length > 0) {\n\t\t\tlet e = f[f.length - 1];\n\t\t\te && typeof e == \"object\" && !Array.isArray(e) && (\"style\" in e || \"icon\" in e) && (p = e, m = f.slice(0, -1));\n\t\t}\n\t\tlet h = {\n\t\t\tlevel: n.error,\n\t\t\tmessage: u,\n\t\t\tlogger: this.name,\n\t\t\tcontext: this.context,\n\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\tmetadata: d,\n\t\t\terror: s,\n\t\t\tstyling: p,\n\t\t\tcorrelationId: this.getCorrelationId()\n\t\t}, g = this.formatter.format(h);\n\t\tif (this.formatter.isSelfContained()) console.error(g);\n\t\telse {\n\t\t\tlet e = [g];\n\t\t\to && e.push(o), d && e.push(d), console.error(...e, ...m);\n\t\t}\n\t}\n\tfatal(e, t, r, ...i) {\n\t\tif (!this.isContextEnabled() || this.logLevel > n.fatal) return;\n\t\tif (typeof e == \"string\" && t && typeof t == \"object\" && !Array.isArray(t) && (\"style\" in t || \"icon\" in t)) {\n\t\t\tlet r = t, i = k(`FATAL: ${e}`, this.sanitizer), a = this.styleEngine.formatMessageWithMetadata(n.fatal, i, this.name, r, this.context);\n\t\t\tconsole.error(a);\n\t\t\treturn;\n\t\t}\n\t\tlet { message: a, serializedError: o, rawError: s, context: c, data: l } = this.parseErrorParameters(e, t, r, i), u = k(a, this.sanitizer), d = c ? E(c, this.sanitizer) : void 0, f = l || [], p, m = f;\n\t\tif (f.length > 0) {\n\t\t\tlet e = f[f.length - 1];\n\t\t\te && typeof e == \"object\" && !Array.isArray(e) && (\"style\" in e || \"icon\" in e) && (p = e, m = f.slice(0, -1));\n\t\t}\n\t\tlet h = {\n\t\t\tlevel: n.fatal,\n\t\t\tmessage: `FATAL: ${u}`,\n\t\t\tlogger: this.name,\n\t\t\tcontext: this.context,\n\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\tmetadata: d,\n\t\t\terror: s,\n\t\t\tstyling: p,\n\t\t\tcorrelationId: this.getCorrelationId()\n\t\t}, g = this.formatter.format(h);\n\t\tif (this.formatter.isSelfContained()) console.error(g);\n\t\telse {\n\t\t\tlet e = [g];\n\t\t\to && e.push(o), d && e.push(d), console.error(...e, ...m);\n\t\t}\n\t}\n\tparseErrorParameters(e, t, n, r = []) {\n\t\tif (e instanceof Error && t === void 0) return {\n\t\t\tmessage: e.message,\n\t\t\tserializedError: i.serialize(e),\n\t\t\trawError: e,\n\t\t\tdata: []\n\t\t};\n\t\tif (typeof e == \"string\" && t === void 0) return {\n\t\t\tmessage: e,\n\t\t\tdata: []\n\t\t};\n\t\tif (typeof e == \"string\" && t instanceof Error && n === void 0) return {\n\t\t\tmessage: e,\n\t\t\tserializedError: i.serialize(t),\n\t\t\trawError: t,\n\t\t\tdata: []\n\t\t};\n\t\tif (typeof e == \"string\" && this.isLogContext(t) && n === void 0) return {\n\t\t\tmessage: e,\n\t\t\tcontext: t,\n\t\t\tdata: []\n\t\t};\n\t\tif (typeof e == \"string\" && t instanceof Error && this.isLogContext(n)) return {\n\t\t\tmessage: e,\n\t\t\tserializedError: i.serialize(t),\n\t\t\trawError: t,\n\t\t\tcontext: n,\n\t\t\tdata: r\n\t\t};\n\t\tlet a = typeof e == \"string\" ? e : \"Unknown error\", o = t instanceof Error ? t : void 0;\n\t\treturn {\n\t\t\tmessage: a,\n\t\t\tserializedError: t ? i.serialize(t) : void 0,\n\t\t\trawError: o,\n\t\t\tdata: n === void 0 ? r : [n, ...r]\n\t\t};\n\t}\n\tisLogContext(e) {\n\t\treturn typeof e == \"object\" && !!e && !Array.isArray(e) && !(e instanceof Error) && !(e instanceof Date) && !(e instanceof RegExp) && typeof e != \"function\";\n\t}\n\tdoLog(e, t, r, ...i) {\n\t\tif (!this.isContextEnabled() || this.logLevel > e) return;\n\t\tlet { metadata: a, restData: o } = this.styleEngine.parseMetadataParameter(r, i), s = this.resolveMessage(t);\n\t\tif (s = k(s, this.sanitizer), !this.handleDeduplication(e, s, a, o)) return;\n\t\tlet c = o?.map((e) => E(e, this.sanitizer)), l, u = {};\n\t\tc && c.length > 0 && c.forEach((e, t) => {\n\t\t\te instanceof Error && !l ? l = e : typeof e == \"object\" && e ? Object.assign(u, e) : u[`arg${t}`] = e;\n\t\t});\n\t\tlet d = {\n\t\t\tlevel: e,\n\t\t\tmessage: s,\n\t\t\tlogger: this.name,\n\t\t\tcontext: this.context,\n\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\tmetadata: Object.keys(u).length > 0 ? u : void 0,\n\t\t\terror: l,\n\t\t\tstyling: a,\n\t\t\tcorrelationId: this.getCorrelationId()\n\t\t}, f = this.formatter.format(d), p = this.formatter.isSelfContained();\n\t\tswitch (e) {\n\t\t\tcase n.trace:\n\t\t\t\tp ? console.trace(f) : console.trace(f, ...c || []);\n\t\t\t\tbreak;\n\t\t\tcase n.debug:\n\t\t\t\tp ? console.debug(f) : console.debug(f, ...c || []);\n\t\t\t\tbreak;\n\t\t\tcase n.info:\n\t\t\t\tp ? console.info(f) : console.info(f, ...c || []);\n\t\t\t\tbreak;\n\t\t\tcase n.warn:\n\t\t\t\tp ? console.warn(f) : console.warn(f, ...c || []);\n\t\t\t\tbreak;\n\t\t\tcase n.error:\n\t\t\tcase n.fatal:\n\t\t\t\tp ? console.error(f) : console.error(f, ...c || []);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tcastLoglevel(e) {\n\t\tif (r(e)) switch (e) {\n\t\t\tcase \"trace\": return n.trace;\n\t\t\tcase \"debug\": return n.debug;\n\t\t\tcase \"info\": return n.info;\n\t\t\tcase \"warn\": return n.warn;\n\t\t\tcase \"error\": return n.error;\n\t\t\tcase \"fatal\": return n.fatal;\n\t\t\tcase \"silent\": return n.silent;\n\t\t}\n\t\tthrow r(e.toLowerCase()) ? new l(`Invalid log level: ${e}. Log levels are case-sensitive. Valid levels: trace, debug, info, warn, error, fatal, silent.`) : new l(`Invalid log level: ${e}. Valid levels: trace, debug, info, warn, error, fatal, silent.`);\n\t}\n\tshouldLogImmediately(e, t) {\n\t\tlet n = (this.parentLogger || this).deduplicator;\n\t\tif (!n) return !0;\n\t\ttry {\n\t\t\treturn n.addMessage(e, t, this.context);\n\t\t} catch (e) {\n\t\t\treturn console.error(\"Logger deduplication error:\", e), !0;\n\t\t}\n\t}\n\thandleDeduplication(e, t, n, r) {\n\t\treturn !n && r.length === 0 ? this.shouldLogImmediately(e, t) : !0;\n\t}\n};\nG = W = U([P(), H(\"design:paramtypes\", [\n\tObject,\n\tc === void 0 ? Object : c,\n\tString,\n\tG === void 0 ? Object : G\n])], G);\n//#endregion\n//#region src/lib/nitro.ts\nfunction K(t = \"api\") {\n\treturn e((e) => {\n\t\tlet n = V(G).forContext(t);\n\t\te.context.logger = n, n.debug(\"Request received\", {\n\t\t\tmethod: e.method,\n\t\t\tpath: e.path,\n\t\t\trequestId: e.context.id\n\t\t});\n\t});\n}\nfunction q(t, n = {}) {\n\tlet { namespace: r = \"api\", level: i = \"debug\", logResponse: a = !1 } = n;\n\treturn e(async (e) => {\n\t\tlet n = V(G).forContext(r), o = Date.now();\n\t\ttry {\n\t\t\tlet r = await t(e), s = Date.now() - o, c = {\n\t\t\t\ttrace: \"trace\",\n\t\t\t\tdebug: \"debug\",\n\t\t\t\tinfo: \"info\",\n\t\t\t\twarn: \"warn\",\n\t\t\t\terror: \"error\",\n\t\t\t\tfatal: \"fatal\",\n\t\t\t\tsilent: void 0\n\t\t\t}[i];\n\t\t\treturn c && typeof n[c] == \"function\" && n[c](`Request completed in ${s}ms`, {\n\t\t\t\tmethod: e.method,\n\t\t\t\tpath: e.path,\n\t\t\t\tduration: s,\n\t\t\t\t...a && r ? { response: r } : {}\n\t\t\t}), r;\n\t\t} catch (t) {\n\t\t\tlet r = Date.now() - o;\n\t\t\tthrow n.error(`Request failed after ${r}ms`, t, {\n\t\t\t\tmethod: e.method,\n\t\t\t\tpath: e.path,\n\t\t\t\tduration: r\n\t\t\t}), t;\n\t\t}\n\t});\n}\n//#endregion\nexport { f as CRITICAL_LEVELS, t as ColorEnum, d as DEFAULT_DEDUPLICATION_CONFIG, v as DEFAULT_SANITIZATION_CONFIG, b as DEFAULT_VALUE_RULES, i as ErrorSerializer, _ as FormatterFactory, p as LogDeduplicator, n as LogLevelEnum, u as LoggerContextError, l as LoggerError, G as LoggerService, c as LoggerStyleEngine, y as SENSITIVE_KEY_PATTERNS, w as applySanitizationRules, D as compileRules, K as createLoggerMiddleware, O as createSanitizer, r as isValidLogLevel, x as sanitizeControlChars, k as sanitizeMessage, E as sanitizeValue, q as withLogging };\n","//#region src/lib/injection-context.ts\nvar e = class {\n\tstatic {\n\t\tthis.contexts = /* @__PURE__ */ new Map();\n\t}\n\tstatic {\n\t\tthis.defaultScope = \"default\";\n\t}\n\tstatic getRegistry(e = this.defaultScope) {\n\t\tthis.contexts.has(e) || this.contexts.set(e, new l());\n\t\tlet t = this.contexts.get(e);\n\t\tif (!t) throw Error(`Failed to create registry for scope '${e}'`);\n\t\treturn t;\n\t}\n\tstatic createScope(e) {\n\t\tif (this.contexts.has(e)) throw Error(`Scope '${e}' already exists`);\n\t\tlet t = new l();\n\t\treturn this.contexts.set(e, t), t;\n\t}\n\tstatic destroyScope(e) {\n\t\tlet t = this.contexts.get(e);\n\t\tt && (t.destroy(), this.contexts.delete(e));\n\t}\n\tstatic async destroyScopeAsync(e) {\n\t\tlet t = this.contexts.get(e);\n\t\tt && (await t.destroyAsync(), this.contexts.delete(e));\n\t}\n\tstatic async clearAllAsync() {\n\t\tlet e = [], t = Array.from(this.contexts.entries());\n\t\tfor (let [n, r] of t) try {\n\t\t\tawait r.destroyAsync();\n\t\t} catch (t) {\n\t\t\tt instanceof p ? e.push(...t.failures) : t instanceof Error && e.push({\n\t\t\t\tserviceName: `scope:${n}`,\n\t\t\t\terror: t\n\t\t\t});\n\t\t}\n\t\tif (this.contexts.clear(), e.length > 0) throw new p(e);\n\t}\n\tstatic setDefaultScope(e) {\n\t\tthis.defaultScope = e;\n\t}\n\tstatic getActiveScopes() {\n\t\treturn Array.from(this.contexts.keys());\n\t}\n\tstatic clearAll() {\n\t\tlet e = Array.from(this.contexts.values());\n\t\tfor (let t of e) t.destroy();\n\t\tthis.contexts.clear();\n\t}\n};\nfunction t(t, n, r = {}) {\n\tlet i = e.getRegistry(n), { required: a = !0 } = r;\n\ttry {\n\t\tlet e = i.getService(t);\n\t\tif (e == null) {\n\t\t\tif (a) throw new u(`Service '${t.name}' not found in scope '${n || \"default\"}' and is required`, t.name);\n\t\t\treturn;\n\t\t}\n\t\treturn e;\n\t} catch (e) {\n\t\tthrow e instanceof u ? e : new u(`Failed to inject service '${t.name}' from scope '${n || \"default\"}'`, t.name, e);\n\t}\n}\nfunction n(t, n, ...r) {\n\tlet i = e.getRegistry(n);\n\ttry {\n\t\ti.register(t, ...r);\n\t} catch (e) {\n\t\tthrow new u(`Failed to register service '${t.name}' in scope '${n || \"default\"}'`, t.name, e);\n\t}\n}\nfunction r(t, n) {\n\tlet r = e.getRegistry(n);\n\ttry {\n\t\tr.registerAsUndefined(t);\n\t} catch (e) {\n\t\tthrow new u(`Failed to register service '${t.name}' as undefined in scope '${n || \"default\"}'`, t.name, e);\n\t}\n}\n//#endregion\n//#region src/lib/symbol-registry.ts\nvar i = Symbol.for(\"@analog-tools/inject:SERVICE_TOKEN\");\nfunction a(e) {\n\treturn Symbol(e || \"ServiceToken\");\n}\nvar o = class {\n\tstatic {\n\t\tthis.tokens = /* @__PURE__ */ new WeakMap();\n\t}\n\tstatic getToken(e) {\n\t\tif (!this.tokens.has(e)) {\n\t\t\tlet t = a(e.name);\n\t\t\tthis.tokens.set(e, t);\n\t\t}\n\t\tlet t = this.tokens.get(e);\n\t\tif (!t) throw Error(`Failed to get token for service ${e.name}`);\n\t\treturn t;\n\t}\n\tstatic setToken(e, t) {\n\t\tthis.tokens.set(e, t);\n\t}\n};\nfunction s(e) {\n\treturn (t) => {\n\t\tlet n = e || o.getToken(t);\n\t\treturn o.setToken(t, n), t.INJECTABLE = !0, t[i] = n, t;\n\t};\n}\n//#endregion\n//#region src/lib/service-registry.ts\nfunction c() {\n\treturn e.getRegistry();\n}\nvar l = class {\n\tconstructor() {\n\t\tthis.serviceMap = /* @__PURE__ */ new Map(), this.initializingServices = /* @__PURE__ */ new Set(), this.initializationPromises = /* @__PURE__ */ new Map(), this.serviceNames = /* @__PURE__ */ new Map(), this.initializedServices = /* @__PURE__ */ new Set(), this.destroyed = !1;\n\t}\n\tgetServiceKey(e) {\n\t\tlet t = e[i];\n\t\tif (!t) throw new f(e.name);\n\t\treturn this.serviceNames.set(t, e.name), t;\n\t}\n\tgetServiceName(e) {\n\t\treturn this.serviceNames.get(e) ?? \"Unknown\";\n\t}\n\tregister(e, ...t) {\n\t\tlet n = this.getServiceKey(e);\n\t\tif (this.initializingServices.has(n)) throw new d([e.name]);\n\t\tif (!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) {\n\t\t\tthis.initializingServices.add(n);\n\t\t\ttry {\n\t\t\t\tlet r = t.length === 0 ? new e() : new e(...t);\n\t\t\t\tthis.serviceMap.set(n, r);\n\t\t\t} finally {\n\t\t\t\tthis.initializingServices.delete(n);\n\t\t\t}\n\t\t}\n\t}\n\tregisterAsUndefined(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\tthis.serviceMap.set(t, void 0);\n\t}\n\tregisterCustomServiceInstance(e, t) {\n\t\tlet n = this.getServiceKey(e);\n\t\tthis.serviceNames.set(n, e.name), this.serviceMap.set(n, t);\n\t}\n\tgetService(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\treturn this.serviceMap.has(t) || this.register(e), this.serviceMap.get(t);\n\t}\n\thasService(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\treturn this.serviceMap.has(t);\n\t}\n\tasync ensureAsyncInitialized(e, t) {\n\t\tif (this.initializedServices.has(t)) return;\n\t\tif (this.initializationPromises.has(t)) {\n\t\t\tlet e = this.initializationPromises.get(t);\n\t\t\tif (e) {\n\t\t\t\tawait e;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tlet n = e;\n\t\tif (typeof n.initializeAsync != \"function\") {\n\t\t\tthis.initializedServices.add(t);\n\t\t\tlet e = Promise.resolve();\n\t\t\treturn this.initializationPromises.set(t, e), e;\n\t\t}\n\t\tlet r = n.initializeAsync().then(() => {\n\t\t\tthis.initializedServices.add(t);\n\t\t}).catch((e) => {\n\t\t\tthrow this.initializationPromises.delete(t), e;\n\t\t});\n\t\tthis.initializationPromises.set(t, r), await r;\n\t}\n\tasync getServiceAsync(e) {\n\t\tlet t = this.getServiceKey(e);\n\t\tthis.serviceMap.has(t) || this.register(e);\n\t\tlet n = this.serviceMap.get(t);\n\t\treturn n !== void 0 && await this.ensureAsyncInitialized(n, t), n;\n\t}\n\tasync registerAsync(e, ...t) {\n\t\tlet n = this.getServiceKey(e);\n\t\t(!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) && this.register(e, ...t);\n\t\tlet r = this.serviceMap.get(n);\n\t\tawait this.ensureAsyncInitialized(r, n);\n\t}\n\tasync destroyAsync() {\n\t\tif (this.destroyed) return;\n\t\tthis.destroyed = !0;\n\t\tlet e = Array.from(this.initializationPromises.values());\n\t\te.length > 0 && await Promise.allSettled(e);\n\t\tlet t = [], n = Array.from(this.serviceMap.entries());\n\t\tfor (let [e, r] of n) {\n\t\t\tif (!this.initializedServices.has(e) || r === void 0) continue;\n\t\t\tlet n = r;\n\t\t\tif (typeof n.onDestroy == \"function\") try {\n\t\t\t\tawait n.onDestroy();\n\t\t\t} catch (n) {\n\t\t\t\tt.push({\n\t\t\t\t\tserviceName: this.getServiceName(e),\n\t\t\t\t\terror: n\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (this.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear(), t.length > 0) throw new p(t);\n\t}\n\tdestroy() {\n\t\tthis.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear();\n\t}\n}, u = class extends Error {\n\tconstructor(e, t, n) {\n\t\tsuper(e), this.token = t, this.name = \"InjectionError\", n && (this.cause = n);\n\t}\n}, d = class extends u {\n\tconstructor(e) {\n\t\tsuper(`Circular dependency detected: ${e.join(\" -> \")}`), this.name = \"CircularDependencyError\";\n\t}\n}, f = class extends u {\n\tconstructor(e) {\n\t\tsuper(`Service '${e}' is missing SERVICE_TOKEN. Add @Injectable() decorator to the class. See: packages/inject/docs/migrations/symbol-tokens.md`, e), this.name = \"MissingServiceTokenError\";\n\t}\n}, p = class extends u {\n\tconstructor(e) {\n\t\tlet t = e.map((e) => `${e.serviceName}: ${e.error.message}`).join(\"; \");\n\t\tsuper(`Failed to destroy ${e.length} service(s): ${t}`), this.failures = e, this.name = \"AggregateDestructionError\";\n\t}\n\tgetErrors() {\n\t\treturn this.failures.map((e) => e.error);\n\t}\n\thasFailure(e) {\n\t\treturn this.failures.some((t) => t.serviceName === e);\n\t}\n};\nfunction m(e, t = {}) {\n\tlet { required: n = !0 } = t;\n\ttry {\n\t\tlet t = c().getService(e);\n\t\tif (t == null) {\n\t\t\tif (n) throw new u(`Service '${e.name}' not found in registry and is required`, e.name);\n\t\t\treturn;\n\t\t}\n\t\treturn t;\n\t} catch (t) {\n\t\tthrow t instanceof u ? t : new u(`Failed to inject service '${e.name}'`, e.name, t);\n\t}\n}\nfunction h(e, ...t) {\n\ttry {\n\t\tc().register(e, ...t);\n\t} catch (t) {\n\t\tthrow new u(`Failed to register service '${e.name}'`, e.name, t);\n\t}\n}\nfunction g(e) {\n\ttry {\n\t\tc().registerAsUndefined(e);\n\t} catch (t) {\n\t\tthrow new u(`Failed to register service '${e.name}' as undefined`, e.name, t);\n\t}\n}\nfunction _(e) {\n\ttry {\n\t\treturn c().hasService(e);\n\t} catch {\n\t\treturn !1;\n\t}\n}\nfunction v(e) {\n\treturn m(e, { required: !1 });\n}\nasync function y(e, t = {}) {\n\tlet { required: n = !0 } = t;\n\ttry {\n\t\tlet t = await c().getServiceAsync(e);\n\t\tif (t == null) {\n\t\t\tif (n) throw new u(`Service '${e.name}' not found in registry and is required`, e.name);\n\t\t\treturn;\n\t\t}\n\t\treturn t;\n\t} catch (t) {\n\t\tthrow t instanceof u ? t : new u(`Failed to inject async service '${e.name}'`, e.name, t);\n\t}\n}\nasync function b(e, ...t) {\n\ttry {\n\t\tawait c().registerAsync(e, ...t);\n\t} catch (t) {\n\t\tthrow t instanceof u ? t : new u(`Failed to register async service '${e.name}'`, e.name, t);\n\t}\n}\nasync function x() {\n\treturn c().destroyAsync();\n}\n//#endregion\n//#region src/lib/inject.testing-util.ts\nfunction S(e, t) {\n\tc().registerCustomServiceInstance(e, t);\n}\nfunction C() {\n\te.clearAll();\n}\nfunction w(t, n, r) {\n\te.getRegistry(r).registerCustomServiceInstance(t, n);\n}\nfunction T(t) {\n\te.destroyScope(t);\n}\n//#endregion\nexport { p as AggregateDestructionError, d as CircularDependencyError, s as Injectable, e as InjectionContext, u as InjectionError, f as MissingServiceTokenError, i as SERVICE_TOKEN, a as createServiceToken, x as destroyAllServicesAsync, _ as hasService, m as inject, y as injectAsync, t as injectScoped, b as registerAsync, S as registerMockService, w as registerMockServiceScoped, h as registerService, g as registerServiceAsUndefined, r as registerServiceAsUndefinedScoped, n as registerServiceScoped, C as resetAllInjections, T as resetScopedInjections, v as tryInject };\n","import { createError, H3Event } from 'h3';\nimport {\n  useSession,\n  getSession,\n  updateSession,\n  destroySession,\n  createUnstorageStore,\n} from '@analog-tools/session';\nimport type { Storage } from 'unstorage';\nimport { AuthSessionData, SessionWithSave, SessionWithHandler } from '../types/auth-session.types';\nimport { LoggerService } from '@analog-tools/logger';\nimport { inject, Injectable } from '@analog-tools/inject';\nimport { type SessionStorageConfig } from '../types/auth.types';\n\n@Injectable()\nexport class SessionService {\n  private readonly storageConfig: SessionStorageConfig;\n  private readonly sessionSecret: string | string[];\n  private store!: Storage<AuthSessionData>;\n  private logger: LoggerService;\n\n  constructor(config: SessionStorageConfig) {\n    this.storageConfig = config;\n\n    this.logger = inject(LoggerService).forContext('SessionService');\n    this.sessionSecret = this.resolveSessionSecret();\n  }\n\n  /**\n   * Resolve and validate the session signing secret. A missing secret is a\n   * fatal misconfiguration: the library used to silently fall back to a shared,\n   * source-visible default, which let anyone forge session cookies. A non-empty\n   * array of secrets is accepted to support key rotation (first entry signs,\n   * the rest still verify).\n   */\n  private resolveSessionSecret(): string | string[] {\n    const secret = this.storageConfig.sessionSecret;\n    const secrets = Array.isArray(secret) ? secret : [secret];\n    const allValid =\n      secrets.length > 0 &&\n      secrets.every((s) => typeof s === 'string' && s.trim().length > 0);\n    if (!allValid) {\n      throw new Error(\n        'sessionStorage.sessionSecret is required. Provide a strong, unique ' +\n          'value or a non-empty array of values (e.g. from a SESSION_SECRET ' +\n          'environment variable) — the library no longer falls back to a ' +\n          'shared default secret.'\n      );\n    }\n    if ((secrets as string[]).some((s) => s.length < 32)) {\n      this.logger.warn(\n        'sessionStorage.sessionSecret is shorter than 32 characters; use a ' +\n          'longer, high-entropy value for HMAC-SHA256 cookie signing.'\n      );\n    }\n    return secret as string | string[];\n  }\n\n  async initSession(event: H3Event): Promise<void> {\n    // Check if session is already initialized\n    const existingSession = getSession<AuthSessionData>(event);\n    \n    if (!existingSession) {\n      this.logger.debug('Initializing request session context');\n      \n      // Create appropriate store based on config\n      if (!this.store) {\n        this.store = await createUnstorageStore<AuthSessionData>(this.storageConfig.driver);\n      }\n      \n      await useSession<AuthSessionData>(event, {\n        store: this.store,\n        secret: this.sessionSecret,\n        name: this.storageConfig.cookieName || 'auth.session',\n        maxAge: 60 * 60 * 24, // 24 hours\n        cookie: {\n          httpOnly: true,\n          secure: process.env['NODE_ENV'] === 'production',\n          sameSite: 'lax', // Always use 'lax' to allow OAuth redirects\n        },\n        // Initialize default session structure with auth property\n        generate: () => ({\n          auth: {\n            isAuthenticated: false,\n          },\n        }),\n      });\n    } else {\n      this.logger.debug(\n        'Session already exists, skipping initialization'\n      );\n    }\n  }\n\n  /**\n   * Get a session by session ID\n   * @param sessionId The session ID\n   * @returns The session object or null if not found\n   */\n  async getSession(sessionId: string): Promise<SessionWithSave | null> {\n    try {\n      const sessionData = await this.store.getItem(sessionId);\n\n      if (!sessionData) {\n        return null;\n      }\n\n      // Create a session object with basic needed functionality\n      return {\n        id: sessionId,\n        data: sessionData as AuthSessionData,\n        save: async () => {\n          await this.store.setItem(sessionId, sessionData);\n        },\n      };\n    } catch (error) {\n      this.logger.error(`Error retrieving session`, error, { sessionId });\n      return null;\n    }\n  }\n\n  /**\n   * Get all active sessions from storage\n   * @returns Array of session objects with update capability\n   */\n  async getActiveSessions(): Promise<SessionWithHandler[]> {\n    try {\n      // Get all session keys from storage\n      const sessionKeys = await this.store.getKeys();\n\n      // Map keys to session objects\n      const sessions = await Promise.all(\n        sessionKeys.map(async (key) => {\n          const sessionData = await this.store.getItem(key);\n          if (!sessionData) return null;\n\n          // Extract session ID from the key (remove prefix if exists)\n          const sessionId = this.storageConfig.prefix && key.startsWith(`${this.storageConfig.prefix}:`)\n            ? key.substring(`${this.storageConfig.prefix}:`.length)\n            : key;\n\n          return {\n            id: sessionId,\n            data: sessionData,\n            update: (updater: (data: AuthSessionData) => AuthSessionData) => {\n              // Apply the updater function to get new data\n              const updatedData = updater(sessionData as AuthSessionData);\n              // Update the local data reference\n              Object.assign(sessionData, updatedData);\n            },\n            save: async () => {\n              await this.store.setItem(key, sessionData);\n            },\n            refetch: async () => {\n              return (await this.store.getItem(key)) as AuthSessionData | null;\n            },\n          };\n        })\n      );\n\n      // Filter out null values\n      return sessions.filter((session): session is SessionWithHandler => session !== null);\n    } catch (error) {\n      this.logger.error('Error retrieving active sessions', error);\n      return [];\n    }\n  }\n\n  async destroyAuthSession(event: H3Event): Promise<void> {\n    try {\n      await this.initSession(event);\n      \n      // Get current session data to check if auth exists\n      const sessionData = getSession<AuthSessionData>(event);\n      \n      if (sessionData?.auth) {\n        // Clear auth data first\n        await updateSession<AuthSessionData>(event, (data) => {\n          const updatedData = { ...data };\n          delete updatedData.auth;\n          return updatedData;\n        });\n      }\n\n      // Destroy the session using new API\n      await destroySession(event);\n      \n    } catch (error) {\n      this.logger.error('Session destruction failed', error);\n      throw createError({\n        statusCode: 500,\n        message: 'Session handling failed',\n      });\n    }\n  }\n\n  async getSessionData<T>(\n    event: H3Event,\n    key: keyof AuthSessionData\n  ): Promise<T | null> {\n    await this.initSession(event);\n    \n    const sessionData = getSession<AuthSessionData>(event);\n    \n    this.logger.debug(\n      `Retrieved session data`,\n      sessionData\n    );\n\n    return (sessionData?.[key] as T) || null;\n  }\n\n  async setSessionData<T>(\n    event: H3Event,\n    key: keyof AuthSessionData,\n    value: T\n  ): Promise<void> {\n    await this.initSession(event);\n    \n    await updateSession<AuthSessionData>(event, (data) => ({\n      ...data,\n      [key]: value,\n    }));\n  }\n\n  async isValidSession(event: H3Event): Promise<boolean> {\n    await this.initSession(event);\n    const sessionData = getSession<AuthSessionData>(event);\n    return !!sessionData;\n  }\n}\n","export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n    const size = buffers.reduce((acc, { length }) => acc + length, 0);\n    const buf = new Uint8Array(size);\n    let i = 0;\n    for (const buffer of buffers) {\n        buf.set(buffer, i);\n        i += buffer.length;\n    }\n    return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n    if (value < 0 || value >= MAX_INT32) {\n        throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n    }\n    buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n    const high = Math.floor(value / MAX_INT32);\n    const low = value % MAX_INT32;\n    const buf = new Uint8Array(8);\n    writeUInt32BE(buf, high, 0);\n    writeUInt32BE(buf, low, 4);\n    return buf;\n}\nexport function uint32be(value) {\n    const buf = new Uint8Array(4);\n    writeUInt32BE(buf, value);\n    return buf;\n}\nexport function encode(string) {\n    const bytes = new Uint8Array(string.length);\n    for (let i = 0; i < string.length; i++) {\n        const code = string.charCodeAt(i);\n        if (code > 127) {\n            throw new TypeError('non-ASCII string encountered in encode()');\n        }\n        bytes[i] = code;\n    }\n    return bytes;\n}\n","export function encodeBase64(input) {\n    if (Uint8Array.prototype.toBase64) {\n        return input.toBase64();\n    }\n    const CHUNK_SIZE = 0x8000;\n    const arr = [];\n    for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n        arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n    }\n    return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n    if (Uint8Array.fromBase64) {\n        return Uint8Array.fromBase64(encoded);\n    }\n    const binary = atob(encoded);\n    const bytes = new Uint8Array(binary.length);\n    for (let i = 0; i < binary.length; i++) {\n        bytes[i] = binary.charCodeAt(i);\n    }\n    return bytes;\n}\n","import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n    if (Uint8Array.fromBase64) {\n        return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n            alphabet: 'base64url',\n        });\n    }\n    let encoded = input;\n    if (encoded instanceof Uint8Array) {\n        encoded = decoder.decode(encoded);\n    }\n    encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n    try {\n        return decodeBase64(encoded);\n    }\n    catch {\n        throw new TypeError('The input to be decoded is not correctly encoded.');\n    }\n}\nexport function encode(input) {\n    let unencoded = input;\n    if (typeof unencoded === 'string') {\n        unencoded = encoder.encode(unencoded);\n    }\n    if (Uint8Array.prototype.toBase64) {\n        return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n    }\n    return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nconst isAlgorithm = (algorithm, name) => algorithm.name === name;\nfunction getHashLength(hash) {\n    return parseInt(hash.name.slice(4), 10);\n}\nfunction checkHashLength(algorithm, expected) {\n    const actual = getHashLength(algorithm.hash);\n    if (actual !== expected)\n        throw unusable(`SHA-${expected}`, 'algorithm.hash');\n}\nfunction getNamedCurve(alg) {\n    switch (alg) {\n        case 'ES256':\n            return 'P-256';\n        case 'ES384':\n            return 'P-384';\n        case 'ES512':\n            return 'P-521';\n        default:\n            throw new Error('unreachable');\n    }\n}\nfunction checkUsage(key, usage) {\n    if (usage && !key.usages.includes(usage)) {\n        throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n    }\n}\nexport function checkSigCryptoKey(key, alg, usage) {\n    switch (alg) {\n        case 'HS256':\n        case 'HS384':\n        case 'HS512': {\n            if (!isAlgorithm(key.algorithm, 'HMAC'))\n                throw unusable('HMAC');\n            checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n            break;\n        }\n        case 'RS256':\n        case 'RS384':\n        case 'RS512': {\n            if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n                throw unusable('RSASSA-PKCS1-v1_5');\n            checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n            break;\n        }\n        case 'PS256':\n        case 'PS384':\n        case 'PS512': {\n            if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n                throw unusable('RSA-PSS');\n            checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n            break;\n        }\n        case 'Ed25519':\n        case 'EdDSA': {\n            if (!isAlgorithm(key.algorithm, 'Ed25519'))\n                throw unusable('Ed25519');\n            break;\n        }\n        case 'ML-DSA-44':\n        case 'ML-DSA-65':\n        case 'ML-DSA-87': {\n            if (!isAlgorithm(key.algorithm, alg))\n                throw unusable(alg);\n            break;\n        }\n        case 'ES256':\n        case 'ES384':\n        case 'ES512': {\n            if (!isAlgorithm(key.algorithm, 'ECDSA'))\n                throw unusable('ECDSA');\n            const expected = getNamedCurve(alg);\n            const actual = key.algorithm.namedCurve;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.namedCurve');\n            break;\n        }\n        default:\n            throw new TypeError('CryptoKey does not support this operation');\n    }\n    checkUsage(key, usage);\n}\nexport function checkEncCryptoKey(key, alg, usage) {\n    switch (alg) {\n        case 'A128GCM':\n        case 'A192GCM':\n        case 'A256GCM': {\n            if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n                throw unusable('AES-GCM');\n            const expected = parseInt(alg.slice(1, 4), 10);\n            const actual = key.algorithm.length;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.length');\n            break;\n        }\n        case 'A128KW':\n        case 'A192KW':\n        case 'A256KW': {\n            if (!isAlgorithm(key.algorithm, 'AES-KW'))\n                throw unusable('AES-KW');\n            const expected = parseInt(alg.slice(1, 4), 10);\n            const actual = key.algorithm.length;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.length');\n            break;\n        }\n        case 'ECDH': {\n            switch (key.algorithm.name) {\n                case 'ECDH':\n                case 'X25519':\n                    break;\n                default:\n                    throw unusable('ECDH or X25519');\n            }\n            break;\n        }\n        case 'PBES2-HS256+A128KW':\n        case 'PBES2-HS384+A192KW':\n        case 'PBES2-HS512+A256KW':\n            if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n                throw unusable('PBKDF2');\n            break;\n        case 'RSA-OAEP':\n        case 'RSA-OAEP-256':\n        case 'RSA-OAEP-384':\n        case 'RSA-OAEP-512': {\n            if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n                throw unusable('RSA-OAEP');\n            checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);\n            break;\n        }\n        default:\n            throw new TypeError('CryptoKey does not support this operation');\n    }\n    checkUsage(key, usage);\n}\n","function message(msg, actual, ...types) {\n    types = types.filter(Boolean);\n    if (types.length > 2) {\n        const last = types.pop();\n        msg += `one of type ${types.join(', ')}, or ${last}.`;\n    }\n    else if (types.length === 2) {\n        msg += `one of type ${types[0]} or ${types[1]}.`;\n    }\n    else {\n        msg += `of type ${types[0]}.`;\n    }\n    if (actual == null) {\n        msg += ` Received ${actual}`;\n    }\n    else if (typeof actual === 'function' && actual.name) {\n        msg += ` Received function ${actual.name}`;\n    }\n    else if (typeof actual === 'object' && actual != null) {\n        if (actual.constructor?.name) {\n            msg += ` Received an instance of ${actual.constructor.name}`;\n        }\n    }\n    return msg;\n}\nexport const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);\nexport const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);\n","export class JOSEError extends Error {\n    static code = 'ERR_JOSE_GENERIC';\n    code = 'ERR_JOSE_GENERIC';\n    constructor(message, options) {\n        super(message, options);\n        this.name = this.constructor.name;\n        Error.captureStackTrace?.(this, this.constructor);\n    }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n    static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n    code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n    claim;\n    reason;\n    payload;\n    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n        super(message, { cause: { claim, reason, payload } });\n        this.claim = claim;\n        this.reason = reason;\n        this.payload = payload;\n    }\n}\nexport class JWTExpired extends JOSEError {\n    static code = 'ERR_JWT_EXPIRED';\n    code = 'ERR_JWT_EXPIRED';\n    claim;\n    reason;\n    payload;\n    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n        super(message, { cause: { claim, reason, payload } });\n        this.claim = claim;\n        this.reason = reason;\n        this.payload = payload;\n    }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n    static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n    code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n    static code = 'ERR_JOSE_NOT_SUPPORTED';\n    code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n    static code = 'ERR_JWE_DECRYPTION_FAILED';\n    code = 'ERR_JWE_DECRYPTION_FAILED';\n    constructor(message = 'decryption operation failed', options) {\n        super(message, options);\n    }\n}\nexport class JWEInvalid extends JOSEError {\n    static code = 'ERR_JWE_INVALID';\n    code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n    static code = 'ERR_JWS_INVALID';\n    code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n    static code = 'ERR_JWT_INVALID';\n    code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n    static code = 'ERR_JWK_INVALID';\n    code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n    static code = 'ERR_JWKS_INVALID';\n    code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n    static code = 'ERR_JWKS_NO_MATCHING_KEY';\n    code = 'ERR_JWKS_NO_MATCHING_KEY';\n    constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n        super(message, options);\n    }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n    [Symbol.asyncIterator];\n    static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n    code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n    constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n        super(message, options);\n    }\n}\nexport class JWKSTimeout extends JOSEError {\n    static code = 'ERR_JWKS_TIMEOUT';\n    code = 'ERR_JWKS_TIMEOUT';\n    constructor(message = 'request timed out', options) {\n        super(message, options);\n    }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n    static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n    code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n    constructor(message = 'signature verification failed', options) {\n        super(message, options);\n    }\n}\n","export function assertCryptoKey(key) {\n    if (!isCryptoKey(key)) {\n        throw new Error('CryptoKey instance expected');\n    }\n}\nexport const isCryptoKey = (key) => {\n    if (key?.[Symbol.toStringTag] === 'CryptoKey')\n        return true;\n    try {\n        return key instanceof CryptoKey;\n    }\n    catch {\n        return false;\n    }\n};\nexport const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';\nexport const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\n","import { decode } from '../util/base64url.js';\nexport const unprotected = Symbol();\nexport function assertNotSet(value, name) {\n    if (value) {\n        throw new TypeError(`${name} can only be called once`);\n    }\n}\nexport function decodeBase64url(value, label, ErrorClass) {\n    try {\n        return decode(value);\n    }\n    catch {\n        throw new ErrorClass(`Failed to base64url decode the ${label}`);\n    }\n}\nexport async function digest(algorithm, data) {\n    const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n    return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\n","const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n    if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n        return false;\n    }\n    if (Object.getPrototypeOf(input) === null) {\n        return true;\n    }\n    let proto = input;\n    while (Object.getPrototypeOf(proto) !== null) {\n        proto = Object.getPrototypeOf(proto);\n    }\n    return Object.getPrototypeOf(input) === proto;\n}\nexport function isDisjoint(...headers) {\n    const sources = headers.filter(Boolean);\n    if (sources.length === 0 || sources.length === 1) {\n        return true;\n    }\n    let acc;\n    for (const header of sources) {\n        const parameters = Object.keys(header);\n        if (!acc || acc.size === 0) {\n            acc = new Set(parameters);\n            continue;\n        }\n        for (const parameter of parameters) {\n            if (acc.has(parameter)) {\n                return false;\n            }\n            acc.add(parameter);\n        }\n    }\n    return true;\n}\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n    ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n","import { JOSENotSupported } from '../util/errors.js';\nimport { checkSigCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nexport function checkKeyLength(alg, key) {\n    if (alg.startsWith('RS') || alg.startsWith('PS')) {\n        const { modulusLength } = key.algorithm;\n        if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n            throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n        }\n    }\n}\nfunction subtleAlgorithm(alg, algorithm) {\n    const hash = `SHA-${alg.slice(-3)}`;\n    switch (alg) {\n        case 'HS256':\n        case 'HS384':\n        case 'HS512':\n            return { hash, name: 'HMAC' };\n        case 'PS256':\n        case 'PS384':\n        case 'PS512':\n            return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 };\n        case 'RS256':\n        case 'RS384':\n        case 'RS512':\n            return { hash, name: 'RSASSA-PKCS1-v1_5' };\n        case 'ES256':\n        case 'ES384':\n        case 'ES512':\n            return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n        case 'Ed25519':\n        case 'EdDSA':\n            return { name: 'Ed25519' };\n        case 'ML-DSA-44':\n        case 'ML-DSA-65':\n        case 'ML-DSA-87':\n            return { name: alg };\n        default:\n            throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n    }\n}\nasync function getSigKey(alg, key, usage) {\n    if (key instanceof Uint8Array) {\n        if (!alg.startsWith('HS')) {\n            throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n        }\n        return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n    }\n    checkSigCryptoKey(key, alg, usage);\n    return key;\n}\nexport async function sign(alg, key, data) {\n    const cryptoKey = await getSigKey(alg, key, 'sign');\n    checkKeyLength(alg, cryptoKey);\n    const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);\n    return new Uint8Array(signature);\n}\nexport async function verify(alg, key, signature, data) {\n    const cryptoKey = await getSigKey(alg, key, 'verify');\n    checkKeyLength(alg, cryptoKey);\n    const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n    try {\n        return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n    }\n    catch {\n        return false;\n    }\n}\n","import { JOSENotSupported } from '../util/errors.js';\nconst unsupportedAlg = 'Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value';\nfunction subtleMapping(jwk) {\n    let algorithm;\n    let keyUsages;\n    switch (jwk.kty) {\n        case 'AKP': {\n            switch (jwk.alg) {\n                case 'ML-DSA-44':\n                case 'ML-DSA-65':\n                case 'ML-DSA-87':\n                    algorithm = { name: jwk.alg };\n                    keyUsages = jwk.priv ? ['sign'] : ['verify'];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        case 'RSA': {\n            switch (jwk.alg) {\n                case 'PS256':\n                case 'PS384':\n                case 'PS512':\n                    algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'RS256':\n                case 'RS384':\n                case 'RS512':\n                    algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'RSA-OAEP':\n                case 'RSA-OAEP-256':\n                case 'RSA-OAEP-384':\n                case 'RSA-OAEP-512':\n                    algorithm = {\n                        name: 'RSA-OAEP',\n                        hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n                    };\n                    keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        case 'EC': {\n            switch (jwk.alg) {\n                case 'ES256':\n                case 'ES384':\n                case 'ES512':\n                    algorithm = {\n                        name: 'ECDSA',\n                        namedCurve: { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[jwk.alg],\n                    };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'ECDH-ES':\n                case 'ECDH-ES+A128KW':\n                case 'ECDH-ES+A192KW':\n                case 'ECDH-ES+A256KW':\n                    algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n                    keyUsages = jwk.d ? ['deriveBits'] : [];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        case 'OKP': {\n            switch (jwk.alg) {\n                case 'Ed25519':\n                case 'EdDSA':\n                    algorithm = { name: 'Ed25519' };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'ECDH-ES':\n                case 'ECDH-ES+A128KW':\n                case 'ECDH-ES+A192KW':\n                case 'ECDH-ES+A256KW':\n                    algorithm = { name: jwk.crv };\n                    keyUsages = jwk.d ? ['deriveBits'] : [];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        default:\n            throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n    }\n    return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n    if (!jwk.alg) {\n        throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n    }\n    const { algorithm, keyUsages } = subtleMapping(jwk);\n    const keyData = { ...jwk };\n    if (keyData.kty !== 'AKP') {\n        delete keyData.alg;\n    }\n    delete keyData.use;\n    return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n","import { isJWK } from './type_checks.js';\nimport { decode } from '../util/base64url.js';\nimport { jwkToKey } from './jwk_to_key.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nconst unusableForAlg = 'given KeyObject instance cannot be used for this algorithm';\nlet cache;\nconst handleJWK = async (key, jwk, alg, freeze = false) => {\n    cache ||= new WeakMap();\n    let cached = cache.get(key);\n    if (cached?.[alg]) {\n        return cached[alg];\n    }\n    const cryptoKey = await jwkToKey({ ...jwk, alg });\n    if (freeze)\n        Object.freeze(key);\n    if (!cached) {\n        cache.set(key, { [alg]: cryptoKey });\n    }\n    else {\n        cached[alg] = cryptoKey;\n    }\n    return cryptoKey;\n};\nconst handleKeyObject = (keyObject, alg) => {\n    cache ||= new WeakMap();\n    let cached = cache.get(keyObject);\n    if (cached?.[alg]) {\n        return cached[alg];\n    }\n    const isPublic = keyObject.type === 'public';\n    const extractable = isPublic ? true : false;\n    let cryptoKey;\n    if (keyObject.asymmetricKeyType === 'x25519') {\n        switch (alg) {\n            case 'ECDH-ES':\n            case 'ECDH-ES+A128KW':\n            case 'ECDH-ES+A192KW':\n            case 'ECDH-ES+A256KW':\n                break;\n            default:\n                throw new TypeError(unusableForAlg);\n        }\n        cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);\n    }\n    if (keyObject.asymmetricKeyType === 'ed25519') {\n        if (alg !== 'EdDSA' && alg !== 'Ed25519') {\n            throw new TypeError(unusableForAlg);\n        }\n        cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n            isPublic ? 'verify' : 'sign',\n        ]);\n    }\n    switch (keyObject.asymmetricKeyType) {\n        case 'ml-dsa-44':\n        case 'ml-dsa-65':\n        case 'ml-dsa-87': {\n            if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {\n                throw new TypeError(unusableForAlg);\n            }\n            cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n                isPublic ? 'verify' : 'sign',\n            ]);\n        }\n    }\n    if (keyObject.asymmetricKeyType === 'rsa') {\n        let hash;\n        switch (alg) {\n            case 'RSA-OAEP':\n                hash = 'SHA-1';\n                break;\n            case 'RS256':\n            case 'PS256':\n            case 'RSA-OAEP-256':\n                hash = 'SHA-256';\n                break;\n            case 'RS384':\n            case 'PS384':\n            case 'RSA-OAEP-384':\n                hash = 'SHA-384';\n                break;\n            case 'RS512':\n            case 'PS512':\n            case 'RSA-OAEP-512':\n                hash = 'SHA-512';\n                break;\n            default:\n                throw new TypeError(unusableForAlg);\n        }\n        if (alg.startsWith('RSA-OAEP')) {\n            return keyObject.toCryptoKey({\n                name: 'RSA-OAEP',\n                hash,\n            }, extractable, isPublic ? ['encrypt'] : ['decrypt']);\n        }\n        cryptoKey = keyObject.toCryptoKey({\n            name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',\n            hash,\n        }, extractable, [isPublic ? 'verify' : 'sign']);\n    }\n    if (keyObject.asymmetricKeyType === 'ec') {\n        const nist = new Map([\n            ['prime256v1', 'P-256'],\n            ['secp384r1', 'P-384'],\n            ['secp521r1', 'P-521'],\n        ]);\n        const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);\n        if (!namedCurve) {\n            throw new TypeError(unusableForAlg);\n        }\n        const expectedCurve = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };\n        if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {\n            cryptoKey = keyObject.toCryptoKey({\n                name: 'ECDSA',\n                namedCurve,\n            }, extractable, [isPublic ? 'verify' : 'sign']);\n        }\n        if (alg.startsWith('ECDH-ES')) {\n            cryptoKey = keyObject.toCryptoKey({\n                name: 'ECDH',\n                namedCurve,\n            }, extractable, isPublic ? [] : ['deriveBits']);\n        }\n    }\n    if (!cryptoKey) {\n        throw new TypeError(unusableForAlg);\n    }\n    if (!cached) {\n        cache.set(keyObject, { [alg]: cryptoKey });\n    }\n    else {\n        cached[alg] = cryptoKey;\n    }\n    return cryptoKey;\n};\nexport async function normalizeKey(key, alg) {\n    if (key instanceof Uint8Array) {\n        return key;\n    }\n    if (isCryptoKey(key)) {\n        return key;\n    }\n    if (isKeyObject(key)) {\n        if (key.type === 'secret') {\n            return key.export();\n        }\n        if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {\n            try {\n                return handleKeyObject(key, alg);\n            }\n            catch (err) {\n                if (err instanceof TypeError) {\n                    throw err;\n                }\n            }\n        }\n        let jwk = key.export({ format: 'jwk' });\n        return handleJWK(key, jwk, alg);\n    }\n    if (isJWK(key)) {\n        if (key.k) {\n            return decode(key.k);\n        }\n        return handleJWK(key, key, alg, true);\n    }\n    throw new Error('unreachable');\n}\n","import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nexport async function importSPKI(spki, alg, options) {\n    if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n        throw new TypeError('\"spki\" must be SPKI formatted string');\n    }\n    return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n    if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n        throw new TypeError('\"x509\" must be X.509 formatted string');\n    }\n    return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n    if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n        throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n    }\n    return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n    if (!isObject(jwk)) {\n        throw new TypeError('JWK must be an object');\n    }\n    let ext;\n    alg ??= jwk.alg;\n    ext ??= options?.extractable ?? jwk.ext;\n    switch (jwk.kty) {\n        case 'oct':\n            if (typeof jwk.k !== 'string' || !jwk.k) {\n                throw new TypeError('missing \"k\" (Key Value) Parameter value');\n            }\n            return decodeBase64URL(jwk.k);\n        case 'RSA':\n            if ('oth' in jwk && jwk.oth !== undefined) {\n                throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n            }\n            return jwkToKey({ ...jwk, alg, ext });\n        case 'AKP': {\n            if (typeof jwk.alg !== 'string' || !jwk.alg) {\n                throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n            }\n            if (alg !== undefined && alg !== jwk.alg) {\n                throw new TypeError('JWK alg and alg option value mismatch');\n            }\n            return jwkToKey({ ...jwk, ext });\n        }\n        case 'EC':\n        case 'OKP':\n            return jwkToKey({ ...jwk, alg, ext });\n        default:\n            throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n    }\n}\n","import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';\nexport function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n    if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n        throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n    }\n    if (!protectedHeader || protectedHeader.crit === undefined) {\n        return new Set();\n    }\n    if (!Array.isArray(protectedHeader.crit) ||\n        protectedHeader.crit.length === 0 ||\n        protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n        throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n    }\n    let recognized;\n    if (recognizedOption !== undefined) {\n        recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n    }\n    else {\n        recognized = recognizedDefault;\n    }\n    for (const parameter of protectedHeader.crit) {\n        if (!recognized.has(parameter)) {\n            throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n        }\n        if (joseHeader[parameter] === undefined) {\n            throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n        }\n        if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n            throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n        }\n    }\n    return new Set(protectedHeader.crit);\n}\n","export function validateAlgorithms(option, algorithms) {\n    if (algorithms !== undefined &&\n        (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n        throw new TypeError(`\"${option}\" option must be an array of strings`);\n    }\n    if (!algorithms) {\n        return undefined;\n    }\n    return new Set(algorithms);\n}\n","import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport { isKeyLike } from './is_key_like.js';\nimport * as jwk from './type_checks.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n    if (key.use !== undefined) {\n        let expected;\n        switch (usage) {\n            case 'sign':\n            case 'verify':\n                expected = 'sig';\n                break;\n            case 'encrypt':\n            case 'decrypt':\n                expected = 'enc';\n                break;\n        }\n        if (key.use !== expected) {\n            throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n        }\n    }\n    if (key.alg !== undefined && key.alg !== alg) {\n        throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n    }\n    if (Array.isArray(key.key_ops)) {\n        let expectedKeyOp;\n        switch (true) {\n            case usage === 'sign' || usage === 'verify':\n            case alg === 'dir':\n            case alg.includes('CBC-HS'):\n                expectedKeyOp = usage;\n                break;\n            case alg.startsWith('PBES2'):\n                expectedKeyOp = 'deriveBits';\n                break;\n            case /^A\\d{3}(?:GCM)?(?:KW)?$/.test(alg):\n                if (!alg.includes('GCM') && alg.endsWith('KW')) {\n                    expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey';\n                }\n                else {\n                    expectedKeyOp = usage;\n                }\n                break;\n            case usage === 'encrypt' && alg.startsWith('RSA'):\n                expectedKeyOp = 'wrapKey';\n                break;\n            case usage === 'decrypt':\n                expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';\n                break;\n        }\n        if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {\n            throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n        }\n    }\n    return true;\n};\nconst symmetricTypeCheck = (alg, key, usage) => {\n    if (key instanceof Uint8Array)\n        return;\n    if (jwk.isJWK(key)) {\n        if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n            return;\n        throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n    }\n    if (!isKeyLike(key)) {\n        throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));\n    }\n    if (key.type !== 'secret') {\n        throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n    }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n    if (jwk.isJWK(key)) {\n        switch (usage) {\n            case 'decrypt':\n            case 'sign':\n                if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n                    return;\n                throw new TypeError(`JSON Web Key for this operation must be a private JWK`);\n            case 'encrypt':\n            case 'verify':\n                if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n                    return;\n                throw new TypeError(`JSON Web Key for this operation must be a public JWK`);\n        }\n    }\n    if (!isKeyLike(key)) {\n        throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n    }\n    if (key.type === 'secret') {\n        throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n    }\n    if (key.type === 'public') {\n        switch (usage) {\n            case 'sign':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n            case 'decrypt':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n        }\n    }\n    if (key.type === 'private') {\n        switch (usage) {\n            case 'verify':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n            case 'encrypt':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n        }\n    }\n};\nexport function checkKeyType(alg, key, usage) {\n    switch (alg.substring(0, 2)) {\n        case 'A1':\n        case 'A2':\n        case 'di':\n        case 'HS':\n        case 'PB':\n            symmetricTypeCheck(alg, key, usage);\n            break;\n        default:\n            asymmetricTypeCheck(alg, key, usage);\n    }\n}\n","import { decode as b64u } from '../../util/base64url.js';\nimport { verify } from '../../lib/signing.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js';\nimport { decodeBase64url } from '../../lib/helpers.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { isObject } from '../../lib/type_checks.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nexport async function flattenedVerify(jws, key, options) {\n    if (!isObject(jws)) {\n        throw new JWSInvalid('Flattened JWS must be an object');\n    }\n    if (jws.protected === undefined && jws.header === undefined) {\n        throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n    }\n    if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n        throw new JWSInvalid('JWS Protected Header incorrect type');\n    }\n    if (jws.payload === undefined) {\n        throw new JWSInvalid('JWS Payload missing');\n    }\n    if (typeof jws.signature !== 'string') {\n        throw new JWSInvalid('JWS Signature missing or incorrect type');\n    }\n    if (jws.header !== undefined && !isObject(jws.header)) {\n        throw new JWSInvalid('JWS Unprotected Header incorrect type');\n    }\n    let parsedProt = {};\n    if (jws.protected) {\n        try {\n            const protectedHeader = b64u(jws.protected);\n            parsedProt = JSON.parse(decoder.decode(protectedHeader));\n        }\n        catch {\n            throw new JWSInvalid('JWS Protected Header is invalid');\n        }\n    }\n    if (!isDisjoint(parsedProt, jws.header)) {\n        throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n    }\n    const joseHeader = {\n        ...parsedProt,\n        ...jws.header,\n    };\n    const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n    let b64 = true;\n    if (extensions.has('b64')) {\n        b64 = parsedProt.b64;\n        if (typeof b64 !== 'boolean') {\n            throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n        }\n    }\n    const { alg } = joseHeader;\n    if (typeof alg !== 'string' || !alg) {\n        throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n    }\n    const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n    if (algorithms && !algorithms.has(alg)) {\n        throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n    }\n    if (b64) {\n        if (typeof jws.payload !== 'string') {\n            throw new JWSInvalid('JWS Payload must be a string');\n        }\n    }\n    else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n        throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n    }\n    let resolvedKey = false;\n    if (typeof key === 'function') {\n        key = await key(parsedProt, jws);\n        resolvedKey = true;\n    }\n    checkKeyType(alg, key, 'verify');\n    const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string'\n        ? b64\n            ? encode(jws.payload)\n            : encoder.encode(jws.payload)\n        : jws.payload);\n    const signature = decodeBase64url(jws.signature, 'signature', JWSInvalid);\n    const k = await normalizeKey(key, alg);\n    const verified = await verify(alg, k, signature, data);\n    if (!verified) {\n        throw new JWSSignatureVerificationFailed();\n    }\n    let payload;\n    if (b64) {\n        payload = decodeBase64url(jws.payload, 'payload', JWSInvalid);\n    }\n    else if (typeof jws.payload === 'string') {\n        payload = encoder.encode(jws.payload);\n    }\n    else {\n        payload = jws.payload;\n    }\n    const result = { payload };\n    if (jws.protected !== undefined) {\n        result.protectedHeader = parsedProt;\n    }\n    if (jws.header !== undefined) {\n        result.unprotectedHeader = jws.header;\n    }\n    if (resolvedKey) {\n        return { ...result, key: k };\n    }\n    return result;\n}\n","import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n    if (jws instanceof Uint8Array) {\n        jws = decoder.decode(jws);\n    }\n    if (typeof jws !== 'string') {\n        throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n    }\n    const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n    if (length !== 3) {\n        throw new JWSInvalid('Invalid Compact JWS');\n    }\n    const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n    const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n    if (typeof key === 'function') {\n        return { ...result, key: verified.key };\n    }\n    return result;\n}\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { encoder, decoder } from './buffer_utils.js';\nimport { isObject } from './type_checks.js';\nconst epoch = (date) => Math.floor(date.getTime() / 1000);\nconst minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport function secs(str) {\n    const matched = REGEX.exec(str);\n    if (!matched || (matched[4] && matched[1])) {\n        throw new TypeError('Invalid time period format');\n    }\n    const value = parseFloat(matched[2]);\n    const unit = matched[3].toLowerCase();\n    let numericDate;\n    switch (unit) {\n        case 'sec':\n        case 'secs':\n        case 'second':\n        case 'seconds':\n        case 's':\n            numericDate = Math.round(value);\n            break;\n        case 'minute':\n        case 'minutes':\n        case 'min':\n        case 'mins':\n        case 'm':\n            numericDate = Math.round(value * minute);\n            break;\n        case 'hour':\n        case 'hours':\n        case 'hr':\n        case 'hrs':\n        case 'h':\n            numericDate = Math.round(value * hour);\n            break;\n        case 'day':\n        case 'days':\n        case 'd':\n            numericDate = Math.round(value * day);\n            break;\n        case 'week':\n        case 'weeks':\n        case 'w':\n            numericDate = Math.round(value * week);\n            break;\n        default:\n            numericDate = Math.round(value * year);\n            break;\n    }\n    if (matched[1] === '-' || matched[4] === 'ago') {\n        return -numericDate;\n    }\n    return numericDate;\n}\nfunction validateInput(label, input) {\n    if (!Number.isFinite(input)) {\n        throw new TypeError(`Invalid ${label} input`);\n    }\n    return input;\n}\nconst normalizeTyp = (value) => {\n    if (value.includes('/')) {\n        return value.toLowerCase();\n    }\n    return `application/${value.toLowerCase()}`;\n};\nconst checkAudiencePresence = (audPayload, audOption) => {\n    if (typeof audPayload === 'string') {\n        return audOption.includes(audPayload);\n    }\n    if (Array.isArray(audPayload)) {\n        return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n    }\n    return false;\n};\nexport function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n    let payload;\n    try {\n        payload = JSON.parse(decoder.decode(encodedPayload));\n    }\n    catch {\n    }\n    if (!isObject(payload)) {\n        throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n    }\n    const { typ } = options;\n    if (typ &&\n        (typeof protectedHeader.typ !== 'string' ||\n            normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n        throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n    }\n    const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n    const presenceCheck = [...requiredClaims];\n    if (maxTokenAge !== undefined)\n        presenceCheck.push('iat');\n    if (audience !== undefined)\n        presenceCheck.push('aud');\n    if (subject !== undefined)\n        presenceCheck.push('sub');\n    if (issuer !== undefined)\n        presenceCheck.push('iss');\n    for (const claim of new Set(presenceCheck.reverse())) {\n        if (!(claim in payload)) {\n            throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n        }\n    }\n    if (issuer &&\n        !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n        throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n    }\n    if (subject && payload.sub !== subject) {\n        throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n    }\n    if (audience &&\n        !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n        throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n    }\n    let tolerance;\n    switch (typeof options.clockTolerance) {\n        case 'string':\n            tolerance = secs(options.clockTolerance);\n            break;\n        case 'number':\n            tolerance = options.clockTolerance;\n            break;\n        case 'undefined':\n            tolerance = 0;\n            break;\n        default:\n            throw new TypeError('Invalid clockTolerance option type');\n    }\n    const { currentDate } = options;\n    const now = epoch(currentDate || new Date());\n    if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n        throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n    }\n    if (payload.nbf !== undefined) {\n        if (typeof payload.nbf !== 'number') {\n            throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n        }\n        if (payload.nbf > now + tolerance) {\n            throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n        }\n    }\n    if (payload.exp !== undefined) {\n        if (typeof payload.exp !== 'number') {\n            throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n        }\n        if (payload.exp <= now - tolerance) {\n            throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n        }\n    }\n    if (maxTokenAge) {\n        const age = now - payload.iat;\n        const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n        if (age - tolerance > max) {\n            throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n        }\n        if (age < 0 - tolerance) {\n            throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n        }\n    }\n    return payload;\n}\nexport class JWTClaimsBuilder {\n    #payload;\n    constructor(payload) {\n        if (!isObject(payload)) {\n            throw new TypeError('JWT Claims Set MUST be an object');\n        }\n        this.#payload = structuredClone(payload);\n    }\n    data() {\n        return encoder.encode(JSON.stringify(this.#payload));\n    }\n    get iss() {\n        return this.#payload.iss;\n    }\n    set iss(value) {\n        this.#payload.iss = value;\n    }\n    get sub() {\n        return this.#payload.sub;\n    }\n    set sub(value) {\n        this.#payload.sub = value;\n    }\n    get aud() {\n        return this.#payload.aud;\n    }\n    set aud(value) {\n        this.#payload.aud = value;\n    }\n    set jti(value) {\n        this.#payload.jti = value;\n    }\n    set nbf(value) {\n        if (typeof value === 'number') {\n            this.#payload.nbf = validateInput('setNotBefore', value);\n        }\n        else if (value instanceof Date) {\n            this.#payload.nbf = validateInput('setNotBefore', epoch(value));\n        }\n        else {\n            this.#payload.nbf = epoch(new Date()) + secs(value);\n        }\n    }\n    set exp(value) {\n        if (typeof value === 'number') {\n            this.#payload.exp = validateInput('setExpirationTime', value);\n        }\n        else if (value instanceof Date) {\n            this.#payload.exp = validateInput('setExpirationTime', epoch(value));\n        }\n        else {\n            this.#payload.exp = epoch(new Date()) + secs(value);\n        }\n    }\n    set iat(value) {\n        if (value === undefined) {\n            this.#payload.iat = epoch(new Date());\n        }\n        else if (value instanceof Date) {\n            this.#payload.iat = validateInput('setIssuedAt', epoch(value));\n        }\n        else if (typeof value === 'string') {\n            this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));\n        }\n        else {\n            this.#payload.iat = validateInput('setIssuedAt', value);\n        }\n    }\n}\n","import { compactVerify } from '../jws/compact/verify.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n    const verified = await compactVerify(jwt, key, options);\n    if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n        throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n    }\n    const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n    const result = { payload, protectedHeader: verified.protectedHeader };\n    if (typeof key === 'function') {\n        return { ...result, key: verified.key };\n    }\n    return result;\n}\n","import { importJWK } from '../key/import.js';\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nfunction getKtyFromAlg(alg) {\n    switch (typeof alg === 'string' && alg.slice(0, 2)) {\n        case 'RS':\n        case 'PS':\n            return 'RSA';\n        case 'ES':\n            return 'EC';\n        case 'Ed':\n            return 'OKP';\n        case 'ML':\n            return 'AKP';\n        default:\n            throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n    }\n}\nfunction isJWKSLike(jwks) {\n    return (jwks &&\n        typeof jwks === 'object' &&\n        Array.isArray(jwks.keys) &&\n        jwks.keys.every(isJWKLike));\n}\nfunction isJWKLike(key) {\n    return isObject(key);\n}\nclass LocalJWKSet {\n    #jwks;\n    #cached = new WeakMap();\n    constructor(jwks) {\n        if (!isJWKSLike(jwks)) {\n            throw new JWKSInvalid('JSON Web Key Set malformed');\n        }\n        this.#jwks = structuredClone(jwks);\n    }\n    jwks() {\n        return this.#jwks;\n    }\n    async getKey(protectedHeader, token) {\n        const { alg, kid } = { ...protectedHeader, ...token?.header };\n        const kty = getKtyFromAlg(alg);\n        const candidates = this.#jwks.keys.filter((jwk) => {\n            let candidate = kty === jwk.kty;\n            if (candidate && typeof kid === 'string') {\n                candidate = kid === jwk.kid;\n            }\n            if (candidate && (typeof jwk.alg === 'string' || kty === 'AKP')) {\n                candidate = alg === jwk.alg;\n            }\n            if (candidate && typeof jwk.use === 'string') {\n                candidate = jwk.use === 'sig';\n            }\n            if (candidate && Array.isArray(jwk.key_ops)) {\n                candidate = jwk.key_ops.includes('verify');\n            }\n            if (candidate) {\n                switch (alg) {\n                    case 'ES256':\n                        candidate = jwk.crv === 'P-256';\n                        break;\n                    case 'ES384':\n                        candidate = jwk.crv === 'P-384';\n                        break;\n                    case 'ES512':\n                        candidate = jwk.crv === 'P-521';\n                        break;\n                    case 'Ed25519':\n                    case 'EdDSA':\n                        candidate = jwk.crv === 'Ed25519';\n                        break;\n                }\n            }\n            return candidate;\n        });\n        const { 0: jwk, length } = candidates;\n        if (length === 0) {\n            throw new JWKSNoMatchingKey();\n        }\n        if (length !== 1) {\n            const error = new JWKSMultipleMatchingKeys();\n            const _cached = this.#cached;\n            error[Symbol.asyncIterator] = async function* () {\n                for (const jwk of candidates) {\n                    try {\n                        yield await importWithAlgCache(_cached, jwk, alg);\n                    }\n                    catch { }\n                }\n            };\n            throw error;\n        }\n        return importWithAlgCache(this.#cached, jwk, alg);\n    }\n}\nasync function importWithAlgCache(cache, jwk, alg) {\n    const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);\n    if (cached[alg] === undefined) {\n        const key = await importJWK({ ...jwk, ext: true }, alg);\n        if (key instanceof Uint8Array || key.type !== 'public') {\n            throw new JWKSInvalid('JSON Web Key Set members must be public keys');\n        }\n        cached[alg] = key;\n    }\n    return cached[alg];\n}\nexport function createLocalJWKSet(jwks) {\n    const set = new LocalJWKSet(jwks);\n    const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n    Object.defineProperties(localJWKSet, {\n        jwks: {\n            value: () => structuredClone(set.jwks()),\n            enumerable: false,\n            configurable: false,\n            writable: false,\n        },\n    });\n    return localJWKSet;\n}\n","import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';\nimport { createLocalJWKSet } from './local.js';\nimport { isObject } from '../lib/type_checks.js';\nfunction isCloudflareWorkers() {\n    return (typeof WebSocketPair !== 'undefined' ||\n        (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n        (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n    const NAME = 'jose';\n    const VERSION = 'v6.2.3';\n    USER_AGENT = `${NAME}/${VERSION}`;\n}\nexport const customFetch = Symbol();\nasync function fetchJwks(url, headers, signal, fetchImpl = fetch) {\n    const response = await fetchImpl(url, {\n        method: 'GET',\n        signal,\n        redirect: 'manual',\n        headers,\n    }).catch((err) => {\n        if (err.name === 'TimeoutError') {\n            throw new JWKSTimeout();\n        }\n        throw err;\n    });\n    if (response.status !== 200) {\n        throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');\n    }\n    try {\n        return await response.json();\n    }\n    catch {\n        throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');\n    }\n}\nexport const jwksCache = Symbol();\nfunction isFreshJwksCache(input, cacheMaxAge) {\n    if (typeof input !== 'object' || input === null) {\n        return false;\n    }\n    if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {\n        return false;\n    }\n    if (!('jwks' in input) ||\n        !isObject(input.jwks) ||\n        !Array.isArray(input.jwks.keys) ||\n        !Array.prototype.every.call(input.jwks.keys, isObject)) {\n        return false;\n    }\n    return true;\n}\nclass RemoteJWKSet {\n    #url;\n    #timeoutDuration;\n    #cooldownDuration;\n    #cacheMaxAge;\n    #jwksTimestamp;\n    #pendingFetch;\n    #headers;\n    #customFetch;\n    #local;\n    #cache;\n    constructor(url, options) {\n        if (!(url instanceof URL)) {\n            throw new TypeError('url must be an instance of URL');\n        }\n        this.#url = new URL(url.href);\n        this.#timeoutDuration =\n            typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;\n        this.#cooldownDuration =\n            typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;\n        this.#cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;\n        this.#headers = new Headers(options?.headers);\n        if (USER_AGENT && !this.#headers.has('User-Agent')) {\n            this.#headers.set('User-Agent', USER_AGENT);\n        }\n        if (!this.#headers.has('accept')) {\n            this.#headers.set('accept', 'application/json');\n            this.#headers.append('accept', 'application/jwk-set+json');\n        }\n        this.#customFetch = options?.[customFetch];\n        if (options?.[jwksCache] !== undefined) {\n            this.#cache = options?.[jwksCache];\n            if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {\n                this.#jwksTimestamp = this.#cache.uat;\n                this.#local = createLocalJWKSet(this.#cache.jwks);\n            }\n        }\n    }\n    pendingFetch() {\n        return !!this.#pendingFetch;\n    }\n    coolingDown() {\n        return typeof this.#jwksTimestamp === 'number'\n            ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration\n            : false;\n    }\n    fresh() {\n        return typeof this.#jwksTimestamp === 'number'\n            ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge\n            : false;\n    }\n    jwks() {\n        return this.#local?.jwks();\n    }\n    async getKey(protectedHeader, token) {\n        if (!this.#local || !this.fresh()) {\n            await this.reload();\n        }\n        try {\n            return await this.#local(protectedHeader, token);\n        }\n        catch (err) {\n            if (err instanceof JWKSNoMatchingKey) {\n                if (this.coolingDown() === false) {\n                    await this.reload();\n                    return this.#local(protectedHeader, token);\n                }\n            }\n            throw err;\n        }\n    }\n    async reload() {\n        if (this.#pendingFetch && isCloudflareWorkers()) {\n            this.#pendingFetch = undefined;\n        }\n        this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch)\n            .then((json) => {\n            this.#local = createLocalJWKSet(json);\n            if (this.#cache) {\n                this.#cache.uat = Date.now();\n                this.#cache.jwks = json;\n            }\n            this.#jwksTimestamp = Date.now();\n            this.#pendingFetch = undefined;\n        })\n            .catch((err) => {\n            this.#pendingFetch = undefined;\n            throw err;\n        });\n        await this.#pendingFetch;\n    }\n}\nexport function createRemoteJWKSet(url, options) {\n    const set = new RemoteJWKSet(url, options);\n    const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n    Object.defineProperties(remoteJWKSet, {\n        coolingDown: {\n            get: () => set.coolingDown(),\n            enumerable: true,\n            configurable: false,\n        },\n        fresh: {\n            get: () => set.fresh(),\n            enumerable: true,\n            configurable: false,\n        },\n        reload: {\n            value: () => set.reload(),\n            enumerable: true,\n            configurable: false,\n            writable: false,\n        },\n        reloading: {\n            get: () => set.pendingFetch(),\n            enumerable: true,\n            configurable: false,\n        },\n        jwks: {\n            value: () => set.jwks(),\n            enumerable: true,\n            configurable: false,\n            writable: false,\n        },\n    });\n    return remoteJWKSet;\n}\n","/**\n * PKCE (RFC 7636) helpers for the authorization-code flow with S256.\n */\n\nexport function base64url(bytes: Uint8Array): string {\n  let binary = '';\n  for (const byte of bytes) {\n    binary += String.fromCharCode(byte);\n  }\n  return btoa(binary)\n    .replace(/\\+/g, '-')\n    .replace(/\\//g, '_')\n    .replace(/=+$/, '');\n}\n\n/**\n * Generate a high-entropy `code_verifier` (43 chars, url-safe).\n */\nexport function generateCodeVerifier(): string {\n  return base64url(globalThis.crypto.getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Derive the S256 `code_challenge` for a `code_verifier`.\n */\nexport async function deriveCodeChallenge(verifier: string): Promise<string> {\n  const digest = await globalThis.crypto.subtle.digest(\n    'SHA-256',\n    new TextEncoder().encode(verifier)\n  );\n  return base64url(new Uint8Array(digest));\n}\n","import { createError, H3Event } from 'h3';\nimport { SessionService } from './session.service';\nimport { AuthSessionData } from '../types/auth-session.types';\nimport type { AnalogAuthConfig } from '../types/auth.types';\nimport { inject, registerService, Injectable } from '@analog-tools/inject';\nimport { LoggerService } from '@analog-tools/logger';\nimport { getSession, refetchSession, regenerateSession, updateSession } from '@analog-tools/session';\nimport { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';\nimport { base64url } from '../utils/pkce';\n\nconst AUTH_FAILED_MESSAGE = 'Authentication failed';\n\n// http is only acceptable for these hosts (local development).\nfunction isLocalDevHost(hostname: string): boolean {\n  return (\n    hostname === 'localhost' ||\n    hostname === '::1' ||\n    hostname === '[::1]' ||\n    /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(hostname)\n  );\n}\n\n/**\n * Parse a URL and require https, except for local-development hosts. Guards\n * against tokens/secrets being sent over cleartext or to a non-https endpoint\n * advertised by a tampered discovery document.\n */\nfunction assertSecureUrl(\n  rawUrl: string,\n  label: string,\n  allowInsecureLocalhost: boolean\n): URL {\n  let url: URL;\n  try {\n    url = new URL(rawUrl);\n  } catch {\n    throw createError({ statusCode: 500, message: `Invalid ${label} URL` });\n  }\n  const isSecure =\n    url.protocol === 'https:' ||\n    (allowInsecureLocalhost &&\n      url.protocol === 'http:' &&\n      isLocalDevHost(url.hostname));\n  if (!isSecure) {\n    throw createError({\n      statusCode: 500,\n      message: `${label} must use https (http is only permitted for a localhost issuer during development)`,\n    });\n  }\n  return url;\n}\n\nfunction normalizeIssuer(issuer: string): string {\n  return issuer.replace(/\\/+$/, '');\n}\n\n/**\n * Build the set of `iss` claim values (trailing-slash variants) accepted for\n * a single configured issuer. Providers disagree on the canonical form:\n * Auth0 emits `https://tenant.auth0.com/` (trailing slash) in both the\n * discovery document and the id_token `iss`, while Keycloak and most others\n * emit it without the slash. The variants stay anchored to the one configured\n * issuer, so they never broaden trust to a different host.\n */\nfunction issuerVariants(issuer: string): string[] {\n  const normalized = normalizeIssuer(issuer);\n  return [...new Set([issuer, normalized, `${normalized}/`])];\n}\n// OIDC Core §3.1.3.6: at_hash is half of the access token hashed with the\n// digest matching the ID token's signing algorithm's bit size (EdDSA uses\n// SHA-512 per the OIDC errata). Unknown algs return null so the caller can\n// fail closed instead of skipping a claim that's actually present.\nfunction hashAlgForJwsAlg(alg: string): 'SHA-256' | 'SHA-384' | 'SHA-512' | null {\n  if (alg === 'EdDSA') return 'SHA-512';\n  const bits = /^[A-Z]{2}(256|384|512)$/.exec(alg)?.[1];\n  return bits ? (`SHA-${bits}` as 'SHA-256' | 'SHA-384' | 'SHA-512') : null;\n}\n\nasync function computeAtHash(accessToken: string, alg: string): Promise<string | null> {\n  const hashAlg = hashAlgForJwsAlg(alg);\n  if (!hashAlg) return null;\n  const digest = await globalThis.crypto.subtle.digest(\n    hashAlg,\n    new TextEncoder().encode(accessToken)\n  );\n  const bytes = new Uint8Array(digest);\n  return base64url(bytes.slice(0, bytes.length / 2));\n}\n\n/**\n * Service for handling OAuth authentication in a Backend-for-Frontend pattern\n */\n\n@Injectable()\nexport class OAuthAuthenticationService {\n  private logger: LoggerService;\n  private inflightRefreshes = new Map<\n    string,\n    Promise<{\n      access_token: string;\n      id_token?: string;\n      refresh_token?: string;\n      expires_in: number;\n    }>\n  >();\n\n  constructor(config: AnalogAuthConfig) {\n    this.logger = inject(LoggerService).forContext(\n      'OAuthAuthenticationService'\n    );\n    registerService(SessionService, config.sessionStorage);\n    this.config = config;\n  }\n\n  // Config object with default values\n  private readonly config!: AnalogAuthConfig;\n\n  // OpenID Configuration cache\n  private openIDConfigCache: OpenIDConfiguration | null = null;\n  private configLastFetched: number | null = null;\n  private readonly CONFIG_CACHE_TTL = 3600000; // 1 hour in milliseconds\n\n  // Add these properties for token refresh configuration\n  private TOKEN_REFRESH_SAFETY_MARGIN = 60 * 5; // 5 minutes in seconds\n\n  // Cached normalized whitelist extensions for efficient lookups\n  private normalizedWhitelistExtensions: Set<string> = new Set();\n\n  // Cached remote JWKS for ID-token verification (keyed by jwks_uri)\n  private jwks?: ReturnType<typeof createRemoteJWKSet>;\n  private jwksUri?: string;\n\n  /**\n   * Validate that the service has been properly initialized\n   * @throws Error if mandatory configuration is missing\n   */\n  private validateConfiguration(): void {\n    if (\n      !this.config.issuer ||\n      !this.config.clientId ||\n      !this.config.clientSecret ||\n      !this.config.callbackUri\n    ) {\n      throw new Error(\n        'OAuth Authentication Service not properly initialized. ' +\n          'Make sure to call AnalogAuth() with valid configuration before using authentication features.'\n      );\n    }\n  }\n\n  // Rest of the code converted to class methods...\n\n  /**\n   * Initialize session for the request\n   */\n  async initSession(event: H3Event): Promise<void> {\n    return await inject(SessionService).initSession(event);\n  }\n\n  getConfig(): AnalogAuthConfig {\n    this.validateConfiguration();\n    return this.config;\n  }\n\n  /**\n   * Safely access a configuration value\n   * @param key The configuration key to retrieve\n   * @param fallbackValue Optional fallback value if the config value doesn't exist\n   * @returns The configuration value or fallback value\n   * @throws Error if the configuration value doesn't exist and no fallback is provided\n   */\n  getConfigValue<K extends keyof AnalogAuthConfig>(\n    key: K,\n    fallbackValue?: AnalogAuthConfig[K]\n  ): AnalogAuthConfig[K] {\n    const value = this.config[key];\n    // Check if value is undefined or empty string\n    if (value === undefined || (typeof value === 'string' && value === '')) {\n      if (fallbackValue !== undefined) {\n        return fallbackValue;\n      }\n\n      // These config values are optional and should return a safe default if missing\n      if (key === 'userHandler' || key === 'logoutUrl' || key === 'audience') {\n        return undefined as AnalogAuthConfig[K];\n      }\n      if (key === 'unprotectedRoutes') {\n        return [] as string[] as AnalogAuthConfig[K];\n      }\n\n      throw new Error(`Configuration value for '${key}' doesn't exist`);\n    }\n    return value;\n  }\n\n  /**\n   * Check if the route is unprotected\n   * @param path The request path\n   * @returns True if the route is unprotected, false otherwise\n   */\n  isUnprotectedRoute(path: string): boolean {\n    const unprotectedRoutes = this.getConfigValue(\n      'unprotectedRoutes',\n      [] as string[]\n    );\n    \n    if (!Array.isArray(unprotectedRoutes)) {\n      return false;\n    }\n    \n    return unprotectedRoutes.some((route) => {\n      // Handle wildcard routes (ending with *)\n      if (route.endsWith('*')) {\n        const routePrefix = route.slice(0, -1);\n        \n        // For wildcards, we want to match paths that have actual content after the prefix\n        // Examples:\n        // - `/api/public/*` should NOT match `/api/public` or `/api/public/`\n        // - `/api/public/*` should match `/api/public/subpath`, `/api/public/anything`\n        if (!path.startsWith(routePrefix)) {\n          return false;\n        }\n        \n        // Check if there's actual content after the prefix (not just empty or single slash)\n        const afterPrefix = path.slice(routePrefix.length);\n        return afterPrefix.length > 0 && afterPrefix !== '/';\n      }\n      \n      // Handle exact route matching - normalize trailing slashes\n      const normalizedRoute = route.endsWith('/') ? route : route + '/';\n      const normalizedPath = path.endsWith('/') ? path : path + '/';\n      \n      // Check both with and without trailing slash\n      return path === route || normalizedPath === normalizedRoute;\n    });\n  }\n\n  /**\n   * Get OAuth authorization URL for login\n   */\n  async getAuthorizationUrl(params: {\n    state: string;\n    codeChallenge: string;\n    nonce: string;\n    redirectUri?: string;\n  }): Promise<string> {\n    this.validateConfiguration();\n\n    const config = await this.getOpenIDConfiguration();\n\n    const audience = this.getConfigValue('audience', undefined);\n\n    const searchparams = {\n      response_type: 'code',\n      client_id: this.getConfigValue('clientId'),\n      redirect_uri: params.redirectUri || this.getConfigValue('callbackUri'),\n      scope: this.getConfigValue('scope'),\n      state: params.state,\n      nonce: params.nonce,\n      code_challenge: params.codeChallenge,\n      code_challenge_method: 'S256',\n      ...(audience ? { audience } : {}),\n    };\n\n    const urlParams = new URLSearchParams(searchparams);\n\n    return `${config.authorization_endpoint}?${urlParams.toString()}`;\n  }\n\n  /**\n   * Exchange authorization code for tokens\n   */\n  private async exchangeCodeForTokens(\n    code: string,\n    codeVerifier: string,\n    redirectUri?: string\n  ) {\n    const config = await this.getOpenIDConfiguration();\n\n    const response = await fetch(config.token_endpoint, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/x-www-form-urlencoded',\n      },\n      body: new URLSearchParams({\n        grant_type: 'authorization_code',\n        client_id: this.getConfigValue('clientId'),\n        client_secret: this.getConfigValue('clientSecret'),\n        code,\n        code_verifier: codeVerifier,\n        redirect_uri: redirectUri || this.getConfigValue('callbackUri'),\n      }).toString(),\n    });\n    if (!response.ok) {\n      const error = await response.json();\n      this.logger.error('Error exchanging code for tokens', error);\n      throw createError({\n        statusCode: 401,\n        message: 'Failed to exchange authorization code',\n      });\n    }\n\n    return await response.json();\n  }\n\n  /**\n   * Refresh access token using refresh token\n   */\n  private async refreshTokens(refreshToken: string): Promise<{\n    access_token: string;\n    id_token?: string;\n    refresh_token?: string;\n    expires_in: number;\n  }> {\n    const config = await this.getOpenIDConfiguration();\n\n    try {\n      const response = await fetch(config.token_endpoint, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/x-www-form-urlencoded',\n        },\n        body: new URLSearchParams({\n          grant_type: 'refresh_token',\n          client_id: this.getConfigValue('clientId'),\n          client_secret: this.getConfigValue('clientSecret'),\n          refresh_token: refreshToken,\n        }).toString(),\n      });\n\n      if (!response.ok) {\n        const error = await response\n          .json()\n          .catch(() => ({ error: 'Unknown error' }));\n        this.logger.error('Error refreshing token', error);\n        throw createError({\n          statusCode: 401,\n          message: 'Failed to refresh token',\n        });\n      }\n\n      return await response.json();\n    } catch (error) {\n      this.logger.error('Error during token refresh', error);\n      throw createError({\n        statusCode: 401,\n        message: 'Failed to refresh authentication token',\n      });\n    }\n  }\n\n  private async refreshTokensDeduped(refreshToken: string): Promise<{\n    access_token: string;\n    id_token?: string;\n    refresh_token?: string;\n    expires_in: number;\n  }> {\n    const existingRefresh = this.inflightRefreshes.get(refreshToken);\n    if (existingRefresh) {\n      return existingRefresh;\n    }\n\n    const refreshPromise = this.refreshTokens(refreshToken).finally(() => {\n      this.inflightRefreshes.delete(refreshToken);\n    });\n\n    this.inflightRefreshes.set(refreshToken, refreshPromise);\n    return refreshPromise;\n  }\n\n  /**\n   * Get user info from OAuth provider with improved error handling and retry logic\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  private async getUserInfo(accessToken: string, maxRetries = 3): Promise<any> {\n    const config = await this.getOpenIDConfiguration();\n    let lastError: Error | null = null;\n\n    // Retry logic for network issues\n    for (let attempt = 1; attempt <= maxRetries; attempt++) {\n      try {\n        const response = await fetch(config.userinfo_endpoint, {\n          headers: {\n            Authorization: `Bearer ${accessToken}`,\n          },\n          // Add timeout to prevent hanging requests\n          signal: AbortSignal.timeout(10000), // 10 second timeout\n        });\n\n        if (!response.ok) {\n          const errorData = await response\n            .json()\n            .catch(() => ({ error: 'Unknown error' }));\n          this.logger.error(`Error getting user info`, errorData, {\n            attempt,\n            maxRetries,\n          });\n\n          // Handle different error scenarios\n          if (response.status === 401) {\n            throw createError({\n              statusCode: 401,\n              message: 'Authentication token is invalid or expired',\n            });\n          } else if (response.status === 429) {\n            // Rate limiting - wait longer before retry\n            const retryAfter = parseInt(\n              response.headers.get('Retry-After') || '5',\n              10\n            );\n            await new Promise((resolve) =>\n              setTimeout(resolve, retryAfter * 1000)\n            );\n            continue;\n          } else if (response.status >= 500) {\n            // Server error - retry after delay\n            await new Promise((resolve) => setTimeout(resolve, attempt * 1000));\n            continue;\n          } else {\n            throw createError({\n              statusCode: response.status,\n              message: `Failed to get user info: ${\n                errorData.error || 'Unknown error'\n              }`,\n            });\n          }\n        }\n\n        const userData = await response.json();\n\n        // Basic validation of user data\n        if (!userData || (!userData.sub && !userData.id)) {\n          throw createError({\n            statusCode: 500,\n            message: 'Invalid user data received from provider',\n          });\n        }\n\n        return userData;\n      } catch (error: unknown) {\n        lastError = error as Error;\n\n        // Don't retry certain errors like invalid token\n        if (\n          error instanceof Error &&\n          'statusCode' in error &&\n          (error as { statusCode: number }).statusCode === 401\n        ) {\n          throw error;\n        }\n\n        // Network errors are retryable\n        if (\n          error instanceof TypeError ||\n          (error instanceof Error && error.name === 'AbortError')\n        ) {\n          this.logger.error(`Network error fetching user info`, error, {\n            attempt,\n            maxRetries,\n          });\n          if (attempt < maxRetries) {\n            // Exponential backoff\n            await new Promise((resolve) =>\n              setTimeout(resolve, Math.pow(2, attempt) * 500)\n            );\n            continue;\n          }\n        }\n\n        // If we're out of retries, rethrow the last error\n        if (attempt === maxRetries) {\n          this.logger.error(`Failed to get user info after multiple attempts`, {\n            maxRetries,\n          });\n          throw createError({\n            statusCode: 500,\n            message: 'Failed to get user info after multiple attempts',\n            cause: lastError,\n          });\n        }\n      }\n    }\n\n    // This should never be reached due to the throw in the last attempt\n    throw createError({\n      statusCode: 500,\n      message: 'Unexpected error getting user info',\n    });\n  }\n\n  /**\n   * Verify an OIDC ID token: signature (via the provider's JWKS), `iss`, `aud`,\n   * `exp`/`nbf`, the per-login `nonce`, `azp` (when present), and — when the\n   * provider sends it — `at_hash` binding the token to `accessToken`. Returns\n   * the verified claims\n   * so the caller can anchor identity in the cryptographically validated token.\n   */\n  private async validateIdToken(\n    idToken: string,\n    nonce: string,\n    accessToken: string\n  ): Promise<JWTPayload> {\n    const config = await this.getOpenIDConfiguration();\n\n    if (!config.jwks_uri) {\n      throw createError({\n        statusCode: 500,\n        message: 'OpenID configuration is missing jwks_uri; cannot verify ID token',\n      });\n    }\n\n    // Only a localhost issuer (development) may use cleartext http; a production\n    // (https) issuer must never fetch signing keys over http, even for localhost.\n    const configuredIssuer = this.getConfigValue('issuer');\n    const issuerUrl = assertSecureUrl(configuredIssuer, 'OAuth issuer', true);\n    const allowInsecureLocalhost =\n      issuerUrl.protocol === 'http:' && isLocalDevHost(issuerUrl.hostname);\n\n    const jwksUrl = assertSecureUrl(\n      config.jwks_uri,\n      'jwks_uri',\n      allowInsecureLocalhost\n    );\n\n    if (!this.jwks || this.jwksUri !== config.jwks_uri) {\n      this.jwks = createRemoteJWKSet(jwksUrl);\n      this.jwksUri = config.jwks_uri;\n    }\n\n    let payload: JWTPayload;\n    let protectedHeader: { alg: string };\n    try {\n      ({ payload, protectedHeader } = await jwtVerify(idToken, this.jwks, {\n        // Trust anchor is the configured issuer, never the fetched metadata.\n        // Accept every trailing-slash variant of the configured issuer so an\n        // id_token `iss` from both slash-preferring providers (Auth0) and\n        // slash-stripping providers (Keycloak) verify against the same config.\n        issuer: issuerVariants(configuredIssuer),\n        audience: this.getConfigValue('clientId'),\n      }));\n    } catch (error) {\n      this.logger.error('ID token validation failed', error);\n      throw createError({ statusCode: 401, message: AUTH_FAILED_MESSAGE });\n    }\n\n    if (payload['nonce'] !== nonce) {\n      this.logger.error('ID token nonce mismatch');\n      throw createError({ statusCode: 401, message: AUTH_FAILED_MESSAGE });\n    }\n\n    if (\n      typeof payload['azp'] !== 'undefined' &&\n      payload['azp'] !== this.getConfigValue('clientId')\n    ) {\n      this.logger.error('ID token azp does not match client ID');\n      throw createError({ statusCode: 401, message: AUTH_FAILED_MESSAGE });\n    }\n\n    // Bind the ID token to the access token it was issued alongside, when the\n    // provider sends at_hash (OIDC Core §3.1.3.6). Absent = provider doesn't\n    // send it; present-but-wrong = token substitution, fail closed either way.\n    if (typeof payload['at_hash'] === 'string') {\n      const expected = await computeAtHash(accessToken, protectedHeader.alg);\n      if (expected === null || expected !== payload['at_hash']) {\n        this.logger.error('ID token at_hash mismatch');\n        throw createError({ statusCode: 401, message: AUTH_FAILED_MESSAGE });\n      }\n    }\n\n    return payload;\n  }\n\n  /**\n   * Handle OAuth callback\n   */\n  async handleCallback(event: H3Event, code: string, state: string) {\n    // Verify state parameter (should be implemented with CSRF protection)\n    if (!state) {\n      throw createError({\n        statusCode: 400,\n        message: 'Invalid state parameter',\n      });\n    }\n\n    // PKCE verifier and nonce were stored on the session by the login route.\n    const session = getSession<AuthSessionData>(event);\n    const codeVerifier = session?.codeVerifier;\n    const nonce = session?.nonce;\n    if (!codeVerifier || !nonce) {\n      throw createError({\n        statusCode: 400,\n        message: 'Missing PKCE verifier or nonce; restart the login flow',\n      });\n    }\n\n    // Exchange code for tokens (PKCE)\n    const tokens = await this.exchangeCodeForTokens(code, codeVerifier);\n    const { access_token, id_token, refresh_token, expires_in } = tokens;\n\n    const requestsOpenIdScope = this.getConfigValue('scope')\n      .split(' ')\n      .includes('openid');\n    if (requestsOpenIdScope && !id_token) {\n      this.logger.error(\n        'Token response is missing id_token for an openid-scoped request'\n      );\n      throw createError({ statusCode: 401, message: AUTH_FAILED_MESSAGE });\n    }\n\n    // Verify the ID token (authenticity + nonce replay protection) when present.\n    let idTokenSub: string | undefined;\n    if (id_token) {\n      const claims = await this.validateIdToken(id_token, nonce, access_token);\n      if (typeof claims.sub !== 'string' || claims.sub.length === 0) {\n        this.logger.error('ID token is missing a subject');\n        throw createError({ statusCode: 401, message: AUTH_FAILED_MESSAGE });\n      }\n      idTokenSub = claims.sub;\n    }\n\n    // Get user info from OAuth provider (profile enrichment)\n    const userData = await this.getUserInfo(access_token);\n\n    // Anchor identity in the verified ID token: userinfo must describe the same\n    // subject, otherwise the tokens have been mixed/substituted.\n    if (\n      idTokenSub &&\n      (typeof userData?.sub !== 'string' || userData.sub !== idTokenSub)\n    ) {\n      this.logger.error('ID token subject does not match userinfo subject');\n      throw createError({ statusCode: 401, message: AUTH_FAILED_MESSAGE });\n    }\n\n    // Store user in database\n    const userHandler = this.getConfigValue('userHandler', undefined);\n\n    let user = userData;\n    if (userHandler && 'createOrUpdateUser' in userHandler) {\n      user = await userHandler.createOrUpdateUser?.(userData);\n    }\n\n    // Store auth data in session using new session API\n    const auth = {\n      isAuthenticated: true,\n      accessToken: access_token,\n      idToken: id_token,\n      refreshToken: refresh_token,\n      expiresAt: Date.now() + expires_in * 1000,\n      userInfo: userData,\n    };\n\n    // Regenerate the session id on privilege elevation (anonymous ->\n    // authenticated) so any pre-auth id a fixation attacker may have planted is\n    // discarded before the authenticated tokens are stored under a fresh id.\n    await regenerateSession(event);\n\n    // Update session with user and auth data; clear transient PKCE/nonce.\n    await updateSession(event, () => ({\n      user,\n      auth,\n      codeVerifier: undefined,\n      nonce: undefined,\n    }));\n\n    if (this.getConfigValue('singleSessionPerUser', false)) {\n      // Optional policy: keep current request session and invalidate\n      // other authenticated sessions for the same resolved user identity.\n      // Guarded so a storage error in this optional cleanup can't fail an\n      // otherwise-successful login (tokens are already saved above).\n      try {\n        await this.invalidateOtherUserSessions(event, user, userData);\n      } catch (error) {\n        this.logger.error('Failed to invalidate other user sessions', error);\n      }\n    }\n\n    // Log successful session save\n    this.logger.debug('Authentication session data saved successfully');\n\n    return { user, tokens };\n  }\n\n  private resolveUserIdentity(\n    user: Record<string, unknown> | null | undefined,\n    userData: Record<string, unknown> | null | undefined\n  ): string | null {\n    const candidates = [\n      user?.['id'],\n      user?.['sub'],\n      userData?.['id'],\n      userData?.['sub'],\n      userData?.['email'],\n    ];\n\n    for (const candidate of candidates) {\n      if (typeof candidate === 'string' && candidate.length > 0) {\n        return candidate;\n      }\n    }\n\n    return null;\n  }\n\n  private resolveSessionIdentity(session: AuthSessionData): string | null {\n    const sessionUser =\n      session.user && typeof session.user === 'object'\n        ? (session.user as Record<string, unknown>)\n        : null;\n    const sessionUserInfo =\n      session.auth?.userInfo && typeof session.auth.userInfo === 'object'\n        ? (session.auth.userInfo as Record<string, unknown>)\n        : null;\n\n    const candidates = [\n      sessionUser?.['id'],\n      sessionUser?.['sub'],\n      sessionUserInfo?.['id'],\n      sessionUserInfo?.['sub'],\n      sessionUserInfo?.['email'],\n    ];\n\n    for (const candidate of candidates) {\n      if (typeof candidate === 'string' && candidate.length > 0) {\n        return candidate;\n      }\n    }\n\n    return null;\n  }\n\n  private async invalidateOtherUserSessions(\n    event: H3Event,\n    user: Record<string, unknown> | null | undefined,\n    userData: Record<string, unknown> | null | undefined\n  ): Promise<void> {\n    const targetIdentity = this.resolveUserIdentity(user, userData);\n    if (!targetIdentity) {\n      this.logger.debug(\n        'Skipping session invalidation because user identity could not be resolved'\n      );\n      return;\n    }\n\n    const currentSessionId =\n      typeof event.context['__session_id__'] === 'string'\n        ? (event.context['__session_id__'] as string)\n        : null;\n\n    if (!currentSessionId) {\n      this.logger.debug(\n        'Skipping session invalidation because current session id is unavailable'\n      );\n      return;\n    }\n\n    const sessionService = inject(SessionService);\n    const activeSessions = await sessionService.getActiveSessions();\n\n    for (const activeSession of activeSessions) {\n      if (activeSession.id === currentSessionId) {\n        continue;\n      }\n\n      if (!activeSession.data.auth?.isAuthenticated) {\n        continue;\n      }\n\n      const sessionIdentity = this.resolveSessionIdentity(activeSession.data);\n      if (!sessionIdentity || sessionIdentity !== targetIdentity) {\n        continue;\n      }\n\n      activeSession.update((data) => {\n        const currentAuth = data.auth;\n        return {\n          ...data,\n          auth: {\n            ...(currentAuth ?? { isAuthenticated: false }),\n            isAuthenticated: false,\n            accessToken: undefined,\n            idToken: undefined,\n            refreshToken: undefined,\n            expiresAt: undefined,\n            userInfo: undefined,\n          },\n          user: null,\n        };\n      });\n\n      await activeSession.save();\n      this.logger.debug('Invalidated stale authenticated session', {\n        sessionId: activeSession.id,\n      });\n    }\n  }\n\n  /**\n   * Calculate if token needs refresh based on safety margin\n   * @param expiresAt Timestamp when token expires\n   * @returns True if token should be refreshed\n   */\n  private shouldRefreshToken(expiresAt: number): boolean {\n    const now = Date.now();\n    // Convert safety margin to milliseconds\n    const safetyMargin = this.TOKEN_REFRESH_SAFETY_MARGIN * 1000;\n    // Return true if token will expire within safety margin\n    return now + safetyMargin > expiresAt;\n  }\n\n  /**\n   * Serverless-compatible method to refresh expiring tokens\n   * This should be called by a scheduled function/CRON job\n   * rather than using setInterval which doesn't work reliably in serverless\n   */\n  async refreshExpiringTokens(): Promise<{\n    refreshed: number;\n    failed: number;\n    total: number;\n  }> {\n    this.logger.debug('Starting bulk token refresh process');\n    \n    try {\n      // Get all active sessions from the session service\n      const sessionService = inject(SessionService);\n      const activeSessions = await sessionService.getActiveSessions();\n      \n      let refreshed = 0;\n      let failed = 0;\n      const total = activeSessions.length;\n      \n      this.logger.debug(`Found ${total} active sessions to check`);\n      \n      // Process each session\n      for (const session of activeSessions) {\n        try {\n          // Skip sessions without valid auth data\n          if (!session.data.auth?.isAuthenticated || \n              !session.data.auth.refreshToken || \n              !session.data.auth.expiresAt) {\n            this.logger.debug(`Skipping session ${session.id} - no valid auth data`);\n            continue;\n          }\n          \n          // Check if token needs refresh (within safety margin)\n          if (!this.shouldRefreshToken(session.data.auth.expiresAt)) {\n            this.logger.debug(`Skipping session ${session.id} - token not expiring soon`);\n            continue;\n          }\n          \n          this.logger.debug(`Refreshing token for session ${session.id}`);\n          \n          // Refresh the token (deduped so this doesn't race a concurrent\n          // request-driven refresh for the same refresh token)\n          const tokens = await this.refreshTokensDeduped(\n            session.data.auth.refreshToken\n          );\n          \n          // Update session data\n          session.update((data) => {\n            const currentAuth = data.auth;\n            if (!currentAuth) return data;\n            \n            return {\n              ...data,\n              auth: {\n                ...currentAuth,\n                accessToken: tokens.access_token,\n                idToken: tokens.id_token || currentAuth.idToken,\n                refreshToken: tokens.refresh_token || currentAuth.refreshToken,\n                expiresAt: Date.now() + tokens.expires_in * 1000,\n              },\n            };\n          });\n          \n          // Save the updated session\n          await session.save();\n          \n          refreshed++;\n          this.logger.debug(`Successfully refreshed token for session ${session.id}`);\n          \n        } catch (error) {\n          failed++;\n          this.logger.error(\n            'Failed to refresh token for session',\n            error,\n            { sessionId: session.id }\n          );\n\n          // Mark session as unauthenticated on refresh failure, unless a\n          // concurrent request-driven refresh already updated this same\n          // session (in storage) with a still-valid token in the meantime.\n          try {\n            const latestData = await session.refetch();\n            const hasLatestValidAuth =\n              !!latestData?.auth?.isAuthenticated &&\n              typeof latestData.auth.expiresAt === 'number' &&\n              latestData.auth.expiresAt > Date.now();\n\n            if (hasLatestValidAuth) {\n              failed--;\n              this.logger.debug(\n                `Skipping unauthenticated mark for session ${session.id} - already refreshed concurrently`\n              );\n              continue;\n            }\n\n            session.update((data) => {\n              const currentAuth = data.auth;\n              if (!currentAuth) return data;\n\n              return {\n                ...data,\n                auth: {\n                  ...currentAuth,\n                  isAuthenticated: false,\n                },\n              };\n            });\n            await session.save();\n          } catch (updateError) {\n            this.logger.error(\n              'Failed to update session after refresh failure',\n              updateError,\n              { sessionId: session.id }\n            );\n          }\n        }\n      }\n      \n      const result = { refreshed, failed, total };\n      this.logger.info(`Bulk token refresh completed`, result);\n      \n      return result;\n      \n    } catch (error) {\n      this.logger.error('Error during bulk token refresh', error);\n      throw createError({\n        statusCode: 500,\n        message: 'Failed to refresh expiring tokens',\n      });\n    }\n  }\n\n  /**\n   * Check if user is authenticated\n   */\n  async isAuthenticated(event: H3Event): Promise<boolean> {\n    await inject(SessionService).initSession(event);\n\n    const session = (await getSession(event)) as AuthSessionData;\n\n    // Ensure auth object exists in session data\n    if (!session?.auth) {\n      await updateSession(event, () => ({\n        auth: { isAuthenticated: false },\n      }));\n\n      return false;\n    }\n\n    // Check if session has auth data\n    if (!session.auth.isAuthenticated) {\n      return false;\n    }\n\n    // Check if token is expired\n    if (session.auth.expiresAt && session.auth.expiresAt < Date.now()) {\n      // Token is expired, try to refresh if refresh token exists\n      if (session.auth.refreshToken) {\n        try {\n          // Refresh the token\n          const tokens = await this.refreshTokensDeduped(\n            session.auth.refreshToken\n          );\n\n          // Update session with new tokens\n          await updateSession(event, (currentSession: AuthSessionData) => ({\n            auth: {\n              ...currentSession.auth,\n              isAuthenticated: true,\n              accessToken: tokens.access_token,\n              idToken: tokens.id_token || session?.auth?.idToken,\n              refreshToken: tokens.refresh_token || session?.auth?.refreshToken,\n              expiresAt: Date.now() + tokens.expires_in * 1000,\n            },\n          }));\n\n          return true;\n        } catch (error) {\n          this.logger.error('Error refreshing token', error);\n\n          // Re-read from storage, not the request-scoped context copy: a\n          // concurrent request may have already refreshed this session\n          // successfully, and getSession(event) can never observe that.\n          const latestSession = await refetchSession<AuthSessionData>(event);\n          const hasLatestValidAuth =\n            !!latestSession?.auth?.isAuthenticated &&\n            typeof latestSession.auth.expiresAt === 'number' &&\n            latestSession.auth.expiresAt > Date.now();\n\n          if (hasLatestValidAuth) {\n            return true;\n          }\n\n          // Clear auth data on refresh token failure\n          await updateSession(event, (currentSession: AuthSessionData) => ({\n            auth: {\n              ...currentSession.auth,\n              isAuthenticated: false,\n            },\n          }));\n\n          this.logger.info('error occurred while refreshing token');\n          this.logger.groupEnd(\n            'OAuthAuthenticationService.isAuthenticated ' + event.path\n          );\n          return false;\n        }\n      } else {\n        // No refresh token available\n        this.logger.info(' No refresh token available');\n        this.logger.groupEnd(\n          'OAuthAuthenticationService.isAuthenticated ' + event.path\n        );\n        return false;\n      }\n    }\n\n    // Check if token needs proactive refresh\n    if (\n      session.auth.expiresAt &&\n      this.shouldRefreshToken(session.auth.expiresAt)\n    ) {\n      // Refresh in background without blocking the request\n      setTimeout(async () => {\n        try {\n          const currentSession = (await getSession(event)) as AuthSessionData;\n          if (\n            !currentSession?.auth?.isAuthenticated ||\n            !currentSession.auth.refreshToken\n          ) {\n            return; // Session no longer valid\n          }\n\n          const tokens = await this.refreshTokensDeduped(\n            currentSession.auth.refreshToken\n          );\n\n          // Update session with new tokens\n          await updateSession(event, (session: AuthSessionData) => ({\n            auth: {\n              ...session.auth,\n              isAuthenticated: true,\n              accessToken: tokens.access_token,\n              idToken: tokens.id_token || currentSession?.auth?.idToken,\n              refreshToken:\n                tokens.refresh_token || currentSession?.auth?.refreshToken,\n              expiresAt: Date.now() + tokens.expires_in * 1000,\n            },\n          }));\n\n          this.logger.debug('Background token refresh completed');\n        } catch (error) {\n          this.logger.error('Background token refresh failed', error);\n        }\n      }, 0);\n    }\n\n    return true;\n  }\n\n  /**\n   * Get authenticated user\n   */\n  async getAuthenticatedUser(event: H3Event) {\n    // Check if user is authenticated\n    if (!(await this.isAuthenticated(event))) {\n      return null;\n    }\n\n    const session = getSession(event) as AuthSessionData;\n\n    const userHandler = this.getConfigValue('userHandler', undefined);\n\n    if (userHandler && 'mapUserToLocal' in userHandler) {\n      return userHandler.mapUserToLocal?.(session.auth?.userInfo);\n    }\n\n    return session.auth?.userInfo;\n  }\n\n  /**\n   * Revoke an access token\n   */\n  private async revokeToken(token: string): Promise<void> {\n    const config = await this.getOpenIDConfiguration();\n    const response = await fetch(config.revocation_endpoint, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/x-www-form-urlencoded',\n      },\n      body: new URLSearchParams({\n        client_id: this.getConfigValue('clientId'),\n        client_secret: this.getConfigValue('clientSecret'),\n        token,\n      }),\n    });\n\n    if (!response.ok) {\n      throw new Error('Failed to revoke token');\n    }\n  }\n\n  /**\n   * Logout user\n   */\n  async logout(event: H3Event): Promise<string> {\n    await inject(SessionService).initSession(event);\n    const session = getSession(event) as AuthSessionData;\n    const config = await this.getOpenIDConfiguration();\n\n    // Revoke access token if it exists\n    if (session?.['auth']?.accessToken) {\n      try {\n        await this.revokeToken(session['auth'].accessToken);\n      } catch (error) {\n        this.logger.error('Failed to revoke access token', error);\n      }\n    }\n\n    // Revoke refresh token if it exists\n    if (session?.auth?.refreshToken) {\n      try {\n        await this.revokeToken(session.auth.refreshToken);\n      } catch (error) {\n        this.logger.error('Failed to revoke refresh token', error);\n      }\n    }\n\n    // Get OAuth logout URL\n    const logoutUrl = new URL(config.end_session_endpoint);\n    logoutUrl.searchParams.append('client_id', this.getConfigValue('clientId'));\n\n    // Add returnTo parameter if configured\n    const returnTo = this.getConfigValue('logoutUrl');\n\n    if (returnTo) {\n      logoutUrl.searchParams.append('returnTo', returnTo);\n    }\n\n    // Clear session\n    await updateSession(event, () => ({\n      auth: { isAuthenticated: false },\n      user: null,\n    }));\n\n    return logoutUrl.toString();\n  }\n\n  /**\n   * Fetch OpenID Configuration from the well-known endpoint\n   */\n  private async getOpenIDConfiguration(): Promise<OpenIDConfiguration> {\n    const now = Date.now();\n\n    // Return cached config if it's still valid\n    if (\n      this.openIDConfigCache &&\n      this.configLastFetched &&\n      now - this.configLastFetched < this.CONFIG_CACHE_TTL\n    ) {\n      return this.openIDConfigCache;\n    }\n\n    const issuer = this.getConfigValue('issuer');\n    // Enforce https on the issuer itself: over TLS the discovery document and\n    // every subsequent token/userinfo call are authenticated, so a network\n    // attacker cannot forge the endpoints the client trusts. Only a localhost\n    // dev issuer may use http; a production https issuer then forces https on\n    // every advertised endpoint too.\n    const issuerUrl = assertSecureUrl(issuer, 'OAuth issuer', true);\n    const allowInsecureLocalhost =\n      issuerUrl.protocol === 'http:' && isLocalDevHost(issuerUrl.hostname);\n\n    let config: OpenIDConfiguration;\n    try {\n      const response = await fetch(\n        `${normalizeIssuer(issuer)}/.well-known/openid-configuration`,\n        {\n          // Reject redirects: a network attacker could otherwise redirect\n          // discovery to an attacker-controlled https endpoint that still\n          // passes validation.\n          redirect: 'error',\n          signal: AbortSignal.timeout(\n            this.getConfigValue('discoveryTimeoutMs', 10000) as number\n          ),\n        }\n      );\n\n      if (!response.ok) {\n        throw new Error(\n          `Failed to fetch OpenID configuration: ${response.statusText}`\n        );\n      }\n\n      config = await response.json();\n    } catch (error) {\n      this.logger.error('Error fetching OpenID configuration', error);\n      throw createError({\n        statusCode: 500,\n        message: 'Failed to fetch OpenID configuration',\n      });\n    }\n\n    this.assertTrustedOpenIDConfiguration(\n      config,\n      issuer,\n      allowInsecureLocalhost\n    );\n\n    this.openIDConfigCache = config;\n    this.configLastFetched = now;\n\n    return config;\n  }\n\n  /**\n   * Validate a fetched OpenID configuration before trusting its endpoints:\n   * the document's `issuer` must match the configured issuer (OIDC Discovery\n   * §4.3), and every advertised endpoint we use must be https (localhost aside).\n   */\n  private assertTrustedOpenIDConfiguration(\n    config: OpenIDConfiguration,\n    issuer: string,\n    allowInsecureLocalhost: boolean\n  ): void {\n    if (\n      typeof config.issuer !== 'string' ||\n      normalizeIssuer(config.issuer) !== normalizeIssuer(issuer)\n    ) {\n      this.logger.error('OpenID configuration issuer mismatch', {\n        expected: issuer,\n        received: config.issuer,\n      });\n      throw createError({\n        statusCode: 500,\n        message:\n          'OpenID configuration issuer does not match the configured issuer',\n      });\n    }\n\n    const endpointKeys = [\n      'authorization_endpoint',\n      'token_endpoint',\n      'userinfo_endpoint',\n      'end_session_endpoint',\n      'revocation_endpoint',\n    ] as const;\n\n    for (const key of endpointKeys) {\n      const endpoint = config[key];\n      if (typeof endpoint !== 'string' || endpoint.length === 0) {\n        throw createError({\n          statusCode: 500,\n          message: `OpenID configuration is missing ${key}`,\n        });\n      }\n      assertSecureUrl(endpoint, `OpenID ${key}`, allowInsecureLocalhost);\n    }\n  }\n}\n\n// OpenID Configuration interface\ninterface OpenIDConfiguration {\n  issuer: string;\n  authorization_endpoint: string;\n  token_endpoint: string;\n  userinfo_endpoint: string;\n  end_session_endpoint: string;\n  revocation_endpoint: string;\n  jwks_uri?: string;\n}\n","import { H3Event } from 'h3';\nimport { inject } from '@analog-tools/inject';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { AuthRoute } from '../types/auth.types';\nimport { LoggerService } from '@analog-tools/logger';\n\n/**\n * Example of a route that checks if the user is authenticated\n * The authentication middleware will automatically handle token refresh if needed\n */\nconst route: AuthRoute = {\n  path: 'authenticated',\n  handler: async (event: H3Event) => {\n    const authService = inject(OAuthAuthenticationService);\n    const logger = inject(LoggerService).forContext('AuthMiddleware');\n\n    const result = { authenticated: await authService.isAuthenticated(event) };\n\n    logger.info('User authentication status checked', result);\n\n    return result;\n  },\n};\n\nexport default route;\n","const SAME_ORIGIN_BASE_URL = 'http://analog-tools.local';\n\nfunction containsControlCharacter(value: string): boolean {\n  for (const character of value) {\n    const characterCode = character.charCodeAt(0);\n\n    if (characterCode <= 0x1f || characterCode === 0x7f) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nexport function sanitizeRedirectUrl(redirectUrl: unknown): string {\n  if (typeof redirectUrl !== 'string') {\n    return '/';\n  }\n\n  const normalizedRedirectUrl = redirectUrl.trim();\n\n  if (\n    normalizedRedirectUrl === '' ||\n    !normalizedRedirectUrl.startsWith('/') ||\n    normalizedRedirectUrl.startsWith('//') ||\n    normalizedRedirectUrl.includes('\\\\') ||\n    containsControlCharacter(normalizedRedirectUrl)\n  ) {\n    return '/';\n  }\n\n  try {\n    const parsedUrl = new URL(normalizedRedirectUrl, SAME_ORIGIN_BASE_URL);\n\n    if (parsedUrl.origin !== SAME_ORIGIN_BASE_URL) {\n      return '/';\n    }\n\n    const safeRedirectUrl = `${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n\n    return safeRedirectUrl.startsWith('//') ? '/' : safeRedirectUrl;\n  } catch {\n    return '/';\n  }\n}\n","import { createError, getQuery, H3Event, sendRedirect } from 'h3';\nimport { AuthRoute } from '../types/auth.types';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { AuthSessionData } from '../types/auth-session.types';\nimport { inject } from '@analog-tools/inject';\nimport { getSession, updateSession } from '@analog-tools/session';\nimport { sanitizeRedirectUrl } from '../utils/sanitizeRedirectUrl';\n\n/**\n * Handles the OAuth callback from the authentication provider.\n * This route is responsible for processing the authorization code\n * and exchanging it for an access token.\n *\n * @param event - The H3 event object containing request and response data.\n * @returns A redirect to the application or an error if the state is invalid.\n */\n/**\n * Reads the sanitized redirectUrl from session and clears it, so a stale\n * value can't be reused by a later hit to this route.\n *\n * `updateSession` merges the updater's return value over the current\n * session data (`{ ...currentData, ...updates }`), so simply omitting the\n * key (e.g. via `delete`) does not clear it - the field must be explicitly\n * set to `undefined` to override the spread.\n */\nasync function resolveAndClearRedirect(event: H3Event): Promise<string> {\n  const currentSessionData = getSession<AuthSessionData>(event);\n  const redirectUrl = sanitizeRedirectUrl(currentSessionData?.redirectUrl);\n\n  await updateSession<AuthSessionData>(event, (data) => ({\n    ...data,\n    redirectUrl: undefined,\n  }));\n\n  return redirectUrl;\n}\n\nconst route: AuthRoute = {\n  path: 'callback',\n  handler: async (event: H3Event) => {\n    const authService = inject(OAuthAuthenticationService);\n\n    // Initialize session\n    await authService.initSession(event);\n\n    if (await authService.isAuthenticated(event)) {\n      const redirectUrl = await resolveAndClearRedirect(event);\n      return sendRedirect(event, redirectUrl);\n    }\n\n    // Get code and state from query parameters\n    const query = getQuery(event);\n    const code = query['code'] as string;\n    const state = query['state'] as string;\n\n    // Verify state parameter with proper null checks and error handling\n    const sessionData = getSession<AuthSessionData>(event);\n    const sessionState = sessionData?.state;\n\n    if (!state || !sessionState || state !== sessionState) {\n      throw createError({\n        statusCode: 400,\n        message:\n          'Invalid or missing state parameter. Authentication flow may have been tampered with.',\n        statusMessage: 'Authorization Failed',\n      });\n    }\n\n    // Clear state from session\n    await updateSession<AuthSessionData>(event, (data) => ({\n      ...data,\n      state: undefined,\n    }));\n\n    // Handle callback\n    await authService.handleCallback(event, code, state);\n\n    // Get redirect URL from session (or default) and clear it\n    const redirectUrl = await resolveAndClearRedirect(event);\n\n    // Redirect to application\n    return sendRedirect(event, redirectUrl);\n  },\n};\n\nexport default route;\n","const webCrypto = globalThis.crypto;\nconst subtle = webCrypto.subtle;\nconst randomUUID = () => {\n  return webCrypto.randomUUID();\n};\nconst getRandomValues = (array) => {\n  return webCrypto.getRandomValues(array);\n};\nconst _crypto = {\n  randomUUID,\n  getRandomValues,\n  subtle\n};\n\nexport { _crypto as default, getRandomValues, randomUUID, subtle };\n","import { getQuery, H3Event, sendRedirect } from 'h3';\nimport { randomUUID } from 'uncrypto';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { AuthSessionData } from '../types/auth-session.types';\nimport { AuthRoute } from '../types/auth.types';\nimport { inject } from '@analog-tools/inject';\nimport { updateSession } from '@analog-tools/session';\nimport { sanitizeRedirectUrl } from '../utils/sanitizeRedirectUrl';\nimport { deriveCodeChallenge, generateCodeVerifier } from '../utils/pkce';\n\nconst route: AuthRoute = {\n  path: 'login',\n  handler: async (event: H3Event) => {\n    const authService = inject(OAuthAuthenticationService);\n\n    // Initialize session\n    await authService.initSession(event);\n\n    // Generate CSRF state, PKCE verifier/challenge, and an OIDC nonce.\n    const state = randomUUID();\n    const nonce = randomUUID();\n    const codeVerifier = generateCodeVerifier();\n    const codeChallenge = await deriveCodeChallenge(codeVerifier);\n\n    // Persist the values the callback needs to verify the response.\n    await updateSession<AuthSessionData>(event, (currentSession) => ({\n      ...currentSession,\n      state,\n      nonce,\n      codeVerifier,\n    }));\n\n    // Get redirect URL from query parameters\n    const query = getQuery(event);\n    const redirectUri = query['redirect_uri'] as string;\n\n    const sanitizedTargetPath = redirectUri\n      ? sanitizeRedirectUrl(redirectUri)\n      : '/';\n\n    await updateSession<AuthSessionData>(event, (currentSession) => ({\n      ...currentSession,\n      redirectUrl:\n        sanitizedTargetPath !== '/' ? sanitizedTargetPath : undefined,\n    }));\n\n    // Get authorization URL\n    const authUrl = await authService.getAuthorizationUrl({\n      state,\n      codeChallenge,\n      nonce,\n    });\n\n    // Redirect to OAuth provider\n    return sendRedirect(event, authUrl);\n  },\n};\n\nexport default route;\n","import { createError, H3Event, sendRedirect } from 'h3';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { AuthRoute } from '../types/auth.types';\nimport { LoggerService } from '@analog-tools/logger';\nimport { inject } from '@analog-tools/inject';\n\nconst route: AuthRoute = {\n  path: 'logout',\n  handler: async (event: H3Event) => {\n    const logger = inject(LoggerService).forContext('LogoutRoute');\n\n    try {\n      const authService = inject(OAuthAuthenticationService);\n\n      // Initialize session\n      await authService.initSession(event);\n\n      // Get logout URL using updated auth service method (which now uses sessionHandler)\n      const logoutUrl = await authService.logout(event);\n\n      // The sessionHandler is already cleared in the logout method\n      // No need to manually destroy it here\n\n      return sendRedirect(event, logoutUrl);\n    } catch (error) {\n      logger.error('Logout failed', error);\n      throw createError({\n        statusCode: 500,\n        message: 'Logout failed',\n      });\n    }\n  },\n};\n\nexport default route;\n","import { H3Event } from 'h3';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { AuthRoute } from '../types/auth.types';\nimport { inject } from '@analog-tools/inject';\n\nconst route: AuthRoute = {\n  path: 'protected-data',\n  handler: async (event: H3Event) => {\n    const authService = inject(OAuthAuthenticationService);\n\n    // The middleware has already verified authentication and refreshed tokens if needed\n    // Now we can get the authenticated user\n    const user = await authService.getAuthenticatedUser(event);\n\n    return {\n      message: 'This is protected data that requires authentication',\n      user,\n    };\n  },\n};\n\nexport default route;\n","/**\n * Constant-time string comparison that leaks neither length nor content through\n * timing.\n *\n * Both inputs are HMAC'd under a fresh random per-call key, so the comparison\n * runs over two fixed-length (32-byte) digests without an early return, and an\n * attacker cannot precompute or correlate the digests across calls. Use this for\n * comparing secrets (e.g. API keys) instead of `===`, which short-circuits on\n * the first differing byte.\n */\nexport async function timingSafeEqual(a: string, b: string): Promise<boolean> {\n  const encoder = new TextEncoder();\n  const keyBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n  const key = await globalThis.crypto.subtle.importKey(\n    'raw',\n    keyBytes,\n    { name: 'HMAC', hash: 'SHA-256' },\n    false,\n    ['sign']\n  );\n\n  const digestA = new Uint8Array(\n    await globalThis.crypto.subtle.sign('HMAC', key, encoder.encode(a))\n  );\n  const digestB = new Uint8Array(\n    await globalThis.crypto.subtle.sign('HMAC', key, encoder.encode(b))\n  );\n\n  let diff = 0;\n  for (let i = 0; i < digestA.length; i++) {\n    diff |= digestA[i] ^ digestB[i];\n  }\n  return diff === 0;\n}\n","import { getRequestHeaders, createError, H3Event } from 'h3';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { AuthRoute } from '../types/auth.types';\nimport { inject } from '@analog-tools/inject';\nimport { LoggerService } from '@analog-tools/logger';\nimport { timingSafeEqual } from '../utils/timing-safe-equal';\n\nconst route: AuthRoute = {\n  path: 'refresh-tokens',\n  handler: async (event: H3Event) => {\n    const logger = inject(LoggerService).forContext('TokenRefresh');\n    const authService = inject(OAuthAuthenticationService);\n    \n    // Verify authorization - use tokenRefreshApiKey from config or fall back to env variable\n    const apiKey = authService.getConfig().tokenRefreshApiKey;\n    if (!apiKey) {\n      logger.error('Token refresh API key not configured in either AnalogAuthConfig.tokenRefreshApiKey or TOKEN_REFRESH_API_KEY env variable');\n      throw createError({\n        statusCode: 500,\n        message: 'Server configuration error',\n      });\n    }\n\n    const authHeader = getRequestHeaders(event).authorization;\n    if (!authHeader || !(await timingSafeEqual(authHeader, `Bearer ${apiKey}`))) {\n      logger.warn('Unauthorized token refresh attempt');\n      throw createError({\n        statusCode: 401,\n        message: 'Unauthorized',\n      });\n    }\n\n    try {\n      \n      const result = await authService.refreshExpiringTokens();\n\n      // Log the results\n      logger.info(`Token refresh job completed`, {\n        refreshed: result.refreshed,\n        failed: result.failed,\n        total: result.total,\n      });\n\n      return {\n        success: true,\n        ...result,\n      };\n    } catch (error) {\n      logger.error('Error in token refresh job', error);\n      throw createError({\n        statusCode: 500,\n        message: 'Failed to refresh tokens',\n      });\n    }\n  },\n};\n\nexport default route;\n","import { createError, H3Event } from 'h3';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { AuthRoute } from '../types/auth.types';\nimport { inject } from '@analog-tools/inject';\n\nconst route: AuthRoute = {\n  path: 'user',\n  handler: async (event: H3Event) => {\n    const authService = inject(OAuthAuthenticationService);\n\n    // Initialize session\n    await authService.initSession(event);\n\n    // Check if user is authenticated\n    if (!(await authService.isAuthenticated(event))) {\n      throw createError({\n        statusCode: 401,\n        message: 'Unauthorized',\n      });\n    }\n\n    // Get authenticated user\n    return authService.getAuthenticatedUser(event);\n  },\n};\n\nexport default route;\n","import authenticated from '../routes/authenticated';\nimport callback from '../routes/callback';\nimport login from '../routes/login';\nimport logout from '../routes/logout';\nimport protectedData from '../routes/protected-data';\nimport refreshTokens from '../routes/refresh-tokens';\nimport user from '../routes/user';\n\n/**\n * Registers all authentication routes dynamically\n * @returns A record of route paths mapped to their handler functions\n */\nexport function registerRoutes() {\n  return { \n    [authenticated.path]: authenticated.handler,\n    [callback.path]: callback.handler,\n    [login.path]: login.handler,\n    [logout.path]: logout.handler,\n    [protectedData.path]: protectedData.handler,\n    [refreshTokens.path]: refreshTokens.handler,\n    [user.path]: user.handler\n  };\n}","export function getLastPathSegment(path: string): string {\n    // Erstellen Sie ein URL-Objekt, um den Pfad zu analysieren\n    const url = new URL(path, 'http://dummy-base'); // Basis-URL erforderlich für relative Pfade\n\n    // Extrahieren Sie den Pfadnamen und teilen Sie ihn in Segmente\n    const segments = url.pathname.split('/').filter(Boolean);\n\n    // Geben Sie den letzten Pfadabschnitt zurück\n    return segments.pop() ?? '';\n}\n","import { createError, H3Event } from 'h3';\nimport { registerRoutes } from './registerRoutes';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { getLastPathSegment } from '../utils/getLastPathSegment';\nimport { inject } from '@analog-tools/inject';\n\nexport async function handleAuthRoute(event: H3Event) {\n  if (event.path.includes('/api/auth/')) {\n    const path = getLastPathSegment(event.path);\n\n    if (!path) {\n      throw createError({\n        statusCode: 400,\n        statusMessage: 'Missing path parameter',\n      });\n    }\n\n    const authService = inject(OAuthAuthenticationService);\n    await authService.initSession(event);\n\n    // Check if the requested path exists in our routes\n    const routes = registerRoutes();\n\n    if (routes[path]) {\n      return routes[path](event);\n    }\n\n    // If route doesn't exist, return a 404 error handler\n\n    throw createError({\n      statusCode: 404,\n      statusMessage: `Authentication route '${path}' not found`,\n    });\n  }\n}\n","import { H3Event } from 'h3';\nimport { inject } from '@analog-tools/inject';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\n\nexport async function checkAuthentication(event: H3Event) {\n  const authService = inject(OAuthAuthenticationService);\n\n  await authService.initSession(event);\n  // Check authentication with token refresh capability\n  return authService.isAuthenticated(event);\n}\n","import { getHeader, getRequestURL, H3Event, sendRedirect } from 'h3';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { LoggerService } from '@analog-tools/logger';\nimport { inject } from '@analog-tools/inject';\nimport { TRPCError } from '@trpc/server';\nimport { checkAuthentication } from './checkAuthentication';\nimport { updateSession } from '@analog-tools/session';\nimport { sanitizeRedirectUrl } from '../utils/sanitizeRedirectUrl';\n\nexport async function useAnalogAuthMiddleware(event: H3Event) {\n  const requestUrl = getRequestURL(event);\n  const pathname = requestUrl.pathname;\n  const authService = inject(OAuthAuthenticationService);\n  const logger = inject(LoggerService).forContext('AuthMiddleware');\n\n  logger.info('Processing authentication middleware', pathname);\n\n  // All /api/auth/* routes are handled by handleAuthRoute.\n  if (pathname.startsWith('/api/auth/')) {\n    return;\n  }\n\n  // tRPC procedures enforce their own auth per-procedure, so the HTTP gate lets\n  // the tRPC endpoint through. Match it on a path boundary — a bare `startsWith`\n  // would also exempt unrelated routes like `/api/trpc-admin`.\n  if (\n    authService.isUnprotectedRoute(pathname) ||\n    pathname === '/api/trpc' ||\n    pathname.startsWith('/api/trpc/')\n  ) {\n    return;\n  }\n\n  await authService.initSession(event);\n  if (await checkAuthentication(event)) {\n    return;\n  }\n\n  // Not authenticated: API calls (fetch=true from the HTTP interceptor) receive\n  // a 401 they can handle; browser navigations are sent to the login page.\n  if (getHeader(event, 'fetch') === 'true') {\n    throw new TRPCError({\n      code: 'UNAUTHORIZED',\n      message: 'User is not authenticated',\n    });\n  }\n\n  logger.debug('Redirecting to login page', { path: pathname });\n  await updateSession(event, (currentSession: Record<string, unknown>) => ({\n    ...currentSession,\n    redirectUrl: sanitizeRedirectUrl(`${requestUrl.pathname}${requestUrl.search}`),\n  }));\n  await sendRedirect(event, '/api/auth/login');\n}\n","import { H3Event } from 'h3';\nimport type { AnalogAuthConfig } from '../types/auth.types';\nimport { OAuthAuthenticationService } from '../services/oauth-authentication.service';\nimport { handleAuthRoute } from './handleAuthRoute';\nimport { useAnalogAuthMiddleware } from './useAnalogAuthMiddleware';\nimport { registerService } from '@analog-tools/inject';\n\n/**\n * Configures and initializes the OAuth authentication service\n *\n * @param config The OAuth authentication configuration\n * @param event The H3 event object\n * @throws Error if any mandatory configuration values are missing\n */\nexport async function useAnalogAuth(config: AnalogAuthConfig, event: H3Event) {\n  // Validate mandatory configuration values\n  const mandatoryFields: Array<keyof AnalogAuthConfig> = [\n    'issuer',\n    'clientId',\n    'clientSecret',\n    'callbackUri',\n  ];\n\n  const missingFields = mandatoryFields.filter((field) => !config[field]);\n\n  if (missingFields.length > 0) {\n    throw new Error(\n      `AnalogAuth initialization failed: Missing mandatory configuration values: ${missingFields.join(\n        ', '\n      )}`\n    );\n  }\n\n  // Initialize the authentication service with validated config\n  registerService(OAuthAuthenticationService, config);\n\n  await useAnalogAuthMiddleware(event);\n\n  return handleAuthRoute(event);\n}\n"],"x_google_ignoreList":[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,30],"mappings":"oJAEA,IAAI,EAAoB,SAAS,EAAG,CACnC,MAAO,GAAE,QAAU,WAAY,EAAE,UAAY,WAAY,EAAE,aAAe,gBAAiB,EAAE,UAAY,YAAa,EAAE,YAAc,WAAY,EAAE,e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