@analog-tools/auth
Version:
Authentication module for AnalogJS applications
3,108 lines • 101 kB
JavaScript
import { createError as e, getHeader as t, getQuery as n, getRequestHeaders as r, getRequestURL as i, sendRedirect as a } from "h3";
import { createUnstorageStore as o, destroySession as s, getSession as c, refetchSession as l, regenerateSession as u, updateSession as d, useSession as f } from "@analog-tools/session";
import { TRPCError as p } from "@trpc/server";
//#region ../../node_modules/@analog-tools/logger/index.js
var m = /* @__PURE__ */ function(e) {
return 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;
}({}), h = /* @__PURE__ */ function(e) {
return 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;
}({});
function g(e) {
return [
"trace",
"debug",
"info",
"warn",
"error",
"fatal",
"silent"
].includes(e);
}
var _ = class e {
static {
this.DEFAULT_MAX_DEPTH = 10;
}
static {
this.CIRCULAR_REF_PLACEHOLDER = "[Circular Reference]";
}
static {
this.MAX_DEPTH_PLACEHOLDER = "[Max Depth Reached]";
}
static {
this.UNABLE_TO_SERIALIZE = "[Unable to serialize]";
}
static {
this.serializationCache = /* @__PURE__ */ new Map();
}
static {
this.MAX_CACHE_SIZE = 100;
}
static getCacheKey(e, t, n, r) {
if (!e.stack) return null;
let i = e.stack.split("\n")[0] || "";
return `${e.name}:${e.message}:${i}:${t}:${n}:${r}`;
}
static addToCache(e, t) {
if (this.serializationCache.size >= this.MAX_CACHE_SIZE) {
let e = this.serializationCache.keys().next().value;
e && this.serializationCache.delete(e);
}
this.serializationCache.set(e, t);
}
static serialize(t, n = {}) {
let { includeStack: r = !0, maxDepth: i = e.DEFAULT_MAX_DEPTH, includeNonEnumerable: a = !1 } = n;
if (t instanceof Error) {
let e = this.getCacheKey(t, r, i, a);
if (e) {
let t = this.serializationCache.get(e);
if (t) return t;
}
let n = this.serializeError(t, r, i, a, /* @__PURE__ */ new WeakSet());
return e && this.addToCache(e, n), n;
}
if (typeof t == "string") return t;
let o = this.safeStringify(t, i, /* @__PURE__ */ new WeakSet());
if (typeof o == "string") return o;
try {
return JSON.stringify(o, null, 2);
} catch {
return String(o);
}
}
static serializeError(e, t, n, r, i = /* @__PURE__ */ new WeakSet()) {
if (i.has(e)) return {
message: e.message,
name: e.name,
[Symbol.for("circular")]: this.CIRCULAR_REF_PLACEHOLDER
};
i.add(e);
let a = {
message: e.message,
name: e.name
};
return 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) => {
if (!(t in a)) try {
let r = e;
a[t] = this.safeStringify(r[t], n - 1, i);
} catch {
a[t] = this.UNABLE_TO_SERIALIZE;
}
}), r && Object.getOwnPropertyNames(e).forEach((t) => {
if (!(t in a) && t !== "stack" && t !== "message" && t !== "name") try {
let r = Object.getOwnPropertyDescriptor(e, t);
if (r && r.enumerable === !1) {
let r = e;
a[t] = this.safeStringify(r[t], n - 1, i);
}
} catch {
a[t] = this.UNABLE_TO_SERIALIZE;
}
}), a;
}
static safeStringify(e, t, n = /* @__PURE__ */ new WeakSet()) {
if (t <= 0) return this.MAX_DEPTH_PLACEHOLDER;
if (typeof e != "object" || !e) return e;
if (n.has(e)) return this.CIRCULAR_REF_PLACEHOLDER;
n.add(e);
try {
if (Array.isArray(e)) {
let r = e.map((e) => this.safeStringify(e, t - 1, n));
return n.delete(e), r;
}
let r = {};
for (let [i, a] of Object.entries(e)) try {
r[i] = this.safeStringify(a, t - 1, n);
} catch {
r[i] = this.UNABLE_TO_SERIALIZE;
}
return n.delete(e), r;
} catch {
return n.delete(e), this.UNABLE_TO_SERIALIZE;
}
}
}, v = {
highlight: {
color: m.LemonYellow,
bold: !0
},
accent: { color: m.SkyBlue },
attention: {
color: m.RoyalPurple,
bold: !0
},
success: { color: m.ForestGreen },
warning: { color: m.TangerineOrange },
error: { color: m.FireRed },
info: { color: m.OceanBlue },
debug: { color: m.SlateGray }
}, ee = {
success: "✅",
warning: "⚠️",
error: "❌",
info: "ℹ️",
debug: "🐞"
}, te = {
trace: m.SlateGray,
debug: m.Cyan,
info: m.ForestGreen,
warn: m.SunflowerYellow,
error: m.FireRed,
fatal: m.FireRed,
silent: m.Reset
}, y = class {
resolveStyle(e, t = "test", n) {
return this.applyStyle(e, t, n);
}
static {
this.INJECTABLE = !0;
}
constructor(e = {}) {
this.styleCache = /* @__PURE__ */ new Map();
let t = process.env.NODE_ENV === "test" || process.env.VITEST === "true";
this.useColors = e.useColors === void 0 ? !t : e.useColors, this.globalStyles = {
...v,
...e.styles
}, this.globalIcons = {
...ee,
...e.icons
};
}
setUseColors(e) {
this.useColors = e;
}
getUseColors() {
return this.useColors;
}
updateStyleConfig(e, t) {
this.globalStyles = {
...this.globalStyles,
...e
}, this.globalIcons = {
...this.globalIcons,
...t
};
}
formatMessage(e, t, n, r, i) {
let a = r ? `[${n}:${r}]` : `[${n}]`;
if (this.useColors) {
let n = this.getColorForLevel(e);
return i && (n = i), `${n}${a} ${t}${m.Reset}`;
} else return `${a} ${t}`;
}
formatMessageWithMetadata(e, t, n, r, i) {
let a = t, o = this.getColorForLevel(e);
if (r?.style) {
let e = this.applyStyle(r.style, n, i);
e && (o = e);
}
return r?.icon && (a = `${this.resolveIcon(r.icon, n, i)} ${t}`), this.formatMessage(e, a, n, i, o);
}
parseMetadataParameter(e, t = []) {
if (e && typeof e == "object" && !Array.isArray(e) && ("style" in e || "icon" in e)) return {
metadata: e,
restData: t
};
let n = e === void 0 ? t : [e, ...t];
if (n.length > 0) {
let e = n[n.length - 1];
if (e && typeof e == "object" && !Array.isArray(e) && ("style" in e || "icon" in e)) return {
metadata: e,
restData: n.slice(0, -1)
};
}
return {
metadata: void 0,
restData: n
};
}
getColorForLevel(e) {
let t = te[h[e]];
return e === h.fatal ? `${m.Bold}${t}` : t || m.Reset;
}
applyStyle(e, t, n) {
let r = this.getStyleCacheValue(e);
if (r !== void 0) return r;
if (typeof e == "string") {
let r = this.getSemanticStyleColor(e, t, n);
return this.setStyleCache(e, r), r;
}
if (typeof e == "object" && "color" in e) {
if (!this.isValidColor(e.color)) {
this.setStyleCache(e, void 0), this.logWarning("Invalid color provided. Only predefined ColorEnum values are allowed.", t, n);
return;
}
let r = this.constructStyleCode(e);
return this.setStyleCache(e, r), r;
}
this.setStyleCache(e, void 0), this.logWarning("Unknown style configuration provided. Only semantic style names or valid ColorEnum objects are allowed.", t, n);
}
isValidColor(e) {
return Object.values(m).includes(e);
}
isValidIcon(e) {
return this.isEmojiIcon(e);
}
getStyleCacheValue(e) {
return this.styleCache.has(e) ? this.styleCache.get(e) : void 0;
}
setStyleCache(e, t) {
this.styleCache.set(e, t);
}
logWarning(e, t, n) {
let r = n ? `${t}:${n}` : t;
console.warn(`[${r}] ${e}`);
}
constructStyleCode(e) {
let t = e.color.toString();
return e.bold && (t += m.Bold), e.underline && (t += m.Underline), t;
}
getSemanticStyleColor(e, t, n) {
if (this.styleCache.has(e)) return this.styleCache.get(e);
let r = this.globalStyles[e];
if (r) {
let t = r.color.toString();
return r.bold && (t += m.Bold), r.underline && (t += m.Underline), this.styleCache.set(e, t), t;
}
let i = n ? `${t}:${n}` : t;
console.warn(`[${i}] Unknown semantic style: ${e}. Falling back to default.`), this.styleCache.set(e, void 0);
}
getStyleCache() {
return this.styleCache;
}
resolveIcon(e, t, n) {
if (this.isValidIcon(e)) return e;
let r = [
"success",
"warning",
"error",
"info",
"debug"
], i = r.find((t) => t === e);
return 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);
}
isEmojiIcon(e) {
return (/* @__PURE__ */ "✅.⚠️.❌.ℹ️.🐞.⭐️.🚀.🔥.✔️.✖️.❓.🔒.🔓.⏳.🕒.⬆️.⬇️.➡️.⬅️.📁.📄.👤.👥.✏️.➕.➖.🔔.⚡️.🎁.🐛.🌟.❤️.👀.⚙️.🔧.🔨.🔑.🎉.📝.🚨.📅.💡.🔍.🔗.🔖.📌.📎.✉️.📞.🌍.☁️.🌈.🌙.☀️.❄️.✨.🎵.📷.🎥.🎤.🔊.🔋.🗑️.💰.💳.🎂.🏅.🏆.👑.🛸.🛡️.🛑.▶️.⏸️.⏺️.⏪.⏩.🔁.🔀.🎲.🎈.🍪.☕️.🍵.🍺.🍷.🍕.🍔.🍟.🍎.🍌.🍒.🍋.🥕.🌽.🥦.🥚.🧀.🍞.🍰.🍦.🍫.🍿.🥓.🍤.🐟.🦀.🐙.🐋.🐬.🐧.🐸.🐢.🐍.🐉.🦄.🐱.🐶.🐭.🐰.🐻.🐼.🐨.🐯.🦁.🐒.🐘.🐎.🐄.🐖.🐑.🐔.🦆.🦢.🦉.🦅.🦜.🦚.🦩.🦋.🐝.🐜.🐞.🕷️.🦂.🐌.🪱.🐛.🦗.🦟.🪰.🪳.🪲".split(".")).includes(e);
}
}, b = class extends Error {
constructor(e) {
super(e), this.name = "LoggerError";
}
}, ne = {
enabled: !1,
windowMs: 5e3,
flushOnCritical: !0
}, re = [h.error, h.fatal], ie = class {
constructor(e, t, n) {
this.config = e, this.formatter = t, this.loggerName = n, this.entries = /* @__PURE__ */ new Map();
}
addMessage(e, t, n = "") {
if (!this.config.enabled || this.config.flushOnCritical && re.includes(e)) return !0;
let r = this.generateFingerprint(t, e, n), i = this.entries.get(r);
return i ? i.count++ : this.entries.set(r, {
message: t,
level: e,
context: n,
firstSeen: Date.now(),
count: 1
}), this.scheduleFlush(), !1;
}
flush() {
if (this.entries.size !== 0) {
this.flushTimer &&= (clearTimeout(this.flushTimer), void 0);
for (let e of this.entries.values()) this.outputMessage(e);
this.entries.clear();
}
}
destroy() {
this.flushTimer &&= (clearTimeout(this.flushTimer), void 0), this.entries.clear();
}
generateFingerprint(e, t, n) {
return `${t}:${n}:${e}`;
}
scheduleFlush() {
this.flushTimer ||= setTimeout(() => {
this.flush();
}, this.config.windowMs);
}
outputMessage(e) {
let t = e.message;
e.count > 1 && (t = `${t} (×${e.count})`);
let n = this.formatter.format({
level: e.level,
message: t,
logger: this.loggerName,
timestamp: new Date(e.firstSeen),
context: e.context || void 0
});
switch (e.level) {
case h.trace:
console.trace(n);
break;
case h.debug:
console.debug(n);
break;
case h.info:
console.info(n);
break;
case h.warn:
console.warn(n);
break;
case h.error:
console.error(n);
break;
case h.fatal:
console.error(n);
break;
}
}
}, ae = class {
constructor(e) {
this.styleEngine = e;
}
format(e) {
return 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);
}
isSelfContained() {
return !1;
}
}, oe = class {
constructor(e) {
this.prettyPrint = e?.prettyPrint ?? !1;
}
format(e) {
try {
let t = {
timestamp: e.timestamp.toISOString(),
level: this.getLevelName(e.level),
logger: e.logger,
message: e.message
};
return 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 = _.serialize(e.error)), JSON.stringify(t, null, this.prettyPrint ? 2 : 0);
} catch (t) {
return console.error("JsonFormatter: Failed to serialize log entry to JSON.", {
error: t,
entry: e
}), `${e.level} [${e.logger}] ${e.message} (formatting error)`;
}
}
isSelfContained() {
return !0;
}
getLevelName(e) {
switch (e) {
case h.trace: return "trace";
case h.debug: return "debug";
case h.info: return "info";
case h.warn: return "warn";
case h.error: return "error";
case h.fatal: return "fatal";
default: return "info";
}
}
}, se = class {
constructor(e) {
this.formatterFn = e;
}
format(e) {
return this.formatterFn(e);
}
isSelfContained() {
return !0;
}
}, ce = class {
static createConsole(e) {
return new ae(new y({ useColors: e?.useColors }));
}
static createJson(e) {
return new oe(e);
}
static createCustom(e) {
return new se(e);
}
}, x = {
enabled: !0,
strategy: "mask",
maxDepth: 10
}, le = [
/password/i,
/token/i,
/secret/i,
/apikey|api_key|api-key/i,
/authorization/i,
/credential/i,
/private/i
], ue = [
{
pattern: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?!\w)/g,
replacement: "[TOKEN]"
},
{
pattern: /\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*(?!\w)/gi,
replacement: "Bearer [TOKEN]"
},
{
pattern: /\b(?:sk_live|sk_test|pk_live|pk_test|ghp|gho|github_pat|xox[baprs]|ya29)[_.-][A-Za-z0-9_.-]{10,}(?!\w)/g,
replacement: "[TOKEN]"
},
{
pattern: /(token|api_?key|secret|auth_?token)\s*[:=]\s*[A-Za-z0-9._~+/-]{10,}=*/gi,
replacement: "$1: [TOKEN]"
},
{
pattern: /\b(?!(.)\1{10})[A-Za-z0-9+/]{16,}={1,2}(?!\w)/g,
replacement: "[TOKEN]"
},
{
pattern: /(?<![A-Za-z0-9+/])(?!(.)\1{10})(?=[A-Za-z0-9+/]*[+/])(?=[A-Za-z0-9+/]*(?:\+|[0-9]))[A-Za-z0-9+/]{16,}(?!\w)/g,
replacement: "[TOKEN]"
},
{
pattern: /\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,
replacement: "[TOKEN]"
},
{
pattern: /\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g,
replacement: "[CARD]"
},
{
pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
replacement: "[EMAIL]"
},
{
pattern: /\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,
replacement: "[IP]"
},
{
pattern: /\b\d{3}-\d{2}-\d{4}\b/g,
replacement: "[SSN]"
}
];
function de(e) {
return e.replace(/\r\n|\r|\n/g, "\\n").replace(/\t/g, "\\t").replace(/[\x00-\x1f\x7f-\x9f]/g, "");
}
function fe(e, t) {
let n = 0;
for (let t = 0; t < e.length; t++) {
let r = e.charCodeAt(t);
n = (n << 5) - n + r, n &= n;
}
return Math.abs(n).toString(16).substring(0, t);
}
function pe(e, t) {
switch (t.strategy) {
case "mask": return e.replace(t.pattern, t.replacement);
case "remove": return e.replace(t.pattern, "");
case "hash": return e.replace(t.pattern, (e) => `[HASH:${fe(e, t.hashLength)}]`);
case "custom": return t.customHandler ? e.replace(t.pattern, t.customHandler) : e.replace(t.pattern, t.replacement);
default: return e.replace(t.pattern, t.replacement);
}
}
function me(e, t) {
let n = e;
for (let e of t) n = pe(n, e);
return n;
}
function he(e) {
return le.some((t) => t.test(e));
}
function S(e, t, n = 0, r = /* @__PURE__ */ new WeakSet()) {
if (!t.enabled || n > t.maxDepth || e == null) return e;
if (typeof e == "string") {
let n = me(e, t.rules);
return n = de(n), n;
}
if (Array.isArray(e)) return r.has(e) ? "[Circular Reference]" : (r.add(e), e.map((e) => S(e, t, n + 1, r)));
if (typeof e == "object") {
if (r.has(e)) return "[Circular Reference]";
r.add(e);
let i = {};
for (let [a, o] of Object.entries(e)) he(a) && typeof o == "string" ? i[a] = "[REDACTED]" : i[a] = S(o, t, n + 1, r);
return i;
}
return e;
}
function ge(e, t) {
return e.map((e) => ({
pattern: e.pattern,
strategy: e.strategy ?? t,
replacement: e.replacement ?? "[REDACTED]",
hashLength: e.hashLength ?? 8,
customHandler: e.customHandler
}));
}
function _e(e) {
let t = e?.enabled ?? x.enabled, n = e?.strategy ?? x.strategy, r = e?.maxDepth ?? x.maxDepth, i;
return i = e?.rules ? e.rules : [...ue, ...e?.customRules ?? []], {
enabled: t,
rules: ge(i, n),
maxDepth: r
};
}
function C(e, t) {
if (!t.enabled) return e;
let n = me(e, t.rules);
return n = de(n), n;
}
(class {
static {
this.contexts = /* @__PURE__ */ new Map();
}
static {
this.defaultScope = "default";
}
static getRegistry(e = this.defaultScope) {
this.contexts.has(e) || this.contexts.set(e, new Se());
let t = this.contexts.get(e);
if (!t) throw Error(`Failed to create registry for scope '${e}'`);
return t;
}
static createScope(e) {
if (this.contexts.has(e)) throw Error(`Scope '${e}' already exists`);
let t = new Se();
return this.contexts.set(e, t), t;
}
static destroyScope(e) {
let t = this.contexts.get(e);
t && (t.destroy(), this.contexts.delete(e));
}
static async destroyScopeAsync(e) {
let t = this.contexts.get(e);
t && (await t.destroyAsync(), this.contexts.delete(e));
}
static async clearAllAsync() {
let e = [], t = Array.from(this.contexts.entries());
for (let [n, r] of t) try {
await r.destroyAsync();
} catch (t) {
t instanceof T ? e.push(...t.failures) : t instanceof Error && e.push({
serviceName: `scope:${n}`,
error: t
});
}
if (this.contexts.clear(), e.length > 0) throw new T(e);
}
static setDefaultScope(e) {
this.defaultScope = e;
}
static getActiveScopes() {
return Array.from(this.contexts.keys());
}
static clearAll() {
let e = Array.from(this.contexts.values());
for (let t of e) t.destroy();
this.contexts.clear();
}
});
var ve = Symbol.for("@analog-tools/inject:SERVICE_TOKEN");
function ye(e) {
return Symbol(e || "ServiceToken");
}
var be = class {
static {
this.tokens = /* @__PURE__ */ new WeakMap();
}
static getToken(e) {
if (!this.tokens.has(e)) {
let t = ye(e.name);
this.tokens.set(e, t);
}
let t = this.tokens.get(e);
if (!t) throw Error(`Failed to get token for service ${e.name}`);
return t;
}
static setToken(e, t) {
this.tokens.set(e, t);
}
};
function xe(e) {
return (t) => {
let n = e || be.getToken(t);
return be.setToken(t, n), t.INJECTABLE = !0, t[ve] = n, t;
};
}
var Se = class {
constructor() {
this.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;
}
getServiceKey(e) {
let t = e[ve];
if (!t) throw new we(e.name);
return this.serviceNames.set(t, e.name), t;
}
getServiceName(e) {
return this.serviceNames.get(e) ?? "Unknown";
}
register(e, ...t) {
let n = this.getServiceKey(e);
if (this.initializingServices.has(n)) throw new Ce([e.name]);
if (!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) {
this.initializingServices.add(n);
try {
let r = t.length === 0 ? new e() : new e(...t);
this.serviceMap.set(n, r);
} finally {
this.initializingServices.delete(n);
}
}
}
registerAsUndefined(e) {
let t = this.getServiceKey(e);
this.serviceMap.set(t, void 0);
}
registerCustomServiceInstance(e, t) {
let n = this.getServiceKey(e);
this.serviceNames.set(n, e.name), this.serviceMap.set(n, t);
}
getService(e) {
let t = this.getServiceKey(e);
return this.serviceMap.has(t) || this.register(e), this.serviceMap.get(t);
}
hasService(e) {
let t = this.getServiceKey(e);
return this.serviceMap.has(t);
}
async ensureAsyncInitialized(e, t) {
if (this.initializedServices.has(t)) return;
if (this.initializationPromises.has(t)) {
let e = this.initializationPromises.get(t);
if (e) {
await e;
return;
}
}
let n = e;
if (typeof n.initializeAsync != "function") {
this.initializedServices.add(t);
let e = Promise.resolve();
return this.initializationPromises.set(t, e), e;
}
let r = n.initializeAsync().then(() => {
this.initializedServices.add(t);
}).catch((e) => {
throw this.initializationPromises.delete(t), e;
});
this.initializationPromises.set(t, r), await r;
}
async getServiceAsync(e) {
let t = this.getServiceKey(e);
this.serviceMap.has(t) || this.register(e);
let n = this.serviceMap.get(t);
return n !== void 0 && await this.ensureAsyncInitialized(n, t), n;
}
async registerAsync(e, ...t) {
let n = this.getServiceKey(e);
(!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) && this.register(e, ...t);
let r = this.serviceMap.get(n);
await this.ensureAsyncInitialized(r, n);
}
async destroyAsync() {
if (this.destroyed) return;
this.destroyed = !0;
let e = Array.from(this.initializationPromises.values());
e.length > 0 && await Promise.allSettled(e);
let t = [], n = Array.from(this.serviceMap.entries());
for (let [e, r] of n) {
if (!this.initializedServices.has(e) || r === void 0) continue;
let n = r;
if (typeof n.onDestroy == "function") try {
await n.onDestroy();
} catch (n) {
t.push({
serviceName: this.getServiceName(e),
error: n
});
}
}
if (this.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear(), t.length > 0) throw new T(t);
}
destroy() {
this.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear();
}
}, w = class extends Error {
constructor(e, t, n) {
super(e), this.token = t, this.name = "InjectionError", n && (this.cause = n);
}
}, Ce = class extends w {
constructor(e) {
super(`Circular dependency detected: ${e.join(" -> ")}`), this.name = "CircularDependencyError";
}
}, we = class extends w {
constructor(e) {
super(`Service '${e}' is missing SERVICE_TOKEN. Add @Injectable() decorator to the class. See: packages/inject/docs/migrations/symbol-tokens.md`, e), this.name = "MissingServiceTokenError";
}
}, T = class extends w {
constructor(e) {
let t = e.map((e) => `${e.serviceName}: ${e.error.message}`).join("; ");
super(`Failed to destroy ${e.length} service(s): ${t}`), this.failures = e, this.name = "AggregateDestructionError";
}
getErrors() {
return this.failures.map((e) => e.error);
}
hasFailure(e) {
return this.failures.some((t) => t.serviceName === e);
}
};
function Te(e, t) {
if (typeof Reflect == "object" && typeof Reflect.metadata == "function") return Reflect.metadata(e, t);
}
function Ee(e, t, n, r) {
var i = arguments.length, a = i < 3 ? t : r === null ? r = Object.getOwnPropertyDescriptor(t, n) : r, o;
if (typeof Reflect == "object" && typeof Reflect.decorate == "function") a = Reflect.decorate(e, t, n, r);
else 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);
return i > 3 && a && Object.defineProperty(t, n, a), a;
}
var E, D = E = class {
constructor(e = {}, t, n, r) {
if (this.config = e, this.childLoggers = {}, this.disabledContexts = [], this.activeGroups = [], r) this.parentLogger = r, this.name = r.name, this.context = n, this.logLevel = r.getLogLevel(), this.styleEngine = r.styleEngine, this.formatter = r.formatter, this.correlationId = r.correlationId, this.sanitizer = r.sanitizer;
else {
if (typeof e.level == "string" && !Object.keys(h).includes(e.level)) throw new b(`Invalid log level: ${e.level}`);
if (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 y({
useColors: e.useColors,
styles: {
...v,
...e.styles
},
icons: {
...ee,
...e.icons
}
}), this.formatter = e.formatter || ce.createConsole({ useColors: this.styleEngine.getUseColors() }), e.deduplication?.enabled) {
let t = {
enabled: !0,
windowMs: e.deduplication.windowMs ?? ne.windowMs,
flushOnCritical: e.deduplication.flushOnCritical ?? ne.flushOnCritical
};
this.deduplicator = new ie(t, this.formatter, this.name);
}
this.sanitizer = _e(e.sanitization);
}
}
resolveMessage(e) {
if (typeof e == "function") try {
return e();
} catch (e) {
return console.error("Logger: Message evaluation failed:", e), `[Message evaluation failed: ${e}]`;
}
return e;
}
isContextEnabled() {
return !this.context || !(this.parentLogger || this).disabledContexts.includes(this.context);
}
setDisabledContexts(e) {
this.disabledContexts = e;
}
getLogLevel() {
return this.logLevel;
}
getDisabledContexts() {
return (this.parentLogger || this).disabledContexts || [];
}
setUseColors(e) {
(this.parentLogger || this).styleEngine.setUseColors(e);
}
getUseColors() {
return (this.parentLogger || this).styleEngine.getUseColors();
}
setCorrelationId(e) {
this.correlationId = e;
}
getCorrelationId() {
return this.correlationId;
}
clearCorrelationId() {
this.correlationId = void 0;
}
forContext(e) {
return this.childLoggers[e] || (this.childLoggers[e] = new E({}, void 0, e, this)), this.childLoggers[e];
}
group(e) {
if (!this.isContextEnabled()) return;
(this.parentLogger?.activeGroups || this.activeGroups).push(e);
let t = this.formatter.format({
level: h.info,
message: `Group: ${e}`,
logger: this.name,
context: this.context,
timestamp: /* @__PURE__ */ new Date(),
correlationId: this.getCorrelationId()
});
console.group(`${t} ▼`);
}
groupEnd(e) {
if (!this.isContextEnabled()) return;
let t = this.parentLogger?.activeGroups || this.activeGroups;
if (e) {
let n = t.lastIndexOf(e);
if (n !== -1) {
let e = t.splice(n);
for (let t = 0; t < e.length; t++) console.groupEnd(), console.log("");
}
} else t.length > 0 && (t.pop(), console.groupEnd(), console.log(""));
}
trace(e, t, ...n) {
this.doLog(h.trace, e, t, ...n);
}
debug(e, t, ...n) {
this.doLog(h.debug, e, t, ...n);
}
info(e, t, ...n) {
this.doLog(h.info, e, t, ...n);
}
warn(e, t, ...n) {
this.doLog(h.warn, e, t, ...n);
}
error(e, t, n, ...r) {
if (!this.isContextEnabled() || this.logLevel > h.error) return;
let { message: i, serializedError: a, rawError: o, context: s, data: c } = this.parseErrorParameters(e, t, n, r), l = C(i, this.sanitizer), u = s ? S(s, this.sanitizer) : void 0, d = c || [], f, p = d;
if (d.length > 0) {
let e = d[d.length - 1];
e && typeof e == "object" && !Array.isArray(e) && ("style" in e || "icon" in e) && (f = e, p = d.slice(0, -1));
}
let m = {
level: h.error,
message: l,
logger: this.name,
context: this.context,
timestamp: /* @__PURE__ */ new Date(),
metadata: u,
error: o,
styling: f,
correlationId: this.getCorrelationId()
}, g = this.formatter.format(m);
if (this.formatter.isSelfContained()) console.error(g);
else {
let e = [g];
a && e.push(a), u && e.push(u), console.error(...e, ...p);
}
}
fatal(e, t, n, ...r) {
if (!this.isContextEnabled() || this.logLevel > h.fatal) return;
if (typeof e == "string" && t && typeof t == "object" && !Array.isArray(t) && ("style" in t || "icon" in t)) {
let n = t, r = C(`FATAL: ${e}`, this.sanitizer), i = this.styleEngine.formatMessageWithMetadata(h.fatal, r, this.name, n, this.context);
console.error(i);
return;
}
let { message: i, serializedError: a, rawError: o, context: s, data: c } = this.parseErrorParameters(e, t, n, r), l = C(i, this.sanitizer), u = s ? S(s, this.sanitizer) : void 0, d = c || [], f, p = d;
if (d.length > 0) {
let e = d[d.length - 1];
e && typeof e == "object" && !Array.isArray(e) && ("style" in e || "icon" in e) && (f = e, p = d.slice(0, -1));
}
let m = {
level: h.fatal,
message: `FATAL: ${l}`,
logger: this.name,
context: this.context,
timestamp: /* @__PURE__ */ new Date(),
metadata: u,
error: o,
styling: f,
correlationId: this.getCorrelationId()
}, g = this.formatter.format(m);
if (this.formatter.isSelfContained()) console.error(g);
else {
let e = [g];
a && e.push(a), u && e.push(u), console.error(...e, ...p);
}
}
parseErrorParameters(e, t, n, r = []) {
if (e instanceof Error && t === void 0) return {
message: e.message,
serializedError: _.serialize(e),
rawError: e,
data: []
};
if (typeof e == "string" && t === void 0) return {
message: e,
data: []
};
if (typeof e == "string" && t instanceof Error && n === void 0) return {
message: e,
serializedError: _.serialize(t),
rawError: t,
data: []
};
if (typeof e == "string" && this.isLogContext(t) && n === void 0) return {
message: e,
context: t,
data: []
};
if (typeof e == "string" && t instanceof Error && this.isLogContext(n)) return {
message: e,
serializedError: _.serialize(t),
rawError: t,
context: n,
data: r
};
let i = typeof e == "string" ? e : "Unknown error", a = t instanceof Error ? t : void 0;
return {
message: i,
serializedError: t ? _.serialize(t) : void 0,
rawError: a,
data: n === void 0 ? r : [n, ...r]
};
}
isLogContext(e) {
return typeof e == "object" && !!e && !Array.isArray(e) && !(e instanceof Error) && !(e instanceof Date) && !(e instanceof RegExp) && typeof e != "function";
}
doLog(e, t, n, ...r) {
if (!this.isContextEnabled() || this.logLevel > e) return;
let { metadata: i, restData: a } = this.styleEngine.parseMetadataParameter(n, r), o = this.resolveMessage(t);
if (o = C(o, this.sanitizer), !this.handleDeduplication(e, o, i, a)) return;
let s = a?.map((e) => S(e, this.sanitizer)), c, l = {};
s && s.length > 0 && s.forEach((e, t) => {
e instanceof Error && !c ? c = e : typeof e == "object" && e ? Object.assign(l, e) : l[`arg${t}`] = e;
});
let u = {
level: e,
message: o,
logger: this.name,
context: this.context,
timestamp: /* @__PURE__ */ new Date(),
metadata: Object.keys(l).length > 0 ? l : void 0,
error: c,
styling: i,
correlationId: this.getCorrelationId()
}, d = this.formatter.format(u), f = this.formatter.isSelfContained();
switch (e) {
case h.trace:
f ? console.trace(d) : console.trace(d, ...s || []);
break;
case h.debug:
f ? console.debug(d) : console.debug(d, ...s || []);
break;
case h.info:
f ? console.info(d) : console.info(d, ...s || []);
break;
case h.warn:
f ? console.warn(d) : console.warn(d, ...s || []);
break;
case h.error:
case h.fatal:
f ? console.error(d) : console.error(d, ...s || []);
break;
}
}
castLoglevel(e) {
if (g(e)) switch (e) {
case "trace": return h.trace;
case "debug": return h.debug;
case "info": return h.info;
case "warn": return h.warn;
case "error": return h.error;
case "fatal": return h.fatal;
case "silent": return h.silent;
}
throw g(e.toLowerCase()) ? new b(`Invalid log level: ${e}. Log levels are case-sensitive. Valid levels: trace, debug, info, warn, error, fatal, silent.`) : new b(`Invalid log level: ${e}. Valid levels: trace, debug, info, warn, error, fatal, silent.`);
}
shouldLogImmediately(e, t) {
let n = (this.parentLogger || this).deduplicator;
if (!n) return !0;
try {
return n.addMessage(e, t, this.context);
} catch (e) {
return console.error("Logger deduplication error:", e), !0;
}
}
handleDeduplication(e, t, n, r) {
return !n && r.length === 0 ? this.shouldLogImmediately(e, t) : !0;
}
};
D = E = Ee([xe(), Te("design:paramtypes", [
Object,
y === void 0 ? Object : y,
String,
D === void 0 ? Object : D
])], D);
//#endregion
//#region ../../node_modules/@analog-tools/inject/index.js
var De = class {
static {
this.contexts = /* @__PURE__ */ new Map();
}
static {
this.defaultScope = "default";
}
static getRegistry(e = this.defaultScope) {
this.contexts.has(e) || this.contexts.set(e, new Ne());
let t = this.contexts.get(e);
if (!t) throw Error(`Failed to create registry for scope '${e}'`);
return t;
}
static createScope(e) {
if (this.contexts.has(e)) throw Error(`Scope '${e}' already exists`);
let t = new Ne();
return this.contexts.set(e, t), t;
}
static destroyScope(e) {
let t = this.contexts.get(e);
t && (t.destroy(), this.contexts.delete(e));
}
static async destroyScopeAsync(e) {
let t = this.contexts.get(e);
t && (await t.destroyAsync(), this.contexts.delete(e));
}
static async clearAllAsync() {
let e = [], t = Array.from(this.contexts.entries());
for (let [n, r] of t) try {
await r.destroyAsync();
} catch (t) {
t instanceof k ? e.push(...t.failures) : t instanceof Error && e.push({
serviceName: `scope:${n}`,
error: t
});
}
if (this.contexts.clear(), e.length > 0) throw new k(e);
}
static setDefaultScope(e) {
this.defaultScope = e;
}
static getActiveScopes() {
return Array.from(this.contexts.keys());
}
static clearAll() {
let e = Array.from(this.contexts.values());
for (let t of e) t.destroy();
this.contexts.clear();
}
}, Oe = Symbol.for("@analog-tools/inject:SERVICE_TOKEN");
function ke(e) {
return Symbol(e || "ServiceToken");
}
var Ae = class {
static {
this.tokens = /* @__PURE__ */ new WeakMap();
}
static getToken(e) {
if (!this.tokens.has(e)) {
let t = ke(e.name);
this.tokens.set(e, t);
}
let t = this.tokens.get(e);
if (!t) throw Error(`Failed to get token for service ${e.name}`);
return t;
}
static setToken(e, t) {
this.tokens.set(e, t);
}
};
function je(e) {
return (t) => {
let n = e || Ae.getToken(t);
return Ae.setToken(t, n), t.INJECTABLE = !0, t[Oe] = n, t;
};
}
function Me() {
return De.getRegistry();
}
var Ne = class {
constructor() {
this.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;
}
getServiceKey(e) {
let t = e[Oe];
if (!t) throw new Fe(e.name);
return this.serviceNames.set(t, e.name), t;
}
getServiceName(e) {
return this.serviceNames.get(e) ?? "Unknown";
}
register(e, ...t) {
let n = this.getServiceKey(e);
if (this.initializingServices.has(n)) throw new Pe([e.name]);
if (!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) {
this.initializingServices.add(n);
try {
let r = t.length === 0 ? new e() : new e(...t);
this.serviceMap.set(n, r);
} finally {
this.initializingServices.delete(n);
}
}
}
registerAsUndefined(e) {
let t = this.getServiceKey(e);
this.serviceMap.set(t, void 0);
}
registerCustomServiceInstance(e, t) {
let n = this.getServiceKey(e);
this.serviceNames.set(n, e.name), this.serviceMap.set(n, t);
}
getService(e) {
let t = this.getServiceKey(e);
return this.serviceMap.has(t) || this.register(e), this.serviceMap.get(t);
}
hasService(e) {
let t = this.getServiceKey(e);
return this.serviceMap.has(t);
}
async ensureAsyncInitialized(e, t) {
if (this.initializedServices.has(t)) return;
if (this.initializationPromises.has(t)) {
let e = this.initializationPromises.get(t);
if (e) {
await e;
return;
}
}
let n = e;
if (typeof n.initializeAsync != "function") {
this.initializedServices.add(t);
let e = Promise.resolve();
return this.initializationPromises.set(t, e), e;
}
let r = n.initializeAsync().then(() => {
this.initializedServices.add(t);
}).catch((e) => {
throw this.initializationPromises.delete(t), e;
});
this.initializationPromises.set(t, r), await r;
}
async getServiceAsync(e) {
let t = this.getServiceKey(e);
this.serviceMap.has(t) || this.register(e);
let n = this.serviceMap.get(t);
return n !== void 0 && await this.ensureAsyncInitialized(n, t), n;
}
async registerAsync(e, ...t) {
let n = this.getServiceKey(e);
(!this.serviceMap.has(n) || this.serviceMap.get(n) === void 0) && this.register(e, ...t);
let r = this.serviceMap.get(n);
await this.ensureAsyncInitialized(r, n);
}
async destroyAsync() {
if (this.destroyed) return;
this.destroyed = !0;
let e = Array.from(this.initializationPromises.values());
e.length > 0 && await Promise.allSettled(e);
let t = [], n = Array.from(this.serviceMap.entries());
for (let [e, r] of n) {
if (!this.initializedServices.has(e) || r === void 0) continue;
let n = r;
if (typeof n.onDestroy == "function") try {
await n.onDestroy();
} catch (n) {
t.push({
serviceName: this.getServiceName(e),
error: n
});
}
}
if (this.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear(), t.length > 0) throw new k(t);
}
destroy() {
this.serviceMap.clear(), this.initializingServices.clear(), this.initializationPromises.clear(), this.initializedServices.clear(), this.serviceNames.clear();
}
}, O = class extends Error {
constructor(e, t, n) {
super(e), this.token = t, this.name = "InjectionError", n && (this.cause = n);
}
}, Pe = class extends O {
constructor(e) {
super(`Circular dependency detected: ${e.join(" -> ")}`), this.name = "CircularDependencyError";
}
}, Fe = class extends O {
constructor(e) {
super(`Service '${e}' is missing SERVICE_TOKEN. Add @Injectable() decorator to the class. See: packages/inject/docs/migrations/symbol-tokens.md`, e), this.name = "MissingServiceTokenError";
}
}, k = class extends O {
constructor(e) {
let t = e.map((e) => `${e.serviceName}: ${e.error.message}`).join("; ");
super(`Failed to destroy ${e.length} service(s): ${t}`), this.failures = e, this.name = "AggregateDestructionError";
}
getErrors() {
return this.failures.map((e) => e.error);
}
hasFailure(e) {
return this.failures.some((t) => t.serviceName === e);
}
};
function A(e, t = {}) {
let { required: n = !0 } = t;
try {
let t = Me().getService(e);
if (t == null) {
if (n) throw new O(`Service '${e.name}' not found in registry and is required`, e.name);
return;
}
return t;
} catch (t) {
throw t instanceof O ? t : new O(`Failed to inject service '${e.name}'`, e.name, t);
}
}
function Ie(e, ...t) {
try {
Me().register(e, ...t);
} catch (t) {
throw new O(`Failed to register service '${e.name}'`, e.name, t);
}
}
//#endregion
//#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorateMetadata.js
function Le(e, t) {
if (typeof Reflect == "object" && typeof Reflect.metadata == "function") return Reflect.metadata(e, t);
}
//#endregion
//#region \0@oxc-project+runtime@0.139.0/helpers/esm/decorate.js
function Re(e, t, n, r) {
var i = arguments.length, a = i < 3 ? t : r === null ? r = Object.getOwnPropertyDescriptor(t, n) : r, o;
if (typeof Reflect == "object" && typeof Reflect.decorate == "function") a = Reflect.decorate(e, t, n, r);
else 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);
return i > 3 && a && Object.defineProperty(t, n, a), a;
}
//#endregion
//#region src/server/services/session.service.ts
var j = class {
constructor(e) {
this.storageConfig = e, this.logger = A(D).forContext("SessionService"), this.sessionSecret = this.resolveSessionSecret();
}
resolveSessionSecret() {
let e = this.storageConfig.sessionSecret, t = Array.isArray(e) ? e : [e];
if (!(t.length > 0 && t.every((e) => typeof e == "string" && e.trim().length > 0))) throw Error("sessionStorage.sessionSecret is required. Provide a strong, unique value or a non-empty array of values (e.g. from a SESSION_SECRET environment variable) — the library no longer falls back to a shared default secret.");
return t.some((e) => e.length < 32) && this.logger.warn("sessionStorage.sessionSecret is shorter than 32 characters; use a longer, high-entropy value for HMAC-SHA256 cookie signing."), e;
}
async initSession(e) {
c(e) ? this.logger.debug("Session already exists, skipping initialization") : (this.logger.debug("Initializing request session context"), this.store ||= await o(this.storageConfig.driver), await f(e, {
store: this.store,
secret: this.sessionSecret,
name: this.storageConfig.cookieName || "auth.session",
maxAge: 3600 * 24,
cookie: {
httpOnly: !0,
secure: process.env.NODE_ENV === "production",
sameSite: "lax"
},
generate: () => ({ auth: { isAuthenticated: !1 } })
}));
}
async getSession(e) {
try {
let t = await this.store.getItem(e);
return t ? {
id: e,
data: t,
save: async () => {
await this.store.setItem(e, t);
}
} : null;
} catch (t) {
return this.logger.error("Error retrieving session", t, { sessionId: e }), null;
}
}
async getActiveSessions() {
try {
let e = await this.store.getKeys();
return (await Promise.all(e.map(async (e) => {
let t = await this.store.getItem(e);
return t ? {
id: this.storageConfig.prefix && e.startsWith(`${this.storageConfig.prefix}:`) ? e.substring(`${this.storageConfig.prefix}:`.length) : e,
data: t,
update: (e) => {
let n = e(t);
Object.assign(t, n);
},
save: async () => {
await this.store.setItem(e, t);
},
refetch: async () => await this.store.getItem(e)
} : null;
}))).filter((e) => e !== null);
} catch (e) {
return this.logger.error("Error retrieving active sessions", e), [];
}
}
async destroyAuthSession(t) {
try {
await this.initSession(t), c(t)?.auth && await d(t, (e) => {
let t = { ...e };
return delete t.auth, t;
}), await s(t);
} catch (t) {
throw this.logger.error("Session destruction failed", t), e({
statusCode: 500,
message: "Session handling failed"
});
}
}
async getSessionData(e, t) {
await this.initSession(e);
let n = c(e);
return this.logger.debug("Retrieved session data", n), n?.[t] || null;
}
async setSessionData(e, t, n) {
await this.initSession(e), await d(e, (e) => ({
...e,
[t]: n
}));
}
async isValidSession(e) {
return await this.initSession(e), !!c(e);
}
};
j = Re([je(), Le("design:paramtypes", [Object])], j);
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/buffer_utils.js
var ze = new TextEncoder(), M = new TextDecoder();
function Be(...e) {
let t = e.reduce((e, { length: t }) => e + t, 0), n = new Uint8Array(t), r = 0;
for (let t of e) n.set(t, r), r += t.length;
return n;
}
function N(e) {
let t = new Uint8Array(e.length);
for (let n = 0; n < e.length; n++) {
let r = e.charCodeAt(n);
if (r > 127) throw TypeError("non-ASCII string encountered in encode()");
t[n] = r;
}
return t;
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/base64.js
function Ve(e) {
if (Uint8Array.fromBase64) return Uint8Array.fromBase64(e);
let t = atob(e), n = new Uint8Array(t.length);
for (let e = 0; e < t.length; e++) n[e] = t.charCodeAt(e);
return n;
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/util/base64url.js
function P(e) {
if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof e == "string" ? e : M.decode(e), { alphabet: "base64url" });
let t = e;
t instanceof Uint8Array && (t = M.decode(t)), t = t.replace(/-/g, "+").replace(/_/g, "/");
try {
return Ve(t);
} catch {
throw TypeError("The input to be decoded is not correctly encoded.");
}
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/crypto_key.js
var F = (e, t = "algorithm.name") => /* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`), I = (e, t) => e.name === t;
function He(e) {
return parseInt(e.name.slice(4), 10);
}
function L(e, t) {
if (He(e.hash) !== t) throw F(`SHA-${t}`, "algorithm.hash");
}
function Ue(e) {
switch (e) {
case "ES256": return "P-256";
case "ES384": return "P-384";
case "ES512": return "P-521";
default: throw Error("unreachable");
}
}
function We(e, t) {
if (t && !e.usages.includes(t)) throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`);
}
function Ge(e, t, n) {
switch (t) {
case "HS256":
case "HS384":
case "HS512":
if (!I(e.algorithm, "HMAC")) throw F("HMAC");
L(e.algorithm, parseInt(t.slice(2), 10));
break;
case "RS256":
case "RS384":
case "RS512":
if (!I(e.algorithm, "RSASSA-PKCS1-v1_5")) throw F("RSASSA-PKCS1-v1_5");
L(e.algorithm, parseInt(t.slice(2), 10));
break;
case "PS256":
case "PS384":
case "PS512":
if (!I(e.algorithm, "RSA-PSS")) throw F("RSA-PSS");
L(e.algorithm, parseInt(t.slice(2), 10));
break;
case "Ed25519":
case "EdDSA":
if (!I(e.algorithm, "Ed25519")) throw F("Ed25519");
break;
case "ML-DSA-44":
case "ML-DSA-65":
case "ML-DSA-87":
if (!I(e.algorithm, t)) throw F(t);
break;
case "ES256":
case "ES384":
case "ES512": {
if (!I(e.algorithm, "ECDSA")) throw F("ECDSA");
let n = Ue(t);
if (e.algorithm.namedCurve !== n) throw F(n, "algorithm.namedCurve");
break;
}
default: throw TypeError("CryptoKey does not support this operation");
}
We(e, n);
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/invalid_key_input.js
function Ke(e, t, ...n) {
if (n = n.filter(Boolean), n.length > 2) {
let t = n.pop();
e += `one of type ${n.join(", ")}, or ${t}.`;
} else n.length === 2 ? e += `one of type ${n[0]} or ${n[1]}.` : e += `of type ${n[0]}.`;
return t == null ? e += ` Received ${t}` : typeof t == "function" && t.name ? e += ` Received function ${t.name}` : typeof t == "object" && t && t.constructor?.name && (e += ` Received an instance of ${t.constructor.name}`), e;
}
var qe = (e, ...t) => Ke("Key must be ", e, ...t), Je = (e, t, ...n) => Ke(`Key for the ${e} algorithm must be `, t, ...n), R = class extends Error {
static code = "ERR_JOSE_GENERIC";
code = "ERR_JOSE_GENERIC";
constructor(e, t) {
super(e, t), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
}
}, z = class extends R {
static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
claim;
reason;
payload;
constructor(e, t, n = "unspecified", r = "unspecified") {
super(e, { cause: {
claim: n,
reason: r,
payload: t
} }), this.claim = n, this.reason = r, this.payload = t;
}
}, Ye = class extends R {
static code = "ERR_JWT_EXPIRED";
code = "ERR_JWT_EXPIRED";
claim;
reason;
payload;
constructor(e, t, n = "unspecified", r = "unspecified") {
super(e, { cause: {
claim: n,
reason: r,
payload: t
} }), this.claim = n, this.reason = r, this.payload = t;
}
}, Xe = class extends R {
static code = "ERR_JOSE_ALG_NOT_ALLOWED";
code = "ERR_JOSE_ALG_NOT_ALLOWED";
}, B = class extends R {
static code = "ERR_JOSE_NOT_SUPPORTED";
code = "ERR_JOSE_NOT_SUPPORTED";
}, V = class extends R {
static code = "ERR_JWS_INVALID";
code = "ERR_JWS_INVALID";
}, Ze = class extends R {
static code = "ERR_JWT_INVALID";
code = "ERR_JWT_INVALID";
}, Qe = class extends R {
static code = "ERR_JWKS_INVALID";
code = "ERR_JWKS_INVALID";
}, $e = class extends R {
static code = "ERR_JWKS_NO_MATCHING_KEY";
code = "ERR_JWKS_NO_MATCHING_KEY";
constructor(e = "no applicable key found in the JSON Web Key Set", t) {
super(e, t);
}
}, et = class extends R {
[Symbol.asyncIterator];
static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
constructor(e = "multiple matching keys found in the JSON Web Key Set", t) {
super(e, t);
}
}, tt = class extends R {
static code = "ERR_JWKS_TIMEOUT";
code = "ERR_JWKS_TIMEOUT";
constructor(e = "request timed out", t) {
super(e, t);
}
}, nt = class extends R {
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
constructor(e = "signature verification failed", t) {
super(e, t);
}
}, rt = (e) => {
if (e?.[Symbol.toStringTag] === "CryptoKey") return !0;
try {
return e instanceof CryptoKey;
} catch {
return !1;
}
}, it = (e) => e?.[Symbol.toStringTag] === "KeyObject", at = (e) => rt(e) || it(e);
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/helpers.js
function ot(e, t, n) {
try {
return P(e);
} catch {
throw new n(`Failed to base64url decode the ${t}`);
}
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/type_checks.js
var st = (e) => typeof e == "object" && !!e;
function H(e) {
if (!st(e) || Object.prototype.toString.call(e) !== "[object Object]") return !1;
if (Object.getPrototypeOf(e) === null) return !0;
let t = e;
for (; Object.getPrototypeOf(t) !== null;) t = Object.getPrototypeOf(t);
return Object.getPrototypeOf(e) === t;
}
function ct(...e) {
let t = e.filter(Boolean);
if (t.length === 0 || t.length === 1) return !0;
let n;
for (let e of t) {
let t = Object.keys(e);
if (!n || n.size === 0) {
n = new Set(t);
continue;
}
for (let e of t) {
if (n.has(e)) return !1;
n.add(e);
}
}
return !0;
}
var U = (e) => H(e) && typeof e.kty == "string", lt = (e) => e.kty !== "oct" && (e.kty === "AKP" && typeof e.priv == "string" || typeof e.d == "string"), ut = (e) => e.kty !== "oct" && e.d === void 0 && e.priv === void 0, dt = (e) => e.kty === "oct" && typeof e.k == "string";
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/signing.js
function ft(e, t) {
if (e.startsWith("RS") || e.startsWith("PS")) {
let { modulusLength: n } = t.algorithm;
if (typeof n != "number" || n < 2048) throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`);
}
}
function pt(e, t) {
let n = `SHA-${e.slice(-3)}`;
switch (e) {
case "HS256":
case "HS384":
case "HS512": return {
hash: n,
name: "HMAC"
};
case "PS256":
case "PS384":
case "PS512": return {
hash: n,
name: "RSA-PSS",
saltLength: parseInt(e.slice(-3), 10) >> 3
};
case "RS256":
case "RS384":
case "RS512": return {
hash: n,
name: "RSASSA-PKCS1-v1_5"
};
case "ES256":
case "ES384":
case "ES512": return {
hash: n,
name: "ECDSA",
namedCurve: t.namedCurve
};
case "Ed25519":
case "EdDSA": return { name: "Ed25519" };
case "ML-DSA-44":
case "ML-DSA-65":
case "ML-DSA-87": return { name: e };
default: throw new B(`alg ${e} is not supported either by JOSE or your javascript runtime`);
}
}
async function mt(e, t, n) {
if (t instanceof Uint8Array) {
if (!e.startsWith("HS")) throw TypeError(qe(t, "CryptoKey", "KeyObject", "JSON Web Key"));
return crypto.subtle.importKey("raw", t, {
hash: `SHA-${e.slice(-3)}`,
name: "HMAC"
}, !1, [n]);
}
return Ge(t, e, n), t;
}
async function ht(e, t, n, r) {
let i = await mt(e, t, "verify");
ft(e, i);
let a = pt(e, i.algorithm);
try {
return await crypto.subtle.verify(a, i, n, r);
} catch {
return !1;
}
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/jwk_to_key.js
var W = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value";
function gt(e) {
let t, n;
switch (e.kty) {
case "AKP":
switch (e.alg) {
case "ML-DSA-44":
case "ML-DSA-65":
case "ML-DSA-87":
t = { name: e.alg }, n = e.priv ? ["sign"] : ["verify"];
break;
default: throw new B(W);
}
break;
case "RSA":
switch (e.alg) {
case "PS256":
case "PS384":
case "PS512":
t = {
name: "RSA-PSS",
hash: `SHA-${e.alg.slice(-3)}`
}, n = e.d ? ["sign"] : ["verify"];
break;
case "RS256":
case "RS384":
case "RS512":
t = {
name: "RSASSA-PKCS1-v1_5",
hash: `SHA-${e.alg.slice(-3)}`
}, n = e.d ? ["sign"] : ["verify"];
break;
case "RSA-OAEP":
case "RSA-OAEP-256":
case "RSA-OAEP-384":
case "RSA-OAEP-512":
t = {
name: "RSA-OAEP",
hash: `SHA-${parseInt(e.alg.slice(-3), 10) || 1}`
}, n = e.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
break;
default: throw new B(W);
}
break;
case "EC":
switch (e.alg) {
case "ES256":
case "ES384":
case "ES512":
t = {
name: "ECDSA",
namedCurve: {
ES256: "P-256",
ES384: "P-384",
ES512: "P-521"
}[e.alg]
}, n = e.d ? ["sign"] : ["verify"];
break;
case "ECDH-ES":
case "ECDH-ES+A128KW":
case "ECDH-ES+A192KW":
case "ECDH-ES+A256KW":
t = {
name: "ECDH",
namedCurve: e.crv
}, n = e.d ? ["deriveBits"] : [];
break;
default: throw new B(W);
}
break;
case "OKP":
switch (e.alg) {
case "Ed25519":
case "EdDSA":
t = { name: "Ed25519" }, n = e.d ? ["sign"] : ["verify"];
break;
case "ECDH-ES":
case "ECDH-ES+A128KW":
case "ECDH-ES+A192KW":
case "ECDH-ES+A256KW":
t = { name: e.crv }, n = e.d ? ["deriveBits"] : [];
break;
default: throw new B(W);
}
break;
default: throw new B("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
}
return {
algorithm: t,
keyUsages: n
};
}
async function G(e) {
if (!e.alg) throw TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
let { algorithm: t, keyUsages: n } = gt(e), r = { ...e };
return r.kty !== "AKP" && delete r.alg, delete r.use, crypto.subtle.importKey("jwk", r, t, e.ext ?? !(e.d || e.priv), e.key_ops ?? n);
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/normalize_key.js
var K = "given KeyObject instance cannot be used for this algorithm", q, _t = async (e, t, n, r = !1) => {
q ||= /* @__PURE__ */ new WeakMap();
let i = q.get(e);
if (i?.[n]) return i[n];
let a = await G({
...t,
alg: n
});
return r && Object.freeze(e), i ? i[n] = a : q.set(e, { [n]: a }), a;
}, vt = (e, t) => {
q ||= /* @__PURE__ */ new WeakMap();
let n = q.get(e);
if (n?.[t]) return n[t];
let r = e.type === "public", i = !!r, a;
if (e.asymmetricKeyType === "x25519") {
switch (t) {
case "ECDH-ES":
case "ECDH-ES+A128KW":
case "ECDH-ES+A192KW":
case "ECDH-ES+A256KW": break;
default: throw TypeError(K);
}
a = e.toCryptoKey(e.asymmetricKeyType, i, r ? [] : ["deriveBits"]);
}
if (e.asymmetricKeyType === "ed25519") {
if (t !== "EdDSA" && t !== "Ed25519") throw TypeError(K);
a = e.toCryptoKey(e.asymmetricKeyType, i, [r ? "verify" : "sign"]);
}
switch (e.asymmetricKeyType) {
case "ml-dsa-44":
case "ml-dsa-65":
case "ml-dsa-87":
if (t !== e.asymmetricKeyType.toUpperCase()) throw TypeError(K);
a = e.toCryptoKey(e.asymmetricKeyType, i, [r ? "verify" : "sign"]);
}
if (e.asymmetricKeyType === "rsa") {
let n;
switch (t) {
case "RSA-OAEP":
n = "SHA-1";
break;
case "RS256":
case "PS256":
case "RSA-OAEP-256":
n = "SHA-256";
break;
case "RS384":
case "PS384":
case "RSA-OAEP-384":
n = "SHA-384";
break;
case "RS512":
case "PS512":
case "RSA-OAEP-512":
n = "SHA-512";
break;
default: throw TypeError(K);
}
if (t.startsWith("RSA-OAEP")) return e.toCryptoKey({
name: "RSA-OAEP",
hash: n
}, i, r ? ["encrypt"] : ["decrypt"]);
a = e.toCryptoKey({
name: t.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
hash: n
}, i, [r ? "verify" : "sign"]);
}
if (e.asymmetricKeyType === "ec") {
let n = (/* @__PURE__ */ new Map([
["prime256v1", "P-256"],
["secp384r1", "P-384"],
["secp521r1", "P-521"]
])).get(e.asymmetricKeyDetails?.namedCurve);
if (!n) throw TypeError(K);
let o = {
ES256: "P-256",
ES384: "P-384",
ES512: "P-521"
};
o[t] && n === o[t] && (a = e.toCryptoKey({
name: "ECDSA",
namedCurve: n
}, i, [r ? "verify" : "sign"])), t.startsWith("ECDH-ES") && (a = e.toCryptoKey({
name: "ECDH",
namedCurve: n
}, i, r ? [] : ["deriveBits"]));
}
if (!a) throw TypeError(K);
return n ? n[t] = a : q.set(e, { [t]: a }), a;
};
async function yt(e, t) {
if (e instanceof Uint8Array || rt(e)) return e;
if (it(e)) {
if (e.type === "secret") return e.export();
if ("toCryptoKey" in e && typeof e.toCryptoKey == "function") try {
return vt(e, t);
} catch (e) {
if (e instanceof TypeError) throw e;
}
return _t(e, e.export({ format: "jwk" }), t);
}
if (U(e)) return e.k ? P(e.k) : _t(e, e, t, !0);
throw Error("unreachable");
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/key/import.js
async function bt(e, t, n) {
if (!H(e)) throw TypeError("JWK must be an object");
let r;
switch (t ??= e.alg, r ??= n?.extractable ?? e.ext, e.kty) {
case "oct":
if (typeof e.k != "string" || !e.k) throw TypeError("missing \"k\" (Key Value) Parameter value");
return P(e.k);
case "RSA":
if ("oth" in e && e.oth !== void 0) throw new B("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
return G({
...e,
alg: t,
ext: r
});
case "AKP":
if (typeof e.alg != "string" || !e.alg) throw TypeError("missing \"alg\" (Algorithm) Parameter value");
if (t !== void 0 && t !== e.alg) throw TypeError("JWK alg and alg option value mismatch");
return G({
...e,
ext: r
});
case "EC":
case "OKP": return G({
...e,
alg: t,
ext: r
});
default: throw new B("Unsupported \"kty\" (Key Type) Parameter value");
}
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/validate_crit.js
function xt(e, t, n, r, i) {
if (i.crit !== void 0 && r?.crit === void 0) throw new e("\"crit\" (Critical) Header Parameter MUST be integrity protected");
if (!r || r.crit === void 0) return /* @__PURE__ */ new Set();
if (!Array.isArray(r.crit) || r.crit.length === 0 || r.crit.some((e) => typeof e != "string" || e.length === 0)) throw new e("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
let a;
a = n === void 0 ? t : new Map([...Object.entries(n), ...t.entries()]);
for (let t of r.crit) {
if (!a.has(t)) throw new B(`Extension Header Parameter "${t}" is not recognized`);
if (i[t] === void 0) throw new e(`Extension Header Parameter "${t}" is missing`);
if (a.get(t) && r[t] === void 0) throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`);
}
return new Set(r.crit);
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/validate_algorithms.js
function St(e, t) {
if (t !== void 0 && (!Array.isArray(t) || t.some((e) => typeof e != "string"))) throw TypeError(`"${e}" option must be an array of strings`);
if (t) return new Set(t);
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/check_key_type.js
var J = (e) => e?.[Symbol.toStringTag], Y = (e, t, n) => {
if (t.use !== void 0) {
let e;
switch (n) {
case "sign":
case "verify":
e = "sig";
break;
case "encrypt":
case "decrypt":
e = "enc";
break;
}
if (t.use !== e) throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`);
}
if (t.alg !== void 0 && t.alg !== e) throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);
if (Array.isArray(t.key_ops)) {
let r;
switch (!0) {
case n === "sign" || n === "verify":
case e === "dir":
case e.includes("CBC-HS"):
r = n;
break;
case e.startsWith("PBES2"):
r = "deriveBits";
break;
case /^A\d{3}(?:GCM)?(?:KW)?$/.test(e):
r = !e.includes("GCM") && e.endsWith("KW") ? n === "encrypt" ? "wrapKey" : "unwrapKey" : n;
break;
case n === "encrypt" && e.startsWith("RSA"):
r = "wrapKey";
break;
case n === "decrypt":
r = e.startsWith("RSA") ? "unwrapKey" : "deriveBits";
break;
}
if (r && t.key_ops?.includes?.(r) === !1) throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`);
}
return !0;
}, Ct = (e, t, n) => {
if (!(t instanceof Uint8Array)) {
if (U(t)) {
if (dt(t) && Y(e, t, n)) return;
throw TypeError("JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present");
}
if (!at(t)) throw TypeError(Je(e, t, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
if (t.type !== "secret") throw TypeError(`${J(t)} instances for symmetric algorithms must be of type "secret"`);
}
}, wt = (e, t, n) => {
if (U(t)) switch (n) {
case "decrypt":
case "sign":
if (lt(t) && Y(e, t, n)) return;
throw TypeError("JSON Web Key for this operation must be a private JWK");
case "encrypt":
case "verify":
if (ut(t) && Y(e, t, n)) return;
throw TypeError("JSON Web Key for this operation must be a public JWK");
}
if (!at(t)) throw TypeError(Je(e, t, "CryptoKey", "KeyObject", "JSON Web Key"));
if (t.type === "secret") throw TypeError(`${J(t)} instances for asymmetric algorithms must not be of type "secret"`);
if (t.type === "public") switch (n) {
case "sign": throw TypeError(`${J(t)} instances for asymmetric algorithm signing must be of type "private"`);
case "decrypt": throw TypeError(`${J(t)} instances for asymmetric algorithm decryption must be of type "private"`);
}
if (t.type === "private") switch (n) {
case "verify": throw TypeError(`${J(t)} instances for asymmetric algorithm verifying must be of type "public"`);
case "encrypt": throw TypeError(`${J(t)} instances for asymmetric algorithm encryption must be of type "public"`);
}
};
function Tt(e, t, n) {
switch (e.substring(0, 2)) {
case "A1":
case "A2":
case "di":
case "HS":
case "PB":
Ct(e, t, n);
break;
default: wt(e, t, n);
}
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jws/flattened/verify.js
async function Et(e, t, n) {
if (!H(e)) throw new V("Flattened JWS must be an object");
if (e.protected === void 0 && e.header === void 0) throw new V("Flattened JWS must have either of the \"protected\" or \"header\" members");
if (e.protected !== void 0 && typeof e.protected != "string") throw new V("JWS Protected Header incorrect type");
if (e.payload === void 0) throw new V("JWS Payload missing");
if (typeof e.signature != "string") throw new V("JWS Signature missing or incorrect type");
if (e.header !== void 0 && !H(e.header)) throw new V("JWS Unprotected Header incorrect type");
let r = {};
if (e.protected) try {
let t = P(e.protected);
r = JSON.parse(M.decode(t));
} catch {
throw new V("JWS Protected Header is invalid");
}
if (!ct(r, e.header)) throw new V("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
let i = {
...r,
...e.header
}, a = xt(V, /* @__PURE__ */ new Map([["b64", !0]]), n?.crit, r, i), o = !0;
if (a.has("b64") && (o = r.b64, typeof o != "boolean")) throw new V("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
let { alg: s } = i;
if (typeof s != "string" || !s) throw new V("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
let c = n && St("algorithms", n.algorithms);
if (c && !c.has(s)) throw new Xe("\"alg\" (Algorithm) Header Parameter value not allowed");
if (o) {
if (typeof e.payload != "string") throw new V("JWS Payload must be a string");
} else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array)) throw new V("JWS Payload must be a string or an Uint8Array instance");
let l = !1;
typeof t == "function" && (t = await t(r, e), l = !0), Tt(s, t, "verify");
let u = Be(e.protected === void 0 ? /* @__PURE__ */ new Uint8Array() : N(e.protected), N("."), typeof e.payload == "string" ? o ? N(e.payload) : ze.encode(e.payload) : e.payload), d = ot(e.signature, "signature", V), f = await yt(t, s);
if (!await ht(s, f, d, u)) throw new nt();
let p;
p = o ? ot(e.payload, "payload", V) : typeof e.payload == "string" ? ze.encode(e.payload) : e.payload;
let m = { payload: p };
return e.protected !== void 0 && (m.protectedHeader = r), e.header !== void 0 && (m.unprotectedHeader = e.header), l ? {
...m,
key: f
} : m;
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jws/compact/verify.js
async function Dt(e, t, n) {
if (e instanceof Uint8Array && (e = M.decode(e)), typeof e != "string") throw new V("Compact JWS must be a string or Uint8Array");
let { 0: r, 1: i, 2: a, length: o } = e.split(".");
if (o !== 3) throw new V("Invalid Compact JWS");
let s = await Et({
payload: i,
protected: r,
signature: a
}, t, n), c = {
payload: s.payload,
protectedHeader: s.protectedHeader
};
return typeof t == "function" ? {
...c,
key: s.key
} : c;
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
var Ot = (e) => Math.floor(e.getTime() / 1e3), kt = 60, At = kt * 60, jt = At * 24, Mt = jt * 7, Nt = jt * 365.25, Pt = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
function Ft(e) {
let t = Pt.exec(e);
if (!t || t[4] && t[1]) throw TypeError("Invalid time period format");
let n = parseFloat(t[2]), r = t[3].toLowerCase(), i;
switch (r) {
case "sec":
case "secs":
case "second":
case "seconds":
case "s":
i = Math.round(n);
break;
case "minute":
case "minutes":
case "min":
case "mins":
case "m":
i = Math.round(n * kt);
break;
case "hour":
case "hours":
case "hr":
case "hrs":
case "h":
i = Math.round(n * At);
break;
case "day":
case "days":
case "d":
i = Math.round(n * jt);
break;
case "week":
case "weeks":
case "w":
i = Math.round(n * Mt);
break;
default:
i = Math.round(n * Nt);
break;
}
return t[1] === "-" || t[4] === "ago" ? -i : i;
}
var It = (e) => e.includes("/") ? e.toLowerCase() : `application/${e.toLowerCase()}`, Lt = (e, t) => typeof e == "string" ? t.includes(e) : Array.isArray(e) ? t.some(Set.prototype.has.bind(new Set(e))) : !1;
function Rt(e, t, n = {}) {
let r;
try {
r = JSON.parse(M.decode(t));
} catch {}
if (!H(r)) throw new Ze("JWT Claims Set must be a top-level JSON object");
let { typ: i } = n;
if (i && (typeof e.typ != "string" || It(e.typ) !== It(i))) throw new z("unexpected \"typ\" JWT header value", r, "typ", "check_failed");
let { requiredClaims: a = [], issuer: o, subject: s, audience: c, maxTokenAge: l } = n, u = [...a];
l !== void 0 && u.push("iat"), c !== void 0 && u.push("aud"), s !== void 0 && u.push("sub"), o !== void 0 && u.push("iss");
for (let e of new Set(u.reverse())) if (!(e in r)) throw new z(`missing required "${e}" claim`, r, e, "missing");
if (o && !(Array.isArray(o) ? o : [o]).includes(r.iss)) throw new z("unexpected \"iss\" claim value", r, "iss", "check_failed");
if (s && r.sub !== s) throw new z("unexpected \"sub\" claim value", r, "sub", "check_failed");
if (c && !Lt(r.aud, typeof c == "string" ? [c] : c)) throw new z("unexpected \"aud\" claim value", r, "aud", "check_failed");
let d;
switch (typeof n.clockTolerance) {
case "string":
d = Ft(n.clockTolerance);
break;
case "number":
d = n.clockTolerance;
break;
case "undefined":
d = 0;
break;
default: throw TypeError("Invalid clockTolerance option type");
}
let { currentDate: f } = n, p = Ot(f || /* @__PURE__ */ new Date());
if ((r.iat !== void 0 || l) && typeof r.iat != "number") throw new z("\"iat\" claim must be a number", r, "iat", "invalid");
if (r.nbf !== void 0) {
if (typeof r.nbf != "number") throw new z("\"nbf\" claim must be a number", r, "nbf", "invalid");
if (r.nbf > p + d) throw new z("\"nbf\" claim timestamp check failed", r, "nbf", "check_failed");
}
if (r.exp !== void 0) {
if (typeof r.exp != "number") throw new z("\"exp\" claim must be a number", r, "exp", "invalid");
if (r.exp <= p - d) throw new Ye("\"exp\" claim timestamp check failed", r, "exp", "check_failed");
}
if (l) {
let e = p - r.iat, t = typeof l == "number" ? l : Ft(l);
if (e - d > t) throw new Ye("\"iat\" claim timestamp check failed (too far in the past)", r, "iat", "check_failed");
if (e < 0 - d) throw new z("\"iat\" claim timestamp check failed (it should be in the past)", r, "iat", "check_failed");
}
return r;
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwt/verify.js
async function zt(e, t, n) {
let r = await Dt(e, t, n);
if (r.protectedHeader.crit?.includes("b64") && r.protectedHeader.b64 === !1) throw new Ze("JWTs MUST NOT use unencoded payload");
let i = {
payload: Rt(r.protectedHeader, r.payload, n),
protectedHeader: r.protectedHeader
};
return typeof t == "function" ? {
...i,
key: r.key
} : i;
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwks/local.js
function Bt(e) {
switch (typeof e == "string" && e.slice(0, 2)) {
case "RS":
case "PS": return "RSA";
case "ES": return "EC";
case "Ed": return "OKP";
case "ML": return "AKP";
default: throw new B("Unsupported \"alg\" value for a JSON Web Key Set");
}
}
function Vt(e) {
return e && typeof e == "object" && Array.isArray(e.keys) && e.keys.every(Ht);
}
function Ht(e) {
return H(e);
}
var Ut = class {
#e;
#t = /* @__PURE__ */ new WeakMap();
constructor(e) {
if (!Vt(e)) throw new Qe("JSON Web Key Set malformed");
this.#e = structuredClone(e);
}
jwks() {
return this.#e;
}
async getKey(e, t) {
let { alg: n, kid: r } = {
...e,
...t?.header
}, i = Bt(n), a = this.#e.keys.filter((e) => {
let t = i === e.kty;
if (t && typeof r == "string" && (t = r === e.kid), t && (typeof e.alg == "string" || i === "AKP") && (t = n === e.alg), t && typeof e.use == "string" && (t = e.use === "sig"), t && Array.isArray(e.key_ops) && (t = e.key_ops.includes("verify")), t) switch (n) {
case "ES256":
t = e.crv === "P-256";
break;
case "ES384":
t = e.crv === "P-384";
break;
case "ES512":
t = e.crv === "P-521";
break;
case "Ed25519":
case "EdDSA":
t = e.crv === "Ed25519";
break;
}
return t;
}), { 0: o, length: s } = a;
if (s === 0) throw new $e();
if (s !== 1) {
let e = new et(), t = this.#t;
throw e[Symbol.asyncIterator] = async function* () {
for (let e of a) try {
yield await Wt(t, e, n);
} catch {}
}, e;
}
return Wt(this.#t, o, n);
}
};
async function Wt(e, t, n) {
let r = e.get(t) || e.set(t, {}).get(t);
if (r[n] === void 0) {
let e = await bt({
...t,
ext: !0
}, n);
if (e instanceof Uint8Array || e.type !== "public") throw new Qe("JSON Web Key Set members must be public keys");
r[n] = e;
}
return r[n];
}
function Gt(e) {
let t = new Ut(e), n = async (e, n) => t.getKey(e, n);
return Object.defineProperties(n, { jwks: {
value: () => structuredClone(t.jwks()),
enumerable: !1,
configurable: !1,
writable: !1
} }), n;
}
//#endregion
//#region ../../node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwks/remote.js
function Kt() {
return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
}
var qt;
(typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (qt = "jose/v6.2.3");
var Jt = Symbol();
async function Yt(e, t, n, r = fetch) {
let i = await r(e, {
method: "GET",
signal: n,
redirect: "manual",
headers: t
}).catch((e) => {
throw e.name === "TimeoutError" ? new tt() : e;
});
if (i.status !== 200) throw new R("Expected 200 OK from the JSON Web Key Set HTTP response");
try {
return await i.json();
} catch {
throw new R("Failed to parse the JSON Web Key Set HTTP response as JSON");
}
}
var Xt = Symbol();
function Zt(e, t) {
return !(typeof e != "object" || !e || !("uat" in e) || typeof e.uat != "number" || Date.now() - e.uat >= t || !("jwks" in e) || !H(e.jwks) || !Array.isArray(e.jwks.keys) || !Array.prototype.every.call(e.jwks.keys, H));
}
var Qt = class {
#e;
#t;
#n;
#r;
#i;
#a;
#o;
#s;
#c;
#l;
constructor(e, t) {
if (!(e instanceof URL)) throw TypeError("url must be an instance of URL");
this.#e = new URL(e.href), this.#t = typeof t?.timeoutDuration == "number" ? t?.timeoutDuration : 5e3, this.#n = typeof t?.cooldownDuration == "number" ? t?.cooldownDuration : 3e4, this.#r = typeof t?.cacheMaxAge == "number" ? t?.cacheMaxAge : 6e5, this.#o = new Headers(t?.headers), qt && !this.#o.has("User-Agent") && this.#o.set("User-Agent", qt), this.#o.has("accept") || (this.#o.set("accept", "application/json"), this.#o.append("accept", "application/jwk-set+json")), this.#s = t?.[Jt], t?.[Xt] !== void 0 && (this.#l = t?.[Xt], Zt(t?.[Xt], this.#r) && (this.#i = this.#l.uat, this.#c = Gt(this.#l.jwks)));
}
pendingFetch() {
return !!this.#a;
}
coolingDown() {
return typeof this.#i == "number" && Date.now() < this.#i + this.#n;
}
fresh() {
return typeof this.#i == "number" && Date.now() < this.#i + this.#r;
}
jwks() {
return this.#c?.jwks();
}
async getKey(e, t) {
(!this.#c || !this.fresh()) && await this.reload();
try {
return await this.#c(e, t);
} catch (n) {
if (n instanceof $e && this.coolingDown() === !1) return await this.reload(), this.#c(e, t);
throw n;
}
}
async reload() {
this.#a && Kt() && (this.#a = void 0), this.#a ||= Yt(this.#e.href, this.#o, AbortSignal.timeout(this.#t), this.#s).then((e) => {
this.#c = Gt(e), this.#l && (this.#l.uat = Date.now(), this.#l.jwks = e), this.#i = Date.now(), this.#a = void 0;
}).catch((e) => {
throw this.#a = void 0, e;
}), await this.#a;
}
};
function $t(e, t) {
let n = new Qt(e, t), r = async (e, t) => n.getKey(e, t);
return Object.defineProperties(r, {
coolingDown: {
get: () => n.coolingDown(),
enumerable: !0,
configurable: !1
},
fresh: {
get: () => n.fresh(),
enumerable: !0,
configurable: !1
},
reload: {
value: () => n.reload(),
enumerable: !0,
configurable: !1,
writable: !1
},
reloading: {
get: () => n.pendingFetch(),
enumerable: !0,
configurable: !1
},
jwks: {
value: () => n.jwks(),
enumerable: !0,
configurable: !1,
writable: !1
}
}), r;
}
//#endregion
//#region src/server/utils/pkce.ts
function en(e) {
let t = "";
for (let n of e) t += String.fromCharCode(n);
return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function tn() {
return en(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
}
async function nn(e) {
let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
return en(new Uint8Array(t));
}
//#endregion
//#region src/server/services/oauth-authentication.service.ts
var X = "Authentication failed";
function rn(e) {
return e === "localhost" || e === "::1" || e === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e);
}
function Z(t, n, r) {
let i;
try {
i = new URL(t);
} catch {
throw e({
statusCode: 500,
message: `Invalid ${n} URL`
});
}
if (!(i.protocol === "https:" || r && i.protocol === "http:" && rn(i.hostname))) throw e({
statusCode: 500,
message: `${n} must use https (http is only permitted for a localhost issuer during development)`
});
return i;
}
function Q(e) {
return e.replace(/\/+$/, "");
}
function an(e) {
let t = Q(e);
return [.../* @__PURE__ */ new Set([
e,
t,
`${t}/`
])];
}
function on(e) {
if (e === "EdDSA") return "SHA-512";
let t = /^[A-Z]{2}(256|384|512)$/.exec(e)?.[1];
return t ? `SHA-${t}` : null;
}
async function sn(e, t) {
let n = on(t);
if (!n) return null;
let r = await globalThis.crypto.subtle.digest(n, new TextEncoder().encode(e)), i = new Uint8Array(r);
return en(i.slice(0, i.length / 2));
}
var $ = class {
constructor(e) {
this.inflightRefreshes = /* @__PURE__ */ new Map(), this.openIDConfigCache = null, this.configLastFetched = null, this.CONFIG_CACHE_TTL = 36e5, this.TOKEN_REFRESH_SAFETY_MARGIN = 300, this.normalizedWhitelistExtensions = /* @__PURE__ */ new Set(), this.logger = A(D).forContext("OAuthAuthenticationService"), Ie(j, e.sessionStorage), this.config = e;
}
validateConfiguration() {
if (!this.config.issuer || !this.config.clientId || !this.config.clientSecret || !this.config.callbackUri) throw Error("OAuth Authentication Service not properly initialized. Make sure to call AnalogAuth() with valid configuration before using authentication features.");
}
async initSession(e) {
return await A(j).initSession(e);
}
getConfig() {
return this.validateConfiguration(), this.config;
}
getConfigValue(e, t) {
let n = this.config[e];
if (n === void 0 || typeof n == "string" && n === "") {
if (t !== void 0) return t;
if (e === "userHandler" || e === "logoutUrl" || e === "audience") return;
if (e === "unprotectedRoutes") return [];
throw Error(`Configuration value for '${e}' doesn't exist`);
}
return n;
}
isUnprotectedRoute(e) {
let t = this.getConfigValue("unprotectedRoutes", []);
return Array.isArray(t) ? t.some((t) => {
if (t.endsWith("*")) {
let n = t.slice(0, -1);
if (!e.startsWith(n)) return !1;
let r = e.slice(n.length);
return r.length > 0 && r !== "/";
}
let n = t.endsWith("/") ? t : t + "/", r = e.endsWith("/") ? e : e + "/";
return e === t || r === n;
}) : !1;
}
async getAuthorizationUrl(e) {
this.validateConfiguration();
let t = await this.getOpenIDConfiguration(), n = this.getConfigValue("audience", void 0), r = {
response_type: "code",
client_id: this.getConfigValue("clientId"),
redirect_uri: e.redirectUri || this.getConfigValue("callbackUri"),
scope: this.getConfigValue("scope"),
state: e.state,
nonce: e.nonce,
code_challenge: e.codeChallenge,
code_challenge_method: "S256",
...n ? { audience: n } : {}
}, i = new URLSearchParams(r);
return `${t.authorization_endpoint}?${i.toString()}`;
}
async exchangeCodeForTokens(t, n, r) {
let i = await this.getOpenIDConfiguration(), a = await fetch(i.token_endpoint, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: this.getConfigValue("clientId"),
client_secret: this.getConfigValue("clientSecret"),
code: t,
code_verifier: n,
redirect_uri: r || this.getConfigValue("callbackUri")
}).toString()
});
if (!a.ok) {
let t = await a.json();
throw this.logger.error("Error exchanging code for tokens", t), e({
statusCode: 401,
message: "Failed to exchange authorization code"
});
}
return await a.json();
}
async refreshTokens(t) {
let n = await this.getOpenIDConfiguration();
try {
let r = await fetch(n.token_endpoint, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: this.getConfigValue("clientId"),
client_secret: this.getConfigValue("clientSecret"),
refresh_token: t
}).toString()
});
if (!r.ok) {
let t = await r.json().catch(() => ({ error: "Unknown error" }));
throw this.logger.error("Error refreshing token", t), e({
statusCode: 401,
message: "Failed to refresh token"
});
}
return await r.json();
} catch (t) {
throw this.logger.error("Error during token refresh", t), e({
statusCode: 401,
message: "Failed to refresh authentication token"
});
}
}
async refreshTokensDeduped(e) {
let t = this.inflightRefreshes.get(e);
if (t) return t;
let n = this.refreshTokens(e).finally(() => {
this.inflightRefreshes.delete(e);
});
return this.inflightRefreshes.set(e, n), n;
}
async getUserInfo(t, n = 3) {
let r = await this.getOpenIDConfiguration(), i = null;
for (let a = 1; a <= n; a++) try {
let i = await fetch(r.userinfo_endpoint, {
headers: { Authorization: `Bearer ${t}` },
signal: AbortSignal.timeout(1e4)
});
if (!i.ok) {
let t = await i.json().catch(() => ({ error: "Unknown error" }));
if (this.logger.error("Error getting user info", t, {
attempt: a,
maxRetries: n
}), i.status === 401) throw e({
statusCode: 401,
message: "Authentication token is invalid or expired"
});
if (i.status === 429) {
let e = parseInt(i.headers.get("Retry-After") || "5", 10);
await new Promise((t) => setTimeout(t, e * 1e3));
continue;
} else if (i.status >= 500) {
await new Promise((e) => setTimeout(e, a * 1e3));
continue;
} else throw e({
statusCode: i.status,
message: `Failed to get user info: ${t.error || "Unknown error"}`
});
}
let o = await i.json();
if (!o || !o.sub && !o.id) throw e({
statusCode: 500,
message: "Invalid user data received from provider"
});
return o;
} catch (t) {
if (i = t, t instanceof Error && "statusCode" in t && t.statusCode === 401) throw t;
if ((t instanceof TypeError || t instanceof Error && t.name === "AbortError") && (this.logger.error("Network error fetching user info", t, {
attempt: a,
maxRetries: n
}), a < n)) {
await new Promise((e) => setTimeout(e, 2 ** a * 500));
continue;
}
if (a === n) throw this.logger.error("Failed to get user info after multiple attempts", { maxRetries: n }), e({
statusCode: 500,
message: "Failed to get user info after multiple attempts",
cause: i
});
}
throw e({
statusCode: 500,
message: "Unexpected error getting user info"
});
}
async validateIdToken(t, n, r) {
let i = await this.getOpenIDConfiguration();
if (!i.jwks_uri) throw e({
statusCode: 500,
message: "OpenID configuration is missing jwks_uri; cannot verify ID token"
});
let a = this.getConfigValue("issuer"), o = Z(a, "OAuth issuer", !0), s = o.protocol === "http:" && rn(o.hostname), c = Z(i.jwks_uri, "jwks_uri", s);
(!this.jwks || this.jwksUri !== i.jwks_uri) && (this.jwks = $t(c), this.jwksUri = i.jwks_uri);
let l, u;
try {
({payload: l, protectedHeader: u} = await zt(t, this.jwks, {
issuer: an(a),
audience: this.getConfigValue("clientId")
}));
} catch (t) {
throw this.logger.error("ID token validation failed", t), e({
statusCode: 401,
message: X
});
}
if (l.nonce !== n) throw this.logger.error("ID token nonce mismatch"), e({
statusCode: 401,
message: X
});
if (l.azp !== void 0 && l.azp !== this.getConfigValue("clientId")) throw this.logger.error("ID token azp does not match client ID"), e({
statusCode: 401,
message: X
});
if (typeof l.at_hash == "string") {
let t = await sn(r, u.alg);
if (t === null || t !== l.at_hash) throw this.logger.error("ID token at_hash mismatch"), e({
statusCode: 401,
message: X
});
}
return l;
}
async handleCallback(t, n, r) {
if (!r) throw e({
statusCode: 400,
message: "Invalid state parameter"
});
let i = c(t), a = i?.codeVerifier, o = i?.nonce;
if (!a || !o) throw e({
statusCode: 400,
message: "Missing PKCE verifier or nonce; restart the login flow"
});
let s = await this.exchangeCodeForTokens(n, a), { access_token: l, id_token: f, refresh_token: p, expires_in: m } = s;
if (this.getConfigValue("scope").split(" ").includes("openid") && !f) throw this.logger.error("Token response is missing id_token for an openid-scoped request"), e({
statusCode: 401,
message: X
});
let h;
if (f) {
let t = await this.validateIdToken(f, o, l);
if (typeof t.sub != "string" || t.sub.length === 0) throw this.logger.error("ID token is missing a subject"), e({
statusCode: 401,
message: X
});
h = t.sub;
}
let g = await this.getUserInfo(l);
if (h && (typeof g?.sub != "string" || g.sub !== h)) throw this.logger.error("ID token subject does not match userinfo subject"), e({
statusCode: 401,
message: X
});
let _ = this.getConfigValue("userHandler", void 0), v = g;
_ && "createOrUpdateUser" in _ && (v = await _.createOrUpdateUser?.(g));
let ee = {
isAuthenticated: !0,
accessToken: l,
idToken: f,
refreshToken: p,
expiresAt: Date.now() + m * 1e3,
userInfo: g
};
if (await u(t), await d(t, () => ({
user: v,
auth: ee,
codeVerifier: void 0,
nonce: void 0
})), this.getConfigValue("singleSessionPerUser", !1)) try {
await this.invalidateOtherUserSessions(t, v, g);
} catch (e) {
this.logger.error("Failed to invalidate other user sessions", e);
}
return this.logger.debug("Authentication session data saved successfully"), {
user: v,
tokens: s
};
}
resolveUserIdentity(e, t) {
let n = [
e?.id,
e?.sub,
t?.id,
t?.sub,
t?.email
];
for (let e of n) if (typeof e == "string" && e.length > 0) return e;
return null;
}
resolveSessionIdentity(e) {
let t = e.user && typeof e.user == "object" ? e.user : null, n = e.auth?.userInfo && typeof e.auth.userInfo == "object" ? e.auth.userInfo : null, r = [
t?.id,
t?.sub,
n?.id,
n?.sub,
n?.email
];
for (let e of r) if (typeof e == "string" && e.length > 0) return e;
return null;
}
async invalidateOtherUserSessions(e, t, n) {
let r = this.resolveUserIdentity(t, n);
if (!r) {
this.logger.debug("Skipping session invalidation because user identity could not be resolved");
return;
}
let i = typeof e.context.__session_id__ == "string" ? e.context.__session_id__ : null;
if (!i) {
this.logger.debug("Skipping session invalidation because current session id is unavailable");
return;
}
let a = await A(j).getActiveSessions();
for (let e of a) {
if (e.id === i || !e.data.auth?.isAuthenticated) continue;
let t = this.resolveSessionIdentity(e.data);
!t || t !== r || (e.update((e) => {
let t = e.auth;
return {
...e,
auth: {
...t ?? { isAuthenticated: !1 },
isAuthenticated: !1,
accessToken: void 0,
idToken: void 0,
refreshToken: void 0,
expiresAt: void 0,
userInfo: void 0
},
user: null
};
}), await e.save(), this.logger.debug("Invalidated stale authenticated session", { sessionId: e.id }));
}
}
shouldRefreshToken(e) {
return Date.now() + this.TOKEN_REFRESH_SAFETY_MARGIN * 1e3 > e;
}
async refreshExpiringTokens() {
this.logger.debug("Starting bulk token refresh process");
try {
let e = await A(j).getActiveSessions(), t = 0, n = 0, r = e.length;
this.logger.debug(`Found ${r} active sessions to check`);
for (let r of e) try {
if (!r.data.auth?.isAuthenticated || !r.data.auth.refreshToken || !r.data.auth.expiresAt) {
this.logger.debug(`Skipping session ${r.id} - no valid auth data`);
continue;
}
if (!this.shouldRefreshToken(r.data.auth.expiresAt)) {
this.logger.debug(`Skipping session ${r.id} - token not expiring soon`);
continue;
}
this.logger.debug(`Refreshing token for session ${r.id}`);
let e = await this.refreshTokensDeduped(r.data.auth.refreshToken);
r.update((t) => {
let n = t.auth;
return n ? {
...t,
auth: {
...n,
accessToken: e.access_token,
idToken: e.id_token || n.idToken,
refreshToken: e.refresh_token || n.refreshToken,
expiresAt: Date.now() + e.expires_in * 1e3
}
} : t;
}), await r.save(), t++, this.logger.debug(`Successfully refreshed token for session ${r.id}`);
} catch (e) {
n++, this.logger.error("Failed to refresh token for session", e, { sessionId: r.id });
try {
let e = await r.refetch();
if (e?.auth?.isAuthenticated && typeof e.auth.expiresAt == "number" && e.auth.expiresAt > Date.now()) {
n--, this.logger.debug(`Skipping unauthenticated mark for session ${r.id} - already refreshed concurrently`);
continue;
}
r.update((e) => {
let t = e.auth;
return t ? {
...e,
auth: {
...t,
isAuthenticated: !1
}
} : e;
}), await r.save();
} catch (e) {
this.logger.error("Failed to update session after refresh failure", e, { sessionId: r.id });
}
}
let i = {
refreshed: t,
failed: n,
total: r
};
return this.logger.info("Bulk token refresh completed", i), i;
} catch (t) {
throw this.logger.error("Error during bulk token refresh", t), e({
statusCode: 500,
message: "Failed to refresh expiring tokens"
});
}
}
async isAuthenticated(e) {
await A(j).initSession(e);
let t = await c(e);
if (!t?.auth) return await d(e, () => ({ auth: { isAuthenticated: !1 } })), !1;
if (!t.auth.isAuthenticated) return !1;
if (t.auth.expiresAt && t.auth.expiresAt < Date.now()) if (t.auth.refreshToken) try {
let n = await this.refreshTokensDeduped(t.auth.refreshToken);
return await d(e, (e) => ({ auth: {
...e.auth,
isAuthenticated: !0,
accessToken: n.access_token,
idToken: n.id_token || t?.auth?.idToken,
refreshToken: n.refresh_token || t?.auth?.refreshToken,
expiresAt: Date.now() + n.expires_in * 1e3
} })), !0;
} catch (t) {
this.logger.error("Error refreshing token", t);
let n = await l(e);
return n?.auth?.isAuthenticated && typeof n.auth.expiresAt == "number" && n.auth.expiresAt > Date.now() ? !0 : (await d(e, (e) => ({ auth: {
...e.auth,
isAuthenticated: !1
} })), this.logger.info("error occurred while refreshing token"), this.logger.groupEnd("OAuthAuthenticationService.isAuthenticated " + e.path), !1);
}
else return this.logger.info(" No refresh token available"), this.logger.groupEnd("OAuthAuthenticationService.isAuthenticated " + e.path), !1;
return t.auth.expiresAt && this.shouldRefreshToken(t.auth.expiresAt) && setTimeout(async () => {
try {
let t = await c(e);
if (!t?.auth?.isAuthenticated || !t.auth.refreshToken) return;
let n = await this.refreshTokensDeduped(t.auth.refreshToken);
await d(e, (e) => ({ auth: {
...e.auth,
isAuthenticated: !0,
accessToken: n.access_token,
idToken: n.id_token || t?.auth?.idToken,
refreshToken: n.refresh_token || t?.auth?.refreshToken,
expiresAt: Date.now() + n.expires_in * 1e3
} })), this.logger.debug("Background token refresh completed");
} catch (e) {
this.logger.error("Background token refresh failed", e);
}
}, 0), !0;
}
async getAuthenticatedUser(e) {
if (!await this.isAuthenticated(e)) return null;
let t = c(e), n = this.getConfigValue("userHandler", void 0);
return n && "mapUserToLocal" in n ? n.mapUserToLocal?.(t.auth?.userInfo) : t.auth?.userInfo;
}
async revokeToken(e) {
let t = await this.getOpenIDConfiguration();
if (!(await fetch(t.revocation_endpoint, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: this.getConfigValue("clientId"),
client_secret: this.getConfigValue("clientSecret"),
token: e
})
})).ok) throw Error("Failed to revoke token");
}
async logout(e) {
await A(j).initSession(e);
let t = c(e), n = await this.getOpenIDConfiguration();
if (t?.auth?.accessToken) try {
await this.revokeToken(t.auth.accessToken);
} catch (e) {
this.logger.error("Failed to revoke access token", e);
}
if (t?.auth?.refreshToken) try {
await this.revokeToken(t.auth.refreshToken);
} catch (e) {
this.logger.error("Failed to revoke refresh token", e);
}
let r = new URL(n.end_session_endpoint);
r.searchParams.append("client_id", this.getConfigValue("clientId"));
let i = this.getConfigValue("logoutUrl");
return i && r.searchParams.append("returnTo", i), await d(e, () => ({
auth: { isAuthenticated: !1 },
user: null
})), r.toString();
}
async getOpenIDConfiguration() {
let t = Date.now();
if (this.openIDConfigCache && this.configLastFetched && t - this.configLastFetched < this.CONFIG_CACHE_TTL) return this.openIDConfigCache;
let n = this.getConfigValue("issuer"), r = Z(n, "OAuth issuer", !0), i = r.protocol === "http:" && rn(r.hostname), a;
try {
let e = await fetch(`${Q(n)}/.well-known/openid-configuration`, {
redirect: "error",
signal: AbortSignal.timeout(this.getConfigValue("discoveryTimeoutMs", 1e4))
});
if (!e.ok) throw Error(`Failed to fetch OpenID configuration: ${e.statusText}`);
a = await e.json();
} catch (t) {
throw this.logger.error("Error fetching OpenID configuration", t), e({
statusCode: 500,
message: "Failed to fetch OpenID configuration"
});
}
return this.assertTrustedOpenIDConfiguration(a, n, i), this.openIDConfigCache = a, this.configLastFetched = t, a;
}
assertTrustedOpenIDConfiguration(t, n, r) {
if (typeof t.issuer != "string" || Q(t.issuer) !== Q(n)) throw this.logger.error("OpenID configuration issuer mismatch", {
expected: n,
received: t.issuer
}), e({
statusCode: 500,
message: "OpenID configuration issuer does not match the configured issuer"
});
for (let n of [
"authorization_endpoint",
"token_endpoint",
"userinfo_endpoint",
"end_session_endpoint",
"revocation_endpoint"
]) {
let i = t[n];
if (typeof i != "string" || i.length === 0) throw e({
statusCode: 500,
message: `OpenID configuration is missing ${n}`
});
Z(i, `OpenID ${n}`, r);
}
}
};
$ = Re([je(), Le("design:paramtypes", [Object])], $);
//#endregion
//#region src/server/routes/authenticated.ts
var cn = {
path: "authenticated",
handler: async (e) => {
let t = A($), n = A(D).forContext("AuthMiddleware"), r = { authenticated: await t.isAuthenticated(e) };
return n.info("User authentication status checked", r), r;
}
}, ln = "http://analog-tools.local";
function un(e) {
for (let t of e) {
let e = t.charCodeAt(0);
if (e <= 31 || e === 127) return !0;
}
return !1;
}
function dn(e) {
if (typeof e != "string") return "/";
let t = e.trim();
if (t === "" || !t.startsWith("/") || t.startsWith("//") || t.includes("\\") || un(t)) return "/";
try {
let e = new URL(t, ln);
if (e.origin !== ln) return "/";
let n = `${e.pathname}${e.search}${e.hash}`;
return n.startsWith("//") ? "/" : n;
} catch {
return "/";
}
}
//#endregion
//#region src/server/routes/callback.ts
async function fn(e) {
let t = dn(c(e)?.redirectUrl);
return await d(e, (e) => ({
...e,
redirectUrl: void 0
})), t;
}
var pn = {
path: "callback",
handler: async (t) => {
let r = A($);
if (await r.initSession(t), await r.isAuthenticated(t)) return a(t, await fn(t));
let i = n(t), o = i.code, s = i.state, l = c(t)?.state;
if (!s || !l || s !== l) throw e({
statusCode: 400,
message: "Invalid or missing state parameter. Authentication flow may have been tampered with.",
statusMessage: "Authorization Failed"
});
return await d(t, (e) => ({
...e,
state: void 0
})), await r.handleCallback(t, o, s), a(t, await fn(t));
}
}, mn = globalThis.crypto;
mn.subtle;
var hn = () => mn.randomUUID(), gn = {
path: "login",
handler: async (e) => {
let t = A($);
await t.initSession(e);
let r = hn(), i = hn(), o = tn(), s = await nn(o);
await d(e, (e) => ({
...e,
state: r,
nonce: i,
codeVerifier: o
}));
let c = n(e).redirect_uri, l = c ? dn(c) : "/";
return await d(e, (e) => ({
...e,
redirectUrl: l === "/" ? void 0 : l
})), a(e, await t.getAuthorizationUrl({
state: r,
codeChallenge: s,
nonce: i
}));
}
}, _n = {
path: "logout",
handler: async (t) => {
let n = A(D).forContext("LogoutRoute");
try {
let e = A($);
return await e.initSession(t), a(t, await e.logout(t));
} catch (t) {
throw n.error("Logout failed", t), e({
statusCode: 500,
message: "Logout failed"
});
}
}
}, vn = {
path: "protected-data",
handler: async (e) => ({
message: "This is protected data that requires authentication",
user: await A($).getAuthenticatedUser(e)
})
};
//#endregion
//#region src/server/utils/timing-safe-equal.ts
async function yn(e, t) {
let n = new TextEncoder(), r = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), i = await globalThis.crypto.subtle.importKey("raw", r, {
name: "HMAC",
hash: "SHA-256"
}, !1, ["sign"]), a = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", i, n.encode(e))), o = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", i, n.encode(t))), s = 0;
for (let e = 0; e < a.length; e++) s |= a[e] ^ o[e];
return s === 0;
}
//#endregion
//#region src/server/routes/refresh-tokens.ts
var bn = {
path: "refresh-tokens",
handler: async (t) => {
let n = A(D).forContext("TokenRefresh"), i = A($), a = i.getConfig().tokenRefreshApiKey;
if (!a) throw n.error("Token refresh API key not configured in either AnalogAuthConfig.tokenRefreshApiKey or TOKEN_REFRESH_API_KEY env variable"), e({
statusCode: 500,
message: "Server configuration error"
});
let o = r(t).authorization;
if (!o || !await yn(o, `Bearer ${a}`)) throw n.warn("Unauthorized token refresh attempt"), e({
statusCode: 401,
message: "Unauthorized"
});
try {
let e = await i.refreshExpiringTokens();
return n.info("Token refresh job completed", {
refreshed: e.refreshed,
failed: e.failed,
total: e.total
}), {
success: !0,
...e
};
} catch (t) {
throw n.error("Error in token refresh job", t), e({
statusCode: 500,
message: "Failed to refresh tokens"
});
}
}
}, xn = {
path: "user",
handler: async (t) => {
let n = A($);
if (await n.initSession(t), !await n.isAuthenticated(t)) throw e({
statusCode: 401,
message: "Unauthorized"
});
return n.getAuthenticatedUser(t);
}
};
//#endregion
//#region src/server/functions/registerRoutes.ts
function Sn() {
return {
[cn.path]: cn.handler,
[pn.path]: pn.handler,
[gn.path]: gn.handler,
[_n.path]: _n.handler,
[vn.path]: vn.handler,
[bn.path]: bn.handler,
[xn.path]: xn.handler
};
}
//#endregion
//#region src/server/utils/getLastPathSegment.ts
function Cn(e) {
return new URL(e, "http://dummy-base").pathname.split("/").filter(Boolean).pop() ?? "";
}
//#endregion
//#region src/server/functions/handleAuthRoute.ts
async function wn(t) {
if (t.path.includes("/api/auth/")) {
let n = Cn(t.path);
if (!n) throw e({
statusCode: 400,
statusMessage: "Missing path parameter"
});
await A($).initSession(t);
let r = Sn();
if (r[n]) return r[n](t);
throw e({
statusCode: 404,
statusMessage: `Authentication route '${n}' not found`
});
}
}
//#endregion
//#region src/server/functions/checkAuthentication.ts
async function Tn(e) {
let t = A($);
return await t.initSession(e), t.isAuthenticated(e);
}
//#endregion
//#region src/server/functions/useAnalogAuthMiddleware.ts
async function En(e) {
let n = i(e), r = n.pathname, o = A($), s = A(D).forContext("AuthMiddleware");
if (s.info("Processing authentication middleware", r), !r.startsWith("/api/auth/") && !(o.isUnprotectedRoute(r) || r === "/api/trpc" || r.startsWith("/api/trpc/")) && (await o.initSession(e), !await Tn(e))) {
if (t(e, "fetch") === "true") throw new p({
code: "UNAUTHORIZED",
message: "User is not authenticated"
});
s.debug("Redirecting to login page", { path: r }), await d(e, (e) => ({
...e,
redirectUrl: dn(`${n.pathname}${n.search}`)
})), await a(e, "/api/auth/login");
}
}
//#endregion
//#region src/server/functions/useAnalogAuth.ts
async function Dn(e, t) {
let n = [
"issuer",
"clientId",
"clientSecret",
"callbackUri"
].filter((t) => !e[t]);
if (n.length > 0) throw Error(`AnalogAuth initialization failed: Missing mandatory configuration values: ${n.join(", ")}`);
return Ie($, e), await En(t), wn(t);
}
//#endregion
export { Tn as checkAuthentication, Dn as useAnalogAuth };
//# sourceMappingURL=index.js.map