fix(sessions): normalize agent session keys for send policy

This commit is contained in:
Peter Steinberger
2026-02-14 20:54:12 +01:00
parent ee8d8be2e3
commit 2a3da21333

View File

@@ -20,11 +20,24 @@ function normalizeMatchValue(raw?: string | null) {
return value ? value : undefined; return value ? value : undefined;
} }
function deriveChannelFromKey(key?: string) { function stripAgentSessionKeyPrefix(key?: string): string | undefined {
if (!key) { if (!key) {
return undefined; return undefined;
} }
const parts = key.split(":").filter(Boolean); const parts = key.split(":").filter(Boolean);
// Canonical agent session keys: agent:<agentId>:<sessionKey...>
if (parts.length >= 3 && parts[0] === "agent") {
return parts.slice(2).join(":");
}
return key;
}
function deriveChannelFromKey(key?: string) {
const normalizedKey = stripAgentSessionKeyPrefix(key);
if (!normalizedKey) {
return undefined;
}
const parts = normalizedKey.split(":").filter(Boolean);
if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) { if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) {
return normalizeMatchValue(parts[0]); return normalizeMatchValue(parts[0]);
} }
@@ -32,13 +45,14 @@ function deriveChannelFromKey(key?: string) {
} }
function deriveChatTypeFromKey(key?: string): SessionChatType | undefined { function deriveChatTypeFromKey(key?: string): SessionChatType | undefined {
if (!key) { const normalizedKey = stripAgentSessionKeyPrefix(key);
if (!normalizedKey) {
return undefined; return undefined;
} }
if (key.includes(":group:")) { if (normalizedKey.includes(":group:")) {
return "group"; return "group";
} }
if (key.includes(":channel:")) { if (normalizedKey.includes(":channel:")) {
return "channel"; return "channel";
} }
return undefined; return undefined;
@@ -69,7 +83,8 @@ export function resolveSendPolicy(params: {
const chatType = const chatType =
normalizeChatType(params.chatType ?? params.entry?.chatType) ?? normalizeChatType(params.chatType ?? params.entry?.chatType) ??
normalizeChatType(deriveChatTypeFromKey(params.sessionKey)); normalizeChatType(deriveChatTypeFromKey(params.sessionKey));
const sessionKey = params.sessionKey ?? ""; const rawSessionKey = params.sessionKey ?? "";
const strippedSessionKey = stripAgentSessionKeyPrefix(rawSessionKey) ?? "";
let allowedMatch = false; let allowedMatch = false;
for (const rule of policy.rules ?? []) { for (const rule of policy.rules ?? []) {
@@ -88,7 +103,11 @@ export function resolveSendPolicy(params: {
if (matchChatType && matchChatType !== chatType) { if (matchChatType && matchChatType !== chatType) {
continue; continue;
} }
if (matchPrefix && !sessionKey.startsWith(matchPrefix)) { if (
matchPrefix &&
!rawSessionKey.startsWith(matchPrefix) &&
!strippedSessionKey.startsWith(matchPrefix)
) {
continue; continue;
} }
if (action === "deny") { if (action === "deny") {