Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

7.6 KB
Raw Blame
import { v4 as uuidv4 } from 'uuid'

import { base64Decode, base64Encode } from 'lib/utils/base64'

import { SKILL_DESCRIPTION_MAX_LENGTH, validateSkillName } from 'products/skills/frontend/skillConstants'

import type { ScoutCreateInitialValues } from '../logics/scoutCreateModalLogic'
import { MAX_SCOUT_DISPLAY_NAME_LENGTH, scoutCronScheduleError } from './scoutRunsWindow'
import { MAX_SCOUT_TAGS, normalizeScoutTags } from './scoutTags'

/**
 * `/inbox/config#createScout=<url-safe base64 JSON>`, e.g. from a posthog.com template page or the
 * community skills store. In the fragment so it never reaches server logs, and prefill-only: the
 * modal opens with these values and a person still submits it.
 */
export interface ScoutTemplatePayload {
    name?: string
    display_name?: string
    description?: string
    body?: string
    config?: ScoutTemplateConfig
}

/**
 * The settings a template may prefill: exactly the ones the create modal shows, so nothing a link
 * sets is hidden from the person submitting it. `network_access`, `model` and
 * `mcp_gateway_server_ids` reach into a project's data and services and never come from a link.
 */
export interface ScoutTemplateConfig {
    run_interval_minutes?: number
    run_cron_schedule?: string | null
    emit?: boolean
    tags?: string[]
}

/** Whole-payload cap, before decoding. Far above any real template, far below abuse territory. */
const MAX_ENCODED_LENGTH = 16384
const MAX_BODY_LENGTH = 20000
const STORED_TEMPLATE_PREFIX = 'stored:'
// Pinned storage key: a rename can strand a draft during navigation.
const STORED_TEMPLATE_KEY_PREFIX = 'posthog.scout-create-template.'
/** Matches the bounds the create form and the API hold a scout's cadence to. */
const MIN_RUN_INTERVAL_MINUTES = 30
const MAX_RUN_INTERVAL_MINUTES = 43200

/** Encode a template as a URL-safe base64 fragment value (used by tests and by link authors). */
export function encodeScoutCreateTemplate(template: ScoutTemplatePayload): string {
    return base64Encode(JSON.stringify(template)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

/** Store a rendered community scout for one navigation. The URL carries only the random key. */
export function storeCommunityScoutCreateTemplate(template: ScoutTemplatePayload): string {
    const id = uuidv4()
    sessionStorage.setItem(`${STORED_TEMPLATE_KEY_PREFIX}${id}`, JSON.stringify(template))
    return `${STORED_TEMPLATE_PREFIX}${id}`
}

/** `{ key: value }` when the cleaner kept the value, and nothing when it dropped it. */
function defined<K extends string, V>(key: K, value: V | undefined): Partial<Record<K, V>> {
    return value === undefined ? {} : ({ [key]: value } as Record<K, V>)
}

/** The cadence, or undefined when the link gave none the create form would accept. */
function cleanInterval(value: unknown): number | undefined {
    if (typeof value !== 'number' || !Number.isInteger(value)) {
        return undefined
    }
    return value >= MIN_RUN_INTERVAL_MINUTES && value <= MAX_RUN_INTERVAL_MINUTES ? value : undefined
}

function cleanCron(value: unknown): string | undefined {
    if (typeof value !== 'string') {
        return undefined
    }
    const schedule = value.trim()
    // The field count alone lets through expressions the create endpoint refuses, such as one that
    // never matches a real date or runs more often than every 30 minutes. Dropping those here opens
    // the form on its own default instead of one that fails the moment it is submitted.
    return scoutCronScheduleError(schedule) === null ? schedule : undefined
}

function cleanTags(value: unknown): string[] | undefined {
    if (!Array.isArray(value) || !value.every((tag) => typeof tag === 'string')) {
        return undefined
    }
    // Normalized here rather than trusted: the tag editor writes normalized tags, so an
    // unnormalized one from a link would be an entry the user cannot reproduce by typing it.
    const tags = normalizeScoutTags(value as string[]).slice(0, MAX_SCOUT_TAGS)
    return tags.length > 0 ? tags : undefined
}

/** Keep the prefillable settings, dropping any field that isn't one or isn't in range. */
function cleanConfig(raw: unknown): ScoutTemplateConfig | null {
    if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
        return null
    }
    const { run_interval_minutes, run_cron_schedule, emit, tags } = raw as Record<string, unknown>
    const config: ScoutTemplateConfig = {
        ...defined('run_interval_minutes', cleanInterval(run_interval_minutes)),
        ...defined('run_cron_schedule', cleanCron(run_cron_schedule)),
        ...defined('emit', typeof emit === 'boolean' ? emit : undefined),
        ...defined('tags', cleanTags(tags)),
    }
    return Object.keys(config).length > 0 ? config : null
}

/** The skill name a link asked for, prefixed if it needs it, or empty when it isn't usable. */
function cleanScoutName(value: unknown): string {
    const name = typeof value === 'string' ? value.trim() : ''
    if (!name) {
        return ''
    }
    return validateSkillName(name) ? '' : name
}

/** The decoded payload object, or null when the value isn't one. */
function parsePayload(raw: unknown): { payload: Record<string, unknown>; stored: boolean } | null {
    if (typeof raw !== 'string' || raw.length === 0 || raw.length > MAX_ENCODED_LENGTH) {
        return null
    }
    let parsed: unknown
    try {
        if (raw.startsWith(STORED_TEMPLATE_PREFIX)) {
            const id = raw.slice(STORED_TEMPLATE_PREFIX.length)
            const key = `${STORED_TEMPLATE_KEY_PREFIX}${id}`
            const value = sessionStorage.getItem(key)
            sessionStorage.removeItem(key)
            parsed = value ? JSON.parse(value) : null
        } else {
            // Accept both base64 alphabets and missing padding, like the desktop deep-link decoder.
            const normalized = raw.replace(/-/g, '+').replace(/_/g, '/')
            const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
            parsed = JSON.parse(base64Decode(padded))
        }
    } catch {
        return null
    }
    if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
        return null
    }
    return { payload: parsed as Record<string, unknown>, stored: raw.startsWith(STORED_TEMPLATE_PREFIX) }
}

/** Decodes a `#createScout=` value into modal initial values. Null means ignore the fragment. */
export function decodeScoutCreateTemplate(raw: unknown): ScoutCreateInitialValues | null {
    const parsedResult = parsePayload(raw)
    if (!parsedResult) {
        return null
    }

    const { payload: parsed, stored } = parsedResult
    const { name, display_name: displayName, description, body, config } = parsed
    const cleanDisplayName =
        typeof displayName === 'string' ? displayName.trim().slice(0, MAX_SCOUT_DISPLAY_NAME_LENGTH) : ''
    const cleanDescription =
        typeof description === 'string' ? description.trim().slice(0, SKILL_DESCRIPTION_MAX_LENGTH) : ''
    const cleanBody = typeof body === 'string' ? (stored ? body : body.trim().slice(0, MAX_BODY_LENGTH)) : ''
    const templateConfig = cleanConfig(config)
    const initialConfig = stored ? { ...templateConfig, mcp_gateway_server_ids: [] } : templateConfig

    // A link that prefills nothing but a name is indistinguishable from noise — require substance.
    if (!cleanDescription && !cleanBody.trim()) {
        return null
    }

    return {
        ...defined('name', cleanScoutName(name) || undefined),
        ...defined('display_name', cleanDisplayName || undefined),
        ...defined('description', cleanDescription || undefined),
        ...defined('body', cleanBody || undefined),
        ...defined('config', initialConfig ?? undefined),
    }
}