diff --git a/apps/console/app/(app)/product-analytics/_components/Shell.tsx b/apps/console/app/(app)/product-analytics/_components/Shell.tsx new file mode 100644 index 00000000..4e5e02e3 --- /dev/null +++ b/apps/console/app/(app)/product-analytics/_components/Shell.tsx @@ -0,0 +1,47 @@ +"use client"; +// Frame of every product analytics screen: title, the four screens, the app +// picker, and (on live screens) a quiet refresh every 10 seconds. +import { useEffect, type ReactNode } from "react"; +import { usePathname, useRouter } from "next/navigation"; + +const SCREENS = [ + { href: "/product-analytics", label: "Events" }, + { href: "/product-analytics/persons", label: "People" }, + { href: "/product-analytics/setup", label: "Setup" }, + { href: "/product-analytics/privacy", label: "Privacy" }, +]; + +export const REFRESH_MS = 10_000; + +export function Shell({ title, apps, app, live = false, children }: { title: string; apps: string[]; app: string | null; live?: boolean; children: ReactNode }) { + const path = usePathname(); + const router = useRouter(); + useEffect(() => { + if (!live) return; + const t = setInterval(() => router.refresh(), REFRESH_MS); + return () => clearInterval(t); + }, [live, router]); + const q = app ? `?app=${encodeURIComponent(app)}` : ""; + return ( + <> +

{title}

+ + {children} + + ); +} diff --git a/apps/console/app/(app)/product-analytics/_lib/http.ts b/apps/console/app/(app)/product-analytics/_lib/http.ts new file mode 100644 index 00000000..758f0a10 --- /dev/null +++ b/apps/console/app/(app)/product-analytics/_lib/http.ts @@ -0,0 +1,119 @@ +// Server-only client for the product analytics service. Every call carries +// a fresh org token scoped to the org's own app ids. + +import { signOrgToken, type Role } from "./token.ts"; + +export interface PaConfig { + url: string; + secret: string; +} + +/** Null when the service is not connected on this deployment (the page says so). */ +export function paConfig(env: Record = process.env): PaConfig | null { + const url = env.PRODUCT_ANALYTICS_URL?.trim(); + const secret = env.PRODUCT_ANALYTICS_CONSOLE_SECRET?.trim(); + if (!url || !secret || secret.length < 32) return null; + return { url: url.replace(/\/$/, ""), secret }; +} + +export interface Scope { + org_id: string; + app_ids: string[]; + role?: Role; +} + +export class PaError extends Error { + status: number; + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +export async function paFetch(cfg: PaConfig, scope: Scope, path: string, init: RequestInit = {}, fetchImpl: typeof fetch = fetch, now = new Date()): Promise { + const token = await signOrgToken(cfg.secret, { org_id: scope.org_id, app_ids: scope.app_ids, role: scope.role ?? "owner" }, now); + const res = await fetchImpl(`${cfg.url}${path}`, { + ...init, + headers: { authorization: `Bearer ${token}`, "content-type": "application/json", ...(init.headers ?? {}) }, + cache: "no-store", + }); + const text = await res.text(); + let body: unknown = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = null; + } + if (!res.ok) { + const msg = body && typeof body === "object" && "error" in body ? String((body as { error: unknown }).error) : "Product analytics could not be reached. Try again shortly."; + throw new PaError(res.status, msg); + } + return body as T; +} + +/** Raw response (for downloads). */ +export async function paRaw(cfg: PaConfig, scope: Scope, path: string, fetchImpl: typeof fetch = fetch, now = new Date()): Promise { + const token = await signOrgToken(cfg.secret, { org_id: scope.org_id, app_ids: scope.app_ids, role: scope.role ?? "owner" }, now); + return fetchImpl(`${cfg.url}${path}`, { headers: { authorization: `Bearer ${token}` }, cache: "no-store" }); +} + +export interface AppRef { + id: string; + name: string; + site_key: string; +} + +/** The app named in `?app=` if it is the org's, else the org's first app. */ +export function pickApp(apps: AppRef[], name: string | undefined): AppRef | null { + return apps.find((a) => a.name === name) ?? apps[0] ?? null; +} + +export interface Status { + project: { id: string; name: string }; + paused: boolean; + first_event: { uuid: string; event: string; at: string } | null; + usage: { month: string; received: number; stored: number; capped: number; dropped: number }; + org_stored_this_month: number; + events_limit: number; + cap_message: string | null; + retention_days: number; +} + +export interface FeedEvent { + uuid: string; + event: string; + distinct_id: string; + timestamp: string; + url: string | null; + screen: string | null; + lib: string | null; +} + +export interface PersonRow { + id: string; + properties: Record; + is_identified: boolean; + created_at: string; + distinct_ids: string[] | null; +} + +export interface PrivacyJob { + id: string; + distinct_id: string; + requested_at: string; + due_at: string; + status: "queued" | "running" | "done" | "failed"; + finished_at: string | null; + result: Record | null; + error: string | null; +} + +export interface Settings { + require_consent: boolean; + autocapture: boolean; + capture_pageview: boolean; + flags_client_key: string | null; + retention_days: number | null; +} + +export const fmtTime = (iso: string | null | undefined) => (iso ? new Date(iso).toISOString().replace("T", " ").slice(0, 16) + " UTC" : ""); diff --git a/apps/console/app/(app)/product-analytics/_lib/token.ts b/apps/console/app/(app)/product-analytics/_lib/token.ts new file mode 100644 index 00000000..168c4bdd --- /dev/null +++ b/apps/console/app/(app)/product-analytics/_lib/token.ts @@ -0,0 +1,19 @@ +// The console's 5-minute org token for the product analytics service: +// HS256 JWT {org_id, app_ids, role, iat, exp} signed with +// PRODUCT_ANALYTICS_CONSOLE_SECRET (the service verifies it with jose). +// WebCrypto only, so it runs on Workers without a new dependency. + +import { b64url, hmacSha256 } from "../../../../lib/crypto.ts"; + +export const TOKEN_TTL_SECONDS = 300; + +export type Role = "owner" | "admin" | "member" | "viewer"; + +const enc = new TextEncoder(); +const part = (v: unknown) => b64url(enc.encode(JSON.stringify(v))); + +export async function signOrgToken(secret: string, claims: { org_id: string; app_ids: string[]; role: Role }, now: Date): Promise { + const iat = Math.floor(now.getTime() / 1000); + const head = `${part({ alg: "HS256", typ: "JWT" })}.${part({ org_id: claims.org_id, app_ids: claims.app_ids, role: claims.role, iat, exp: iat + TOKEN_TTL_SECONDS })}`; + return `${head}.${b64url(await hmacSha256(enc.encode(secret), head))}`; +} diff --git a/apps/console/app/(app)/product-analytics/page.tsx b/apps/console/app/(app)/product-analytics/page.tsx new file mode 100644 index 00000000..fc7e39f9 --- /dev/null +++ b/apps/console/app/(app)/product-analytics/page.tsx @@ -0,0 +1,107 @@ +import { currentSession } from "../../../lib/current.ts"; +import { deps } from "../../../lib/deps.ts"; +import { Shell } from "./_components/Shell.tsx"; +import { fmtTime, paConfig, paFetch, PaError, pickApp, type FeedEvent, type Status } from "./_lib/http.ts"; + +export const dynamic = "force-dynamic"; + +// Events screen: the first-event proof and the live feed of the latest +// events for one app (refreshed every 10 seconds). +export default async function ProductAnalyticsPage({ searchParams }: { searchParams: { app?: string } }) { + const s = (await currentSession())!; + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, searchParams.app); + const names = apps.map((a) => a.name); + const cfg = paConfig(); + if (!app) { + return ( + +
+

Add an app first. Its events appear here.

+ Add an app +
+
+ ); + } + if (!cfg) { + return ( + +
+

Product analytics is arriving on this deployment. Page analytics under Insights keeps working meanwhile.

+
+
+ ); + } + const scope = { org_id: s.org, app_ids: apps.map((a) => a.id) }; + let status: Status | null = null; + let feed: FeedEvent[] = []; + let problem: string | null = null; + try { + [status, { events: feed }] = await Promise.all([ + paFetch(cfg, scope, `/v1/projects/${app.id}/status`), + paFetch<{ events: FeedEvent[] }>(cfg, scope, `/v1/projects/${app.id}/events?limit=50`), + ]); + } catch (e) { + problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly."; + } + return ( + + {problem ? ( +
+

{problem}

+
+ ) : null} + {status ? ( +
+

First event

+ {status.first_event ? ( +

+ Received {status.first_event.event} at {fmtTime(status.first_event.at)}. +

+ ) : ( + <> +

Waiting for the first event from {app.name}.

+ Set up the app + + )} + {status.paused ?

This organization is paused, so new events are not stored.

: null} + {status.cap_message ?

{status.cap_message}

: null} +

+ This month: {status.usage.stored.toLocaleString("en-US")} stored, {status.usage.capped.toLocaleString("en-US")} counted over the limit. +

+
+ ) : null} + {status ? ( +
+

Latest events

+ {feed.length === 0 ? ( +

No events yet. They appear here within seconds of arriving.

+ ) : ( + + + + + + + + + + + {feed.map((e) => ( + + + + + + + ))} + +
TimeEventPersonWhere
{fmtTime(e.timestamp)}{e.event} + {e.distinct_id} + {e.screen ?? e.url ?? ""}
+ )} +
+ ) : null} +
+ ); +} diff --git a/apps/console/app/(app)/product-analytics/persons/[distinct_id]/export/route.ts b/apps/console/app/(app)/product-analytics/persons/[distinct_id]/export/route.ts new file mode 100644 index 00000000..26e56ccd --- /dev/null +++ b/apps/console/app/(app)/product-analytics/persons/[distinct_id]/export/route.ts @@ -0,0 +1,21 @@ +// Download one person's data as one JSON file (proxied from the service with +// a fresh org token; the session decides the org). +import { sessionFromRequest } from "../../../../../../lib/current.ts"; +import { deps } from "../../../../../../lib/deps.ts"; +import { paConfig, paRaw, pickApp } from "../../../_lib/http.ts"; + +export const dynamic = "force-dynamic"; + +export async function GET(req: Request, { params }: { params: { distinct_id: string } }) { + const s = await sessionFromRequest(req); + if (!s) return new Response(JSON.stringify({ error: "Sign in again." }), { status: 401, headers: { "content-type": "application/json" } }); + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, new URL(req.url).searchParams.get("app") ?? undefined); + const cfg = paConfig(); + if (!app || !cfg) return new Response(JSON.stringify({ error: "Product analytics is arriving on this deployment." }), { status: 503, headers: { "content-type": "application/json" } }); + const res = await paRaw(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons/${encodeURIComponent(decodeURIComponent(params.distinct_id))}/export`); + return new Response(res.body, { + status: res.status, + headers: { "content-type": "application/json", "content-disposition": 'attachment; filename="person-export.json"', "cache-control": "no-store" }, + }); +} diff --git a/apps/console/app/(app)/product-analytics/persons/[distinct_id]/page.tsx b/apps/console/app/(app)/product-analytics/persons/[distinct_id]/page.tsx new file mode 100644 index 00000000..9abcf46a --- /dev/null +++ b/apps/console/app/(app)/product-analytics/persons/[distinct_id]/page.tsx @@ -0,0 +1,104 @@ +import { redirect } from "next/navigation"; +import { currentSession } from "../../../../../lib/current.ts"; +import { deps } from "../../../../../lib/deps.ts"; +import { Shell } from "../../_components/Shell.tsx"; +import { fmtTime, paConfig, paFetch, PaError, pickApp, type PersonRow } from "../../_lib/http.ts"; + +export const dynamic = "force-dynamic"; + +interface Detail { + person: PersonRow; + distinct_ids: string[]; + events: { uuid: string; event: string; timestamp: string; url: string | null }[]; + event_count: number; +} + +async function requestDeletion(form: FormData) { + "use server"; + const s = await currentSession(); + if (!s) redirect("/"); + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, String(form.get("app") ?? "")); + const cfg = paConfig(); + const id = String(form.get("distinct_id") ?? ""); + if (!app || !cfg || !id) redirect("/product-analytics/privacy"); + await paFetch(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons/${encodeURIComponent(id)}/delete`, { method: "POST" }); + redirect(`/product-analytics/privacy?app=${encodeURIComponent(app.name)}`); +} + +// One person: their ids, properties and latest events; export or delete. +export default async function PersonPage({ params, searchParams }: { params: { distinct_id: string }; searchParams: { app?: string } }) { + const s = (await currentSession())!; + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, searchParams.app); + const cfg = paConfig(); + const distinctId = decodeURIComponent(params.distinct_id); + let detail: Detail | null = null; + let problem: string | null = null; + if (app && cfg) { + try { + detail = await paFetch(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons/${encodeURIComponent(distinctId)}`); + } catch (e) { + problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly."; + } + } + const q = app ? `?app=${encodeURIComponent(app.name)}` : ""; + return ( + a.name)} app={app?.name ?? null}> + {problem ? ( +
+

{problem}

+
+ ) : null} + {detail ? ( + <> +
+

{distinctId}

+

+ Also known as: {detail.distinct_ids.filter((d) => d !== distinctId).join(", ") || "no other ids"}. {detail.event_count.toLocaleString("en-US")} events. +

+ + + {Object.entries(detail.person.properties) + .filter(([k]) => !k.startsWith("$initial_")) + .slice(0, 40) + .map(([k, v]) => ( + + + + + ))} + +
{k}{typeof v === "string" ? v : JSON.stringify(v)}
+
+
+

Latest events

+ + + {detail.events.map((e) => ( + + + + + + ))} + +
{fmtTime(e.timestamp)}{e.event}{e.url ?? ""}
+
+
+

Privacy

+
+ Download their data +
+ + + +
+
+

Deleting removes their events, ids and properties. The Privacy screen shows the request until it is done.

+
+ + ) : null} +
+ ); +} diff --git a/apps/console/app/(app)/product-analytics/persons/page.tsx b/apps/console/app/(app)/product-analytics/persons/page.tsx new file mode 100644 index 00000000..4ec16f19 --- /dev/null +++ b/apps/console/app/(app)/product-analytics/persons/page.tsx @@ -0,0 +1,68 @@ +import { currentSession } from "../../../../lib/current.ts"; +import { deps } from "../../../../lib/deps.ts"; +import { Shell } from "../_components/Shell.tsx"; +import { fmtTime, paConfig, paFetch, PaError, pickApp, type PersonRow } from "../_lib/http.ts"; + +export const dynamic = "force-dynamic"; + +// People: find one person by id, email or name. +export default async function PersonsPage({ searchParams }: { searchParams: { app?: string; q?: string } }) { + const s = (await currentSession())!; + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, searchParams.app); + const cfg = paConfig(); + const q = (searchParams.q ?? "").slice(0, 200); + let persons: PersonRow[] = []; + let problem: string | null = null; + if (app && cfg) { + try { + ({ persons } = await paFetch<{ persons: PersonRow[] }>(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/persons?limit=50&search=${encodeURIComponent(q)}`)); + } catch (e) { + problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly."; + } + } + return ( + a.name)} app={app?.name ?? null}> +
+
+ {app ? : null} + + +
+
+
+ {!app ?

Add an app first.

: null} + {app && !cfg ?

Product analytics is arriving on this deployment.

: null} + {problem ?

{problem}

: null} + {app && cfg && !problem && persons.length === 0 ?

{q ? "Nobody matches that." : "No people yet. A person appears with their first event."}

: null} + {persons.length ? ( + + + + + + + + + + + {persons.map((p) => { + const id = p.distinct_ids?.[0] ?? p.id; + return ( + + + + + + + ); + })} + +
PersonEmailSigned inFirst seen
+ {id} + {typeof p.properties.email === "string" ? p.properties.email : ""}{p.is_identified ? "Yes" : "No"}{fmtTime(p.created_at)}
+ ) : null} +
+
+ ); +} diff --git a/apps/console/app/(app)/product-analytics/privacy/page.tsx b/apps/console/app/(app)/product-analytics/privacy/page.tsx new file mode 100644 index 00000000..3bf67a40 --- /dev/null +++ b/apps/console/app/(app)/product-analytics/privacy/page.tsx @@ -0,0 +1,78 @@ +import { currentSession } from "../../../../lib/current.ts"; +import { deps } from "../../../../lib/deps.ts"; +import { Shell } from "../_components/Shell.tsx"; +import { fmtTime, paConfig, paFetch, PaError, pickApp, type PrivacyJob, type Status } from "../_lib/http.ts"; + +export const dynamic = "force-dynamic"; + +const STATUS_WORDS: Record = { + queued: "Waiting", + running: "Deleting now", + done: "Deleted", + failed: "Could not finish; retry from the person's page", +}; + +// Privacy: what is kept, for how long, and every deletion request. +export default async function PrivacyPage({ searchParams }: { searchParams: { app?: string } }) { + const s = (await currentSession())!; + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, searchParams.app); + const cfg = paConfig(); + let jobs: PrivacyJob[] = []; + let status: Status | null = null; + let problem: string | null = null; + if (app && cfg) { + const scope = { org_id: s.org, app_ids: apps.map((a) => a.id) }; + try { + [{ jobs }, status] = await Promise.all([ + paFetch<{ jobs: PrivacyJob[] }>(cfg, scope, `/v1/projects/${app.id}/privacy/jobs`), + paFetch(cfg, scope, `/v1/projects/${app.id}/status`), + ]); + } catch (e) { + problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly."; + } + } + const pending = jobs.some((j) => j.status === "queued" || j.status === "running"); + return ( + a.name)} app={app?.name ?? null} live={pending}> +
+

What is kept

+
    +
  • No IP address is stored or logged. The country comes from the network edge.
  • +
  • Nothing is sent from a visitor's device before they agree, unless you turn that off in Setup.
  • + {status ?
  • Events are kept {status.retention_days} days, then removed.
  • : null} +
  • A person can be deleted or exported from their page under People.
  • +
+
+
+

Deletion requests

+ {problem ?

{problem}

: null} + {!problem && jobs.length === 0 ?

No requests yet.

: null} + {jobs.length ? ( + + + + + + + + + + + + {jobs.map((j) => ( + + + + + + + + ))} + +
PersonAskedDue byStatusFinished
{j.distinct_id}{fmtTime(j.requested_at)}{fmtTime(j.due_at)}{STATUS_WORDS[j.status]}{j.finished_at ? `${fmtTime(j.finished_at)} (${j.result?.events ?? 0} events)` : ""}
+ ) : null} +
+
+ ); +} diff --git a/apps/console/app/(app)/product-analytics/setup/page.tsx b/apps/console/app/(app)/product-analytics/setup/page.tsx new file mode 100644 index 00000000..61baf818 --- /dev/null +++ b/apps/console/app/(app)/product-analytics/setup/page.tsx @@ -0,0 +1,122 @@ +import { redirect } from "next/navigation"; +import { currentSession } from "../../../../lib/current.ts"; +import { deps } from "../../../../lib/deps.ts"; +import { Shell } from "../_components/Shell.tsx"; +import { fmtTime, paConfig, paFetch, PaError, pickApp, type Settings, type Status } from "../_lib/http.ts"; + +export const dynamic = "force-dynamic"; + +const HOST_DEFAULT = "https://pa.railyard.ereboslab.com"; + +async function saveSettings(form: FormData) { + "use server"; + const s = await currentSession(); + if (!s) redirect("/"); + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, String(form.get("app") ?? "")); + const cfg = paConfig(); + if (!app || !cfg) redirect("/product-analytics/setup"); + const key = String(form.get("flags_client_key") ?? "").trim(); + await paFetch(cfg, { org_id: s.org, app_ids: apps.map((a) => a.id) }, `/v1/projects/${app.id}/settings`, { + method: "PUT", + body: JSON.stringify({ + require_consent: form.get("require_consent") === "on", + autocapture: form.get("autocapture") === "on", + capture_pageview: form.get("capture_pageview") === "on", + flags_client_key: key || null, + }), + }); + redirect(`/product-analytics/setup?app=${encodeURIComponent(app.name)}&saved=1`); +} + +// Setup: the two lines the app needs, then proof that its first event arrived. +export default async function SetupPage({ searchParams }: { searchParams: { app?: string; saved?: string } }) { + const s = (await currentSession())!; + const apps = await deps().repo.listApps(s.org); + const app = pickApp(apps, searchParams.app); + const cfg = paConfig(); + const host = process.env.PRODUCT_ANALYTICS_PUBLIC_URL?.trim() || HOST_DEFAULT; + let status: Status | null = null; + let settings: Settings | null = null; + let problem: string | null = null; + if (app && cfg) { + const scope = { org_id: s.org, app_ids: apps.map((a) => a.id) }; + try { + [status, { settings }] = await Promise.all([ + paFetch(cfg, scope, `/v1/projects/${app.id}/status`), + paFetch<{ settings: Settings }>(cfg, scope, `/v1/projects/${app.id}/settings`), + ]); + } catch (e) { + problem = e instanceof PaError ? e.message : "Product analytics could not be reached. Try again shortly."; + } + } + return ( + a.name)} app={app?.name ?? null} live={!!status && !status.first_event}> + {!app ? ( +
+

Add an app first.

+ Add an app +
+ ) : ( + <> +
+

1. Add the package

+
+              npm install @railyard/analytics-js
+            
+

Scribase projects already have these lines after scribase add analytics.

+
+              {`NEXT_PUBLIC_ANALYTICS_SITE=${app.site_key}\nNEXT_PUBLIC_ANALYTICS_HOST=${host}`}
+            
+

Expo uses EXPO_PUBLIC_ and Vite uses VITE_ in front of the same names.

+
+
+

2. Send the first event

+
+              {`import { createAnalytics } from "@railyard/analytics-js";\n\nconst analytics = createAnalytics();\nanalytics.setConsent("granted"); // from your consent banner\nanalytics.capture("signed_up");`}
+            
+ {problem ?

{problem}

: null} + {!cfg ?

Product analytics is arriving on this deployment.

: null} + {status?.first_event ? ( +

+ Done: {status.first_event.event} arrived at {fmtTime(status.first_event.at)}. +

+ ) : status ? ( +

Waiting for the first event. This screen checks every 10 seconds.

+ ) : null} +
+ {settings ? ( +
+

Settings

+ {searchParams.saved ?

Saved.

: null} +
+ +

+ +

+

+ +

+

+ +

+

+ +

+ +
+
+ ) : null} + + )} +
+ ); +} diff --git a/apps/console/components/Nav.tsx b/apps/console/components/Nav.tsx index 83a9f166..30b131d6 100644 --- a/apps/console/components/Nav.tsx +++ b/apps/console/components/Nav.tsx @@ -5,6 +5,7 @@ import { SignOutIcon } from "./Icons.tsx"; const LINKS = [ { href: "/apps", label: "Apps" }, { href: "/insights", label: "Insights" }, + { href: "/product-analytics", label: "Product analytics" }, { href: "/usage", label: "Usage" }, { href: "/billing", label: "Billing" }, ];