(
args: { account?: AccountRef; brand?: BrandRef; plans?: unknown },
mode: 'open' | 'training',
userId?: string,
moduleId?: string,
)
| 374 | * the spec's `account` invariant on every step). |
| 375 | */ |
| 376 | export function sessionKeyFromArgs( |
| 377 | args: { account?: AccountRef; brand?: BrandRef; plans?: unknown }, |
| 378 | mode: 'open' | 'training', |
| 379 | userId?: string, |
| 380 | moduleId?: string, |
| 381 | ): string { |
| 382 | if (mode === 'training' && userId) { |
| 383 | const safeUser = safeKey(userId, 128, SAFE_ACCOUNT_ID_RE) ?? 'default'; |
| 384 | const safeModule = safeKey(moduleId, 128, SAFE_ACCOUNT_ID_RE) ?? 'default'; |
| 385 | return `training:${safeUser}:${safeModule}`; |
| 386 | } |
| 387 | const account = args.account; |
| 388 | const domain = account?.brand?.domain ?? args.brand?.domain; |
| 389 | const safeDomain = safeKey(domain, MAX_DOMAIN_LEN, SAFE_DOMAIN_RE); |
| 390 | if (safeDomain) { |
| 391 | // DNS is case-insensitive — normalise so Example.com and example.com share a session. |
| 392 | return `open:${safeDomain.toLowerCase()}`; |
| 393 | } |
| 394 | if (domain && !safeDomain) { |
| 395 | logger.debug({ domain }, 'Rejected brand.domain as session key; falling back'); |
| 396 | } |
| 397 | if (account?.account_id) { |
| 398 | const safe = safeKey(account.account_id, MAX_ACCOUNT_ID_LEN, SAFE_ACCOUNT_ID_RE); |
| 399 | if (safe) return `open:${safe}`; |
| 400 | } |
| 401 | if (Array.isArray(args.plans) && args.plans.length > 0) { |
| 402 | const first = args.plans[0] as { brand?: BrandRef } | undefined; |
| 403 | const planDomain = first?.brand?.domain; |
| 404 | const safePlanDomain = safeKey(planDomain, MAX_DOMAIN_LEN, SAFE_DOMAIN_RE); |
| 405 | if (safePlanDomain) return `open:${safePlanDomain.toLowerCase()}`; |
| 406 | if (planDomain && !safePlanDomain) { |
| 407 | logger.debug({ domain: planDomain }, 'Rejected plans[0].brand.domain as session key; falling back'); |
| 408 | } |
| 409 | } |
| 410 | return 'open:default'; |
| 411 | } |
| 412 | |
| 413 | // ── TTL cleanup ────────────────────────────────────────────────── |
| 414 |
no test coverage detected