@littlefriend/cli 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -2
- package/dist/index.js +904 -719
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -131,7 +131,7 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
|
131
131
|
import { createServer } from "node:http";
|
|
132
132
|
|
|
133
133
|
// src/version.ts
|
|
134
|
-
var VERSION = "0.1.
|
|
134
|
+
var VERSION = "0.1.5";
|
|
135
135
|
var USER_AGENT = `littlefriend-cli/${VERSION}`;
|
|
136
136
|
|
|
137
137
|
// src/oauth.ts
|
|
@@ -631,145 +631,622 @@ var Api = class {
|
|
|
631
631
|
}
|
|
632
632
|
};
|
|
633
633
|
|
|
634
|
-
//
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
634
|
+
// ../contract/dist/actors.js
|
|
635
|
+
var ACTOR_CLASS_LABELS = {
|
|
636
|
+
browser: "Interactive browser",
|
|
637
|
+
search_crawler: "Search crawler",
|
|
638
|
+
ai_crawler: "AI crawler",
|
|
639
|
+
ai_agent: "User-directed AI agent",
|
|
640
|
+
monitor: "Uptime and monitoring",
|
|
641
|
+
preview: "Link preview",
|
|
642
|
+
automation: "Suspected automation",
|
|
643
|
+
unknown: "Unknown"
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
// ../contract/dist/limits.js
|
|
647
|
+
var LIMITS = {
|
|
648
|
+
/** Max request body accepted by the collector, in bytes (before decompression). */
|
|
649
|
+
maxBodyBytes: 16 * 1024,
|
|
650
|
+
/** Max events in one batch. */
|
|
651
|
+
maxEventsPerBatch: 50,
|
|
652
|
+
/** Max custom properties on one event. */
|
|
653
|
+
maxProps: 8,
|
|
654
|
+
maxPropKeyLength: 32,
|
|
655
|
+
maxPropStringLength: 64,
|
|
656
|
+
maxEventNameLength: 64,
|
|
657
|
+
maxRouteLength: 256,
|
|
658
|
+
maxHostLength: 253,
|
|
659
|
+
maxCampaignValueLength: 64,
|
|
660
|
+
/** Events observed further in the past than this are rejected as stale. */
|
|
661
|
+
maxPastSkewMs: 24 * 60 * 60 * 1e3,
|
|
662
|
+
/** Events observed further in the future than this are rejected as clock skew. */
|
|
663
|
+
maxFutureSkewMs: 10 * 60 * 1e3,
|
|
664
|
+
/** Browser SDK flush triggers. */
|
|
665
|
+
browserFlushEvents: 10,
|
|
666
|
+
browserFlushMs: 5e3,
|
|
667
|
+
/** Browser SDK bounded pending queue, in bytes of serialized events. */
|
|
668
|
+
browserMaxPendingBytes: 64 * 1024,
|
|
669
|
+
/** Journey sessions: inactivity timeout and hard lifetime. */
|
|
670
|
+
sessionIdleMs: 30 * 60 * 1e3,
|
|
671
|
+
sessionMaxMs: 24 * 60 * 60 * 1e3
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
// ../contract/dist/apps.js
|
|
675
|
+
var PLATFORMS = ["web", "ios", "macos", "android"];
|
|
676
|
+
var APP_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+)+$/;
|
|
677
|
+
var APP_ID_MAX = 155;
|
|
678
|
+
function validAppId(id) {
|
|
679
|
+
return typeof id === "string" && id.length <= APP_ID_MAX && APP_ID_RE.test(id);
|
|
680
|
+
}
|
|
681
|
+
function normalizeAppId(id) {
|
|
682
|
+
return validAppId(id) ? id.toLowerCase() : null;
|
|
683
|
+
}
|
|
684
|
+
var UTM_FIELDS = [
|
|
685
|
+
["utm_source", "s"],
|
|
686
|
+
["utm_medium", "m"],
|
|
687
|
+
["utm_campaign", "c"]
|
|
688
|
+
];
|
|
689
|
+
var UTM_EXTENDED_FIELDS = [
|
|
690
|
+
...UTM_FIELDS,
|
|
691
|
+
["utm_term", "t"],
|
|
692
|
+
["utm_content", "n"]
|
|
693
|
+
];
|
|
694
|
+
|
|
695
|
+
// ../contract/dist/channels.js
|
|
696
|
+
var AI_ASSISTANT_HOSTS = [
|
|
697
|
+
{ host: "chatgpt.com", label: "ChatGPT", operator: "OpenAI" },
|
|
698
|
+
{ host: "chat.openai.com", label: "ChatGPT", operator: "OpenAI" },
|
|
699
|
+
{ host: "perplexity.ai", label: "Perplexity", operator: "Perplexity" },
|
|
700
|
+
{ host: "claude.ai", label: "Claude", operator: "Anthropic" },
|
|
701
|
+
{ host: "gemini.google.com", label: "Gemini", operator: "Google" },
|
|
702
|
+
{ host: "copilot.microsoft.com", label: "Microsoft Copilot", operator: "Microsoft" },
|
|
703
|
+
{ host: "you.com", label: "You.com", operator: "You.com" },
|
|
704
|
+
{ host: "phind.com", label: "Phind", operator: "Phind" }
|
|
705
|
+
];
|
|
706
|
+
|
|
707
|
+
// ../contract/dist/flows.js
|
|
708
|
+
var FLOW_START_DEFINITIONS = [
|
|
709
|
+
{
|
|
710
|
+
key: "flow_step",
|
|
711
|
+
label: "Step",
|
|
712
|
+
definition: "Page views in a row of the same page type (or the same page) are one step. A goal is a step of its own, right after the page where it happened. Anything before the first page view is left out."
|
|
713
|
+
},
|
|
714
|
+
{
|
|
715
|
+
key: "flow_start_sessions",
|
|
716
|
+
label: "Sessions",
|
|
717
|
+
definition: "Journey sessions that started in the range and whose first step is this one. Sessions are not people."
|
|
718
|
+
},
|
|
719
|
+
{
|
|
720
|
+
key: "flow_start_share",
|
|
721
|
+
label: "Share",
|
|
722
|
+
definition: "These sessions divided by all sessions with a step."
|
|
723
|
+
},
|
|
724
|
+
{ key: "flow_went_on", label: "Went on", definition: "Of these sessions, the share with a second step." },
|
|
725
|
+
{
|
|
726
|
+
key: "flow_converted",
|
|
727
|
+
label: "Converted",
|
|
728
|
+
definition: "Of these sessions, the share that reached at least one goal."
|
|
665
729
|
}
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
730
|
+
];
|
|
731
|
+
var FLOW_DEFINITIONS = [
|
|
732
|
+
FLOW_START_DEFINITIONS[0],
|
|
733
|
+
{
|
|
734
|
+
key: "flow_node",
|
|
735
|
+
label: "Sessions at a step",
|
|
736
|
+
definition: "Sessions that started at the starting point and reached this step in this position. The count after it is the page views merged into the step: pages when grouped by type, views when grouped by page."
|
|
737
|
+
},
|
|
738
|
+
{ key: "flow_left", label: "Left", definition: "The session had no more steps and has ended." },
|
|
739
|
+
{
|
|
740
|
+
key: "flow_browsing",
|
|
741
|
+
label: "Still browsing",
|
|
742
|
+
definition: "The session has no more steps yet but has not ended, so it may continue. A session ends after 30 idle minutes."
|
|
743
|
+
},
|
|
744
|
+
{
|
|
745
|
+
key: "flow_other",
|
|
746
|
+
label: "Other",
|
|
747
|
+
definition: "Pages beyond the busiest ones in that step, together. Their links are merged too."
|
|
748
|
+
},
|
|
749
|
+
{
|
|
750
|
+
key: "flow_continued",
|
|
751
|
+
label: "Continued",
|
|
752
|
+
definition: "In the last column: sessions with more steps than the chart shows."
|
|
673
753
|
}
|
|
674
|
-
|
|
675
|
-
}
|
|
676
|
-
function joinList(items, word) {
|
|
677
|
-
if (items.length <= 1) return items.join("");
|
|
678
|
-
return `${items.slice(0, -1).join(", ")} ${word} ${items[items.length - 1]}`;
|
|
679
|
-
}
|
|
680
|
-
var orList = (items) => joinList(items, "or");
|
|
681
|
-
var andList = (items) => joinList(items, "and");
|
|
682
|
-
function requireYes(ctx, what) {
|
|
683
|
-
if (!flag(ctx, "yes")) throw usageError(`This ${what}. Add --yes to confirm.`);
|
|
684
|
-
}
|
|
685
|
-
var YES = { yes: { type: "boolean" } };
|
|
686
|
-
function arg(ctx, index, what) {
|
|
687
|
-
const v = ctx.args[index];
|
|
688
|
-
if (!v) throw usageError(`Missing ${what}.`);
|
|
689
|
-
return v;
|
|
690
|
-
}
|
|
691
|
-
var enc = encodeURIComponent;
|
|
754
|
+
];
|
|
692
755
|
|
|
693
|
-
//
|
|
694
|
-
function
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
}
|
|
706
|
-
function fields(pairs) {
|
|
707
|
-
const width = Math.max(...pairs.map(([k]) => k.length));
|
|
708
|
-
return pairs.map(([k, v]) => `${`${k}:`.padEnd(width + 2)}${cell(v)}`.trimEnd()).join("\n");
|
|
709
|
-
}
|
|
710
|
-
function when(iso) {
|
|
711
|
-
if (!iso) return "";
|
|
712
|
-
const d = new Date(iso);
|
|
713
|
-
if (Number.isNaN(d.getTime())) return iso;
|
|
714
|
-
return `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
715
|
-
}
|
|
716
|
-
function count(n) {
|
|
717
|
-
return typeof n === "number" && Number.isFinite(n) ? n.toLocaleString("en-US") : "";
|
|
718
|
-
}
|
|
719
|
-
function percent(fraction) {
|
|
720
|
-
if (typeof fraction !== "number" || !Number.isFinite(fraction)) return "";
|
|
721
|
-
return `${(fraction * 100).toFixed(1).replace(/\.0$/, "")}%`;
|
|
722
|
-
}
|
|
723
|
-
function duration(ms) {
|
|
724
|
-
if (typeof ms !== "number" || !Number.isFinite(ms)) return "";
|
|
725
|
-
const s = Math.round(ms / 1e3);
|
|
726
|
-
if (s < 60) return `${s}s`;
|
|
727
|
-
return `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
|
|
728
|
-
}
|
|
729
|
-
function lines(...parts) {
|
|
730
|
-
return parts.filter((p) => typeof p === "string").join("\n");
|
|
731
|
-
}
|
|
732
|
-
function plural(n, one, many2 = `${one}s`) {
|
|
733
|
-
return `${n} ${n === 1 ? one : many2}`;
|
|
756
|
+
// ../contract/dist/kya.js
|
|
757
|
+
function principalRank(level) {
|
|
758
|
+
switch (level) {
|
|
759
|
+
case "none":
|
|
760
|
+
return 0;
|
|
761
|
+
case "user_initiated":
|
|
762
|
+
return 1;
|
|
763
|
+
case "signed_user":
|
|
764
|
+
return 2;
|
|
765
|
+
default:
|
|
766
|
+
return 3;
|
|
767
|
+
}
|
|
734
768
|
}
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
769
|
+
var SIGNED_USER_TAGS = ["agent-browser-auth", "agent-payer-auth"];
|
|
770
|
+
function evidenceRank(evidence) {
|
|
771
|
+
switch (evidence) {
|
|
772
|
+
case "none":
|
|
773
|
+
return 0;
|
|
774
|
+
case "self_declared":
|
|
775
|
+
return 1;
|
|
776
|
+
case "network_verified":
|
|
777
|
+
return 2;
|
|
778
|
+
default:
|
|
779
|
+
return 3;
|
|
780
|
+
}
|
|
740
781
|
}
|
|
741
|
-
|
|
742
|
-
|
|
782
|
+
var lower = (s) => s.toLowerCase();
|
|
783
|
+
function pathMatches(path, prefix) {
|
|
784
|
+
if (prefix === "/")
|
|
785
|
+
return true;
|
|
786
|
+
const p = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
|
|
787
|
+
return path === p || path.startsWith(`${p}/`);
|
|
743
788
|
}
|
|
744
|
-
function
|
|
745
|
-
|
|
789
|
+
function doorRuleMatches(match, facts) {
|
|
790
|
+
if (match.classes && !match.classes.includes(facts.class))
|
|
791
|
+
return false;
|
|
792
|
+
if (match.purposes && !match.purposes.includes(facts.purpose))
|
|
793
|
+
return false;
|
|
794
|
+
if (match.operators && !(facts.operator && match.operators.map(lower).includes(lower(facts.operator))))
|
|
795
|
+
return false;
|
|
796
|
+
if (match.products && !(facts.product && match.products.map(lower).includes(lower(facts.product))))
|
|
797
|
+
return false;
|
|
798
|
+
if (match.evidenceBelow && !(evidenceRank(facts.evidence) < evidenceRank(match.evidenceBelow)))
|
|
799
|
+
return false;
|
|
800
|
+
if (match.principalBelow && !(principalRank(facts.principal) < principalRank(match.principalBelow)))
|
|
801
|
+
return false;
|
|
802
|
+
if (match.spoofed !== void 0 && match.spoofed !== facts.spoofed)
|
|
803
|
+
return false;
|
|
804
|
+
if (match.paths && !match.paths.some((p) => pathMatches(facts.path, p)))
|
|
805
|
+
return false;
|
|
806
|
+
if (match.methods && !match.methods.map(lower).includes(lower(facts.method)))
|
|
807
|
+
return false;
|
|
808
|
+
return true;
|
|
746
809
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
if (
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
`You belong to ${all.length} workspaces. Pass --workspace <id|slug|name>:
|
|
755
|
-
${describeWorkspaces(all)}`
|
|
756
|
-
);
|
|
757
|
-
}
|
|
758
|
-
const lower3 = ref.toLowerCase();
|
|
759
|
-
const found = all.find((w) => w.id === ref) ?? all.find((w) => w.slug === lower3) ?? all.filter((w) => w.name.toLowerCase() === lower3);
|
|
760
|
-
if (Array.isArray(found)) {
|
|
761
|
-
if (found.length === 1) return found[0];
|
|
762
|
-
if (found.length > 1) {
|
|
763
|
-
throw usageError(`More than one workspace is named ${ref}. Use its id:
|
|
764
|
-
${describeWorkspaces(found)}`);
|
|
765
|
-
}
|
|
766
|
-
throw new CliError(
|
|
767
|
-
`No workspace matches ${ref}. Your workspaces:
|
|
768
|
-
${describeWorkspaces(all)}`,
|
|
769
|
-
"WORKSPACE_NOT_FOUND"
|
|
770
|
-
);
|
|
810
|
+
function evaluateDoor(policy, facts) {
|
|
811
|
+
if (!policy || facts.class === "browser")
|
|
812
|
+
return { action: "allow", ruleId: null };
|
|
813
|
+
for (const rule of policy.rules) {
|
|
814
|
+
if (!doorRuleMatches(rule.match, facts))
|
|
815
|
+
continue;
|
|
816
|
+
return rule.action === "limit" && rule.limit ? { action: "limit", ruleId: rule.id, limit: rule.limit } : { action: rule.action, ruleId: rule.id };
|
|
771
817
|
}
|
|
772
|
-
return
|
|
818
|
+
return { action: "allow", ruleId: null };
|
|
819
|
+
}
|
|
820
|
+
var DOOR_PRESET_NAMES = [
|
|
821
|
+
"open",
|
|
822
|
+
"no_training",
|
|
823
|
+
"verified_only",
|
|
824
|
+
"commerce"
|
|
825
|
+
];
|
|
826
|
+
var AGENT_CLASSES = [
|
|
827
|
+
"search_crawler",
|
|
828
|
+
"ai_crawler",
|
|
829
|
+
"ai_agent",
|
|
830
|
+
"monitor",
|
|
831
|
+
"preview",
|
|
832
|
+
"automation",
|
|
833
|
+
"unknown"
|
|
834
|
+
];
|
|
835
|
+
var BLOCK_SPOOFED = {
|
|
836
|
+
id: "spoofed",
|
|
837
|
+
label: "Block agents that fail their operator check",
|
|
838
|
+
match: { spoofed: true },
|
|
839
|
+
action: "block"
|
|
840
|
+
};
|
|
841
|
+
var DOOR_PRESETS = {
|
|
842
|
+
open: [],
|
|
843
|
+
no_training: [
|
|
844
|
+
{
|
|
845
|
+
id: "no-training",
|
|
846
|
+
label: "Block AI training crawlers",
|
|
847
|
+
match: { purposes: ["ai_training"] },
|
|
848
|
+
action: "block"
|
|
849
|
+
}
|
|
850
|
+
],
|
|
851
|
+
verified_only: [
|
|
852
|
+
BLOCK_SPOOFED,
|
|
853
|
+
{
|
|
854
|
+
id: "unverified",
|
|
855
|
+
label: "Slow down agents that are not verified",
|
|
856
|
+
match: { classes: AGENT_CLASSES, evidenceBelow: "network_verified" },
|
|
857
|
+
action: "limit",
|
|
858
|
+
limit: { perMinute: 60, burst: 20 }
|
|
859
|
+
}
|
|
860
|
+
],
|
|
861
|
+
commerce: [
|
|
862
|
+
BLOCK_SPOOFED,
|
|
863
|
+
{
|
|
864
|
+
id: "checkout",
|
|
865
|
+
label: "Checkout and accounts need an agent acting for a signed-in user",
|
|
866
|
+
match: {
|
|
867
|
+
// Not `unknown`: a person whose browser does not look like one must still reach checkout.
|
|
868
|
+
classes: ["ai_agent", "automation"],
|
|
869
|
+
paths: ["/checkout", "/cart", "/account"],
|
|
870
|
+
principalBelow: "signed_user"
|
|
871
|
+
},
|
|
872
|
+
action: "require_signature"
|
|
873
|
+
}
|
|
874
|
+
]
|
|
875
|
+
};
|
|
876
|
+
|
|
877
|
+
// ../contract/dist/origins.js
|
|
878
|
+
var REFUSED_ORIGIN_SCHEMES = [
|
|
879
|
+
// Script and inline content.
|
|
880
|
+
"javascript",
|
|
881
|
+
"vbscript",
|
|
882
|
+
"data",
|
|
883
|
+
"blob",
|
|
884
|
+
"filesystem",
|
|
885
|
+
// Files and blank pages, which send `Origin: null`.
|
|
886
|
+
"file",
|
|
887
|
+
"about",
|
|
888
|
+
"content",
|
|
889
|
+
// Browser pages and extensions.
|
|
890
|
+
"chrome",
|
|
891
|
+
"chrome-extension",
|
|
892
|
+
"chrome-untrusted",
|
|
893
|
+
"chrome-search",
|
|
894
|
+
"devtools",
|
|
895
|
+
"edge",
|
|
896
|
+
"brave",
|
|
897
|
+
"opera",
|
|
898
|
+
"vivaldi",
|
|
899
|
+
"view-source",
|
|
900
|
+
"resource",
|
|
901
|
+
"moz-extension",
|
|
902
|
+
"safari-extension",
|
|
903
|
+
"safari-web-extension",
|
|
904
|
+
"ms-browser-extension",
|
|
905
|
+
// Protocols that are never a page.
|
|
906
|
+
"ftp",
|
|
907
|
+
"ws",
|
|
908
|
+
"wss",
|
|
909
|
+
"mailto",
|
|
910
|
+
"tel",
|
|
911
|
+
"sms",
|
|
912
|
+
"intent",
|
|
913
|
+
"market"
|
|
914
|
+
];
|
|
915
|
+
var REFUSED = new Set(REFUSED_ORIGIN_SCHEMES);
|
|
916
|
+
|
|
917
|
+
// ../contract/dist/referrers.js
|
|
918
|
+
var ANDROID_APP_HOSTS = Object.freeze({
|
|
919
|
+
"com.google.android.gm": "mail.google.com",
|
|
920
|
+
"com.microsoft.office.outlook": "outlook.live.com",
|
|
921
|
+
"com.yahoo.mobile.client.android.mail": "mail.yahoo.com",
|
|
922
|
+
"ch.protonmail.android": "mail.proton.me",
|
|
923
|
+
"com.google.android.googlequicksearchbox": "google.com",
|
|
924
|
+
"com.linkedin.android": "linkedin.com",
|
|
925
|
+
"com.facebook.katana": "facebook.com",
|
|
926
|
+
"com.facebook.orca": "facebook.com",
|
|
927
|
+
"com.facebook.lite": "facebook.com",
|
|
928
|
+
"com.instagram.android": "instagram.com",
|
|
929
|
+
"com.instagram.barcelona": "threads.net",
|
|
930
|
+
"com.twitter.android": "x.com",
|
|
931
|
+
"com.reddit.frontpage": "reddit.com",
|
|
932
|
+
"com.google.android.youtube": "youtube.com",
|
|
933
|
+
"com.zhiliaoapp.musically": "tiktok.com",
|
|
934
|
+
"xyz.blueskyweb.app": "bsky.app",
|
|
935
|
+
"com.pinterest": "pinterest.com",
|
|
936
|
+
"com.slack": "slack.com",
|
|
937
|
+
"com.discord": "discord.com",
|
|
938
|
+
"org.telegram.messenger": "t.me",
|
|
939
|
+
"com.whatsapp": "whatsapp.com",
|
|
940
|
+
"com.openai.chatgpt": "chatgpt.com",
|
|
941
|
+
"ai.perplexity.app.android": "perplexity.ai",
|
|
942
|
+
"com.anthropic.claude": "claude.ai",
|
|
943
|
+
"com.google.android.apps.bard": "gemini.google.com",
|
|
944
|
+
"com.microsoft.copilot": "copilot.microsoft.com"
|
|
945
|
+
});
|
|
946
|
+
|
|
947
|
+
// ../contract/dist/replay.js
|
|
948
|
+
var REPLAY_MASK_CHAR = "\u2588";
|
|
949
|
+
var REPLAY_ALWAYS_BLOCKED = [
|
|
950
|
+
"img",
|
|
951
|
+
"picture",
|
|
952
|
+
"video",
|
|
953
|
+
"audio",
|
|
954
|
+
"iframe",
|
|
955
|
+
"object",
|
|
956
|
+
"embed",
|
|
957
|
+
"canvas",
|
|
958
|
+
"svg image"
|
|
959
|
+
];
|
|
960
|
+
var REPLAY_KEPT_ATTRIBUTES = [
|
|
961
|
+
"class",
|
|
962
|
+
"id",
|
|
963
|
+
"style",
|
|
964
|
+
"role",
|
|
965
|
+
"type",
|
|
966
|
+
"name",
|
|
967
|
+
"for",
|
|
968
|
+
"rel",
|
|
969
|
+
"media",
|
|
970
|
+
"href",
|
|
971
|
+
"width",
|
|
972
|
+
"height",
|
|
973
|
+
"colspan",
|
|
974
|
+
"rowspan",
|
|
975
|
+
"dir",
|
|
976
|
+
"lang",
|
|
977
|
+
"hidden",
|
|
978
|
+
"open",
|
|
979
|
+
"disabled",
|
|
980
|
+
"readonly",
|
|
981
|
+
"multiple",
|
|
982
|
+
"viewbox",
|
|
983
|
+
"d",
|
|
984
|
+
"fill",
|
|
985
|
+
"stroke",
|
|
986
|
+
"stroke-width",
|
|
987
|
+
"points",
|
|
988
|
+
"x",
|
|
989
|
+
"y",
|
|
990
|
+
"cx",
|
|
991
|
+
"cy",
|
|
992
|
+
"r",
|
|
993
|
+
"rx",
|
|
994
|
+
"ry",
|
|
995
|
+
"transform",
|
|
996
|
+
"aria-hidden",
|
|
997
|
+
"aria-expanded",
|
|
998
|
+
"aria-current",
|
|
999
|
+
"aria-disabled",
|
|
1000
|
+
"aria-pressed"
|
|
1001
|
+
];
|
|
1002
|
+
var REPLAY_TEXT_ATTRIBUTES = [
|
|
1003
|
+
"title",
|
|
1004
|
+
"alt",
|
|
1005
|
+
"placeholder",
|
|
1006
|
+
"aria-label",
|
|
1007
|
+
"aria-description"
|
|
1008
|
+
];
|
|
1009
|
+
var REPLAY_UNMASK_PRESET = [
|
|
1010
|
+
"nav",
|
|
1011
|
+
"header",
|
|
1012
|
+
"footer",
|
|
1013
|
+
"h1",
|
|
1014
|
+
"h2",
|
|
1015
|
+
"h3",
|
|
1016
|
+
"h4",
|
|
1017
|
+
"button",
|
|
1018
|
+
"label",
|
|
1019
|
+
"th",
|
|
1020
|
+
"legend",
|
|
1021
|
+
"[role=button]",
|
|
1022
|
+
"[role=tab]",
|
|
1023
|
+
"[role=menuitem]"
|
|
1024
|
+
];
|
|
1025
|
+
var REPLAY_LIMITS = {
|
|
1026
|
+
/** One POST body, compressed. Keepalive requests on page hide must stay under 64 KB. */
|
|
1027
|
+
maxChunkBytes: 256 * 1024,
|
|
1028
|
+
/** One chunk after gunzip. Anything larger is refused before it is parsed. */
|
|
1029
|
+
maxChunkRawBytes: 4 * 1024 * 1024,
|
|
1030
|
+
/**
|
|
1031
|
+
* A chunk that carries a full snapshot may be larger: a heavy page's first snapshot with its
|
|
1032
|
+
* inlined stylesheets can pass maxChunkBytes on its own. Every other chunk keeps the normal limits.
|
|
1033
|
+
*/
|
|
1034
|
+
maxSnapshotChunkBytes: 1024 * 1024,
|
|
1035
|
+
maxSnapshotChunkRawBytes: 10 * 1024 * 1024,
|
|
1036
|
+
maxChunkEvents: 5e3,
|
|
1037
|
+
/** Stored bytes per session, compressed. Past it the collector answers 202 and drops. */
|
|
1038
|
+
maxSessionBytes: 12 * 1024 * 1024,
|
|
1039
|
+
/** Recorded time per page load. The recorder stops after it. */
|
|
1040
|
+
maxPageMs: 60 * 60 * 1e3,
|
|
1041
|
+
/** The recorder flushes a chunk this often, or sooner when it reaches flushBytes raw. */
|
|
1042
|
+
flushMs: 1e4,
|
|
1043
|
+
flushBytes: 128 * 1024,
|
|
1044
|
+
/** Two interactions closer than this are one stretch of activity. Longer gaps are skippable. */
|
|
1045
|
+
idleGapMs: 5e3,
|
|
1046
|
+
/** A rage click: this many clicks within rageWindowMs inside rageRadiusPx. */
|
|
1047
|
+
rageClicks: 3,
|
|
1048
|
+
rageWindowMs: 1e3,
|
|
1049
|
+
rageRadiusPx: 30,
|
|
1050
|
+
maxSelectors: 50,
|
|
1051
|
+
maxSelectorLength: 200,
|
|
1052
|
+
maxExcludeRoutes: 50,
|
|
1053
|
+
/**
|
|
1054
|
+
* A recording with at least this many clicks is kept when its session ends, whatever its
|
|
1055
|
+
* active time: a short visit of a few taps on a phone is still worth watching.
|
|
1056
|
+
*/
|
|
1057
|
+
keepWithClicks: 3,
|
|
1058
|
+
/**
|
|
1059
|
+
* Recordings a workspace may start per UTC calendar month without a card on file. The
|
|
1060
|
+
* collector and the API read REPLAY_FREE_RECORDINGS_PER_MONTH first, so both agree.
|
|
1061
|
+
*/
|
|
1062
|
+
freeRecordingsPerMonth: 10
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
// ../contract/dist/replay-sanitize.js
|
|
1066
|
+
var REPLAY_SOURCE = {
|
|
1067
|
+
Mutation: 0,
|
|
1068
|
+
MouseMove: 1,
|
|
1069
|
+
MouseInteraction: 2,
|
|
1070
|
+
Scroll: 3,
|
|
1071
|
+
ViewportResize: 4,
|
|
1072
|
+
Input: 5,
|
|
1073
|
+
TouchMove: 6,
|
|
1074
|
+
MediaInteraction: 7,
|
|
1075
|
+
StyleSheetRule: 8,
|
|
1076
|
+
CanvasMutation: 9,
|
|
1077
|
+
Font: 10,
|
|
1078
|
+
Log: 11,
|
|
1079
|
+
Drag: 12,
|
|
1080
|
+
StyleDeclaration: 13,
|
|
1081
|
+
Selection: 14,
|
|
1082
|
+
AdoptedStyleSheet: 15,
|
|
1083
|
+
CustomElement: 16
|
|
1084
|
+
};
|
|
1085
|
+
var REPLAY_MAX_SCANNED_TEXT = 32 * 1024;
|
|
1086
|
+
var MASKED_RE = new RegExp(`^[\\s${REPLAY_MASK_CHAR}]*$`, "u");
|
|
1087
|
+
var BLOCKED_TAGS = /* @__PURE__ */ new Set([
|
|
1088
|
+
...REPLAY_ALWAYS_BLOCKED.map((s) => s.split(/\s+/).pop()),
|
|
1089
|
+
"frame",
|
|
1090
|
+
"frameset",
|
|
1091
|
+
"applet",
|
|
1092
|
+
"portal",
|
|
1093
|
+
"fencedframe"
|
|
1094
|
+
]);
|
|
1095
|
+
var KEPT = new Set(REPLAY_KEPT_ATTRIBUTES);
|
|
1096
|
+
var TEXT_ATTRS = new Set(REPLAY_TEXT_ATTRIBUTES);
|
|
1097
|
+
var INTERACTION_SOURCES = /* @__PURE__ */ new Set([
|
|
1098
|
+
REPLAY_SOURCE.MouseMove,
|
|
1099
|
+
REPLAY_SOURCE.MouseInteraction,
|
|
1100
|
+
REPLAY_SOURCE.Scroll,
|
|
1101
|
+
REPLAY_SOURCE.ViewportResize,
|
|
1102
|
+
REPLAY_SOURCE.Input,
|
|
1103
|
+
REPLAY_SOURCE.TouchMove,
|
|
1104
|
+
REPLAY_SOURCE.Drag,
|
|
1105
|
+
REPLAY_SOURCE.Selection
|
|
1106
|
+
]);
|
|
1107
|
+
|
|
1108
|
+
// ../contract/dist/reports.js
|
|
1109
|
+
var FUNNEL_MAX_STEPS = 8;
|
|
1110
|
+
|
|
1111
|
+
// src/command.ts
|
|
1112
|
+
function str(ctx, name) {
|
|
1113
|
+
const v = ctx.values[name];
|
|
1114
|
+
if (Array.isArray(v)) {
|
|
1115
|
+
const last = v[v.length - 1];
|
|
1116
|
+
return typeof last === "string" ? last : void 0;
|
|
1117
|
+
}
|
|
1118
|
+
return typeof v === "string" ? v : void 0;
|
|
1119
|
+
}
|
|
1120
|
+
function flag(ctx, name) {
|
|
1121
|
+
return ctx.values[name] === true;
|
|
1122
|
+
}
|
|
1123
|
+
function many(ctx, name) {
|
|
1124
|
+
const v = ctx.values[name];
|
|
1125
|
+
if (Array.isArray(v)) return v.filter((x) => typeof x === "string");
|
|
1126
|
+
return typeof v === "string" ? [v] : [];
|
|
1127
|
+
}
|
|
1128
|
+
function has(ctx, name) {
|
|
1129
|
+
return ctx.values[name] !== void 0;
|
|
1130
|
+
}
|
|
1131
|
+
function requiredStr(ctx, name, what) {
|
|
1132
|
+
const v = str(ctx, name)?.trim();
|
|
1133
|
+
if (!v) throw usageError(`--${name} is required: ${what}.`);
|
|
1134
|
+
return v;
|
|
1135
|
+
}
|
|
1136
|
+
function intOpt(ctx, name, min, max) {
|
|
1137
|
+
const raw = str(ctx, name);
|
|
1138
|
+
if (raw === void 0) return void 0;
|
|
1139
|
+
const n = Number(raw);
|
|
1140
|
+
if (!/^-?\d+$/.test(raw.trim()) || n < min || n > max) {
|
|
1141
|
+
throw usageError(`--${name} must be a whole number from ${min} to ${max}. Got ${raw}.`);
|
|
1142
|
+
}
|
|
1143
|
+
return n;
|
|
1144
|
+
}
|
|
1145
|
+
function oneOf(ctx, name, allowed) {
|
|
1146
|
+
const raw = str(ctx, name);
|
|
1147
|
+
if (raw === void 0) return void 0;
|
|
1148
|
+
if (!allowed.includes(raw)) {
|
|
1149
|
+
throw usageError(`--${name} must be ${orList(allowed)}. Got ${raw}.`);
|
|
1150
|
+
}
|
|
1151
|
+
return raw;
|
|
1152
|
+
}
|
|
1153
|
+
function joinList(items, word) {
|
|
1154
|
+
if (items.length <= 1) return items.join("");
|
|
1155
|
+
return `${items.slice(0, -1).join(", ")} ${word} ${items[items.length - 1]}`;
|
|
1156
|
+
}
|
|
1157
|
+
var orList = (items) => joinList(items, "or");
|
|
1158
|
+
var andList = (items) => joinList(items, "and");
|
|
1159
|
+
function requireYes(ctx, what) {
|
|
1160
|
+
if (!flag(ctx, "yes")) throw usageError(`This ${what}. Add --yes to confirm.`);
|
|
1161
|
+
}
|
|
1162
|
+
var YES = { yes: { type: "boolean" } };
|
|
1163
|
+
function arg(ctx, index, what) {
|
|
1164
|
+
const v = ctx.args[index];
|
|
1165
|
+
if (!v) throw usageError(`Missing ${what}.`);
|
|
1166
|
+
return v;
|
|
1167
|
+
}
|
|
1168
|
+
var enc = encodeURIComponent;
|
|
1169
|
+
|
|
1170
|
+
// src/format.ts
|
|
1171
|
+
function cell(value) {
|
|
1172
|
+
if (value === null || value === void 0) return "";
|
|
1173
|
+
if (typeof value === "boolean") return value ? "yes" : "no";
|
|
1174
|
+
return String(value);
|
|
1175
|
+
}
|
|
1176
|
+
function table(headers, rows) {
|
|
1177
|
+
const all = [headers, ...rows.map((r) => r.map(cell))];
|
|
1178
|
+
const widths = headers.map((_, i) => Math.max(...all.map((r) => (r[i] ?? "").length)));
|
|
1179
|
+
return all.map(
|
|
1180
|
+
(r) => r.map((c, i) => i === r.length - 1 ? c : c.padEnd(widths[i] ?? 0)).join(" ").trimEnd()
|
|
1181
|
+
).join("\n");
|
|
1182
|
+
}
|
|
1183
|
+
function fields(pairs) {
|
|
1184
|
+
const width = Math.max(...pairs.map(([k]) => k.length));
|
|
1185
|
+
return pairs.map(([k, v]) => `${`${k}:`.padEnd(width + 2)}${cell(v)}`.trimEnd()).join("\n");
|
|
1186
|
+
}
|
|
1187
|
+
function when(iso) {
|
|
1188
|
+
if (!iso) return "";
|
|
1189
|
+
const d = new Date(iso);
|
|
1190
|
+
if (Number.isNaN(d.getTime())) return iso;
|
|
1191
|
+
return `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
1192
|
+
}
|
|
1193
|
+
function count(n) {
|
|
1194
|
+
return typeof n === "number" && Number.isFinite(n) ? n.toLocaleString("en-US") : "";
|
|
1195
|
+
}
|
|
1196
|
+
function percent(fraction) {
|
|
1197
|
+
if (typeof fraction !== "number" || !Number.isFinite(fraction)) return "";
|
|
1198
|
+
return `${(fraction * 100).toFixed(1).replace(/\.0$/, "")}%`;
|
|
1199
|
+
}
|
|
1200
|
+
function duration(ms) {
|
|
1201
|
+
if (typeof ms !== "number" || !Number.isFinite(ms)) return "";
|
|
1202
|
+
const s = Math.round(ms / 1e3);
|
|
1203
|
+
if (s < 60) return `${s}s`;
|
|
1204
|
+
return `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
|
|
1205
|
+
}
|
|
1206
|
+
function lines(...parts) {
|
|
1207
|
+
return parts.filter((p) => typeof p === "string").join("\n");
|
|
1208
|
+
}
|
|
1209
|
+
function plural(n, one, many2 = `${one}s`) {
|
|
1210
|
+
return `${n} ${n === 1 ? one : many2}`;
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// src/resolve.ts
|
|
1214
|
+
async function accountAndWorkspaces(ctx) {
|
|
1215
|
+
const res = await ctx.api().get("/api/workspaces");
|
|
1216
|
+
return { user: res.user ?? null, workspaces: res.workspaces ?? [] };
|
|
1217
|
+
}
|
|
1218
|
+
async function listWorkspaces(ctx) {
|
|
1219
|
+
return (await accountAndWorkspaces(ctx)).workspaces;
|
|
1220
|
+
}
|
|
1221
|
+
function describeWorkspaces(list) {
|
|
1222
|
+
return list.map((w) => ` ${w.slug} ${w.name} (${w.id})`).join("\n");
|
|
1223
|
+
}
|
|
1224
|
+
async function resolveWorkspace(ctx) {
|
|
1225
|
+
const all = await listWorkspaces(ctx);
|
|
1226
|
+
const ref = ctx.workspaceRef?.trim();
|
|
1227
|
+
if (!ref) {
|
|
1228
|
+
if (all.length === 1) return all[0];
|
|
1229
|
+
if (all.length === 0) throw new CliError("You are not a member of any workspace yet.", "NO_WORKSPACE");
|
|
1230
|
+
throw usageError(
|
|
1231
|
+
`You belong to ${all.length} workspaces. Pass --workspace <id|slug|name>:
|
|
1232
|
+
${describeWorkspaces(all)}`
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
const lower3 = ref.toLowerCase();
|
|
1236
|
+
const found = all.find((w) => w.id === ref) ?? all.find((w) => w.slug === lower3) ?? all.filter((w) => w.name.toLowerCase() === lower3);
|
|
1237
|
+
if (Array.isArray(found)) {
|
|
1238
|
+
if (found.length === 1) return found[0];
|
|
1239
|
+
if (found.length > 1) {
|
|
1240
|
+
throw usageError(`More than one workspace is named ${ref}. Use its id:
|
|
1241
|
+
${describeWorkspaces(found)}`);
|
|
1242
|
+
}
|
|
1243
|
+
throw new CliError(
|
|
1244
|
+
`No workspace matches ${ref}. Your workspaces:
|
|
1245
|
+
${describeWorkspaces(all)}`,
|
|
1246
|
+
"WORKSPACE_NOT_FOUND"
|
|
1247
|
+
);
|
|
1248
|
+
}
|
|
1249
|
+
return found;
|
|
773
1250
|
}
|
|
774
1251
|
async function listProjects(ctx, workspaceId) {
|
|
775
1252
|
const res = await ctx.api().get(`/api/workspaces/${enc(workspaceId)}/projects`);
|
|
@@ -816,15 +1293,91 @@ ${describeProjects(projects)}`
|
|
|
816
1293
|
throw usageError(`More than one project matches ${ref}. Use its id:
|
|
817
1294
|
${describeProjects(matches)}`);
|
|
818
1295
|
}
|
|
819
|
-
throw new CliError(
|
|
820
|
-
projects.length > 0 ? `No project matches ${ref}. Projects you can see:
|
|
821
|
-
${describeProjects(projects)}` : `No project matches ${ref}, and there are no projects yet.`,
|
|
822
|
-
"PROJECT_NOT_FOUND"
|
|
823
|
-
);
|
|
824
|
-
}
|
|
825
|
-
function projectPath(project, rest = "") {
|
|
826
|
-
return `/api/projects/${enc(project.id)}${rest}`;
|
|
827
|
-
}
|
|
1296
|
+
throw new CliError(
|
|
1297
|
+
projects.length > 0 ? `No project matches ${ref}. Projects you can see:
|
|
1298
|
+
${describeProjects(projects)}` : `No project matches ${ref}, and there are no projects yet.`,
|
|
1299
|
+
"PROJECT_NOT_FOUND"
|
|
1300
|
+
);
|
|
1301
|
+
}
|
|
1302
|
+
function projectPath(project, rest = "") {
|
|
1303
|
+
return `/api/projects/${enc(project.id)}${rest}`;
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
// src/commands/apps.ts
|
|
1307
|
+
var APP_ID_HINT = "Use the app's bundle id or package name, like com.acme.shop.";
|
|
1308
|
+
var appsOf = (p) => [...p.allowedApps ?? []];
|
|
1309
|
+
function listText(project, apps) {
|
|
1310
|
+
return apps.length > 0 ? apps.join("\n") : `${project.name} lists no apps yet. Add one: littlefriend apps add com.acme.shop`;
|
|
1311
|
+
}
|
|
1312
|
+
async function save(ctx, project, allowedApps) {
|
|
1313
|
+
const { project: saved } = await ctx.api().patch(projectPath(project), { allowedApps });
|
|
1314
|
+
return appsOf(saved);
|
|
1315
|
+
}
|
|
1316
|
+
var appsList = {
|
|
1317
|
+
path: ["apps", "list"],
|
|
1318
|
+
summary: "List the apps allowed to send data to the project",
|
|
1319
|
+
usage: "",
|
|
1320
|
+
example: "littlefriend apps list",
|
|
1321
|
+
async run(ctx) {
|
|
1322
|
+
const project = await resolveProject(ctx);
|
|
1323
|
+
const allowedApps = appsOf(project);
|
|
1324
|
+
return { data: { allowedApps }, text: listText(project, allowedApps) };
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
var appsAdd = {
|
|
1328
|
+
path: ["apps", "add"],
|
|
1329
|
+
summary: "Allow an app by its bundle id or package name",
|
|
1330
|
+
usage: "<app-id>",
|
|
1331
|
+
example: "littlefriend apps add com.acme.shop",
|
|
1332
|
+
args: { min: 1, max: 1 },
|
|
1333
|
+
async run(ctx) {
|
|
1334
|
+
const raw = arg(ctx, 0, "the app id, such as com.acme.shop");
|
|
1335
|
+
const id = normalizeAppId(raw);
|
|
1336
|
+
if (!id) throw usageError(`${raw} is not an app id. ${APP_ID_HINT}`);
|
|
1337
|
+
const project = await resolveProject(ctx);
|
|
1338
|
+
const current = appsOf(project);
|
|
1339
|
+
if (current.some((a) => a.toLowerCase() === id)) {
|
|
1340
|
+
return {
|
|
1341
|
+
data: { allowedApps: current },
|
|
1342
|
+
text: lines(`${project.name} already allows ${id}.`, "", listText(project, current))
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
const allowedApps = await save(ctx, project, [...current, id]);
|
|
1346
|
+
return {
|
|
1347
|
+
data: { allowedApps },
|
|
1348
|
+
text: lines(`Added ${id} to the allowed apps of ${project.name}.`, "", listText(project, allowedApps))
|
|
1349
|
+
};
|
|
1350
|
+
}
|
|
1351
|
+
};
|
|
1352
|
+
var appsRemove = {
|
|
1353
|
+
path: ["apps", "remove"],
|
|
1354
|
+
summary: "Stop accepting data from an app",
|
|
1355
|
+
usage: "<app-id>",
|
|
1356
|
+
example: "littlefriend apps remove com.acme.shop",
|
|
1357
|
+
args: { min: 1, max: 1 },
|
|
1358
|
+
async run(ctx) {
|
|
1359
|
+
const id = arg(ctx, 0, "the app id, such as com.acme.shop").toLowerCase();
|
|
1360
|
+
const project = await resolveProject(ctx);
|
|
1361
|
+
const current = appsOf(project);
|
|
1362
|
+
const next = current.filter((a) => a.toLowerCase() !== id);
|
|
1363
|
+
if (next.length === current.length) {
|
|
1364
|
+
return {
|
|
1365
|
+
data: { allowedApps: current },
|
|
1366
|
+
text: lines(`${project.name} does not list ${id}.`, "", listText(project, current))
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
const allowedApps = await save(ctx, project, next);
|
|
1370
|
+
return {
|
|
1371
|
+
data: { allowedApps },
|
|
1372
|
+
text: lines(
|
|
1373
|
+
`Removed ${id} from the allowed apps of ${project.name}.`,
|
|
1374
|
+
"",
|
|
1375
|
+
listText(project, allowedApps)
|
|
1376
|
+
)
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
};
|
|
1380
|
+
var appsCommands = [appsList, appsAdd, appsRemove];
|
|
828
1381
|
|
|
829
1382
|
// src/commands/auth.ts
|
|
830
1383
|
async function lookupEmail(io, origin, accessToken) {
|
|
@@ -2361,579 +2914,202 @@ function parseV6(input) {
|
|
|
2361
2914
|
const lastColon = ip.lastIndexOf(":");
|
|
2362
2915
|
const lastPart = ip.slice(lastColon + 1);
|
|
2363
2916
|
if (lastPart.includes(".")) {
|
|
2364
|
-
tail = parseV4(lastPart);
|
|
2365
|
-
if (tail === null)
|
|
2366
|
-
return null;
|
|
2367
|
-
ip = `${ip.slice(0, lastColon + 1)}0:0`;
|
|
2368
|
-
}
|
|
2369
|
-
const halves = ip.split("::");
|
|
2370
|
-
if (halves.length > 2)
|
|
2371
|
-
return null;
|
|
2372
|
-
const head = halves[0] ? halves[0].split(":") : [];
|
|
2373
|
-
const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
2374
|
-
const missing = 8 - head.length - rest.length;
|
|
2375
|
-
if (halves.length === 1 && missing !== 0)
|
|
2376
|
-
return null;
|
|
2377
|
-
if (missing < 0)
|
|
2378
|
-
return null;
|
|
2379
|
-
const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...rest];
|
|
2380
|
-
if (groups.length !== 8)
|
|
2381
|
-
return null;
|
|
2382
|
-
let n = 0n;
|
|
2383
|
-
for (const g of groups) {
|
|
2384
|
-
if (!/^[0-9a-f]{1,4}$/i.test(g))
|
|
2385
|
-
return null;
|
|
2386
|
-
n = n << 16n | BigInt(Number.parseInt(g, 16));
|
|
2387
|
-
}
|
|
2388
|
-
if (tail !== null)
|
|
2389
|
-
n = n & ~0xffffffffn | tail;
|
|
2390
|
-
return n;
|
|
2391
|
-
}
|
|
2392
|
-
var MAPPED_PREFIX = 0xffffn << 32n;
|
|
2393
|
-
function parseIp(input) {
|
|
2394
|
-
if (typeof input !== "string")
|
|
2395
|
-
return null;
|
|
2396
|
-
const ip = input.trim();
|
|
2397
|
-
if (ip.length === 0 || ip.length > 64)
|
|
2398
|
-
return null;
|
|
2399
|
-
const v4 = parseV4(ip);
|
|
2400
|
-
if (v4 !== null)
|
|
2401
|
-
return { v: 4, n: v4 };
|
|
2402
|
-
const v6 = parseV6(ip);
|
|
2403
|
-
if (v6 === null)
|
|
2404
|
-
return null;
|
|
2405
|
-
if (v6 >> 32n === MAPPED_PREFIX >> 32n)
|
|
2406
|
-
return { v: 4, n: v6 & 0xffffffffn };
|
|
2407
|
-
return { v: 6, n: v6 };
|
|
2408
|
-
}
|
|
2409
|
-
function parseCidr(input) {
|
|
2410
|
-
if (typeof input !== "string")
|
|
2411
|
-
return null;
|
|
2412
|
-
const [addr, len, extra] = input.trim().split("/");
|
|
2413
|
-
if (addr === void 0 || extra !== void 0)
|
|
2414
|
-
return null;
|
|
2415
|
-
const p = parseIp(addr);
|
|
2416
|
-
if (!p)
|
|
2417
|
-
return null;
|
|
2418
|
-
const width = p.v === 4 ? 32 : 128;
|
|
2419
|
-
const mappedFromV6 = p.v === 4 && addr.includes(":");
|
|
2420
|
-
let bits = width;
|
|
2421
|
-
if (len !== void 0) {
|
|
2422
|
-
if (!/^\d{1,3}$/.test(len))
|
|
2423
|
-
return null;
|
|
2424
|
-
bits = Number(len);
|
|
2425
|
-
if (mappedFromV6)
|
|
2426
|
-
bits -= 96;
|
|
2427
|
-
if (bits < 0 || bits > width)
|
|
2428
|
-
return null;
|
|
2429
|
-
}
|
|
2430
|
-
const mask = bits === 0 ? 0n : (1n << BigInt(bits)) - 1n << BigInt(width - bits);
|
|
2431
|
-
return { v: p.v, base: p.n & mask, bits };
|
|
2432
|
-
}
|
|
2433
|
-
var NON_PUBLIC_V4 = [
|
|
2434
|
-
"0.0.0.0/8",
|
|
2435
|
-
"10.0.0.0/8",
|
|
2436
|
-
"100.64.0.0/10",
|
|
2437
|
-
"127.0.0.0/8",
|
|
2438
|
-
"169.254.0.0/16",
|
|
2439
|
-
"172.16.0.0/12",
|
|
2440
|
-
"192.0.0.0/24",
|
|
2441
|
-
"192.0.2.0/24",
|
|
2442
|
-
"192.88.99.0/24",
|
|
2443
|
-
"192.168.0.0/16",
|
|
2444
|
-
"198.18.0.0/15",
|
|
2445
|
-
"198.51.100.0/24",
|
|
2446
|
-
"203.0.113.0/24",
|
|
2447
|
-
"224.0.0.0/4",
|
|
2448
|
-
"240.0.0.0/4"
|
|
2449
|
-
].map((c) => parseCidr(c));
|
|
2450
|
-
var NON_PUBLIC_V6 = [
|
|
2451
|
-
"::/128",
|
|
2452
|
-
"::1/128",
|
|
2453
|
-
"64:ff9b::/96",
|
|
2454
|
-
"64:ff9b:1::/48",
|
|
2455
|
-
"100::/64",
|
|
2456
|
-
"2001::/32",
|
|
2457
|
-
"2001:db8::/32",
|
|
2458
|
-
"2002::/16",
|
|
2459
|
-
"fc00::/7",
|
|
2460
|
-
"fe80::/10",
|
|
2461
|
-
"fec0::/10",
|
|
2462
|
-
"ff00::/8"
|
|
2463
|
-
].map((c) => parseCidr(c));
|
|
2464
|
-
|
|
2465
|
-
// ../classify/dist/signature.js
|
|
2466
|
-
var KNOWN_SIGNATURE_AGENTS = {
|
|
2467
|
-
"https://chatgpt.com": {
|
|
2468
|
-
operator: "OpenAI",
|
|
2469
|
-
product: "ChatGPT agent",
|
|
2470
|
-
class: "ai_agent",
|
|
2471
|
-
purpose: "ai_agent"
|
|
2472
|
-
},
|
|
2473
|
-
"https://agent.bot.goog": {
|
|
2474
|
-
operator: "Google",
|
|
2475
|
-
product: "Google-Agent",
|
|
2476
|
-
class: "ai_agent",
|
|
2477
|
-
purpose: "ai_agent"
|
|
2478
|
-
}
|
|
2479
|
-
};
|
|
2480
|
-
|
|
2481
|
-
// ../classify/dist/version.js
|
|
2482
|
-
var RULES_VERSION = "2026-09-29.2";
|
|
2483
|
-
|
|
2484
|
-
// ../classify/dist/actor.js
|
|
2485
|
-
function verdict(cls, operator, product, evidence, reason, purpose, verification) {
|
|
2486
|
-
return {
|
|
2487
|
-
class: cls,
|
|
2488
|
-
operator,
|
|
2489
|
-
product,
|
|
2490
|
-
evidence,
|
|
2491
|
-
reason,
|
|
2492
|
-
rulesVersion: RULES_VERSION,
|
|
2493
|
-
purpose,
|
|
2494
|
-
verification
|
|
2495
|
-
};
|
|
2496
|
-
}
|
|
2497
|
-
function signatureNote(signature) {
|
|
2498
|
-
if (signature?.status === "invalid")
|
|
2499
|
-
return ` Its request signature failed verification: ${lower(signature.reason)}.`;
|
|
2500
|
-
return "";
|
|
2501
|
-
}
|
|
2502
|
-
function lower(s) {
|
|
2503
|
-
return s.length > 0 ? s[0]?.toLowerCase() + s.slice(1) : s;
|
|
2504
|
-
}
|
|
2505
|
-
function hasVerification(rule) {
|
|
2506
|
-
return (rule.verify?.ipRangeSources?.length ?? 0) + (rule.verify?.reverseDnsSuffixes?.length ?? 0) > 0;
|
|
2507
|
-
}
|
|
2508
|
-
function ruleVerdict(rule, network, signature) {
|
|
2509
|
-
const op = rule.operator;
|
|
2510
|
-
const badSignature = signature?.status === "invalid";
|
|
2511
|
-
if (network?.status === "verified" && op && !badSignature) {
|
|
2512
|
-
const how = network.method === "ip_ranges" ? `verified against ${op}'s published IP ranges` : "verified by reverse and forward DNS";
|
|
2513
|
-
return verdict(rule.class, op, rule.product, "network_verified", `${rule.product}, ${how}.`, rule.purpose, "verified");
|
|
2514
|
-
}
|
|
2515
|
-
if (!op) {
|
|
2516
|
-
return verdict(rule.class, null, rule.product, "none", `${rule.product} user agent.${signatureNote(signature)}`, rule.purpose, badSignature ? "suspected_spoof" : "no_claim");
|
|
2517
|
-
}
|
|
2518
|
-
if (network?.status === "mismatch") {
|
|
2519
|
-
const why = network.method === "ip_ranges" ? `the address is not in ${op}'s published ranges` : `the address does not verify with ${op}'s reverse DNS`;
|
|
2520
|
-
return verdict(rule.class, op, rule.product, "self_declared", `Claims to be ${rule.product}, but ${why}.${signatureNote(signature)}`, rule.purpose, "suspected_spoof");
|
|
2521
|
-
}
|
|
2522
|
-
const status = badSignature ? "suspected_spoof" : hasVerification(rule) ? "unchecked" : "unverifiable";
|
|
2523
|
-
return verdict(rule.class, op, rule.product, "self_declared", `Self-declared ${rule.product} (user agent only).${signatureNote(signature)}`, rule.purpose, status);
|
|
2524
|
-
}
|
|
2525
|
-
function classifyActor(input) {
|
|
2526
|
-
const ua = typeof input.ua === "string" ? input.ua.trim() : "";
|
|
2527
|
-
const rule = ua.length > 0 ? matchBotRule(ua) : null;
|
|
2528
|
-
const signature = input.signature;
|
|
2529
|
-
if (signature?.status === "verified") {
|
|
2530
|
-
const known = KNOWN_SIGNATURE_AGENTS[signature.agent];
|
|
2531
|
-
const host = new URL(signature.agent).host;
|
|
2532
|
-
if (known) {
|
|
2533
|
-
if (rule && rule.operator === known.operator) {
|
|
2534
|
-
return verdict(rule.class, known.operator, rule.product, "signature_verified", `${rule.product}, verified request signature from ${host}.`, rule.purpose, "verified");
|
|
2535
|
-
}
|
|
2536
|
-
const claim = rule ? ` Its user agent claims ${rule.product}.` : "";
|
|
2537
|
-
return verdict(known.class, known.operator, known.product, "signature_verified", `${known.product}, verified request signature from ${host}.${claim}`, known.purpose, "verified");
|
|
2538
|
-
}
|
|
2539
|
-
const cls = rule ? rule.class : isBrowserLike(ua) ? "browser" : "unknown";
|
|
2540
|
-
const purpose = rule ? rule.purpose : "unknown";
|
|
2541
|
-
if (rule?.operator) {
|
|
2542
|
-
return verdict(cls, host, null, "signature_verified", `Request signed by ${host}. Its user agent claims ${rule.product}.`, purpose, "verified");
|
|
2543
|
-
}
|
|
2544
|
-
return verdict(cls, host, rule?.product ?? null, "signature_verified", `Request signed by ${host}.`, purpose, "verified");
|
|
2545
|
-
}
|
|
2546
|
-
const spoofed = signature?.status === "invalid" ? "suspected_spoof" : "no_claim";
|
|
2547
|
-
if (ua.length === 0)
|
|
2548
|
-
return verdict("unknown", null, null, "none", `No user agent.${signatureNote(signature)}`, "unknown", spoofed);
|
|
2549
|
-
if (rule)
|
|
2550
|
-
return ruleVerdict(rule, input.network, signature);
|
|
2551
|
-
if (isBrowserLike(ua))
|
|
2552
|
-
return verdict("browser", null, null, "none", `Browser user agent.${signatureNote(signature)}`, "human", spoofed);
|
|
2553
|
-
return verdict("unknown", null, null, "none", `Unrecognized user agent.${signatureNote(signature)}`, "unknown", spoofed);
|
|
2554
|
-
}
|
|
2555
|
-
var RULE_BY_PRODUCT = /* @__PURE__ */ new Map();
|
|
2556
|
-
for (const rule of [...BOT_RULES, GENERIC_BOT_RULE]) {
|
|
2557
|
-
if (!RULE_BY_PRODUCT.has(rule.product))
|
|
2558
|
-
RULE_BY_PRODUCT.set(rule.product, rule);
|
|
2559
|
-
}
|
|
2560
|
-
|
|
2561
|
-
// ../contract/dist/actors.js
|
|
2562
|
-
var ACTOR_CLASS_LABELS = {
|
|
2563
|
-
browser: "Interactive browser",
|
|
2564
|
-
search_crawler: "Search crawler",
|
|
2565
|
-
ai_crawler: "AI crawler",
|
|
2566
|
-
ai_agent: "User-directed AI agent",
|
|
2567
|
-
monitor: "Uptime and monitoring",
|
|
2568
|
-
preview: "Link preview",
|
|
2569
|
-
automation: "Suspected automation",
|
|
2570
|
-
unknown: "Unknown"
|
|
2571
|
-
};
|
|
2572
|
-
|
|
2573
|
-
// ../contract/dist/channels.js
|
|
2574
|
-
var AI_ASSISTANT_HOSTS = [
|
|
2575
|
-
{ host: "chatgpt.com", label: "ChatGPT", operator: "OpenAI" },
|
|
2576
|
-
{ host: "chat.openai.com", label: "ChatGPT", operator: "OpenAI" },
|
|
2577
|
-
{ host: "perplexity.ai", label: "Perplexity", operator: "Perplexity" },
|
|
2578
|
-
{ host: "claude.ai", label: "Claude", operator: "Anthropic" },
|
|
2579
|
-
{ host: "gemini.google.com", label: "Gemini", operator: "Google" },
|
|
2580
|
-
{ host: "copilot.microsoft.com", label: "Microsoft Copilot", operator: "Microsoft" },
|
|
2581
|
-
{ host: "you.com", label: "You.com", operator: "You.com" },
|
|
2582
|
-
{ host: "phind.com", label: "Phind", operator: "Phind" }
|
|
2583
|
-
];
|
|
2584
|
-
|
|
2585
|
-
// ../contract/dist/kya.js
|
|
2586
|
-
function principalRank(level) {
|
|
2587
|
-
switch (level) {
|
|
2588
|
-
case "none":
|
|
2589
|
-
return 0;
|
|
2590
|
-
case "user_initiated":
|
|
2591
|
-
return 1;
|
|
2592
|
-
case "signed_user":
|
|
2593
|
-
return 2;
|
|
2594
|
-
default:
|
|
2595
|
-
return 3;
|
|
2917
|
+
tail = parseV4(lastPart);
|
|
2918
|
+
if (tail === null)
|
|
2919
|
+
return null;
|
|
2920
|
+
ip = `${ip.slice(0, lastColon + 1)}0:0`;
|
|
2596
2921
|
}
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2922
|
+
const halves = ip.split("::");
|
|
2923
|
+
if (halves.length > 2)
|
|
2924
|
+
return null;
|
|
2925
|
+
const head = halves[0] ? halves[0].split(":") : [];
|
|
2926
|
+
const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
2927
|
+
const missing = 8 - head.length - rest.length;
|
|
2928
|
+
if (halves.length === 1 && missing !== 0)
|
|
2929
|
+
return null;
|
|
2930
|
+
if (missing < 0)
|
|
2931
|
+
return null;
|
|
2932
|
+
const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...rest];
|
|
2933
|
+
if (groups.length !== 8)
|
|
2934
|
+
return null;
|
|
2935
|
+
let n = 0n;
|
|
2936
|
+
for (const g of groups) {
|
|
2937
|
+
if (!/^[0-9a-f]{1,4}$/i.test(g))
|
|
2938
|
+
return null;
|
|
2939
|
+
n = n << 16n | BigInt(Number.parseInt(g, 16));
|
|
2609
2940
|
}
|
|
2941
|
+
if (tail !== null)
|
|
2942
|
+
n = n & ~0xffffffffn | tail;
|
|
2943
|
+
return n;
|
|
2610
2944
|
}
|
|
2611
|
-
var
|
|
2612
|
-
function
|
|
2613
|
-
if (
|
|
2614
|
-
return
|
|
2615
|
-
const
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
if (
|
|
2620
|
-
return
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
if (match.evidenceBelow && !(evidenceRank(facts.evidence) < evidenceRank(match.evidenceBelow)))
|
|
2628
|
-
return false;
|
|
2629
|
-
if (match.principalBelow && !(principalRank(facts.principal) < principalRank(match.principalBelow)))
|
|
2630
|
-
return false;
|
|
2631
|
-
if (match.spoofed !== void 0 && match.spoofed !== facts.spoofed)
|
|
2632
|
-
return false;
|
|
2633
|
-
if (match.paths && !match.paths.some((p) => pathMatches(facts.path, p)))
|
|
2634
|
-
return false;
|
|
2635
|
-
if (match.methods && !match.methods.map(lower2).includes(lower2(facts.method)))
|
|
2636
|
-
return false;
|
|
2637
|
-
return true;
|
|
2945
|
+
var MAPPED_PREFIX = 0xffffn << 32n;
|
|
2946
|
+
function parseIp(input) {
|
|
2947
|
+
if (typeof input !== "string")
|
|
2948
|
+
return null;
|
|
2949
|
+
const ip = input.trim();
|
|
2950
|
+
if (ip.length === 0 || ip.length > 64)
|
|
2951
|
+
return null;
|
|
2952
|
+
const v4 = parseV4(ip);
|
|
2953
|
+
if (v4 !== null)
|
|
2954
|
+
return { v: 4, n: v4 };
|
|
2955
|
+
const v6 = parseV6(ip);
|
|
2956
|
+
if (v6 === null)
|
|
2957
|
+
return null;
|
|
2958
|
+
if (v6 >> 32n === MAPPED_PREFIX >> 32n)
|
|
2959
|
+
return { v: 4, n: v6 & 0xffffffffn };
|
|
2960
|
+
return { v: 6, n: v6 };
|
|
2638
2961
|
}
|
|
2639
|
-
function
|
|
2640
|
-
if (
|
|
2641
|
-
return
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2962
|
+
function parseCidr(input) {
|
|
2963
|
+
if (typeof input !== "string")
|
|
2964
|
+
return null;
|
|
2965
|
+
const [addr, len, extra] = input.trim().split("/");
|
|
2966
|
+
if (addr === void 0 || extra !== void 0)
|
|
2967
|
+
return null;
|
|
2968
|
+
const p = parseIp(addr);
|
|
2969
|
+
if (!p)
|
|
2970
|
+
return null;
|
|
2971
|
+
const width = p.v === 4 ? 32 : 128;
|
|
2972
|
+
const mappedFromV6 = p.v === 4 && addr.includes(":");
|
|
2973
|
+
let bits = width;
|
|
2974
|
+
if (len !== void 0) {
|
|
2975
|
+
if (!/^\d{1,3}$/.test(len))
|
|
2976
|
+
return null;
|
|
2977
|
+
bits = Number(len);
|
|
2978
|
+
if (mappedFromV6)
|
|
2979
|
+
bits -= 96;
|
|
2980
|
+
if (bits < 0 || bits > width)
|
|
2981
|
+
return null;
|
|
2646
2982
|
}
|
|
2647
|
-
|
|
2983
|
+
const mask = bits === 0 ? 0n : (1n << BigInt(bits)) - 1n << BigInt(width - bits);
|
|
2984
|
+
return { v: p.v, base: p.n & mask, bits };
|
|
2648
2985
|
}
|
|
2649
|
-
var
|
|
2650
|
-
"
|
|
2651
|
-
"
|
|
2652
|
-
"
|
|
2653
|
-
"
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
"
|
|
2657
|
-
"
|
|
2658
|
-
"
|
|
2659
|
-
"
|
|
2660
|
-
"
|
|
2661
|
-
"
|
|
2662
|
-
"
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
verified_only: [
|
|
2681
|
-
BLOCK_SPOOFED,
|
|
2682
|
-
{
|
|
2683
|
-
id: "unverified",
|
|
2684
|
-
label: "Slow down agents that are not verified",
|
|
2685
|
-
match: { classes: AGENT_CLASSES, evidenceBelow: "network_verified" },
|
|
2686
|
-
action: "limit",
|
|
2687
|
-
limit: { perMinute: 60, burst: 20 }
|
|
2688
|
-
}
|
|
2689
|
-
],
|
|
2690
|
-
commerce: [
|
|
2691
|
-
BLOCK_SPOOFED,
|
|
2692
|
-
{
|
|
2693
|
-
id: "checkout",
|
|
2694
|
-
label: "Checkout and accounts need an agent acting for a signed-in user",
|
|
2695
|
-
match: {
|
|
2696
|
-
// Not `unknown`: a person whose browser does not look like one must still reach checkout.
|
|
2697
|
-
classes: ["ai_agent", "automation"],
|
|
2698
|
-
paths: ["/checkout", "/cart", "/account"],
|
|
2699
|
-
principalBelow: "signed_user"
|
|
2700
|
-
},
|
|
2701
|
-
action: "require_signature"
|
|
2702
|
-
}
|
|
2703
|
-
]
|
|
2704
|
-
};
|
|
2705
|
-
|
|
2706
|
-
// ../contract/dist/limits.js
|
|
2707
|
-
var LIMITS = {
|
|
2708
|
-
/** Max request body accepted by the collector, in bytes (before decompression). */
|
|
2709
|
-
maxBodyBytes: 16 * 1024,
|
|
2710
|
-
/** Max events in one batch. */
|
|
2711
|
-
maxEventsPerBatch: 50,
|
|
2712
|
-
/** Max custom properties on one event. */
|
|
2713
|
-
maxProps: 8,
|
|
2714
|
-
maxPropKeyLength: 32,
|
|
2715
|
-
maxPropStringLength: 64,
|
|
2716
|
-
maxEventNameLength: 64,
|
|
2717
|
-
maxRouteLength: 256,
|
|
2718
|
-
maxHostLength: 253,
|
|
2719
|
-
maxCampaignValueLength: 64,
|
|
2720
|
-
/** Events observed further in the past than this are rejected as stale. */
|
|
2721
|
-
maxPastSkewMs: 24 * 60 * 60 * 1e3,
|
|
2722
|
-
/** Events observed further in the future than this are rejected as clock skew. */
|
|
2723
|
-
maxFutureSkewMs: 10 * 60 * 1e3,
|
|
2724
|
-
/** Browser SDK flush triggers. */
|
|
2725
|
-
browserFlushEvents: 10,
|
|
2726
|
-
browserFlushMs: 5e3,
|
|
2727
|
-
/** Browser SDK bounded pending queue, in bytes of serialized events. */
|
|
2728
|
-
browserMaxPendingBytes: 64 * 1024,
|
|
2729
|
-
/** Journey sessions: inactivity timeout and hard lifetime. */
|
|
2730
|
-
sessionIdleMs: 30 * 60 * 1e3,
|
|
2731
|
-
sessionMaxMs: 24 * 60 * 60 * 1e3
|
|
2732
|
-
};
|
|
2733
|
-
|
|
2734
|
-
// ../contract/dist/origins.js
|
|
2735
|
-
var REFUSED_ORIGIN_SCHEMES = [
|
|
2736
|
-
// Script and inline content.
|
|
2737
|
-
"javascript",
|
|
2738
|
-
"vbscript",
|
|
2739
|
-
"data",
|
|
2740
|
-
"blob",
|
|
2741
|
-
"filesystem",
|
|
2742
|
-
// Files and blank pages, which send `Origin: null`.
|
|
2743
|
-
"file",
|
|
2744
|
-
"about",
|
|
2745
|
-
"content",
|
|
2746
|
-
// Browser pages and extensions.
|
|
2747
|
-
"chrome",
|
|
2748
|
-
"chrome-extension",
|
|
2749
|
-
"chrome-untrusted",
|
|
2750
|
-
"chrome-search",
|
|
2751
|
-
"devtools",
|
|
2752
|
-
"edge",
|
|
2753
|
-
"brave",
|
|
2754
|
-
"opera",
|
|
2755
|
-
"vivaldi",
|
|
2756
|
-
"view-source",
|
|
2757
|
-
"resource",
|
|
2758
|
-
"moz-extension",
|
|
2759
|
-
"safari-extension",
|
|
2760
|
-
"safari-web-extension",
|
|
2761
|
-
"ms-browser-extension",
|
|
2762
|
-
// Protocols that are never a page.
|
|
2763
|
-
"ftp",
|
|
2764
|
-
"ws",
|
|
2765
|
-
"wss",
|
|
2766
|
-
"mailto",
|
|
2767
|
-
"tel",
|
|
2768
|
-
"sms",
|
|
2769
|
-
"intent",
|
|
2770
|
-
"market"
|
|
2771
|
-
];
|
|
2772
|
-
var REFUSED = new Set(REFUSED_ORIGIN_SCHEMES);
|
|
2986
|
+
var NON_PUBLIC_V4 = [
|
|
2987
|
+
"0.0.0.0/8",
|
|
2988
|
+
"10.0.0.0/8",
|
|
2989
|
+
"100.64.0.0/10",
|
|
2990
|
+
"127.0.0.0/8",
|
|
2991
|
+
"169.254.0.0/16",
|
|
2992
|
+
"172.16.0.0/12",
|
|
2993
|
+
"192.0.0.0/24",
|
|
2994
|
+
"192.0.2.0/24",
|
|
2995
|
+
"192.88.99.0/24",
|
|
2996
|
+
"192.168.0.0/16",
|
|
2997
|
+
"198.18.0.0/15",
|
|
2998
|
+
"198.51.100.0/24",
|
|
2999
|
+
"203.0.113.0/24",
|
|
3000
|
+
"224.0.0.0/4",
|
|
3001
|
+
"240.0.0.0/4"
|
|
3002
|
+
].map((c) => parseCidr(c));
|
|
3003
|
+
var NON_PUBLIC_V6 = [
|
|
3004
|
+
"::/128",
|
|
3005
|
+
"::1/128",
|
|
3006
|
+
"64:ff9b::/96",
|
|
3007
|
+
"64:ff9b:1::/48",
|
|
3008
|
+
"100::/64",
|
|
3009
|
+
"2001::/32",
|
|
3010
|
+
"2001:db8::/32",
|
|
3011
|
+
"2002::/16",
|
|
3012
|
+
"fc00::/7",
|
|
3013
|
+
"fe80::/10",
|
|
3014
|
+
"fec0::/10",
|
|
3015
|
+
"ff00::/8"
|
|
3016
|
+
].map((c) => parseCidr(c));
|
|
2773
3017
|
|
|
2774
|
-
// ../
|
|
2775
|
-
var
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
"
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
"class",
|
|
2789
|
-
"id",
|
|
2790
|
-
"style",
|
|
2791
|
-
"role",
|
|
2792
|
-
"type",
|
|
2793
|
-
"name",
|
|
2794
|
-
"for",
|
|
2795
|
-
"rel",
|
|
2796
|
-
"media",
|
|
2797
|
-
"href",
|
|
2798
|
-
"width",
|
|
2799
|
-
"height",
|
|
2800
|
-
"colspan",
|
|
2801
|
-
"rowspan",
|
|
2802
|
-
"dir",
|
|
2803
|
-
"lang",
|
|
2804
|
-
"hidden",
|
|
2805
|
-
"open",
|
|
2806
|
-
"disabled",
|
|
2807
|
-
"readonly",
|
|
2808
|
-
"multiple",
|
|
2809
|
-
"viewbox",
|
|
2810
|
-
"d",
|
|
2811
|
-
"fill",
|
|
2812
|
-
"stroke",
|
|
2813
|
-
"stroke-width",
|
|
2814
|
-
"points",
|
|
2815
|
-
"x",
|
|
2816
|
-
"y",
|
|
2817
|
-
"cx",
|
|
2818
|
-
"cy",
|
|
2819
|
-
"r",
|
|
2820
|
-
"rx",
|
|
2821
|
-
"ry",
|
|
2822
|
-
"transform",
|
|
2823
|
-
"aria-hidden",
|
|
2824
|
-
"aria-expanded",
|
|
2825
|
-
"aria-current",
|
|
2826
|
-
"aria-disabled",
|
|
2827
|
-
"aria-pressed"
|
|
2828
|
-
];
|
|
2829
|
-
var REPLAY_TEXT_ATTRIBUTES = [
|
|
2830
|
-
"title",
|
|
2831
|
-
"alt",
|
|
2832
|
-
"placeholder",
|
|
2833
|
-
"aria-label",
|
|
2834
|
-
"aria-description"
|
|
2835
|
-
];
|
|
2836
|
-
var REPLAY_UNMASK_PRESET = [
|
|
2837
|
-
"nav",
|
|
2838
|
-
"header",
|
|
2839
|
-
"footer",
|
|
2840
|
-
"h1",
|
|
2841
|
-
"h2",
|
|
2842
|
-
"h3",
|
|
2843
|
-
"h4",
|
|
2844
|
-
"button",
|
|
2845
|
-
"label",
|
|
2846
|
-
"th",
|
|
2847
|
-
"legend",
|
|
2848
|
-
"[role=button]",
|
|
2849
|
-
"[role=tab]",
|
|
2850
|
-
"[role=menuitem]"
|
|
2851
|
-
];
|
|
2852
|
-
var REPLAY_LIMITS = {
|
|
2853
|
-
/** One POST body, compressed. Keepalive requests on page hide must stay under 64 KB. */
|
|
2854
|
-
maxChunkBytes: 256 * 1024,
|
|
2855
|
-
/** One chunk after gunzip. Anything larger is refused before it is parsed. */
|
|
2856
|
-
maxChunkRawBytes: 4 * 1024 * 1024,
|
|
2857
|
-
/**
|
|
2858
|
-
* A chunk that carries a full snapshot may be larger: a heavy page's first snapshot with its
|
|
2859
|
-
* inlined stylesheets can pass maxChunkBytes on its own. Every other chunk keeps the normal limits.
|
|
2860
|
-
*/
|
|
2861
|
-
maxSnapshotChunkBytes: 1024 * 1024,
|
|
2862
|
-
maxSnapshotChunkRawBytes: 10 * 1024 * 1024,
|
|
2863
|
-
maxChunkEvents: 5e3,
|
|
2864
|
-
/** Stored bytes per session, compressed. Past it the collector answers 202 and drops. */
|
|
2865
|
-
maxSessionBytes: 12 * 1024 * 1024,
|
|
2866
|
-
/** Recorded time per page load. The recorder stops after it. */
|
|
2867
|
-
maxPageMs: 60 * 60 * 1e3,
|
|
2868
|
-
/** The recorder flushes a chunk this often, or sooner when it reaches flushBytes raw. */
|
|
2869
|
-
flushMs: 1e4,
|
|
2870
|
-
flushBytes: 128 * 1024,
|
|
2871
|
-
/** Two interactions closer than this are one stretch of activity. Longer gaps are skippable. */
|
|
2872
|
-
idleGapMs: 5e3,
|
|
2873
|
-
/** A rage click: this many clicks within rageWindowMs inside rageRadiusPx. */
|
|
2874
|
-
rageClicks: 3,
|
|
2875
|
-
rageWindowMs: 1e3,
|
|
2876
|
-
rageRadiusPx: 30,
|
|
2877
|
-
maxSelectors: 50,
|
|
2878
|
-
maxSelectorLength: 200,
|
|
2879
|
-
maxExcludeRoutes: 50,
|
|
2880
|
-
/**
|
|
2881
|
-
* A recording with at least this many clicks is kept when its session ends, whatever its
|
|
2882
|
-
* active time: a short visit of a few taps on a phone is still worth watching.
|
|
2883
|
-
*/
|
|
2884
|
-
keepWithClicks: 3,
|
|
2885
|
-
/**
|
|
2886
|
-
* Recordings a workspace may start per UTC calendar month without a card on file. The
|
|
2887
|
-
* collector and the API read REPLAY_FREE_RECORDINGS_PER_MONTH first, so both agree.
|
|
2888
|
-
*/
|
|
2889
|
-
freeRecordingsPerMonth: 10
|
|
3018
|
+
// ../classify/dist/signature.js
|
|
3019
|
+
var KNOWN_SIGNATURE_AGENTS = {
|
|
3020
|
+
"https://chatgpt.com": {
|
|
3021
|
+
operator: "OpenAI",
|
|
3022
|
+
product: "ChatGPT agent",
|
|
3023
|
+
class: "ai_agent",
|
|
3024
|
+
purpose: "ai_agent"
|
|
3025
|
+
},
|
|
3026
|
+
"https://agent.bot.goog": {
|
|
3027
|
+
operator: "Google",
|
|
3028
|
+
product: "Google-Agent",
|
|
3029
|
+
class: "ai_agent",
|
|
3030
|
+
purpose: "ai_agent"
|
|
3031
|
+
}
|
|
2890
3032
|
};
|
|
2891
3033
|
|
|
2892
|
-
// ../
|
|
2893
|
-
var
|
|
2894
|
-
Mutation: 0,
|
|
2895
|
-
MouseMove: 1,
|
|
2896
|
-
MouseInteraction: 2,
|
|
2897
|
-
Scroll: 3,
|
|
2898
|
-
ViewportResize: 4,
|
|
2899
|
-
Input: 5,
|
|
2900
|
-
TouchMove: 6,
|
|
2901
|
-
MediaInteraction: 7,
|
|
2902
|
-
StyleSheetRule: 8,
|
|
2903
|
-
CanvasMutation: 9,
|
|
2904
|
-
Font: 10,
|
|
2905
|
-
Log: 11,
|
|
2906
|
-
Drag: 12,
|
|
2907
|
-
StyleDeclaration: 13,
|
|
2908
|
-
Selection: 14,
|
|
2909
|
-
AdoptedStyleSheet: 15,
|
|
2910
|
-
CustomElement: 16
|
|
2911
|
-
};
|
|
2912
|
-
var REPLAY_MAX_SCANNED_TEXT = 32 * 1024;
|
|
2913
|
-
var MASKED_RE = new RegExp(`^[\\s${REPLAY_MASK_CHAR}]*$`, "u");
|
|
2914
|
-
var BLOCKED_TAGS = /* @__PURE__ */ new Set([
|
|
2915
|
-
...REPLAY_ALWAYS_BLOCKED.map((s) => s.split(/\s+/).pop()),
|
|
2916
|
-
"frame",
|
|
2917
|
-
"frameset",
|
|
2918
|
-
"applet",
|
|
2919
|
-
"portal",
|
|
2920
|
-
"fencedframe"
|
|
2921
|
-
]);
|
|
2922
|
-
var KEPT = new Set(REPLAY_KEPT_ATTRIBUTES);
|
|
2923
|
-
var TEXT_ATTRS = new Set(REPLAY_TEXT_ATTRIBUTES);
|
|
2924
|
-
var INTERACTION_SOURCES = /* @__PURE__ */ new Set([
|
|
2925
|
-
REPLAY_SOURCE.MouseMove,
|
|
2926
|
-
REPLAY_SOURCE.MouseInteraction,
|
|
2927
|
-
REPLAY_SOURCE.Scroll,
|
|
2928
|
-
REPLAY_SOURCE.ViewportResize,
|
|
2929
|
-
REPLAY_SOURCE.Input,
|
|
2930
|
-
REPLAY_SOURCE.TouchMove,
|
|
2931
|
-
REPLAY_SOURCE.Drag,
|
|
2932
|
-
REPLAY_SOURCE.Selection
|
|
2933
|
-
]);
|
|
3034
|
+
// ../classify/dist/version.js
|
|
3035
|
+
var RULES_VERSION = "2026-09-29.2";
|
|
2934
3036
|
|
|
2935
|
-
// ../
|
|
2936
|
-
|
|
3037
|
+
// ../classify/dist/actor.js
|
|
3038
|
+
function verdict(cls, operator, product, evidence, reason, purpose, verification) {
|
|
3039
|
+
return {
|
|
3040
|
+
class: cls,
|
|
3041
|
+
operator,
|
|
3042
|
+
product,
|
|
3043
|
+
evidence,
|
|
3044
|
+
reason,
|
|
3045
|
+
rulesVersion: RULES_VERSION,
|
|
3046
|
+
purpose,
|
|
3047
|
+
verification
|
|
3048
|
+
};
|
|
3049
|
+
}
|
|
3050
|
+
function signatureNote(signature) {
|
|
3051
|
+
if (signature?.status === "invalid")
|
|
3052
|
+
return ` Its request signature failed verification: ${lower2(signature.reason)}.`;
|
|
3053
|
+
return "";
|
|
3054
|
+
}
|
|
3055
|
+
function lower2(s) {
|
|
3056
|
+
return s.length > 0 ? s[0]?.toLowerCase() + s.slice(1) : s;
|
|
3057
|
+
}
|
|
3058
|
+
function hasVerification(rule) {
|
|
3059
|
+
return (rule.verify?.ipRangeSources?.length ?? 0) + (rule.verify?.reverseDnsSuffixes?.length ?? 0) > 0;
|
|
3060
|
+
}
|
|
3061
|
+
function ruleVerdict(rule, network, signature) {
|
|
3062
|
+
const op = rule.operator;
|
|
3063
|
+
const badSignature = signature?.status === "invalid";
|
|
3064
|
+
if (network?.status === "verified" && op && !badSignature) {
|
|
3065
|
+
const how = network.method === "ip_ranges" ? `verified against ${op}'s published IP ranges` : "verified by reverse and forward DNS";
|
|
3066
|
+
return verdict(rule.class, op, rule.product, "network_verified", `${rule.product}, ${how}.`, rule.purpose, "verified");
|
|
3067
|
+
}
|
|
3068
|
+
if (!op) {
|
|
3069
|
+
return verdict(rule.class, null, rule.product, "none", `${rule.product} user agent.${signatureNote(signature)}`, rule.purpose, badSignature ? "suspected_spoof" : "no_claim");
|
|
3070
|
+
}
|
|
3071
|
+
if (network?.status === "mismatch") {
|
|
3072
|
+
const why = network.method === "ip_ranges" ? `the address is not in ${op}'s published ranges` : `the address does not verify with ${op}'s reverse DNS`;
|
|
3073
|
+
return verdict(rule.class, op, rule.product, "self_declared", `Claims to be ${rule.product}, but ${why}.${signatureNote(signature)}`, rule.purpose, "suspected_spoof");
|
|
3074
|
+
}
|
|
3075
|
+
const status = badSignature ? "suspected_spoof" : hasVerification(rule) ? "unchecked" : "unverifiable";
|
|
3076
|
+
return verdict(rule.class, op, rule.product, "self_declared", `Self-declared ${rule.product} (user agent only).${signatureNote(signature)}`, rule.purpose, status);
|
|
3077
|
+
}
|
|
3078
|
+
function classifyActor(input) {
|
|
3079
|
+
const ua = typeof input.ua === "string" ? input.ua.trim() : "";
|
|
3080
|
+
const rule = ua.length > 0 ? matchBotRule(ua) : null;
|
|
3081
|
+
const signature = input.signature;
|
|
3082
|
+
if (signature?.status === "verified") {
|
|
3083
|
+
const known = KNOWN_SIGNATURE_AGENTS[signature.agent];
|
|
3084
|
+
const host = new URL(signature.agent).host;
|
|
3085
|
+
if (known) {
|
|
3086
|
+
if (rule && rule.operator === known.operator) {
|
|
3087
|
+
return verdict(rule.class, known.operator, rule.product, "signature_verified", `${rule.product}, verified request signature from ${host}.`, rule.purpose, "verified");
|
|
3088
|
+
}
|
|
3089
|
+
const claim = rule ? ` Its user agent claims ${rule.product}.` : "";
|
|
3090
|
+
return verdict(known.class, known.operator, known.product, "signature_verified", `${known.product}, verified request signature from ${host}.${claim}`, known.purpose, "verified");
|
|
3091
|
+
}
|
|
3092
|
+
const cls = rule ? rule.class : isBrowserLike(ua) ? "browser" : "unknown";
|
|
3093
|
+
const purpose = rule ? rule.purpose : "unknown";
|
|
3094
|
+
if (rule?.operator) {
|
|
3095
|
+
return verdict(cls, host, null, "signature_verified", `Request signed by ${host}. Its user agent claims ${rule.product}.`, purpose, "verified");
|
|
3096
|
+
}
|
|
3097
|
+
return verdict(cls, host, rule?.product ?? null, "signature_verified", `Request signed by ${host}.`, purpose, "verified");
|
|
3098
|
+
}
|
|
3099
|
+
const spoofed = signature?.status === "invalid" ? "suspected_spoof" : "no_claim";
|
|
3100
|
+
if (ua.length === 0)
|
|
3101
|
+
return verdict("unknown", null, null, "none", `No user agent.${signatureNote(signature)}`, "unknown", spoofed);
|
|
3102
|
+
if (rule)
|
|
3103
|
+
return ruleVerdict(rule, input.network, signature);
|
|
3104
|
+
if (isBrowserLike(ua))
|
|
3105
|
+
return verdict("browser", null, null, "none", `Browser user agent.${signatureNote(signature)}`, "human", spoofed);
|
|
3106
|
+
return verdict("unknown", null, null, "none", `Unrecognized user agent.${signatureNote(signature)}`, "unknown", spoofed);
|
|
3107
|
+
}
|
|
3108
|
+
var RULE_BY_PRODUCT = /* @__PURE__ */ new Map();
|
|
3109
|
+
for (const rule of [...BOT_RULES, GENERIC_BOT_RULE]) {
|
|
3110
|
+
if (!RULE_BY_PRODUCT.has(rule.product))
|
|
3111
|
+
RULE_BY_PRODUCT.set(rule.product, rule);
|
|
3112
|
+
}
|
|
2937
3113
|
|
|
2938
3114
|
// ../classify/dist/channel.js
|
|
2939
3115
|
var AI_HOSTS = AI_ASSISTANT_HOSTS.map((a) => a.host);
|
|
@@ -3624,7 +3800,7 @@ This copy of the CLI was built without the setup guide.
|
|
|
3624
3800
|
Read it at ${DOCS_URL}
|
|
3625
3801
|
`;
|
|
3626
3802
|
function bundledGuide() {
|
|
3627
|
-
return true ? { text: "# Set up Little Friend in a product: guide for coding agents\n\nYou are a coding agent working in a product's repository. This guide takes you from nothing to a verified Little Friend install: the project, the script, events, goals, funnels, session replay, server events and AI agent visibility. It ends with a report for the person who asked.\n\nWork through the steps in order. Each decision has a default: use it unless the repo or the person who asked says otherwise. When a step does not apply, skip it and say why in the report.\n\n## Contents\n\n0. [Conventions](#0-conventions)\n1. [What Little Friend is, and the rules](#1-what-little-friend-is-and-the-rules)\n2. [Sign in once per machine](#2-sign-in-once-per-machine)\n3. [Read the repo and plan the journeys](#3-read-the-repo-and-plan-the-journeys)\n4. [Workspace, project, mode and consent](#4-workspace-project-mode-and-consent)\n5. [Install the script](#5-install-the-script)\n6. [Content Security Policy](#6-content-security-policy)\n7. [Custom events](#7-custom-events)\n8. [Goals](#8-goals)\n9. [Funnels](#9-funnels)\n10. [Identify signed-in people](#10-identify-signed-in-people)\n11. [Session replay](#11-session-replay)\n12. [Server events](#12-server-events)\n13. [Crawlers and AI agents: the door and a log drain](#13-crawlers-and-ai-agents-the-door-and-a-log-drain)\n14. [Hybrid and native apps](#14-hybrid-and-native-apps)\n15. [Verify](#15-verify)\n16. [Launch checklist](#16-launch-checklist)\n17. [Report back](#17-report-back)\n\n## 0. Conventions\n\n- **The CLI.** Run it as `npx --yes @littlefriend/cli <command>`. It needs Node 22 or later. This guide writes `littlefriend <command>` for short: type the full `npx` form, unless the CLI is installed globally.\n- **Scope flags.** Commands that work on a project take `--project <id>`, and commands that work in a workspace take `--workspace <id or name>`. Agent shells often drop environment variables between calls, so pass the flags on every command. The examples below leave them out to stay short. The CLI also reads `LITTLEFRIEND_PROJECT` and `LITTLEFRIEND_WORKSPACE`.\n- **Reading output.** Add `--json` when you need a value from the output, such as an id. Errors go to stderr with a non-zero exit code. With `--json`, they are also printed on stdout as `{ \"error\": { \"code\", \"message\" } }`.\n- **Secrets.** Server keys (`lfs_`), edge keys (`lfe_`), read keys (`lfr_`) and drain secrets are shown once. Never put them in your messages, logs, commits or the report. Write keys to an env file with `--write-env` (step 12). The public site key (`lf_`) is fine to commit.\n- **Credentials.** `~/.littlefriend/credentials.json` holds the sign-in. Never read it, print it or copy it into a repo.\n- **Deletes.** Never delete or revoke a project, key, goal, funnel or drain you did not create in this session.\n- **Repo rules win.** Follow the product repo's own rules for branches, commits, dependencies and deploys.\n- **The code wins.** `littlefriend <command> --help` shows a command's flags. If this guide and the CLI disagree, trust the CLI and say so in the report.\n\n## 1. What Little Friend is, and the rules\n\nLittle Friend is privacy-first web analytics (littlefriend.io). A small script, `lf.js`, counts page views, sources, clicks and named events without cookies. Server events count outcomes your backend confirms. Log drains and `@littlefriend/edge` show crawlers and AI agents, and the door decides which agents get in. Reports live at app.littlefriend.io.\n\nThe product must keep these rules. If a task would break one, stop and ask.\n\n1. **No personal data** in event names, property keys or values, routes, ids, or goal and funnel names. Personal data means emails, names, usernames, phone numbers, addresses, account or card numbers, text a person typed, and anything else that points to one person.\n2. **`identify` takes an opaque id** from the product's own database, such as `usr_8f3k2`. Never an email, a phone number, a name, or a hash of any of them.\n3. **No typed text.** Never send form values, search queries or error messages as properties. Report a failed form with a short category, such as `validation` or `server`.\n4. **Secret keys stay on the server.** Never put `lfs_`, `lfe_` or `lfr_` keys in client code, or in a variable a bundler exposes to the browser (`NEXT_PUBLIC_`, `VITE_`, `PUBLIC_`, `NUXT_PUBLIC_`, `EXPO_PUBLIC_`).\n5. **No extra tracking.** Do not add cookies, storage or fingerprinting for analytics. Do not work around Global Privacy Control or a visitor's opt-out: the script already honors both.\n6. **Unknown stays unknown.** Never combine an IP address with device traits to guess who someone is.\n\nLittle Friend also strips query strings and fragments (except allowlisted `utm_*` values), turns id-like and personal-looking path segments into `:id` or `:redacted`, drops property values that look like an email or a long number, and never reads form values or page text. Treat that as a safety net. Rule 1 still applies.\n\n## 2. Sign in once per machine\n\n```sh\nlittlefriend whoami\n```\n\nIf it names an account, go to step 3. Otherwise:\n\n```sh\nlittlefriend login\n```\n\nIt opens a browser, prints the URL too, and waits up to 5 minutes. The person who owns the Little Friend account approves the login in the browser. Tell them a sign-in page is waiting, then wait. If nobody approves in time, stop and ask. Do not retry in a loop.\n\n- The CLI acts with that person's role in each workspace. Creating projects, keys, goals, funnels and settings needs the editor or owner role.\n- In CI, set `LITTLEFRIEND_TOKEN` to an access token instead of signing in.\n- `littlefriend logout` revokes the sign-in and deletes the local credentials.\n\n## 3. Read the repo and plan the journeys\n\nCollect these facts before you create anything. They drive every later decision, and most of them go into the report.\n\n| Fact | Where to look |\n|---|---|\n| Product name and production domain | README, deploy config (`vercel.json`, `fly.toml`, `netlify.toml`, `wrangler.toml`), site URL env vars, canonical tags, sitemap config |\n| Every host the product serves pages from | `www.`, `app.`, docs subdomains, redirect config |\n| Web framework | `package.json` and config files. The table in step 5 maps them |\n| Where the HTML `<head>` is rendered | Root layout, `index.html`, document template |\n| Sign-in | Auth libraries (Auth.js, Clerk, Supabase, Lucia, Better Auth, Passport), `/login` and `/signup` routes, a current-user hook |\n| Money | Checkout, pricing, plans, trials, payment webhooks |\n| Onboarding and activation | First-run screens, \"create your first ...\" flows, invites |\n| Pages with private data | Account, settings, billing, admin, messages, documents, and any health, legal or financial records |\n| Consent tool | A cookie banner or consent manager (OneTrust, Cookiebot, Osano, Klaro, a custom one) |\n| Content Security Policy | Search code, config and headers files for `Content-Security-Policy` |\n| Server runtime and host | API routes, server framework (Express, Celsian, Hono, Next.js route handlers), Workers, Fly or Vercel config |\n| Env files | `.env`, `.env.local`, `.env.example`, and what `.gitignore` ignores |\n| App shells | `capacitor.config.*`, `ionic.config.json`, Cordova `config.xml`, `src-tauri/`, an Electron main process, React Native or Expo |\n| Existing analytics | Google Analytics, Plausible, PostHog, Segment or Vercel Analytics calls |\n\nExisting analytics: leave them in place unless asked to remove them. Their event lists are good candidates for your named events and goals.\n\n### Plan the journeys\n\nBefore you add a single event, decide what this product exists to get people to do, and which paths lead there. Steps 7 to 9 build exactly this plan, so every event, goal and funnel has a reason.\n\n1. **Say the product's job in one sentence:** who arrives, and what a good visit ends with. Read the home page, the pricing page, the main call to action, and the signup or checkout code.\n2. **List the outcomes, most valuable first.** Usually 1 to 3: money (purchase, upgrade, trial), an account (signup), a lead (contact, demo booked), or activation, the first time someone gets value (created a project, sent an invite, published a page).\n3. **Write one journey per top outcome, at most 3.** A journey is the path a person takes from arriving to the outcome, in 3 to 5 steps they would recognize: where it really starts (a landing page, pricing, a docs page), the moment they commit (opened signup, started checkout), and the outcome itself.\n4. **Decide how each step is seen.** A page is a route step (`route:/pricing`). An action inside a page, or something the server confirms, is a named event you add in step 7 (`event:signup.start`). The outcome becomes a goal in step 8, and the journey becomes a saved funnel in step 9.\n5. **Check the routes.** Read the router for each route step. Ids and personal segments are stored as `:id` or `:redacted`, so `/projects/42/settings` is stored as `/projects/:id/settings`.\n\nStart from the row that fits, then change it to match what the code really does:\n\n| Product | Outcome | Journey |\n|---|---|---|\n| App or SaaS | Signup, then activation | `route:/` \u2192 `route:/pricing` \u2192 `event:signup.start` \u2192 `goal:<Signup id>` \u2192 `goal:<Activated id>` |\n| Store | Purchase | `route:/products/:id` \u2192 `event:cart.add` \u2192 `event:checkout.start` \u2192 `goal:<Purchase id>` |\n| Services or lead generation | Contact or booking | `route:/` \u2192 `route:/services` \u2192 `event:contact.open` \u2192 `goal:<Contact sent id>` |\n| Docs or open source | Adoption | `route:/docs` \u2192 `route:/docs/getting-started` \u2192 `goal:<Install copied id>`, a goal on `install.copy` |\n| Marketing site for an app on another host | A visitor heads to sign up | `route:/` \u2192 `route:/pricing` \u2192 `goal:<Signup click id>`, a goal on `cta.signup` |\n\n**A journey ends at the edge of its host.** A journey-mode session lives in one tab's session storage, which browsers keep apart for each host. A visit that moves from `example.com` to `app.example.com` becomes two sessions. Give each host its own funnel: end the marketing site's funnel on a goal for a named event fired when the signup link is clicked (`lf('track', 'cta.signup')`), and start the app's funnel at its signup page.\n\nKeep the plan small and useful:\n\n- Pick what someone running the product would ask about on a Monday: \"Of the people who saw pricing, how many started a trial?\" If nobody would act on a number, do not build it.\n- At most 3 funnels and 5 goals per project. Every funnel ends on a goal.\n- A step the code cannot see yet (no route, no event) needs an event in step 7. Note it in the plan.\n- A server-confirmed outcome joins the journey only when the server event carries the browser's correlation id (step 12). Plan that, or end the funnel on the browser event just before it.\n- Aggregate mode has no sessions, so it has no funnels. Plan goals only, and say so in the report.\n\nWrite the plan into the report (step 17) as a table before you build anything:\n\n| Journey | Outcome goal | Steps, and how each is seen |\n|---|---|---|\n| Signup | Signup (server) | `/pricing` route, `signup.start` event on the button, `signup.completed` server event with the browser's correlation id |\n\n## 4. Workspace, project, mode and consent\n\n### Workspace\n\n```sh\nlittlefriend workspaces list\n```\n\n| Situation | Workspace |\n|---|---|\n| The person who asked named one | That one |\n| The list shows one workspace | That one |\n| Several, and nobody named one | Stop and ask. Never guess |\n| The one you need is missing | Stop and ask. The CLI does not create workspaces |\n\n### Reuse before you create\n\n```sh\nlittlefriend projects list --workspace <workspace>\n```\n\nIf a project already has the product's domain, reuse it: note its id and site key, and run `littlefriend projects get` to see its mode and allowed origins. Never create a second project for the same domain.\n\nOne product is one project, even when its marketing pages and app live on different hosts of the same domain. List every host in allowed origins.\n\n### Mode\n\n| The product has | Mode |\n|---|---|\n| Sign-in, signup, onboarding, checkout, or any flow of several steps | `journey` |\n| Only marketing or content pages, and no sign-in | `aggregate` |\n| It is a site you build for a client | `aggregate`, unless the client asked for journeys |\n\n- Aggregate mode keeps counts only, with no session or visitor key anywhere. It still gives views, sources, pages, devices, countries, events and goals.\n- Journey mode adds sessions, timelines, funnels, paths, entry and exit pages, session replay and identify. Its session id lives in the tab's session storage and ends after 30 idle minutes (24 hours at most).\n\n### Consent\n\n| Situation | Do this |\n|---|---|\n| The product already runs a consent tool | Use `--consent required` in step 5. Call `lf('consent', 'journey')` when the tool grants analytics consent, and `lf('consent', 'aggregate')` when it is withdrawn |\n| No consent tool, journey mode | Ask the person who asked whether to ship without a banner. Do not add a consent tool yourself |\n| Aggregate mode | Nothing to wire |\n\nUntil consent arrives, the script counts in aggregate mode. A browser that sends Global Privacy Control always stays in aggregate mode.\n\nIf the product has a privacy page, add this text for journey mode:\n\n> We use Little Friend for privacy-friendly analytics. It sets no cookies and does not store IP addresses. To connect the pages you view in one visit, it keeps a random id in your browser tab's session storage. The visit ends after 30 minutes of inactivity, and the id is gone when you close the tab. If your browser sends Global Privacy Control, your visit is only counted, never connected.\n\nIn aggregate mode, use only the first two sentences. With session replay on (step 11), add:\n\n> Some visits are recorded as a masked copy of the pages you view. Text stays hidden unless we chose to show it, form entries are never recorded, and recordings are deleted within 7 days.\n\nIf there is no privacy page, say so in the report.\n\n### Create the project\n\n```sh\nlittlefriend projects create --name \"Acme\" --domain acme.com --mode journey \\\n --origin https://acme.com --origin https://www.acme.com --origin http://localhost:3000 \\\n --timezone America/New_York\n```\n\nIt prints the project id and the public site key. Keep both for the rest of the guide and the report.\n\n- `--domain`: the production host. Little Friend stores it lowercase, without a scheme, path or `www.`.\n- `--origin`, once per origin: every production host that serves pages, plus the local dev server's origin so you can verify before deploy (step 15). Add app origins from step 14. Preview deploys and any origin not listed get `403` and count nowhere, which is intended. An empty list accepts every origin.\n- `--timezone`: the time zone the business reports in. Without it, reports use UTC.\n- To change origins later, run `littlefriend projects update` and pass the complete list: every origin already there plus the new ones.\n\n## 5. Install the script\n\nPrint the exact code for the stack:\n\n```sh\nlittlefriend snippet --framework next --mode journey\n```\n\nIt prints what to add, with the site key filled in, and the CSP lines the site needs. Add `--consent required` when step 4 said so. Add `--replay` only in step 11.\n\n| The repo has | `--framework` | Where the code goes |\n|---|---|---|\n| `next` | `next` | The root layout: `app/layout.tsx` (App Router) or `pages/_document.tsx` (Pages Router) |\n| `nuxt` | `nuxt` | `nuxt.config.ts` |\n| `@sveltejs/kit` | `sveltekit` | `src/app.html` |\n| `astro` | `astro` | The layout every page shares, often `src/layouts/Layout.astro` |\n| `@remix-run/*`, or React Router with `app/root.tsx` | `remix` | `app/root.tsx` |\n| `react` with Vite or another bundler, no framework | `react` | `index.html` |\n| `vue` with Vite | `vue` | `index.html` |\n| `@angular/core` | `angular` | `src/index.html` |\n| A WordPress theme or plugin | `wordpress` | Where the snippet says |\n| `what-framework`, a Shopify theme, plain HTML, anything else | `html` | The `<head>` every page shares: `index.html`, the document template, `layout/theme.liquid` |\n| A bundled app where you want typed functions | `npm` | The client entry, once at startup |\n\nThe snippet is the source of truth for the code. The last column is where to look first.\n\nRules:\n\n- **One tracker per page.** Use the tag or the npm package (`@littlefriend/tracker`), never both. Load it on every page, once.\n- **Single-page apps need nothing extra.** History API navigations count as page views. If the router does not use the History API, call `lf('page')` after each navigation.\n- **Outside production, mark traffic as test.** Add `data-test` to the tag, or pass `test: true` to `init`, when the build is not production (for example `process.env.NODE_ENV !== 'production'` or `import.meta.env.DEV`). Test traffic shows in the live install check and never in reports.\n- **Name dynamic routes.** Id-like segments already become `:id`. For readable groups, such as `/blog/:slug`, add `data-routes='[\"/blog/:slug\"]'` to the tag, pass `routes` to `init`, or call `lf('route', '/blog/:slug')`. Goals and funnel steps match these routes exactly.\n- **Calls before the script loads.** If the product's own code calls `lf(...)`, add this stub above the tag, so `lf` exists before the deferred script runs. Calls wait in a queue until it loads.\n\n```html\n<script>window.lf=window.lf||function(){(lf.q=lf.q||[]).push(arguments)}</script>\n```\n\n- **Secret scanners.** The site key (`lf_`) is public, but gitleaks and similar scanners may flag it as an API key. Add an allowlist entry for that exact key rather than hiding it. A constant named `LITTLE_FRIEND_SITE` rather than `..._KEY` trips fewer rules.\n- **Monorepo build caches.** If the tag only renders in production (for example on `VERCEL_ENV`), declare that variable for the build task in `turbo.json` or the cache's equivalent. Otherwise a preview build and a production build can share one cached output.\n\nWith the tag in a TypeScript app, declare the global once, for example in `src/lf.d.ts`:\n\n```ts\ndeclare global {\n function lf(command: string, ...args: unknown[]): void;\n}\nexport {};\n```\n\n## 6. Content Security Policy\n\nSkip this step if the product sets no CSP. Otherwise add:\n\n```text\nscript-src https://cdn.littlefriend.io\nconnect-src https://in.littlefriend.io\n```\n\n- With the npm package, the tracker is part of your bundle, so only `connect-src` is needed.\n- The replay script comes from the same host as `lf.js` and sends to the same collector. It needs no other entries.\n- A policy with a nonce or `'strict-dynamic'` ignores host entries for scripts. Give the tag the page's nonce, or use the npm package.\n- Update every copy of the policy: `Content-Security-Policy-Report-Only`, `<meta http-equiv>` tags, and the test files that assert headers.\n- Common places: `next.config.*` `headers()`, `middleware.ts` or `proxy.ts`, `vercel.json`, `netlify.toml`, `_headers`, Helmet options, server header code.\n\n## 7. Custom events\n\nThe script sends these on its own: page views, outbound links, downloads, engaged time and, with `data-scroll`, scroll depth. The `$` prefix is reserved for them.\n\nAdd the named events your journey plan (step 3) needs, and the few the product's key feature needs. Three ways to add more:\n\n```html\n<!-- A named click: sends $click with { \"id\": \"pricing.start_trial\", \"plan\": \"pro\" } -->\n<button data-lf=\"pricing.start_trial\" data-lf-plan=\"pro\">Start free trial</button>\n\n<!-- A tracked form: sends $form_start and $form_submit with { \"id\": \"signup\" } -->\n<form data-lf-form=\"signup\">...</form>\n```\n\n```ts\n// A named event, after the thing really happened\nlf('track', 'signup.completed', { plan: 'pro' });\n\n// A failed form: a short category, never the message\nlf('formError', 'signup', 'validation');\n```\n\nWith npm, import the same names: `track`, `formError`, `page`, `route`, `consent`, `optout`, `optin`.\n\n**Goals and funnel steps match an event name or a route, never a property.** Every `data-lf` click arrives as `$click`, and every tracked form as `$form_submit`. For anything that becomes a goal or a funnel step, fire its own named event with `track`.\n\n### Names\n\n- `area.action`, lowercase: dots between parts, underscores inside a part. `signup.start`, `signup.completed`, `onboarding.project_created`, `checkout.start`, `order.completed`, `plan.upgraded`, `invite.sent`.\n- Past tense for outcomes (`completed`, `created`, `sent`). `start` or `open` for intent.\n- The pattern is `^[a-z][a-z0-9_.:-]{0,63}$`. `data-lf` ids follow the same convention.\n- Fire outcome events after the server call succeeds, never on the button press. Fire intent events on the press.\n- Aim for 5 to 15 named events: the steps of signup, onboarding, activation and checkout, and the product's key feature. Do not name every click.\n\n| Good | Bad | Why the bad one fails |\n|---|---|---|\n| `signup.completed` | `Signup Completed` | Uppercase and spaces are refused |\n| `checkout.start` | `click_button_3` | Says nothing about the product |\n| `invite.sent` with `{ role: 'editor' }` | `invite.sent.jane@acme.com` | Personal data in the name |\n| `order.completed` with `{ plan: 'pro' }` | `order_8812_completed` | An id in the name makes a new event per order |\n| `search.submit` with `{ results: 12 }` | `search.submit` with `{ query: 'knee pain' }` | Typed text is personal data |\n| `project.created` | `$project_created` | `$` is reserved |\n\n### Properties\n\n- Up to 8 per event. Keys are lowercase snake case, up to 32 characters. Values are strings, numbers or booleans. Strings are cut to 64 characters.\n- Use small fixed sets (`plan`, `step`, `method`, `role`, `source`) and counts.\n- A value that looks like an email or a long run of digits is dropped, even when sent on purpose.\n\n## 8. Goals\n\nA goal is a conversion. Create 2 to 5, one for each outcome in your journey plan (step 3), most valuable first.\n\n| Product | Goals to start with |\n|---|---|\n| App or SaaS with sign-in | Signup (server), activation: the first key action, upgrade or trial started (server) |\n| Store | Purchase (server, with value), checkout started |\n| Lead generation | Contact form sent, demo booked, the thank-you page |\n| Content or docs | Newsletter signup, a named event on the link to the product's signup |\n\n- Prefer server-confirmed goals for money and accounts: `--source server --server-confirmed`. `--source server` counts only events your server sends with a secret key, and `--server-confirmed` also marks the goal that way in reports, so a reader knows a browser cannot fake it. Use browser goals for intent, or when there is no backend.\n- A route goal matches the stored route exactly. Check the routes with `littlefriend report pages` first.\n- Create goals before launch. A goal counts from the moment it is saved.\n- Name goals in plain words: \"Signup\", \"Purchase\", \"Demo booked\".\n\n```sh\nlittlefriend goals create --name \"Signup\" --event signup.completed --source server --server-confirmed\nlittlefriend goals create --name \"Purchase\" --event order.completed --source server --server-confirmed\nlittlefriend goals create --name \"Activated\" --event project.created\nlittlefriend goals create --name \"Contact sent\" --route /contact/thanks\nlittlefriend goals list\n```\n\nKeep the goal ids (`goal_...`) for funnels and the report.\n\n## 9. Funnels\n\nJourney mode only. Save one funnel for each journey in your plan (step 3), 1 to 3 in all, named after the journey.\n\nA funnel has 1 to 8 steps in order. Each step is `route:/path`, `event:<name>` or `goal:<goalId>`. A session reaches a step when it has done the steps before it, in that order.\n\n| Flow | Steps |\n|---|---|\n| Signup | `route:/pricing` \u2192 `event:signup.start` \u2192 `goal:<Signup id>` |\n| Activation | `goal:<Signup id>` \u2192 `event:onboarding.profile_completed` \u2192 `goal:<Activated id>` |\n| Checkout | `route:/pricing` \u2192 `event:checkout.start` \u2192 `goal:<Purchase id>` |\n\n- Keep 3 to 5 steps. Start broad and end on a goal.\n- A server event joins a session only when it carries that session's correlation id or session id (step 12). Without one, a server-only goal as the last step is never reached. Pass a correlation id, or end on a browser event.\n\n```sh\nlittlefriend funnels create --name \"Signup\" \\\n --step route:/pricing --step event:signup.start --step goal:goal_XXXXXXXX\nlittlefriend funnels list\nlittlefriend funnels report fnl_XXXXXXXX --from 2026-10-01 --to 2026-10-07\n```\n\nDates are `YYYY-MM-DD` in the project's time zone.\n\n## 10. Identify signed-in people\n\nJourney mode only. `lf('identify', ...)` is handled by the replay script, so it needs step 11. Without replay, skip this step.\n\n```ts\n// Wherever the app knows the signed-in user: after sign-in and on each page load\nlf('identify', user.id); // your own opaque id, such as usr_8f3k2\n\n// On sign-out\nlf('identify', null);\n```\n\nWith npm: `import { identify } from '@littlefriend/replay'`, then `identify(user.id)` and `identify(null)`.\n\n- The ref is 1 to 64 letters, digits, `_`, `.`, `:` and `-`. UUIDs and prefixed ids work.\n- Prefix numeric ids, such as `usr_4821937`. A ref of seven or more bare digits is refused.\n- Never an email, a phone number, a name, a username, or a hash of any of them. Emails are refused.\n- The ref lasts for the journey session in that tab. Call it on each page load while signed in, so the next session carries it too.\n- Before consent it waits in memory, and a Global Privacy Control visitor sends nothing.\n- With a ref, a workspace owner can find one person's sessions and erase their sessions, events and recordings (Settings, Replay, Forget a person).\n\n## 11. Session replay\n\nReplay records a journey session as a masked copy of the page: layout, scrolling, clicks and page changes. Every word is masked until you choose to show it. Form values, checked boxes, chosen options, images, video, audio, canvas and iframes are never recorded.\n\n### Decide\n\n| Situation | Replay |\n|---|---|\n| Journey mode, and the person who asked wants replay | On |\n| Journey mode, and nobody said | Ask first. Each workspace records up to 10 sessions a month free. More needs a card on file (Settings, Billing). Past the allowance, recording stops until a card is added or the month ends. Your own test recordings count too |\n| Pages show health, legal or financial records, or other people's private messages | Off, unless the owner asks |\n| Aggregate mode | Not available |\n\n### Defaults\n\n| Setting | Default |\n|---|---|\n| Sample rate | `100`, unless the site expects more than about 1,000 recorded sessions a day. Then sample down, for example to `25`. Each project stores up to 1 GiB of recordings a day, about 2,000 typical recordings, and refuses more until midnight UTC |\n| Text shown | Nav, header, footer, headings, buttons, labels, table headers, legends, tabs, menu items |\n| Hidden elements | Support chat, third-party widgets, and any region that lists other people's data |\n| Pages never recorded | `/account`, `/settings`, `/billing`, `/checkout`, `/admin`, plus every private-data route from step 3 |\n| Minimum active time | 2 seconds, the built-in default. A shorter recording is dropped unless it has at least 3 clicks |\n\n### Turn it on\n\n```sh\nlittlefriend replay enable --rate 100\nlittlefriend replay set \\\n --unmask nav --unmask header --unmask footer \\\n --unmask h1 --unmask h2 --unmask h3 --unmask h4 \\\n --unmask button --unmask label --unmask th --unmask legend \\\n --unmask \"[role=button]\" --unmask \"[role=tab]\" --unmask \"[role=menuitem]\" \\\n --block .support-chat \\\n --exclude /account --exclude /settings --exclude /billing --exclude /checkout --exclude /admin\nlittlefriend snippet --framework next --mode journey --replay\n```\n\n- `replay set` replaces each list. Pass every item every time.\n- Add the replay code the snippet prints after `lf.js`, with the same site key. With npm, call `startReplay({ site })` from `@littlefriend/replay` after `init`.\n- An excluded route covers itself and every path below it: `/account` covers `/account/billing`. `*` stands for one segment: `/projects/*/settings` covers `/projects/acme/settings` and everything below it. Up to 50 routes, each at most 100 characters, with no query or fragment.\n- Selectors: tag names, classes, ids and attribute selectors with plain values, joined by spaces, `>` or commas. Pseudo-classes, sibling selectors and `*` are refused. Up to 50 per list, 200 characters each.\n\n### Mark the HTML\n\nEmails, phone numbers and card numbers stay masked even in shown text. Names do not. Search the shown regions (header, nav, account menu, buttons) for places that print the signed-in person's name, company, initials or avatar label, and mask them again:\n\n```html\n<header>\n <nav>...</nav>\n <button class=\"account-menu\" data-lf-mask>{user.name}</button>\n</header>\n\n<aside class=\"support-chat\" data-lf-block>...</aside>\n```\n\n- `data-lf-mask` masks text again inside a shown region.\n- `data-lf-block` leaves an element out, drawn as an empty box. Use it for regions whose shape alone says too much, and on sensitive parts of routes that draw their page late after navigation.\n- `data-lf-unmask` shows the text of one element, for plain product copy such as plan names and prices.\n\n`littlefriend replay get` shows the settings, and says the replay script is installed once the first recording arrives.\n\n## 12. Server events\n\nSend outcomes the backend confirms: account created, payment succeeded, plan changed. Default: yes for every product with sign-in or payments.\n\n### The key\n\n```sh\ngit check-ignore -q .env.local && echo ignored\nlittlefriend keys create --kind server --label \"acme server\" --write-env .env.local --env-name LF_SERVER_KEY\n```\n\n- Use the env file the framework loads (`.env.local` for Next.js, often `.env` elsewhere). It must be ignored by git. If `git check-ignore` prints nothing, add the file to `.gitignore` first.\n- With `--write-env`, the CLI appends `LF_SERVER_KEY=...` only if the name is not set yet, and never prints the secret.\n- Add `LF_SERVER_KEY=` with no value to `.env.example`, if the repo has one.\n- Production needs the same variable in the host's secret store. Copy it from the env file without printing it, if you have the host's CLI and the repo's rules allow it. Otherwise list it under \"Needs a person\". Check each host CLI's `--help` before you run these:\n\n```sh\n# Vercel\ngrep '^LF_SERVER_KEY=' .env.local | cut -d= -f2- | tr -d '\\n' | vercel env add LF_SERVER_KEY production\n\n# Fly\ngrep '^LF_SERVER_KEY=' .env | fly secrets import -a <app>\n\n# Cloudflare Workers (the edge key from step 13)\ngrep '^LF_EDGE_KEY=' .env | cut -d= -f2- | tr -d '\\n' | wrangler secret put LF_EDGE_KEY\n```\n\n### Send from Node.js\n\nInstall `@littlefriend/node` with the repo's package manager (Node 18.17 or later). Create one client at module scope:\n\n```ts\n// lib/little-friend.ts\nimport { LittleFriend } from '@littlefriend/node';\n\nconst key = process.env.LF_SERVER_KEY;\nexport const lf = key ? new LittleFriend({ key }) : null;\n```\n\nThen send each outcome where the backend confirms it: after the account row is written, in the payment webhook, after the plan change commits.\n\n```ts\nimport { createHash } from 'node:crypto';\nimport { lf } from './lib/little-friend';\n\nlf?.track({\n // 8 to 32 letters, digits, _ or -. The same id on a retry counts once.\n id: createHash('sha256').update(order.id).digest('base64url').slice(0, 32),\n name: 'order.completed',\n props: { plan: order.plan },\n value: { amount: order.totalCents, currency: 'USD' }, // minor units\n correlationId: order.checkoutRef, // optional, see below\n});\n\nawait lf?.flush(); // in a serverless function, before it returns\n```\n\n- `track` never throws. A bad event goes to `onError`, which logs a warning by default.\n- In serverless functions (Vercel, Next.js route handlers and server actions), `await lf.flush()` before returning. In a long-running server, `await lf.shutdown()` when the process exits.\n- Derive `id` from the record, as above. Raw UUIDs (36 characters) and short numeric ids fail the id rule.\n- Other languages: POST `{ \"v\": 1, \"events\": [ ... ] }` to `https://in.littlefriend.io/v1/server` with `Authorization: Bearer $LF_SERVER_KEY`. Retry `429` and `503` after `Retry-After`. Never retry a `400`. Details: https://littlefriend.io/docs/goals#http\n\n### Join server outcomes to journeys\n\nIn journey mode, a server event joins the visitor's session when it carries the same correlation id as a browser event:\n\n```ts\n// Browser, when checkout starts: a random id for this attempt, sent to the server with the form\nconst checkoutRef = crypto.randomUUID();\nlf('track', 'checkout.start', { plan: 'pro' }, checkoutRef);\n```\n\nThe server stores `checkoutRef` with the order and passes it as `correlationId`. A correlation id is 16 to 64 letters, digits, `_` or `-`, and never only digits and dashes. Aggregate mode drops it.\n\n## 13. Crawlers and AI agents: the door and a log drain\n\n`lf.js` sees only browsers. Crawlers and AI agents rarely run JavaScript, so Little Friend needs the requests themselves.\n\n| Where the product runs | See agents with | Door |\n|---|---|---|\n| Vercel, any framework, static too | A Vercel log drain | Next.js: `nextProxy` in `proxy.ts` (Next.js 16) or `middleware.ts` (Next.js 15). Other frameworks: skip it and say so |\n| Next.js on another host | `wrapFetch(edge, handler, { waitUntil })` in route handlers, or `nodeMiddleware(edge)` in a custom Node server | `nextProxy`, as on Vercel |\n| Cloudflare Workers | `withLittleFriend` from `@littlefriend/edge` | Add `door: createDoor` |\n| Node with Express, Connect or `node:http` | `nodeMiddleware(edge)` | `nodeDoor(createDoor(lf), createEdge(lf))` in its place |\n| Bun, Deno, Hono or another fetch handler | `wrapFetch(edge, handler)` | `wrapFetch(edge, handler, { door })` |\n| Celsian | `observeCelsian(app, edge)` | None built in. Skip it and say so |\n| Static hosting without functions, not on Vercel | Only with a Worker in front | Only with a Worker in front |\n\nA request both a drain and the edge package report is counted once.\n\nRequests to the project's ignored routes are counted and not kept. Every project starts with `/api`, because an app calling its own API (session checks, polling, presence) is not a crawler or an agent. Add the product's other API paths, such as `/trpc` or `/graphql`:\n\n```sh\nlittlefriend projects update --add-ignored-route /trpc\n```\n\nRemove `/api` only when the owner wants to watch who calls the API, and say so in the report.\n\n### A Vercel log drain\n\n```sh\nlittlefriend drains list\nlittlefriend drains create --provider vercel\n```\n\n- Check `drains list` first. Reuse an active drain.\n- `drains create` prints the endpoint, the header and the signing secret, once. Create it only when you can paste them into Vercel in the same sitting: in the team's settings, add a log drain for this project only, all sources, production, and 100% sampling. Drains need a Vercel Pro or Enterprise team.\n- If you cannot reach Vercel's settings, do not create the drain. List it under \"Needs a person\": they can do both halves on the dashboard's Agents page, with Add a Vercel log drain.\n- A lost secret: `littlefriend drains rotate <id>` issues a new pair and keeps the old one working for 24 hours.\n- Within minutes of traffic, the Coverage card on the Agents page shows the drain as Live.\n\n### `@littlefriend/edge` and the door\n\nUse this when the product has code that runs on every request. Install `@littlefriend/edge` 0.3.0 or later. The door came in 0.2.0, and 0.3.0 stops sending requests to ignored routes. If the repo already depends on `^0.2.0`, change it to `^0.3.0`: that range never picks up 0.3.0 on its own.\n\n1. Create an edge key into the env file, as in step 12:\n\n```sh\nlittlefriend keys create --kind edge --label \"acme edge\" --write-env .env.local --env-name LF_EDGE_KEY\n```\n\n2. Install `@littlefriend/edge` and wire it for the runtime in the table above. The exact code for each runtime is on https://littlefriend.io/docs/agents (sections Any host and The door). For Next.js 16:\n\n```ts\n// proxy.ts\nimport { createDoor, createEdge, nextProxy } from '@littlefriend/edge';\nimport { NextResponse } from 'next/server';\n\nconst lf = { key: process.env.LF_EDGE_KEY!, ipHeader: 'x-forwarded-for' };\nexport const proxy = nextProxy(createDoor(lf), NextResponse, createEdge(lf));\nexport const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };\n```\n\n3. Set `ipHeader` to the header the host sets to the client address: `x-forwarded-for` on Vercel, `cf-connecting-ip` on Cloudflare, `fly-client-ip` on Fly. Without it, no address is sent and operator address checks cannot run.\n\n4. Pick a preset and keep dry run:\n\n```sh\nlittlefriend door set --preset verified_only --mode dry_run\nlittlefriend door simulate --ua \"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2; +https://openai.com/gptbot)\" --path /blog\n```\n\n| Product | Preset |\n|---|---|\n| A store with `/checkout`, `/cart` or `/account` | `commerce` |\n| An app or API with sign-in | `verified_only` |\n| Content, docs or marketing | `no_training` |\n| Unsure | `open` |\n\n- Dry run decides every request and records what it would have done. It never changes a response.\n- **Never switch the door to live.** The owner does that after reading 7 days of the door's report on the Agents page.\n- A browser always gets in, whatever the rules say.\n- `commerce` matches `/checkout`, `/cart` and `/account`. If the store uses other paths, say so in the report.\n\n## 14. Hybrid and native apps\n\n**Hybrid apps** (Capacitor, Ionic, Cordova, Tauri, Electron, React Native WebView) show web pages. Install the script in the app's web code as in step 5, then add the origin the web view sends to the project's allowed origins, with the complete list:\n\n```sh\nlittlefriend projects update --origin https://acme.com --origin https://www.acme.com \\\n --origin http://localhost:3000 --origin capacitor://localhost --origin https://localhost\n```\n\n| App shell | Origin to add |\n|---|---|\n| Capacitor on iOS | `capacitor://localhost` |\n| Capacitor on Android | `https://localhost` |\n| Ionic with its Cordova web view | `ionic://localhost` on iOS, `http://localhost` on Android |\n| Cordova | `app://localhost` on iOS (scheme preference set to `app`), `https://localhost` on Android |\n| Tauri | `tauri://localhost` on macOS, iOS and Linux. `http://tauri.localhost` on Windows and Android, or `https://tauri.localhost` with `useHttpsScheme` |\n| Electron | The scheme and host the app serves from, such as `app://myapp` |\n| React Native WebView | The origin of the site it loads |\n\n- If the shell's config changes the scheme or host, add the ones it sets.\n- An Electron app that loads pages from files sends no origin. Leave the list empty, or serve the app from its own scheme (for example `electron-serve`, which serves `app://-`).\n- If the repo deliberately skips analytics inside the shell, keep that and say so in the report.\n\n**Native screens** (SwiftUI, UIKit, Jetpack Compose, Flutter, React Native views) have no web page for the script. Send the outcomes they lead to from the backend with `@littlefriend/node` (step 12). The server key never goes inside the app.\n\n## 15. Verify\n\n1. Run the product: the local dev server (its origin is on the list from step 4), or the deployed site.\n2. Load the site in a real browser (Playwright, agent-browser, or a person). `curl` does not run the script. Headless Chrome says so in its user agent and is counted as automation, so its visits stay out of page views and funnels, which count people. For the journey walks in item 9, run the browser headed or give it a desktop Chrome user agent. Then run `littlefriend verify --source browser --since 10 --wait 120`. It exits 0 once an accepted event from the browser in the last 10 minutes shows up, and prints its time, route and source. `--source browser` matters on a project with a log drain or the edge SDK, whose events would otherwise pass for the tag's. It exits 1 when none arrives in time. On a project that already has traffic, keep `--since` short, so an older event cannot pass for yours.\n3. In the browser's network panel, `POST https://in.littlefriend.io/v1/e` answers `202` with `{\"accepted\": n, \"dropped\": 0}`. The console shows no CSP errors.\n4. Click through each flow with a named event and confirm each name in the request bodies. Any `dropped` above 0 means a name or property broke a rule. The live install check (Settings, Install) shows every field kept, every property dropped, and why.\n5. Replay: in the browser's network panel, `GET https://in.littlefriend.io/v1/r/config?k=<site key>` returns `\"on\": true`, and `POST /v1/r` answers `202`. From `curl`, send the page's origin with `-H 'Origin: https://<domain>'`: without an allowed origin the answer is `\"on\": false`. Then `littlefriend replay get` reads installed.\n6. Server events: run the flow that sends one. `verify` shows source `server`, or `await lf.flush()` resolves with `accepted: 1`.\n7. Agents: `littlefriend door get` shows the policy and its mode. On the dashboard's Agents page, the Coverage card shows the drain as Live, and the door page shows that the door has read its rules.\n8. A few minutes later: `littlefriend report overview` and `littlefriend report goals` for a sanity check.\n9. Walk each journey in your plan once, in one tab, step by step, on a page without `data-test` (test events stay out of reports). A few minutes later, `littlefriend funnels report fnl_XXXXXXXX` shows that session at every step. A step at 0 means its route or event name does not match what arrives: compare it with `littlefriend report pages` and the request bodies.\n\nVerify on production after the deploy too, without `data-test`.\n\n| Symptom | Cause |\n|---|---|\n| No request to `in.littlefriend.io` | CSP blocks the script, or the tag never rendered |\n| `403` `origin_not_allowed` | The page's origin is not in allowed origins |\n| `400` | Wrong or malformed site key, or a malformed batch |\n| Sessions unavailable, funnels empty | The project or the snippet is not in journey mode. Both must be |\n| Replay `403` `replay_off`, `session_in_aggregate_mode` or `route_excluded` | Replay is off, the project is in aggregate mode, or the page is excluded |\n| Replay `402` `replay_card_required` | The workspace used its free recordings this month and has no card on file |\n| Replay `429` `quota_exceeded` | The project stored its 1 GiB of recordings for the day, or one address used its share of that. It clears at midnight UTC. If it happens often, lower the sample rate |\n| Server events `rejected` in `onError` | Wrong kind of key, or a revoked one |\n\n## 16. Launch checklist\n\n- [ ] One project for the domain, in the right workspace, in the right mode.\n- [ ] Allowed origins list every production host, every app origin and the dev origin.\n- [ ] The script is on every page, once, with `data-test` outside production.\n- [ ] CSP updated, including report-only copies and header tests.\n- [ ] Every goal and funnel step has its own named event. No personal data in names, properties or routes.\n- [ ] The journey plan is written down, with one goal per outcome.\n- [ ] 2 to 5 goals and, in journey mode, 1 to 3 funnels saved, one per journey in the plan.\n- [ ] Each journey was walked once and shows at every step of its funnel report.\n- [ ] `identify` sends an opaque id, and `null` on sign-out (replay only).\n- [ ] Replay: shown regions checked for names, private routes excluded, widgets blocked.\n- [ ] Server key in an ignored env file and in the host's secrets. Serverless code flushes.\n- [ ] Door in dry run where the runtime allows it. Drain connected on Vercel.\n- [ ] Ignored routes cover the product's own API paths.\n- [ ] Privacy page text added.\n- [ ] `littlefriend verify --source browser` exits 0 on production, and batches show `\"dropped\": 0`.\n- [ ] No secret in your changes: `git diff <base branch> | grep -E 'lf[ser]_[A-Za-z0-9]'` prints nothing.\n- [ ] Report sent.\n\n## 17. Report back\n\nEnd with this report, filled in. Use \"skipped\" with a reason where a step did not apply. Never include a secret.\n\n```markdown\n## Little Friend setup: <product>\n\n- Repo and branch:\n- Domain and hosts:\n- Workspace:\n- Project id and site key (lf_):\n- Mode and consent:\n- Allowed origins:\n- Snippet: --framework <name>, in <file>\n- CSP: <files changed, or none needed>\n- Journey plan: <the table from step 3: journey, outcome goal, steps and how each is seen>\n- Named events: <name, where it fires>\n- Goals: <id, name, match>\n- Funnels: <id, name, steps>\n- Identify: <where it is called, what id it sends, or skipped>\n- Replay: <on or off, rate, shown, hidden, excluded routes>\n- Server events: <events, files, env var names, host secrets set or not>\n- Agents: <drain id and status, door runtime, preset and mode, or skipped>\n- Ignored routes: <the list, and any change from /api>\n- Hybrid or native: <origins added, backend events, or none>\n- Privacy page: <updated, or no privacy page>\n- Verify: <time, route and source that verify printed, local and production>\n- Skipped, and why:\n- Needs a person: <drains to connect, secrets to set, questions>\n- Guide or CLI problems found:\n```\n", bundled: true } : { text: GUIDE_PLACEHOLDER, bundled: false };
|
|
3803
|
+
return true ? { text: "# Set up Little Friend in a product: guide for coding agents\n\nYou are a coding agent working in a product's repository. This guide takes you from nothing to a verified Little Friend install: the project, the script, events, goals, funnels, session replay, server events and AI agent visibility. It ends with a report for the person who asked.\n\nWork through the steps in order. Each decision has a default: use it unless the repo or the person who asked says otherwise. When a step does not apply, skip it and say why in the report.\n\n## Contents\n\n0. [Conventions](#0-conventions)\n1. [What Little Friend is, and the rules](#1-what-little-friend-is-and-the-rules)\n2. [Sign in once per machine](#2-sign-in-once-per-machine)\n3. [Read the repo and plan the journeys](#3-read-the-repo-and-plan-the-journeys)\n4. [Workspace, project, mode and consent](#4-workspace-project-mode-and-consent)\n5. [Install the script](#5-install-the-script)\n6. [Content Security Policy](#6-content-security-policy)\n7. [Custom events](#7-custom-events)\n8. [Goals](#8-goals)\n9. [Funnels](#9-funnels)\n10. [Identify signed-in people](#10-identify-signed-in-people)\n11. [Session replay](#11-session-replay)\n12. [Server events](#12-server-events)\n13. [Crawlers and AI agents: the door and a log drain](#13-crawlers-and-ai-agents-the-door-and-a-log-drain)\n14. [Hybrid and native apps](#14-hybrid-and-native-apps)\n15. [Verify](#15-verify)\n16. [Launch checklist](#16-launch-checklist)\n17. [Report back](#17-report-back)\n\n## 0. Conventions\n\n- **The CLI.** Run it as `npx --yes @littlefriend/cli <command>`. It needs Node 22 or later. This guide writes `littlefriend <command>` for short: type the full `npx` form, unless the CLI is installed globally.\n- **Scope flags.** Commands that work on a project take `--project <id>`, and commands that work in a workspace take `--workspace <id or name>`. Agent shells often drop environment variables between calls, so pass the flags on every command. The examples below leave them out to stay short. The CLI also reads `LITTLEFRIEND_PROJECT` and `LITTLEFRIEND_WORKSPACE`.\n- **Reading output.** Add `--json` when you need a value from the output, such as an id. Errors go to stderr with a non-zero exit code. With `--json`, they are also printed on stdout as `{ \"error\": { \"code\", \"message\" } }`.\n- **Secrets.** Server keys (`lfs_`), edge keys (`lfe_`), read keys (`lfr_`) and drain secrets are shown once. Never put them in your messages, logs, commits or the report. Write keys to an env file with `--write-env` (step 12). The public site key (`lf_`) is fine to commit.\n- **Credentials.** `~/.littlefriend/credentials.json` holds the sign-in. Never read it, print it or copy it into a repo.\n- **Deletes.** Never delete or revoke a project, key, goal, funnel or drain you did not create in this session.\n- **Repo rules win.** Follow the product repo's own rules for branches, commits, dependencies and deploys.\n- **The code wins.** `littlefriend <command> --help` shows a command's flags. If this guide and the CLI disagree, trust the CLI and say so in the report.\n\n## 1. What Little Friend is, and the rules\n\nLittle Friend is privacy-first web analytics (littlefriend.io). A small script, `lf.js`, counts page views, sources, clicks and named events without cookies. Server events count outcomes your backend confirms. Log drains and `@littlefriend/edge` show crawlers and AI agents, and the door decides which agents get in. Reports live at app.littlefriend.io.\n\nThe product must keep these rules. If a task would break one, stop and ask.\n\n1. **No personal data** in event names, property keys or values, routes, ids, or goal and funnel names. Personal data means emails, names, usernames, phone numbers, addresses, account or card numbers, text a person typed, and anything else that points to one person.\n2. **`identify` takes an opaque id** from the product's own database, such as `usr_8f3k2`. Never an email, a phone number, a name, or a hash of any of them.\n3. **No typed text.** Never send form values, search queries or error messages as properties. Report a failed form with a short category, such as `validation` or `server`.\n4. **Secret keys stay on the server.** Never put `lfs_`, `lfe_` or `lfr_` keys in client code, or in a variable a bundler exposes to the browser (`NEXT_PUBLIC_`, `VITE_`, `PUBLIC_`, `NUXT_PUBLIC_`, `EXPO_PUBLIC_`).\n5. **No extra tracking.** Do not add cookies, storage or fingerprinting for analytics. Do not work around Global Privacy Control or a visitor's opt-out: the script already honors both.\n6. **Unknown stays unknown.** Never combine an IP address with device traits to guess who someone is.\n\nLittle Friend also strips query strings and fragments (except allowlisted `utm_*` values), turns id-like and personal-looking path segments into `:id` or `:redacted`, drops property values that look like an email or a long number, and never reads form values or page text. Treat that as a safety net. Rule 1 still applies.\n\n## 2. Sign in once per machine\n\n```sh\nlittlefriend whoami\n```\n\nIf it names an account, go to step 3. Otherwise:\n\n```sh\nlittlefriend login\n```\n\nIt opens a browser, prints the URL too, and waits up to 5 minutes. The person who owns the Little Friend account approves the login in the browser. Tell them a sign-in page is waiting, then wait. If nobody approves in time, stop and ask. Do not retry in a loop.\n\n- The CLI acts with that person's role in each workspace. Creating projects, keys, goals, funnels and settings needs the editor or owner role.\n- In CI, set `LITTLEFRIEND_TOKEN` to an access token instead of signing in.\n- `littlefriend logout` revokes the sign-in and deletes the local credentials.\n\n## 3. Read the repo and plan the journeys\n\nCollect these facts before you create anything. They drive every later decision, and most of them go into the report.\n\n| Fact | Where to look |\n|---|---|\n| Product name and production domain | README, deploy config (`vercel.json`, `fly.toml`, `netlify.toml`, `wrangler.toml`), site URL env vars, canonical tags, sitemap config |\n| Every host the product serves pages from | `www.`, `app.`, docs subdomains, redirect config |\n| Web framework | `package.json` and config files. The table in step 5 maps them |\n| Where the HTML `<head>` is rendered | Root layout, `index.html`, document template |\n| Sign-in | Auth libraries (Auth.js, Clerk, Supabase, Lucia, Better Auth, Passport), `/login` and `/signup` routes, a current-user hook |\n| Money | Checkout, pricing, plans, trials, payment webhooks |\n| Onboarding and activation | First-run screens, \"create your first ...\" flows, invites |\n| Pages with private data | Account, settings, billing, admin, messages, documents, and any health, legal or financial records |\n| Consent tool | A cookie banner or consent manager (OneTrust, Cookiebot, Osano, Klaro, a custom one) |\n| Content Security Policy | Search code, config and headers files for `Content-Security-Policy` |\n| Server runtime and host | API routes, server framework (Express, Celsian, Hono, Next.js route handlers), Workers, Fly or Vercel config |\n| Env files | `.env`, `.env.local`, `.env.example`, and what `.gitignore` ignores |\n| App shells | `capacitor.config.*`, `ionic.config.json`, Cordova `config.xml`, `src-tauri/`, an Electron main process, React Native or Expo |\n| Existing analytics | Google Analytics, Plausible, PostHog, Segment or Vercel Analytics calls |\n\nExisting analytics: leave them in place unless asked to remove them. Their event lists are good candidates for your named events and goals.\n\n### Plan the journeys\n\nBefore you add a single event, decide what this product exists to get people to do, and which paths lead there. Steps 7 to 9 build exactly this plan, so every event, goal and funnel has a reason.\n\n1. **Say the product's job in one sentence:** who arrives, and what a good visit ends with. Read the home page, the pricing page, the main call to action, and the signup or checkout code.\n2. **List the outcomes, most valuable first.** Usually 1 to 3: money (purchase, upgrade, trial), an account (signup), a lead (contact, demo booked), or activation, the first time someone gets value (created a project, sent an invite, published a page).\n3. **Write one journey per top outcome, at most 3.** A journey is the path a person takes from arriving to the outcome, in 3 to 5 steps they would recognize: where it really starts (a landing page, pricing, a docs page), the moment they commit (opened signup, started checkout), and the outcome itself.\n4. **Decide how each step is seen.** A page is a route step (`route:/pricing`). An action inside a page, or something the server confirms, is a named event you add in step 7 (`event:signup.start`). The outcome becomes a goal in step 8, and the journey becomes a saved funnel in step 9.\n5. **Check the routes.** Read the router for each route step. Ids and personal segments are stored as `:id` or `:redacted`, so `/projects/42/settings` is stored as `/projects/:id/settings`.\n\nStart from the row that fits, then change it to match what the code really does:\n\n| Product | Outcome | Journey |\n|---|---|---|\n| App or SaaS | Signup, then activation | `route:/` \u2192 `route:/pricing` \u2192 `event:signup.start` \u2192 `goal:<Signup id>` \u2192 `goal:<Activated id>` |\n| Store | Purchase | `route:/products/:id` \u2192 `event:cart.add` \u2192 `event:checkout.start` \u2192 `goal:<Purchase id>` |\n| Services or lead generation | Contact or booking | `route:/` \u2192 `route:/services` \u2192 `event:contact.open` \u2192 `goal:<Contact sent id>` |\n| Docs or open source | Adoption | `route:/docs` \u2192 `route:/docs/getting-started` \u2192 `goal:<Install copied id>`, a goal on `install.copy` |\n| Marketing site for an app on another host | A visitor heads to sign up | `route:/` \u2192 `route:/pricing` \u2192 `goal:<Signup click id>`, a goal on `cta.signup` |\n\n**A journey ends at the edge of its host.** A journey-mode session lives in one tab's session storage, which browsers keep apart for each host. A visit that moves from `example.com` to `app.example.com` becomes two sessions. Give each host its own funnel: end the marketing site's funnel on a goal for a named event fired when the signup link is clicked (`lf('track', 'cta.signup')`), and start the app's funnel at its signup page.\n\nKeep the plan small and useful:\n\n- Pick what someone running the product would ask about on a Monday: \"Of the people who saw pricing, how many started a trial?\" If nobody would act on a number, do not build it.\n- At most 3 funnels and 5 goals per project. Every funnel ends on a goal.\n- A step the code cannot see yet (no route, no event) needs an event in step 7. Note it in the plan.\n- A server-confirmed outcome joins the journey only when the server event carries the browser's correlation id (step 12). Plan that, or end the funnel on the browser event just before it.\n- Aggregate mode has no sessions, so it has no funnels. Plan goals only, and say so in the report.\n\nWrite the plan into the report (step 17) as a table before you build anything:\n\n| Journey | Outcome goal | Steps, and how each is seen |\n|---|---|---|\n| Signup | Signup (server) | `/pricing` route, `signup.start` event on the button, `signup.completed` server event with the browser's correlation id |\n\n## 4. Workspace, project, mode and consent\n\n### Workspace\n\n```sh\nlittlefriend workspaces list\n```\n\n| Situation | Workspace |\n|---|---|\n| The person who asked named one | That one |\n| The list shows one workspace | That one |\n| Several, and nobody named one | Stop and ask. Never guess |\n| The one you need is missing | Stop and ask. The CLI does not create workspaces |\n\n### Reuse before you create\n\n```sh\nlittlefriend projects list --workspace <workspace>\n```\n\nIf a project already has the product's domain, reuse it: note its id and site key, and run `littlefriend projects get` to see its mode and allowed origins. Never create a second project for the same domain.\n\nOne product is one project, even when its marketing pages and app live on different hosts of the same domain. List every host in allowed origins.\n\n### Mode\n\n| The product has | Mode |\n|---|---|\n| Sign-in, signup, onboarding, checkout, or any flow of several steps | `journey` |\n| Only marketing or content pages, and no sign-in | `aggregate` |\n| It is a site you build for a client | `aggregate`, unless the client asked for journeys |\n\n- Aggregate mode keeps counts only, with no session or visitor key anywhere. It still gives views, sources, pages, devices, countries, events and goals.\n- Journey mode adds sessions, timelines, funnels, paths, entry and exit pages, session replay and identify. Its session id lives in the tab's session storage and ends after 30 idle minutes (24 hours at most).\n\n### Consent\n\n| Situation | Do this |\n|---|---|\n| The product already runs a consent tool | Use `--consent required` in step 5. Call `lf('consent', 'journey')` when the tool grants analytics consent, and `lf('consent', 'aggregate')` when it is withdrawn |\n| No consent tool, journey mode | Ask the person who asked whether to ship without a banner. Do not add a consent tool yourself |\n| Aggregate mode | Nothing to wire |\n\nUntil consent arrives, the script counts in aggregate mode. A browser that sends Global Privacy Control always stays in aggregate mode.\n\nIf the product has a privacy page, add this text for journey mode:\n\n> We use Little Friend for privacy-friendly analytics. It sets no cookies and does not store IP addresses. To connect the pages you view in one visit, it keeps a random id in your browser tab's session storage. The visit ends after 30 minutes of inactivity, and the id is gone when you close the tab. If your browser sends Global Privacy Control, your visit is only counted, never connected.\n\nIn aggregate mode, use only the first two sentences. With session replay on (step 11), add:\n\n> Some visits are recorded as a masked copy of the pages you view. Text stays hidden unless we chose to show it, form entries are never recorded, and recordings are deleted within 7 days.\n\nIf there is no privacy page, say so in the report.\n\n### Create the project\n\n```sh\nlittlefriend projects create --name \"Acme\" --domain acme.com --mode journey \\\n --origin https://acme.com --origin https://www.acme.com --origin http://localhost:3000 \\\n --timezone America/New_York\n```\n\nIt prints the project id and the public site key. Keep both for the rest of the guide and the report.\n\n- `--domain`: the production host. Little Friend stores it lowercase, without a scheme, path or `www.`.\n- `--origin`, once per origin: every production host that serves pages, plus the local dev server's origin so you can verify before deploy (step 15). Add app origins from step 14. Preview deploys and any origin not listed get `403` and count nowhere, which is intended. An empty list accepts every origin.\n- `--timezone`: the time zone the business reports in. Without it, reports use UTC.\n- To add an origin later, run `littlefriend projects update --add-origin https://app.acme.com`. `--remove-origin` takes one out, and `--origin` replaces the whole list.\n- A native iOS or macOS app sends no origin. List its bundle id with `littlefriend apps add com.acme.shop`.\n\n## 5. Install the script\n\nPrint the exact code for the stack:\n\n```sh\nlittlefriend snippet --framework next --mode journey\n```\n\nIt prints what to add, with the site key filled in, and the CSP lines the site needs. Add `--consent required` when step 4 said so. Add `--replay` only in step 11.\n\n| The repo has | `--framework` | Where the code goes |\n|---|---|---|\n| `next` | `next` | The root layout: `app/layout.tsx` (App Router) or `pages/_document.tsx` (Pages Router) |\n| `nuxt` | `nuxt` | `nuxt.config.ts` |\n| `@sveltejs/kit` | `sveltekit` | `src/app.html` |\n| `astro` | `astro` | The layout every page shares, often `src/layouts/Layout.astro` |\n| `@remix-run/*`, or React Router with `app/root.tsx` | `remix` | `app/root.tsx` |\n| `react` with Vite or another bundler, no framework | `react` | `index.html` |\n| `vue` with Vite | `vue` | `index.html` |\n| `@angular/core` | `angular` | `src/index.html` |\n| A WordPress theme or plugin | `wordpress` | Where the snippet says |\n| `what-framework`, a Shopify theme, plain HTML, anything else | `html` | The `<head>` every page shares: `index.html`, the document template, `layout/theme.liquid` |\n| A bundled app where you want typed functions | `npm` | The client entry, once at startup |\n\nThe snippet is the source of truth for the code. The last column is where to look first.\n\nRules:\n\n- **One tracker per page.** Use the tag or the npm package (`@littlefriend/tracker`), never both. Load it on every page, once.\n- **Single-page apps need nothing extra.** History API navigations count as page views. If the router does not use the History API, call `lf('page')` after each navigation. Call it for navigations only, never for a screen the load or a History API navigation already recorded.\n- **Outside production, mark traffic as test.** Add `data-test` to the tag, or pass `test: true` to `init`, when the build is not production (for example `process.env.NODE_ENV !== 'production'` or `import.meta.env.DEV`). Test traffic shows in the live install check and never in reports.\n- **Name dynamic routes.** Id-like segments already become `:id`. For readable groups, such as `/blog/:slug`, add `data-routes='[\"/blog/:slug\"]'` to the tag, pass `routes` to `init`, or call `lf('route', '/blog/:slug')`. Goals and funnel steps match these routes exactly.\n- **Calls before the script loads.** If the product's own code calls `lf(...)`, add this stub above the tag, so `lf` exists before the deferred script runs. Calls wait in a queue until it loads.\n\n```html\n<script>window.lf=window.lf||function(){(lf.q=lf.q||[]).push(arguments)}</script>\n```\n\n- **Secret scanners.** The site key (`lf_`) is public, but gitleaks and similar scanners may flag it as an API key. Add an allowlist entry for that exact key rather than hiding it. A constant named `LITTLE_FRIEND_SITE` rather than `..._KEY` trips fewer rules.\n- **Monorepo build caches.** If the tag only renders in production (for example on `VERCEL_ENV`), declare that variable for the build task in `turbo.json` or the cache's equivalent. Otherwise a preview build and a production build can share one cached output.\n\nWith the tag in a TypeScript app, declare the global once, for example in `src/lf.d.ts`:\n\n```ts\ndeclare global {\n function lf(command: string, ...args: unknown[]): void;\n}\nexport {};\n```\n\n## 6. Content Security Policy\n\nSkip this step if the product sets no CSP. Otherwise add:\n\n```text\nscript-src https://cdn.littlefriend.io\nconnect-src https://in.littlefriend.io\n```\n\n- With the npm package, the tracker is part of your bundle, so only `connect-src` is needed.\n- The replay script comes from the same host as `lf.js` and sends to the same collector. It needs no other entries.\n- A policy with a nonce or `'strict-dynamic'` ignores host entries for scripts. Give the tag the page's nonce, or use the npm package.\n- Update every copy of the policy: `Content-Security-Policy-Report-Only`, `<meta http-equiv>` tags, and the test files that assert headers.\n- Common places: `next.config.*` `headers()`, `middleware.ts` or `proxy.ts`, `vercel.json`, `netlify.toml`, `_headers`, Helmet options, server header code.\n\n## 7. Custom events\n\nThe script sends these on its own: page views, outbound links, downloads, engaged time and, with `data-scroll`, scroll depth. The `$` prefix is reserved for them.\n\nAdd the named events your journey plan (step 3) needs, and the few the product's key feature needs. Three ways to add more:\n\n```html\n<!-- A named click: sends $click with { \"id\": \"pricing.start_trial\", \"plan\": \"pro\" } -->\n<button data-lf=\"pricing.start_trial\" data-lf-plan=\"pro\">Start free trial</button>\n\n<!-- A tracked form: sends $form_start and $form_submit with { \"id\": \"signup\" } -->\n<form data-lf-form=\"signup\">...</form>\n```\n\n```ts\n// A named event, after the thing really happened\nlf('track', 'signup.completed', { plan: 'pro' });\n\n// A failed form: a short category, never the message\nlf('formError', 'signup', 'validation');\n```\n\nWith npm, import the same names: `track`, `formError`, `page`, `route`, `consent`, `optout`, `optin`.\n\n**Goals and funnel steps match an event name or a route, never a property.** Every `data-lf` click arrives as `$click`, and every tracked form as `$form_submit`. For anything that becomes a goal or a funnel step, fire its own named event with `track`.\n\n### Names\n\n- `area.action`, lowercase: dots between parts, underscores inside a part. `signup.start`, `signup.completed`, `onboarding.project_created`, `checkout.start`, `order.completed`, `plan.upgraded`, `invite.sent`.\n- Past tense for outcomes (`completed`, `created`, `sent`). `start` or `open` for intent.\n- The pattern is `^[a-z][a-z0-9_.:-]{0,63}$`. `data-lf` ids follow the same convention.\n- Fire outcome events after the server call succeeds, never on the button press. Fire intent events on the press.\n- Aim for 5 to 15 named events: the steps of signup, onboarding, activation and checkout, and the product's key feature. Do not name every click.\n\n| Good | Bad | Why the bad one fails |\n|---|---|---|\n| `signup.completed` | `Signup Completed` | Uppercase and spaces are refused |\n| `checkout.start` | `click_button_3` | Says nothing about the product |\n| `invite.sent` with `{ role: 'editor' }` | `invite.sent.jane@acme.com` | Personal data in the name |\n| `order.completed` with `{ plan: 'pro' }` | `order_8812_completed` | An id in the name makes a new event per order |\n| `search.submit` with `{ results: 12 }` | `search.submit` with `{ query: 'knee pain' }` | Typed text is personal data |\n| `project.created` | `$project_created` | `$` is reserved |\n\n### Properties\n\n- Up to 8 per event. Keys are lowercase snake case, up to 32 characters. Values are strings, numbers or booleans. Strings are cut to 64 characters.\n- Use small fixed sets (`plan`, `step`, `method`, `role`, `source`) and counts.\n- A value that looks like an email or a long run of digits is dropped, even when sent on purpose.\n\n### Page types (optional)\n\nFlows group pages by type. Little Friend suggests types from your paths, and owners and editors can change the rules in Settings, Page types. When a page's type can't be told from its path, set it on the page:\n\n```html\n<meta name=\"lf:type\" content=\"comparison\">\n```\n\nThe value is a lowercase key: letters, digits, `-` or `_`, starting with a letter, at most 32 characters. A tag beats the URL rules for that page. The tracker reads this one tag and nothing else.\n\nOn a client-side navigation the page view is recorded when the URL changes. Its type is read after the next animation frame, or at once when the tab is hidden, so head managers that write the tag on render are read correctly. On page load the tag is read when the script runs, so put it in the HTML the server sends.\n\n## 8. Goals\n\nA goal is a conversion. Create 2 to 5, one for each outcome in your journey plan (step 3), most valuable first.\n\n| Product | Goals to start with |\n|---|---|\n| App or SaaS with sign-in | Signup (server), activation: the first key action, upgrade or trial started (server) |\n| Store | Purchase (server, with value), checkout started |\n| Lead generation | Contact form sent, demo booked, the thank-you page |\n| Content or docs | Newsletter signup, a named event on the link to the product's signup |\n\n- Prefer server-confirmed goals for money and accounts: `--source server --server-confirmed`. `--source server` counts only events your server sends with a secret key, and `--server-confirmed` also marks the goal that way in reports, so a reader knows a browser cannot fake it. Use browser goals for intent, or when there is no backend.\n- A route goal matches the stored route exactly. Check the routes with `littlefriend report pages` first.\n- Create goals before launch. A goal counts from the moment it is saved.\n- Name goals in plain words: \"Signup\", \"Purchase\", \"Demo booked\".\n\n```sh\nlittlefriend goals create --name \"Signup\" --event signup.completed --source server --server-confirmed\nlittlefriend goals create --name \"Purchase\" --event order.completed --source server --server-confirmed\nlittlefriend goals create --name \"Activated\" --event project.created\nlittlefriend goals create --name \"Contact sent\" --route /contact/thanks\nlittlefriend goals list\n```\n\nKeep the goal ids (`goal_...`) for funnels and the report.\n\n## 9. Funnels\n\nJourney mode only. Save one funnel for each journey in your plan (step 3), 1 to 3 in all, named after the journey.\n\nA funnel has 1 to 8 steps in order. Each step is `route:/path`, `event:<name>` or `goal:<goalId>`. A session reaches a step when it has done the steps before it, in that order.\n\n| Flow | Steps |\n|---|---|\n| Signup | `route:/pricing` \u2192 `event:signup.start` \u2192 `goal:<Signup id>` |\n| Activation | `goal:<Signup id>` \u2192 `event:onboarding.profile_completed` \u2192 `goal:<Activated id>` |\n| Checkout | `route:/pricing` \u2192 `event:checkout.start` \u2192 `goal:<Purchase id>` |\n\n- Keep 3 to 5 steps. Start broad and end on a goal.\n- A server event joins a session only when it carries that session's correlation id or session id (step 12). Without one, a server-only goal as the last step is never reached. Pass a correlation id, or end on a browser event.\n\n```sh\nlittlefriend funnels create --name \"Signup\" \\\n --step route:/pricing --step event:signup.start --step goal:goal_XXXXXXXX\nlittlefriend funnels list\nlittlefriend funnels report fnl_XXXXXXXX --from 2026-10-01 --to 2026-10-07\n```\n\nDates are `YYYY-MM-DD` in the project's time zone.\n\n## 10. Identify signed-in people\n\nJourney mode only. `lf('identify', ...)` is handled by the replay script, so it needs step 11. Without replay, skip this step.\n\n```ts\n// Wherever the app knows the signed-in user: after sign-in and on each page load\nlf('identify', user.id); // your own opaque id, such as usr_8f3k2\n\n// On sign-out\nlf('identify', null);\n```\n\nWith npm: `import { identify } from '@littlefriend/replay'`, then `identify(user.id)` and `identify(null)`.\n\n- The ref is 1 to 64 letters, digits, `_`, `.`, `:` and `-`. UUIDs and prefixed ids work.\n- Prefix numeric ids, such as `usr_4821937`. A ref of seven or more bare digits is refused.\n- Never an email, a phone number, a name, a username, or a hash of any of them. Emails are refused.\n- The ref lasts for the journey session in that tab. Call it on each page load while signed in, so the next session carries it too.\n- Before consent it waits in memory, and a Global Privacy Control visitor sends nothing.\n- With a ref, a workspace owner can find one person's sessions and erase their sessions, events and recordings (Settings, Replay, Forget a person).\n\n## 11. Session replay\n\nReplay records a journey session as a masked copy of the page: layout, scrolling, clicks and page changes. Every word is masked until you choose to show it. Form values, checked boxes, chosen options, images, video, audio, canvas and iframes are never recorded.\n\n### Decide\n\n| Situation | Replay |\n|---|---|\n| Journey mode, and the person who asked wants replay | On |\n| Journey mode, and nobody said | Ask first. Each workspace records up to 10 sessions a month free. More needs a card on file (Settings, Billing). Past the allowance, recording stops until a card is added or the month ends. Your own test recordings count too |\n| Pages show health, legal or financial records, or other people's private messages | Off, unless the owner asks |\n| Aggregate mode | Not available |\n\n### Defaults\n\n| Setting | Default |\n|---|---|\n| Sample rate | `100`, unless the site expects more than about 1,000 recorded sessions a day. Then sample down, for example to `25`. Each project stores up to 1 GiB of recordings a day, about 2,000 typical recordings, and refuses more until midnight UTC |\n| Text shown | Nav, header, footer, headings, buttons, labels, table headers, legends, tabs, menu items |\n| Hidden elements | Support chat, third-party widgets, and any region that lists other people's data |\n| Pages never recorded | `/account`, `/settings`, `/billing`, `/checkout`, `/admin`, plus every private-data route from step 3 |\n| Minimum active time | 2 seconds, the built-in default. A shorter recording is dropped unless it has at least 3 clicks |\n\n### Turn it on\n\n```sh\nlittlefriend replay enable --rate 100\nlittlefriend replay set \\\n --unmask nav --unmask header --unmask footer \\\n --unmask h1 --unmask h2 --unmask h3 --unmask h4 \\\n --unmask button --unmask label --unmask th --unmask legend \\\n --unmask \"[role=button]\" --unmask \"[role=tab]\" --unmask \"[role=menuitem]\" \\\n --block .support-chat \\\n --exclude /account --exclude /settings --exclude /billing --exclude /checkout --exclude /admin\nlittlefriend snippet --framework next --mode journey --replay\n```\n\n- `replay set` replaces each list. Pass every item every time.\n- Add the replay code the snippet prints after `lf.js`, with the same site key. With npm, call `startReplay({ site })` from `@littlefriend/replay` after `init`.\n- An excluded route covers itself and every path below it: `/account` covers `/account/billing`. `*` stands for one segment: `/projects/*/settings` covers `/projects/acme/settings` and everything below it. Up to 50 routes, each at most 100 characters, with no query or fragment.\n- Selectors: tag names, classes, ids and attribute selectors with plain values, joined by spaces, `>` or commas. Pseudo-classes, sibling selectors and `*` are refused. Up to 50 per list, 200 characters each.\n\n### Mark the HTML\n\nEmails, phone numbers and card numbers stay masked even in shown text. Names do not. Search the shown regions (header, nav, account menu, buttons) for places that print the signed-in person's name, company, initials or avatar label, and mask them again:\n\n```html\n<header>\n <nav>...</nav>\n <button class=\"account-menu\" data-lf-mask>{user.name}</button>\n</header>\n\n<aside class=\"support-chat\" data-lf-block>...</aside>\n```\n\n- `data-lf-mask` masks text again inside a shown region.\n- `data-lf-block` leaves an element out, drawn as an empty box. Use it for regions whose shape alone says too much, and on sensitive parts of routes that draw their page late after navigation.\n- `data-lf-unmask` shows the text of one element, for plain product copy such as plan names and prices.\n\n`littlefriend replay get` shows the settings, and says the replay script is installed once the first recording arrives.\n\n## 12. Server events\n\nSend outcomes the backend confirms: account created, payment succeeded, plan changed. Default: yes for every product with sign-in or payments.\n\n### The key\n\n```sh\ngit check-ignore -q .env.local && echo ignored\nlittlefriend keys create --kind server --label \"acme server\" --write-env .env.local --env-name LF_SERVER_KEY\n```\n\n- Use the env file the framework loads (`.env.local` for Next.js, often `.env` elsewhere). It must be ignored by git. If `git check-ignore` prints nothing, add the file to `.gitignore` first.\n- With `--write-env`, the CLI appends `LF_SERVER_KEY=...` only if the name is not set yet, and never prints the secret.\n- Add `LF_SERVER_KEY=` with no value to `.env.example`, if the repo has one.\n- Production needs the same variable in the host's secret store. Copy it from the env file without printing it, if you have the host's CLI and the repo's rules allow it. Otherwise list it under \"Needs a person\". Check each host CLI's `--help` before you run these:\n\n```sh\n# Vercel\ngrep '^LF_SERVER_KEY=' .env.local | cut -d= -f2- | tr -d '\\n' | vercel env add LF_SERVER_KEY production\n\n# Fly\ngrep '^LF_SERVER_KEY=' .env | fly secrets import -a <app>\n\n# Cloudflare Workers (the edge key from step 13)\ngrep '^LF_EDGE_KEY=' .env | cut -d= -f2- | tr -d '\\n' | wrangler secret put LF_EDGE_KEY\n```\n\n### Send from Node.js\n\nInstall `@littlefriend/node` with the repo's package manager (Node 18.17 or later). Create one client at module scope:\n\n```ts\n// lib/little-friend.ts\nimport { LittleFriend } from '@littlefriend/node';\n\nconst key = process.env.LF_SERVER_KEY;\nexport const lf = key ? new LittleFriend({ key }) : null;\n```\n\nThen send each outcome where the backend confirms it: after the account row is written, in the payment webhook, after the plan change commits.\n\n```ts\nimport { createHash } from 'node:crypto';\nimport { lf } from './lib/little-friend';\n\nlf?.track({\n // 8 to 32 letters, digits, _ or -. The same id on a retry counts once.\n id: createHash('sha256').update(order.id).digest('base64url').slice(0, 32),\n name: 'order.completed',\n props: { plan: order.plan },\n value: { amount: order.totalCents, currency: 'USD' }, // minor units\n correlationId: order.checkoutRef, // optional, see below\n});\n\nawait lf?.flush(); // in a serverless function, before it returns\n```\n\n- `track` never throws. A bad event goes to `onError`, which logs a warning by default.\n- In serverless functions (Vercel, Next.js route handlers and server actions), `await lf.flush()` before returning. In a long-running server, `await lf.shutdown()` when the process exits.\n- Derive `id` from the record, as above. Raw UUIDs (36 characters) and short numeric ids fail the id rule.\n- Other languages: POST `{ \"v\": 1, \"events\": [ ... ] }` to `https://in.littlefriend.io/v1/server` with `Authorization: Bearer $LF_SERVER_KEY`. Retry `429` and `503` after `Retry-After`. Never retry a `400`. Details: https://littlefriend.io/docs/goals#http\n\n### Join server outcomes to journeys\n\nIn journey mode, a server event joins the visitor's session when it carries the same correlation id as a browser event:\n\n```ts\n// Browser, when checkout starts: a random id for this attempt, sent to the server with the form\nconst checkoutRef = crypto.randomUUID();\nlf('track', 'checkout.start', { plan: 'pro' }, checkoutRef);\n```\n\nThe server stores `checkoutRef` with the order and passes it as `correlationId`. A correlation id is 16 to 64 letters, digits, `_` or `-`, and never only digits and dashes. Aggregate mode drops it.\n\n## 13. Crawlers and AI agents: the door and a log drain\n\n`lf.js` sees only browsers. Crawlers and AI agents rarely run JavaScript, so Little Friend needs the requests themselves.\n\n| Where the product runs | See agents with | Door |\n|---|---|---|\n| Vercel, any framework, static too | A Vercel log drain | Next.js: `nextProxy` in `proxy.ts` (Next.js 16) or `middleware.ts` (Next.js 15). Other frameworks: skip it and say so |\n| Next.js on another host | `wrapFetch(edge, handler, { waitUntil })` in route handlers, or `nodeMiddleware(edge)` in a custom Node server | `nextProxy`, as on Vercel |\n| Cloudflare Workers | `withLittleFriend` from `@littlefriend/edge` | Add `door: createDoor` |\n| Node with Express, Connect or `node:http` | `nodeMiddleware(edge)` | `nodeDoor(createDoor(lf), createEdge(lf))` in its place |\n| Bun, Deno, Hono or another fetch handler | `wrapFetch(edge, handler)` | `wrapFetch(edge, handler, { door })` |\n| Celsian | `observeCelsian(app, edge)` | None built in. Skip it and say so |\n| Static hosting without functions, not on Vercel | Only with a Worker in front | Only with a Worker in front |\n\nA request both a drain and the edge package report is counted once.\n\nRequests to the project's ignored routes are counted and not kept. Every project starts with `/api`, because an app calling its own API (session checks, polling, presence) is not a crawler or an agent. Add the product's other API paths, such as `/trpc` or `/graphql`:\n\n```sh\nlittlefriend projects update --add-ignored-route /trpc\n```\n\nRemove `/api` only when the owner wants to watch who calls the API, and say so in the report.\n\n### A Vercel log drain\n\n```sh\nlittlefriend drains list\nlittlefriend drains create --provider vercel\n```\n\n- Check `drains list` first. Reuse an active drain.\n- `drains create` prints the endpoint, the header and the signing secret, once. Create it only when you can paste them into Vercel in the same sitting: in the team's settings, add a log drain for this project only, all sources, production, and 100% sampling. Drains need a Vercel Pro or Enterprise team.\n- If you cannot reach Vercel's settings, do not create the drain. List it under \"Needs a person\": they can do both halves on the dashboard's Agents page, with Add a Vercel log drain.\n- A lost secret: `littlefriend drains rotate <id>` issues a new pair and keeps the old one working for 24 hours.\n- Within minutes of traffic, the Coverage card on the Agents page shows the drain as Live.\n\n### `@littlefriend/edge` and the door\n\nUse this when the product has code that runs on every request. Install `@littlefriend/edge` 0.3.0 or later. The door came in 0.2.0, and 0.3.0 stops sending requests to ignored routes. If the repo already depends on `^0.2.0`, change it to `^0.3.0`: that range never picks up 0.3.0 on its own.\n\n1. Create an edge key into the env file, as in step 12:\n\n```sh\nlittlefriend keys create --kind edge --label \"acme edge\" --write-env .env.local --env-name LF_EDGE_KEY\n```\n\n2. Install `@littlefriend/edge` and wire it for the runtime in the table above. The exact code for each runtime is on https://littlefriend.io/docs/agents (sections Any host and The door). For Next.js 16:\n\n```ts\n// proxy.ts\nimport { createDoor, createEdge, nextProxy } from '@littlefriend/edge';\nimport { NextResponse } from 'next/server';\n\nconst lf = { key: process.env.LF_EDGE_KEY!, ipHeader: 'x-forwarded-for' };\nexport const proxy = nextProxy(createDoor(lf), NextResponse, createEdge(lf));\nexport const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };\n```\n\n3. Set `ipHeader` to the header the host sets to the client address: `x-forwarded-for` on Vercel, `cf-connecting-ip` on Cloudflare, `fly-client-ip` on Fly. Without it, no address is sent and operator address checks cannot run.\n\n4. Pick a preset and keep dry run:\n\n```sh\nlittlefriend door set --preset verified_only --mode dry_run\nlittlefriend door simulate --ua \"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2; +https://openai.com/gptbot)\" --path /blog\n```\n\n| Product | Preset |\n|---|---|\n| A store with `/checkout`, `/cart` or `/account` | `commerce` |\n| An app or API with sign-in | `verified_only` |\n| Content, docs or marketing | `no_training` |\n| Unsure | `open` |\n\n- Dry run decides every request and records what it would have done. It never changes a response.\n- **Never switch the door to live.** The owner does that after reading 7 days of the door's report on the Agents page.\n- A browser always gets in, whatever the rules say.\n- `commerce` matches `/checkout`, `/cart` and `/account`. If the store uses other paths, say so in the report.\n\n## 14. Hybrid and native apps\n\n**Hybrid apps** (Capacitor, Ionic, Cordova, Tauri, Electron, React Native WebView, or the app's own WKWebView or Android WebView) show web pages. Install the script in the app's web code as in step 5, then add the origin the web view sends to the project's allowed origins:\n\n```sh\nlittlefriend projects update --add-origin capacitor://localhost --add-origin https://localhost\n```\n\n| App shell | Origin to add |\n|---|---|\n| Capacitor on iOS | `capacitor://localhost` |\n| Capacitor on Android | `https://localhost` |\n| Ionic with its Cordova web view | `ionic://localhost` on iOS, `http://localhost` on Android |\n| Cordova | `app://localhost` on iOS (scheme preference set to `app`), `https://localhost` on Android |\n| Tauri | `tauri://localhost` on macOS, iOS and Linux. `http://tauri.localhost` on Windows and Android, or `https://tauri.localhost` with `useHttpsScheme` |\n| Electron | The scheme and host the app serves from, such as `app://myapp` |\n| React Native WebView | The origin of the site it loads |\n| WKWebView with a custom scheme handler | The scheme and host you register, such as `app://localhost` |\n| WKWebView loading a file URL | No origin, see below |\n| Android WebView with WebViewAssetLoader | `https://appassets.androidplatform.net`, or `https://localhost` with `setDomain(\"localhost\")` |\n| Android WebView loading `file:///android_asset` | No origin, see below |\n\n- If the shell's config changes the scheme or host, add the ones it sets.\n- A page loaded from a file has no origin: an Android WebView on `file:///android_asset` sends `Origin: null`, a WKWebView that opened it with `loadFileURL` sends `Origin: null` from `fetch` and `Origin: file://` from `sendBeacon`, and an Electron app that loads its pages from files sends no `Origin` header at all. No list can name any of those, so leave the list empty, or serve the app from a scheme (a `WKURLSchemeHandler`, or `electron-serve`, which serves `app://-`) or from the asset loader. The script sends only the page's file name as the route, such as `/index.html`, so the folders above it, which can hold the user's name, never leave the device; the collector keeps the same rule for scripts older than 0.1.2, and keeps a route a current script names, such as `/settings/profile`, whole.\n- A file page cannot `pushState` to a new path: engines allow only a new query or fragment there. A hash-routed app names its routes itself. Name the starting route before the script loads, in the inline queue stub, as the template your router matches, such as `lf('route', '/orders/:id')`, or as the route part of the hash alone, `lf('route', '/' + location.hash.replace(/^#\\/?/, '').split(/[?&=]/)[0])`, so the load's own page view carries it. Never pass the whole fragment, since a fragment can carry a query or a sign-in token. The script cuts a named route at the first `?` or `#`, redacts a segment that holds `=` and replaces id-like segments, but a route should hold no values to begin with. After each later navigation, once the hash has changed, call `lf('route', '/settings')`, then `lf('page')`. Call `lf('page')` for navigations only: a router hook that also fires for the starting screen must skip that first call, or the screen counts twice. An app that routes with `pushState` gets its page views on its own and never calls `lf('page')`.\n- Apps on iOS send no referrer. A link opened from an Android app in Chrome arrives as `android-app://<package>/`, and a known app is stored under its web host, such as `mail.google.com` for Gmail, in that app's channel. The package table is under Webmail and email apps in `docs/METRICS.md`, published at https://littlefriend.io/docs/metrics#channels.\n- Events queued when the app goes to the background are sent as the page is hidden. An app killed while on screen (a crash, a force stop) loses what was queued in its last 5 seconds, and a kill and relaunch starts a new session.\n- UTM tags on a deep link are read like any landing: pass the link's query on to the page URL (`index.html?utm_source=newsletter&utm_medium=email`) and the visit lands in that channel with those values.\n- For local testing, an https asset-loader or Capacitor page cannot reach an http collector except at `localhost`: on the Android emulator, run `adb reverse tcp:<port> tcp:<port>` and point `data-api` at `http://localhost:<port>`. The real collector is https and needs neither.\n- If the repo deliberately skips analytics inside the shell, keep that and say so in the report.\n\n### Native apps\n\nScreens drawn natively with SwiftUI, UIKit or AppKit send their own screens and events through the Swift SDK. The full guide is https://littlefriend.io/docs/ios.\n\n1. **Install the SDK.** Add the Swift package that https://littlefriend.io/docs/ios#install names, from `0.1.0`, and link its `LittleFriend` product.\n2. **Start it with the project's site key**, the public `lf_` key the script uses, once as the app launches, in the mode chosen in step 4. Leave the options out for aggregate mode.\n\n ```swift\n // The SwiftUI App's init, or application(_:didFinishLaunchingWithOptions:)\n var options = LittleFriend.Options()\n options.mode = .journey\n LittleFriend.start(key: \"<site key>\", options: options)\n ```\n\n With consent required, set the consent option to `.required`, and call `LittleFriend.consent(.journey)` when the person agrees, as step 4 describes for the script.\n3. **Add the app id to Allowed apps**: the app's bundle id. A project admits only the apps it lists. Until the app is listed, its batches are refused with `403 app_not_allowed`, and the dashboard's data health strip names it.\n\n ```sh\n littlefriend apps add com.acme.shop\n ```\n\n4. **Name the screens** with route templates, never values, as on the web. SwiftUI: `.lfScreen(\"/products/:id\", type: \"product\")` on each screen's view. Anywhere else: `LittleFriend.screen(\"/orders/:id\", type: \"order\")`. A UIKit app can set `autoScreens` and give each view controller a route with `LFScreen` and `lfRoute`.\n5. **Track the events the plan names**, with the same names and properties as the web, so the goals and funnels of steps 8 and 9 count both: `LittleFriend.track(\"signup\", props: [\"plan\": .string(\"pro\")])`.\n6. **Call `LittleFriend.flush()` after a correlated event.** In journey mode, give the app's event the correlation id the server sends with the confirmed outcome (step 12), `correlationId: hash`, and call `LittleFriend.flush()` right after it, so it goes out at once. When the app's event arrives first, the server's outcome counts under the app's platform.\n7. **Verify.** Open a screen in the app, then run `littlefriend verify --source browser --since 10 --wait 120`: app batches count under the browser source. The iOS Simulator sends test traffic, which verify shows as test traffic and reports never store. A release build on a device sends real traffic.\n\nNative Android screens, and Flutter and React Native views, send the outcomes they lead to from the backend with `@littlefriend/node` (step 12). The server key never goes inside the app.\n\n## 15. Verify\n\n1. Run the product: the local dev server (its origin is on the list from step 4), or the deployed site.\n2. Load the site in a real browser (Playwright, agent-browser, or a person). `curl` does not run the script. Headless Chrome says so in its user agent and is counted as automation, so its visits stay out of page views and funnels, which count people. For the journey walks in item 9, run the browser headed or give it a desktop Chrome user agent. Then run `littlefriend verify --source browser --since 10 --wait 120`. It exits 0 once an accepted event from the browser in the last 10 minutes shows up, and prints its time, route and source. `--source browser` matters on a project with a log drain or the edge SDK, whose events would otherwise pass for the tag's. It exits 1 when none arrives in time. On a project that already has traffic, keep `--since` short, so an older event cannot pass for yours.\n3. In the browser's network panel, `POST https://in.littlefriend.io/v1/e` answers `202` with `{\"accepted\": n, \"dropped\": 0}`. The console shows no CSP errors.\n4. Click through each flow with a named event and confirm each name in the request bodies. Any `dropped` above 0 means a name or property broke a rule. The live install check (Settings, Install) shows every field kept, every property dropped, and why.\n5. Replay: in the browser's network panel, `GET https://in.littlefriend.io/v1/r/config?k=<site key>` returns `\"on\": true`, and `POST /v1/r` answers `202`. From `curl`, send the page's origin with `-H 'Origin: https://<domain>'`: without an allowed origin the answer is `\"on\": false`. Then `littlefriend replay get` reads installed.\n6. Server events: run the flow that sends one. `verify` shows source `server`, or `await lf.flush()` resolves with `accepted: 1`.\n7. Agents: `littlefriend door get` shows the policy and its mode. On the dashboard's Agents page, the Coverage card shows the drain as Live, and the door page shows that the door has read its rules.\n8. A few minutes later: `littlefriend report overview` and `littlefriend report goals` for a sanity check.\n9. Walk each journey in your plan once, in one tab, step by step, on a page without `data-test` (test events stay out of reports). A few minutes later, `littlefriend funnels report fnl_XXXXXXXX` shows that session at every step. A step at 0 means its route or event name does not match what arrives: compare it with `littlefriend report pages` and the request bodies.\n\nVerify on production after the deploy too, without `data-test`.\n\n| Symptom | Cause |\n|---|---|\n| No request to `in.littlefriend.io` | CSP blocks the script, or the tag never rendered |\n| `403` `origin_not_allowed` | The page's origin is not in allowed origins |\n| `400` | Wrong or malformed site key, or a malformed batch |\n| Sessions unavailable, funnels empty | The project or the snippet is not in journey mode. Both must be |\n| Replay `403` `replay_off`, `session_in_aggregate_mode` or `route_excluded` | Replay is off, the project is in aggregate mode, or the page is excluded |\n| Replay `402` `replay_card_required` | The workspace used its free recordings this month and has no card on file |\n| Replay `429` `quota_exceeded` | The project stored its 1 GiB of recordings for the day, or one address used its share of that. It clears at midnight UTC. If it happens often, lower the sample rate |\n| Server events `rejected` in `onError` | Wrong kind of key, or a revoked one |\n\n## 16. Launch checklist\n\n- [ ] One project for the domain, in the right workspace, in the right mode.\n- [ ] Allowed origins list every production host, every app origin and the dev origin.\n- [ ] The script is on every page, once, with `data-test` outside production.\n- [ ] CSP updated, including report-only copies and header tests.\n- [ ] Every goal and funnel step has its own named event. No personal data in names, properties or routes.\n- [ ] The journey plan is written down, with one goal per outcome.\n- [ ] 2 to 5 goals and, in journey mode, 1 to 3 funnels saved, one per journey in the plan.\n- [ ] Each journey was walked once and shows at every step of its funnel report.\n- [ ] `identify` sends an opaque id, and `null` on sign-out (replay only).\n- [ ] Replay: shown regions checked for names, private routes excluded, widgets blocked.\n- [ ] Server key in an ignored env file and in the host's secrets. Serverless code flushes.\n- [ ] Door in dry run where the runtime allows it. Drain connected on Vercel.\n- [ ] Ignored routes cover the product's own API paths.\n- [ ] Privacy page text added.\n- [ ] `littlefriend verify --source browser` exits 0 on production, and batches show `\"dropped\": 0`.\n- [ ] No secret in your changes: `git diff <base branch> | grep -E 'lf[ser]_[A-Za-z0-9]'` prints nothing.\n- [ ] Report sent.\n\n## 17. Report back\n\nEnd with this report, filled in. Use \"skipped\" with a reason where a step did not apply. Never include a secret.\n\n```markdown\n## Little Friend setup: <product>\n\n- Repo and branch:\n- Domain and hosts:\n- Workspace:\n- Project id and site key (lf_):\n- Mode and consent:\n- Allowed origins:\n- Snippet: --framework <name>, in <file>\n- CSP: <files changed, or none needed>\n- Journey plan: <the table from step 3: journey, outcome goal, steps and how each is seen>\n- Named events: <name, where it fires>\n- Goals: <id, name, match>\n- Funnels: <id, name, steps>\n- Identify: <where it is called, what id it sends, or skipped>\n- Replay: <on or off, rate, shown, hidden, excluded routes>\n- Server events: <events, files, env var names, host secrets set or not>\n- Agents: <drain id and status, door runtime, preset and mode, or skipped>\n- Ignored routes: <the list, and any change from /api>\n- Hybrid or native: <origins added, apps listed and SDKs started, backend events, or none>\n- Privacy page: <updated, or no privacy page>\n- Verify: <time, route and source that verify printed, local and production>\n- Skipped, and why:\n- Needs a person: <drains to connect, secrets to set, questions>\n- Guide or CLI problems found:\n```\n", bundled: true } : { text: GUIDE_PLACEHOLDER, bundled: false };
|
|
3628
3804
|
}
|
|
3629
3805
|
var guide = {
|
|
3630
3806
|
path: ["guide"],
|
|
@@ -4114,7 +4290,7 @@ ${r.unavailableReason}` : null,
|
|
|
4114
4290
|
s.enabled && r.available && !r.installed ? "\nAdd lf-replay.js next to lf.js to start recording: littlefriend snippet --replay" : null
|
|
4115
4291
|
);
|
|
4116
4292
|
}
|
|
4117
|
-
async function
|
|
4293
|
+
async function save2(ctx, body, done) {
|
|
4118
4294
|
const project = await resolveProject(ctx);
|
|
4119
4295
|
const res = await ctx.api().put(projectPath(project, "/replay/settings"), body);
|
|
4120
4296
|
if (!res.available && res.unavailableReason && res.settings.enabled)
|
|
@@ -4140,7 +4316,7 @@ var replayEnable = {
|
|
|
4140
4316
|
options: { rate: { type: "string" } },
|
|
4141
4317
|
async run(ctx) {
|
|
4142
4318
|
const rate = intOpt(ctx, "rate", 1, 100);
|
|
4143
|
-
return
|
|
4319
|
+
return save2(ctx, { enabled: true, ...rate !== void 0 ? { sampleRate: rate } : {} }, "Replay is on.");
|
|
4144
4320
|
}
|
|
4145
4321
|
};
|
|
4146
4322
|
var replayDisable = {
|
|
@@ -4149,7 +4325,7 @@ var replayDisable = {
|
|
|
4149
4325
|
usage: "",
|
|
4150
4326
|
example: "littlefriend replay disable",
|
|
4151
4327
|
async run(ctx) {
|
|
4152
|
-
return
|
|
4328
|
+
return save2(ctx, { enabled: false }, "Replay is off. Pages with lf-replay.js record nothing.");
|
|
4153
4329
|
}
|
|
4154
4330
|
};
|
|
4155
4331
|
var LISTS = [
|
|
@@ -4221,6 +4397,12 @@ var replayCommands = [replayGet, replayEnable, replayDisable, replaySet];
|
|
|
4221
4397
|
// src/commands/report.ts
|
|
4222
4398
|
var REPORTS = ["overview", "pages", "sources", "goals", "countries"];
|
|
4223
4399
|
var TOP = 10;
|
|
4400
|
+
var PLATFORM_NAMES = {
|
|
4401
|
+
web: "Web",
|
|
4402
|
+
ios: "iOS",
|
|
4403
|
+
macos: "macOS",
|
|
4404
|
+
android: "Android"
|
|
4405
|
+
};
|
|
4224
4406
|
function metricValue(m) {
|
|
4225
4407
|
if (!m.available || m.value === null) return "unavailable";
|
|
4226
4408
|
if (m.unit === "percent") return percent(m.value);
|
|
@@ -4248,10 +4430,11 @@ function breakdownTable(title, b) {
|
|
|
4248
4430
|
])
|
|
4249
4431
|
);
|
|
4250
4432
|
}
|
|
4251
|
-
function header(name, meta) {
|
|
4433
|
+
function header(name, meta, platform) {
|
|
4252
4434
|
const warn = meta.caveats.filter((c) => c.severity === "warn").map((c) => `Note: ${c.message}`);
|
|
4435
|
+
const only = platform ? `, ${PLATFORM_NAMES[platform]} only` : "";
|
|
4253
4436
|
return lines(
|
|
4254
|
-
`${name}, ${meta.range.from} to ${meta.range.to} (${meta.timezone}), ${meta.mode} mode.`,
|
|
4437
|
+
`${name}, ${meta.range.from} to ${meta.range.to} (${meta.timezone}), ${meta.mode} mode${only}.`,
|
|
4255
4438
|
...warn,
|
|
4256
4439
|
meta.freshness.backlogBatches > 0 ? `Note: ${count(meta.freshness.backlogBatches)} batches are still being processed, so the newest events may be missing.` : null
|
|
4257
4440
|
);
|
|
@@ -4259,16 +4442,17 @@ function header(name, meta) {
|
|
|
4259
4442
|
var report = {
|
|
4260
4443
|
path: ["report"],
|
|
4261
4444
|
summary: "Quick numbers for a sanity check",
|
|
4262
|
-
usage: `[${REPORTS.join("|")}] [--from <date>] [--to <date>]`,
|
|
4445
|
+
usage: `[${REPORTS.join("|")}] [--from <date>] [--to <date>] [--platform ${PLATFORMS.join("|")}]`,
|
|
4263
4446
|
example: "littlefriend report sources --from 2026-09-01 --to 2026-09-28",
|
|
4264
4447
|
args: { min: 0, max: 1 },
|
|
4265
|
-
options: RANGE_OPTIONS,
|
|
4448
|
+
options: { ...RANGE_OPTIONS, platform: { type: "string" } },
|
|
4266
4449
|
async run(ctx) {
|
|
4267
4450
|
const which = ctx.args[0] ?? "overview";
|
|
4268
4451
|
if (!REPORTS.includes(which)) throw usageError(`The report is ${orList(REPORTS)}. Got ${ctx.args[0]}.`);
|
|
4452
|
+
const platform = oneOf(ctx, "platform", PLATFORMS);
|
|
4269
4453
|
const project = await resolveProject(ctx);
|
|
4270
4454
|
const range = dateRange(ctx, project.timezone);
|
|
4271
|
-
const query = { from: range.from, to: range.to, compare: "none" };
|
|
4455
|
+
const query = { from: range.from, to: range.to, compare: "none", ...platform ? { platform } : {} };
|
|
4272
4456
|
const api = ctx.api();
|
|
4273
4457
|
switch (which) {
|
|
4274
4458
|
case "overview": {
|
|
@@ -4276,7 +4460,7 @@ var report = {
|
|
|
4276
4460
|
return {
|
|
4277
4461
|
data: r,
|
|
4278
4462
|
text: lines(
|
|
4279
|
-
header(project.name, r.meta),
|
|
4463
|
+
header(project.name, r.meta, platform),
|
|
4280
4464
|
"",
|
|
4281
4465
|
metricsTable(r.metrics),
|
|
4282
4466
|
"",
|
|
@@ -4291,7 +4475,7 @@ var report = {
|
|
|
4291
4475
|
return {
|
|
4292
4476
|
data: r,
|
|
4293
4477
|
text: lines(
|
|
4294
|
-
header(project.name, r.meta),
|
|
4478
|
+
header(project.name, r.meta, platform),
|
|
4295
4479
|
"",
|
|
4296
4480
|
breakdownTable("Page", r.pages),
|
|
4297
4481
|
"",
|
|
@@ -4304,7 +4488,7 @@ var report = {
|
|
|
4304
4488
|
return {
|
|
4305
4489
|
data: r,
|
|
4306
4490
|
text: lines(
|
|
4307
|
-
header(project.name, r.meta),
|
|
4491
|
+
header(project.name, r.meta, platform),
|
|
4308
4492
|
"",
|
|
4309
4493
|
breakdownTable("Channel", r.channels),
|
|
4310
4494
|
"",
|
|
@@ -4319,7 +4503,7 @@ var report = {
|
|
|
4319
4503
|
return {
|
|
4320
4504
|
data: r,
|
|
4321
4505
|
text: lines(
|
|
4322
|
-
header(project.name, r.meta),
|
|
4506
|
+
header(project.name, r.meta, platform),
|
|
4323
4507
|
"",
|
|
4324
4508
|
r.goals.length > 0 ? table(
|
|
4325
4509
|
["GOAL", "COMPLETIONS", "CONVERSION", "SERVER-CONFIRMED"],
|
|
@@ -4340,7 +4524,7 @@ var report = {
|
|
|
4340
4524
|
});
|
|
4341
4525
|
return {
|
|
4342
4526
|
data: r,
|
|
4343
|
-
text: lines(header(project.name, r.meta), "", breakdownTable("Country", r.breakdown))
|
|
4527
|
+
text: lines(header(project.name, r.meta, platform), "", breakdownTable("Country", r.breakdown))
|
|
4344
4528
|
};
|
|
4345
4529
|
}
|
|
4346
4530
|
}
|
|
@@ -4953,6 +5137,7 @@ var COMMANDS = [
|
|
|
4953
5137
|
...doorCommands,
|
|
4954
5138
|
...drainCommands,
|
|
4955
5139
|
...verifyCommands,
|
|
5140
|
+
...appsCommands,
|
|
4956
5141
|
...reportCommands,
|
|
4957
5142
|
...guideCommands
|
|
4958
5143
|
];
|
|
@@ -4974,7 +5159,7 @@ var GLOBAL_HELP = `Global flags
|
|
|
4974
5159
|
Exit codes: 0 done, 1 failed or nothing arrived, 2 wrong flags, 3 sign in needed.`;
|
|
4975
5160
|
var SECTIONS = [
|
|
4976
5161
|
{ title: "Sign in", groups: ["login", "logout", "whoami"] },
|
|
4977
|
-
{ title: "Workspaces and projects", groups: ["workspaces", "projects"] },
|
|
5162
|
+
{ title: "Workspaces and projects", groups: ["workspaces", "projects", "apps"] },
|
|
4978
5163
|
{ title: "Install", groups: ["snippet", "keys", "verify"] },
|
|
4979
5164
|
{ title: "Measure", groups: ["goals", "funnels", "report"] },
|
|
4980
5165
|
{ title: "Session replay, the agent door and log drains", groups: ["replay", "door", "drains"] },
|