🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Replace fixed onboarding drip with state-machine lifecycle emails (#1162)
Goldflag3d059a10159f
diff --git a/server/drizzle/0015_round_trish_tilby.sql b/server/drizzle/0015_round_trish_tilby.sqlnew file mode 100644index 000000000..5c888d8a0--- /dev/null+++ b/server/drizzle/0015_round_trish_tilby.sql@@ -0,0 +1,11 @@+CREATE TABLE "lifecycle_email_log" (+ "id" serial PRIMARY KEY NOT NULL,+ "user_id" text NOT NULL,+ "email_key" text NOT NULL,+ "site_id" integer,+ "sent_at" timestamp DEFAULT now() NOT NULL,+ CONSTRAINT "lifecycle_email_log_user_email_key_unique" UNIQUE("user_id","email_key")+);+--> statement-breakpoint+ALTER TABLE "sites" ADD COLUMN "detected_platform" text;--> statement-breakpoint+ALTER TABLE "lifecycle_email_log" ADD CONSTRAINT "lifecycle_email_log_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;\ No newline at end of filediff --git a/server/drizzle/meta/0015_snapshot.json b/server/drizzle/meta/0015_snapshot.jsonnew file mode 100644index 000000000..645129e0f--- /dev/null+++ b/server/drizzle/meta/0015_snapshot.json@@ -0,0 +1,3009 @@+{+ "id": "dceb98ae-704d-44a6-b038-41469969e981",+ "prevId": "f1e9d929-9eb0-4d14-9a41-037b634844fe",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "accountId": {+ "name": "accountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "providerId": {+ "name": "providerId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "accessToken": {+ "name": "accessToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refreshToken": {+ "name": "refreshToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "idToken": {+ "name": "idToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accessTokenExpiresAt": {+ "name": "accessTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refreshTokenExpiresAt": {+ "name": "refreshTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "account_userId_user_id_fk": {+ "name": "account_userId_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.active_sessions": {+ "name": "active_sessions",+ "schema": "",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "last_activity": {+ "name": "last_activity",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "referenceId": {+ "name": "referenceId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refillInterval": {+ "name": "refillInterval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refillAmount": {+ "name": "refillAmount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lastRefillAt": {+ "name": "lastRefillAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "rateLimitEnabled": {+ "name": "rateLimitEnabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "rateLimitTimeWindow": {+ "name": "rateLimitTimeWindow",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "rateLimitMax": {+ "name": "rateLimitMax",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "requestCount": {+ "name": "requestCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lastRequest": {+ "name": "lastRequest",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "configId": {+ "name": "configId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cancellation_feedback": {+ "name": "cancellation_feedback",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason_details": {+ "name": "reason_details",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "retention_offer_shown": {+ "name": "retention_offer_shown",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "retention_offer_accepted": {+ "name": "retention_offer_accepted",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "plan_name_at_cancellation": {+ "name": "plan_name_at_cancellation",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthly_event_count_at_cancellation": {+ "name": "monthly_event_count_at_cancellation",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.dashboards": {+ "name": "dashboards",+ "schema": "",+ "columns": {+ "dashboard_id": {+ "name": "dashboard_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"cards\":[]}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "dashboards_site_id_sites_site_id_fk": {+ "name": "dashboards_site_id_sites_site_id_fk",+ "tableFrom": "dashboards",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboards_user_id_user_id_fk": {+ "name": "dashboards_user_id_user_id_fk",+ "tableFrom": "dashboards",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.experiments": {+ "name": "experiments",+ "schema": "",+ "columns": {+ "experiment_id": {+ "name": "experiment_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "feature_flag_id": {+ "name": "feature_flag_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "primary_goal_id": {+ "name": "primary_goal_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "hypothesis": {+ "name": "hypothesis",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'draft'"+ },+ "winning_variant": {+ "name": "winning_variant",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "ended_at": {+ "name": "ended_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "experiments_site_idx": {+ "name": "experiments_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "experiments_feature_flag_idx": {+ "name": "experiments_feature_flag_idx",+ "columns": [+ {+ "expression": "feature_flag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "experiments_primary_goal_idx": {+ "name": "experiments_primary_goal_idx",+ "columns": [+ {+ "expression": "primary_goal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "experiments_site_id_sites_site_id_fk": {+ "name": "experiments_site_id_sites_site_id_fk",+ "tableFrom": "experiments",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",+ "tableFrom": "experiments",+ "tableTo": "feature_flags",+ "columnsFrom": [+ "feature_flag_id"+ ],+ "columnsTo": [+ "flag_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "experiments_primary_goal_id_goals_goal_id_fk": {+ "name": "experiments_primary_goal_id_goals_goal_id_fk",+ "tableFrom": "experiments",+ "tableTo": "goals",+ "columnsFrom": [+ "primary_goal_id"+ ],+ "columnsTo": [+ "goal_id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "experiments_site_flag_unique": {+ "name": "experiments_site_flag_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "feature_flag_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "experiments_status_check": {+ "name": "experiments_status_check",+ "value": "status IN ('draft', 'running', 'paused', 'completed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.feature_flags": {+ "name": "feature_flags",+ "schema": "",+ "columns": {+ "flag_id": {+ "name": "flag_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "runtime": {+ "name": "runtime",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'client'"+ },+ "flag_type": {+ "name": "flag_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'boolean'"+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "variants": {+ "name": "variants",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "rollout_percentage": {+ "name": "rollout_percentage",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 100+ },+ "rules": {+ "name": "rules",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "condition_sets": {+ "name": "condition_sets",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "salt": {+ "name": "salt",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "md5(random()::text || clock_timestamp()::text)"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feature_flags_site_idx": {+ "name": "feature_flags_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "feature_flags_site_id_sites_site_id_fk": {+ "name": "feature_flags_site_id_sites_site_id_fk",+ "tableFrom": "feature_flags",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "feature_flags_site_key_unique": {+ "name": "feature_flags_site_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "feature_flags_rollout_check": {+ "name": "feature_flags_rollout_check",+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"+ },+ "feature_flags_runtime_check": {+ "name": "feature_flags_runtime_check",+ "value": "runtime IN ('client', 'server', 'both')"+ },+ "feature_flags_type_check": {+ "name": "feature_flags_type_check",+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"+ }+ },+ "isRLSEnabled": false+ },+ "public.funnels": {+ "name": "funnels",+ "schema": "",+ "columns": {+ "report_id": {+ "name": "report_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "data": {+ "name": "data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "funnels_site_id_sites_site_id_fk": {+ "name": "funnels_site_id_sites_site_id_fk",+ "tableFrom": "funnels",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "funnels_user_id_user_id_fk": {+ "name": "funnels_user_id_user_id_fk",+ "tableFrom": "funnels",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.goals": {+ "name": "goals",+ "schema": "",+ "columns": {+ "goal_id": {+ "name": "goal_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_type": {+ "name": "goal_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "goals_site_id_sites_site_id_fk": {+ "name": "goals_site_id_sites_site_id_fk",+ "tableFrom": "goals",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.gsc_connections": {+ "name": "gsc_connections",+ "schema": "",+ "columns": {+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "gsc_property_url": {+ "name": "gsc_property_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "gsc_connections_site_id_sites_site_id_fk": {+ "name": "gsc_connections_site_id_sites_site_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_status": {+ "name": "import_status",+ "schema": "",+ "columns": {+ "import_id": {+ "name": "import_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "platform": {+ "name": "platform",+ "type": "import_platform_enum",+ "typeSchema": "public",+ "primaryKey": false,+ "notNull": true+ },+ "imported_events": {+ "name": "imported_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "skipped_events": {+ "name": "skipped_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "invalid_events": {+ "name": "invalid_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "import_status_site_id_sites_site_id_fk": {+ "name": "import_status_site_id_sites_site_id_fk",+ "tableFrom": "import_status",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "import_status_organization_id_organization_id_fk": {+ "name": "import_status_organization_id_organization_id_fk",+ "tableFrom": "import_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "inviterId": {+ "name": "inviterId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "has_restricted_site_access": {+ "name": "has_restricted_site_access",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "site_ids": {+ "name": "site_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "teamId": {+ "name": "teamId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "invitation_inviterId_user_id_fk": {+ "name": "invitation_inviterId_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviterId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "invitation_organizationId_organization_id_fk": {+ "name": "invitation_organizationId_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "invitation_teamId_team_id_fk": {+ "name": "invitation_teamId_team_id_fk",+ "tableFrom": "invitation",+ "tableTo": "team",+ "columnsFrom": [+ "teamId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.lifecycle_email_log": {+ "name": "lifecycle_email_log",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_key": {+ "name": "email_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "sent_at": {+ "name": "sent_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "lifecycle_email_log_user_id_user_id_fk": {+ "name": "lifecycle_email_log_user_id_user_id_fk",+ "tableFrom": "lifecycle_email_log",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "lifecycle_email_log_user_email_key_unique": {+ "name": "lifecycle_email_log_user_email_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "email_key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member": {+ "name": "member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "has_restricted_site_access": {+ "name": "has_restricted_site_access",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "member_organizationId_organization_id_fk": {+ "name": "member_organizationId_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "member_userId_user_id_fk": {+ "name": "member_userId_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member_site_access": {+ "name": "member_site_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "member_id": {+ "name": "member_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "member_site_access_member_idx": {+ "name": "member_site_access_member_idx",+ "columns": [+ {+ "expression": "member_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_site_access_site_idx": {+ "name": "member_site_access_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "member_site_access_member_id_member_id_fk": {+ "name": "member_site_access_member_id_member_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "member",+ "columnsFrom": [+ "member_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_site_access_site_id_sites_site_id_fk": {+ "name": "member_site_access_site_id_sites_site_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_site_access_created_by_user_id_fk": {+ "name": "member_site_access_created_by_user_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "member_site_access_unique": {+ "name": "member_site_access_unique",+ "nullsNotDistinct": false,+ "columns": [+ "member_id",+ "site_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauthAccessToken": {+ "name": "oauthAccessToken",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "accessToken": {+ "name": "accessToken",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refreshToken": {+ "name": "refreshToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accessTokenExpiresAt": {+ "name": "accessTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "refreshTokenExpiresAt": {+ "name": "refreshTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "clientId": {+ "name": "clientId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",+ "tableFrom": "oauthAccessToken",+ "tableTo": "oauthApplication",+ "columnsFrom": [+ "clientId"+ ],+ "columnsTo": [+ "clientId"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauthAccessToken_userId_user_id_fk": {+ "name": "oauthAccessToken_userId_user_id_fk",+ "tableFrom": "oauthAccessToken",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauthAccessToken_accessToken_unique": {+ "name": "oauthAccessToken_accessToken_unique",+ "nullsNotDistinct": false,+ "columns": [+ "accessToken"+ ]+ },+ "oauthAccessToken_refreshToken_unique": {+ "name": "oauthAccessToken_refreshToken_unique",+ "nullsNotDistinct": false,+ "columns": [+ "refreshToken"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauthApplication": {+ "name": "oauthApplication",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "clientId": {+ "name": "clientId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "clientSecret": {+ "name": "clientSecret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "redirectUrls": {+ "name": "redirectUrls",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "oauthApplication_userId_user_id_fk": {+ "name": "oauthApplication_userId_user_id_fk",+ "tableFrom": "oauthApplication",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauthApplication_clientId_unique": {+ "name": "oauthApplication_clientId_unique",+ "nullsNotDistinct": false,+ "columns": [+ "clientId"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauthConsent": {+ "name": "oauthConsent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "clientId": {+ "name": "clientId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "consentGiven": {+ "name": "consentGiven",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "oauthConsent_clientId_oauthApplication_clientId_fk": {+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",+ "tableFrom": "oauthConsent",+ "tableTo": "oauthApplication",+ "columnsFrom": [+ "clientId"+ ],+ "columnsTo": [+ "clientId"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauthConsent_userId_user_id_fk": {+ "name": "oauthConsent_userId_user_id_fk",+ "tableFrom": "oauthConsent",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization": {+ "name": "organization",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthlyEventCount": {+ "name": "monthlyEventCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "overMonthlyLimit": {+ "name": "overMonthlyLimit",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "approachingLimitNotifiedPeriodStart": {+ "name": "approachingLimitNotifiedPeriodStart",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "planOverride": {+ "name": "planOverride",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "custom_plan": {+ "name": "custom_plan",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ipAddress": {+ "name": "ipAddress",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "userAgent": {+ "name": "userAgent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "impersonatedBy": {+ "name": "impersonatedBy",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activeOrganizationId": {+ "name": "activeOrganizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activeTeamId": {+ "name": "activeTeamId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_userId_user_id_fk": {+ "name": "session_userId_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.sites": {+ "name": "sites",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "site_id": {+ "name": "site_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "public": {+ "name": "public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "embed_enabled": {+ "name": "embed_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "saltUserIds": {+ "name": "saltUserIds",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "blockBots": {+ "name": "blockBots",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "first_party_proxy": {+ "name": "first_party_proxy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "excluded_ips": {+ "name": "excluded_ips",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_countries": {+ "name": "excluded_countries",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_paths": {+ "name": "excluded_paths",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_hostnames": {+ "name": "excluded_hostnames",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_user_agents": {+ "name": "excluded_user_agents",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_asns": {+ "name": "excluded_asns",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_query_params": {+ "name": "excluded_query_params",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "sessionReplay": {+ "name": "sessionReplay",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "webVitals": {+ "name": "webVitals",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackErrors": {+ "name": "trackErrors",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackOutbound": {+ "name": "trackOutbound",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackUrlParams": {+ "name": "trackUrlParams",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackInitialPageView": {+ "name": "trackInitialPageView",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackSpaNavigation": {+ "name": "trackSpaNavigation",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackIp": {+ "name": "trackIp",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackButtonClicks": {+ "name": "trackButtonClicks",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackCopy": {+ "name": "trackCopy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackFormInteractions": {+ "name": "trackFormInteractions",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "api_key": {+ "name": "api_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "private_link_key": {+ "name": "private_link_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tags": {+ "name": "tags",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "detected_platform": {+ "name": "detected_platform",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "sites_created_by_user_id_fk": {+ "name": "sites_created_by_user_id_fk",+ "tableFrom": "sites",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "sites_organization_id_organization_id_fk": {+ "name": "sites_organization_id_organization_id_fk",+ "tableFrom": "sites",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "sites_type_check": {+ "name": "sites_type_check",+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"+ }+ },+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "team_organizationId_organization_id_fk": {+ "name": "team_organizationId_organization_id_fk",+ "tableFrom": "team",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.teamMember": {+ "name": "teamMember",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "teamId": {+ "name": "teamId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "teamMember_teamId_team_id_fk": {+ "name": "teamMember_teamId_team_id_fk",+ "tableFrom": "teamMember",+ "tableTo": "team",+ "columnsFrom": [+ "teamId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "teamMember_userId_user_id_fk": {+ "name": "teamMember_userId_user_id_fk",+ "tableFrom": "teamMember",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_site_access": {+ "name": "team_site_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_site_access_team_idx": {+ "name": "team_site_access_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_site_access_site_idx": {+ "name": "team_site_access_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_site_access_team_id_team_id_fk": {+ "name": "team_site_access_team_id_team_id_fk",+ "tableFrom": "team_site_access",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_site_access_site_id_sites_site_id_fk": {+ "name": "team_site_access_site_id_sites_site_id_fk",+ "tableFrom": "team_site_access",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_site_access_unique": {+ "name": "team_site_access_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "site_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.telemetry": {+ "name": "telemetry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "instance_id": {+ "name": "instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "timestamp": {+ "name": "timestamp",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "version": {+ "name": "version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "table_counts": {+ "name": "table_counts",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "clickhouse_size_gb": {+ "name": "clickhouse_size_gb",+ "type": "real",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'user'"+ },+ "displayUsername": {+ "name": "displayUsername",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "banReason": {+ "name": "banReason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banExpires": {+ "name": "banExpires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "overMonthlyLimit": {+ "name": "overMonthlyLimit",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "monthlyEventCount": {+ "name": "monthlyEventCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "sendAutoEmailReports": {+ "name": "sendAutoEmailReports",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "scheduled_tip_email_ids": {+ "name": "scheduled_tip_email_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_username_unique": {+ "name": "user_username_unique",+ "nullsNotDistinct": false,+ "columns": [+ "username"+ ]+ },+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_aliases": {+ "name": "user_aliases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "anonymous_id": {+ "name": "anonymous_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_aliases_user_idx": {+ "name": "user_aliases_user_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_aliases_anon_idx": {+ "name": "user_aliases_anon_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "anonymous_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_aliases_site_id_sites_site_id_fk": {+ "name": "user_aliases_site_id_sites_site_id_fk",+ "tableFrom": "user_aliases",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_aliases_site_anon_unique": {+ "name": "user_aliases_site_anon_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "anonymous_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_profiles": {+ "name": "user_profiles",+ "schema": "",+ "columns": {+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "traits": {+ "name": "traits",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_profiles_site_idx": {+ "name": "user_profiles_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_profiles_site_id_sites_site_id_fk": {+ "name": "user_profiles_site_id_sites_site_id_fk",+ "tableFrom": "user_profiles",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "user_profiles_site_id_user_id_pk": {+ "name": "user_profiles_site_id_user_id_pk",+ "columns": [+ "site_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {+ "public.import_platform_enum": {+ "name": "import_platform_enum",+ "schema": "public",+ "values": [+ "umami",+ "simple_analytics",+ "plausible"+ ]+ }+ },+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.jsonindex fa3614a33..ea604da8f 100644--- a/server/drizzle/meta/_journal.json+++ b/server/drizzle/meta/_journal.json@@ -106,6 +106,13 @@"when": 1786751242462,"tag": "0014_huge_dagger","breakpoints": true+ },+ {+ "idx": 15,+ "version": "7",+ "when": 1788371100067,+ "tag": "0015_round_trish_tilby",+ "breakpoints": true}]}\ No newline at end of filediff --git a/server/src/api/sites/checkInstall.ts b/server/src/api/sites/checkInstall.tsnew file mode 100644index 000000000..b26d603da--- /dev/null+++ b/server/src/api/sites/checkInstall.ts@@ -0,0 +1,110 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { verifyExpiringPayload } from "../../lib/signedToken.js";+import { fetchHomepage, hasRybbitScript } from "../../services/lifecycleEmails/platformDetect.js";++/**+ * Public endpoint linked from the "still nothing from your site" lifecycle+ * email. Fetches the domain's homepage server-side and reports whether the+ * tracking snippet for *this* site is present. The signed, expiring+ * (siteId, domain) pair keeps it from being used as an open fetch proxy, and+ * a small per-IP limiter keeps a leaked link from being a probe loop.+ */++const RATE_LIMIT_WINDOW_MS = 60_000;+const RATE_LIMIT_MAX = 5;+const rateBuckets = new Map<string, { count: number; resetAt: number }>();++const isRateLimited = (ip: string): boolean => {+ const nowMs = Date.now();+ const bucket = rateBuckets.get(ip);+ if (!bucket || bucket.resetAt < nowMs) {+ // Opportunistic cleanup so the map doesn't grow unbounded+ if (rateBuckets.size > 10_000) {+ for (const [key, value] of rateBuckets) {+ if (value.resetAt < nowMs) rateBuckets.delete(key);+ }+ }+ rateBuckets.set(ip, { count: 1, resetAt: nowMs + RATE_LIMIT_WINDOW_MS });+ return false;+ }+ bucket.count += 1;+ return bucket.count > RATE_LIMIT_MAX;+};++export const checkInstall = async (+ request: FastifyRequest<{ Querystring: { siteId?: string; domain?: string; exp?: string; sig?: string } }>,+ reply: FastifyReply+) => {+ const { siteId, domain, exp, sig } = request.query;+ const siteIdNum = Number(siteId);++ if (+ !domain ||+ !sig ||+ !exp ||+ !Number.isInteger(siteIdNum) ||+ !verifyExpiringPayload(`check-install:${siteIdNum}:${domain}`, exp, sig)+ ) {+ return reply.status(400).type("text/html").send(page("Invalid link", "This install-check link is invalid or expired."));+ }++ if (isRateLimited(request.ip)) {+ return reply+ .status(429)+ .type("text/html")+ .send(page("Slow down", "Too many checks in a row - wait a minute and try again."));+ }++ const html = await fetchHomepage(domain);++ if (html === null) {+ return reply+ .type("text/html")+ .send(+ page(+ `Couldn't reach ${escapeHtml(domain)}`,+ `We couldn't fetch your homepage just now. If the site is up, it may be blocking automated requests - check the page source manually for the Rybbit snippet, or reply to the email and we'll help.`+ )+ );+ }++ if (hasRybbitScript(html, siteIdNum)) {+ return reply+ .type("text/html")+ .send(+ page(+ `The snippet is installed on ${escapeHtml(domain)}`,+ `We found the Rybbit script with your site ID on your homepage. If data still isn't showing up after a few minutes, an adblocker may be blocking your own test visits - try a private window, or see <a href="https://rybbit.com/docs/script-troubleshooting">the troubleshooting guide</a>.`+ )+ );+ }++ return reply+ .type("text/html")+ .send(+ page(+ `The snippet isn't on ${escapeHtml(domain)} yet`,+ `We fetched your homepage and couldn't find the Rybbit script with your site ID in it. Add the snippet to the <head> of every page and redeploy - see <a href="https://rybbit.com/docs/script">the install guide</a>. If a snippet is there but for a different site ID, data is being sent to the wrong site.`+ )+ );+};++const escapeHtml = (value: string) =>+ value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);++const page = (title: string, body: string) => `<!doctype html>+<html>+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>${title} - Rybbit</title>+ <style>+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #0e1013; color: #e5e7eb; display: flex; justify-content: center; padding: 80px 24px; margin: 0; }+ main { max-width: 480px; }+ h1 { font-size: 20px; color: #fff; }+ p { line-height: 1.6; color: #9ca3af; }+ a { color: #10b981; }+ </style>+</head>+<body><main><h1>${title}</h1><p>${body}</p></main></body>+</html>`;diff --git a/server/src/api/sites/index.ts b/server/src/api/sites/index.tsindex 0fce68ac9..408c678ea 100644--- a/server/src/api/sites/index.ts+++ b/server/src/api/sites/index.ts@@ -3,6 +3,7 @@ export { addSite } from "./addSite.js";export { deleteSite } from "./deleteSite.js";export { getSite } from "./getSite.js";export { getSiteHasData } from "./getSiteHasData.js";+export { checkInstall } from "./checkInstall.js";export { getSiteIsPublic } from "./getSiteIsPublic.js";export { getSiteUsage } from "./getSiteUsage.js";export { getEmbedStats } from "./getEmbedStats.js";diff --git a/server/src/api/user/unsubscribeMarketing.ts b/server/src/api/user/unsubscribeMarketing.tsindex 77c8a2b57..6742f1545 100644--- a/server/src/api/user/unsubscribeMarketing.ts+++ b/server/src/api/user/unsubscribeMarketing.ts@@ -3,8 +3,16 @@ import { eq } from "drizzle-orm";import { DateTime } from "luxon";import { db } from "../../db/postgres/postgres.js";import { user } from "../../db/postgres/schema.js";-import { unsubscribeContact, cancelScheduledEmail } from "../../lib/email/email.js";-import { onboardingTipsService } from "../../services/onboardingTips/onboardingTipsService.js";+import { cancelScheduledEmail, unsubscribeContact } from "../../lib/email/email.js";+import { verifyExpiringPayload } from "../../lib/signedToken.js";++// Cancel tip emails pre-scheduled in Resend for users who signed up before the+// lifecycle email system replaced the fixed drip. Remove once those have aged out.+const cancelLegacyScheduledTips = async (emailIds: string[]): Promise<void> => {+ for (const emailId of emailIds) {+ await cancelScheduledEmail(emailId);+ }+};// Authenticated user unsubscribeexport const unsubscribeMarketing = async (request: FastifyRequest, reply: FastifyReply) => {@@ -29,7 +37,7 @@ export const unsubscribeMarketing = async (request: FastifyRequest, reply: Fasti// Cancel scheduled tip emailsconst emailIds = (userData.scheduledTipEmailIds as string[]) || [];- await onboardingTipsService.cancelScheduledEmails(emailIds);+ await cancelLegacyScheduledTips(emailIds);// Clear the scheduled email IDsawait db@@ -53,14 +61,30 @@ export const unsubscribeMarketing = async (request: FastifyRequest, reply: Fasti// One-click unsubscribe handler// GET: User clicks link in email - show confirmation page// POST: Email client's List-Unsubscribe-Post - return 200 OK+// Unsigned links are honored only until this date: emails sent before link+// signing existed (2026-09) carry no signature, and unsubscribe links must+// keep working for a while. After the cutoff every link must carry a valid+// signed (email, exp) pair, closing the unsubscribe-anyone hole for good.+const LEGACY_UNSIGNED_CUTOFF = DateTime.fromISO("2026-12-01T00:00:00Z");+export const oneClickUnsubscribeMarketing = async (- request: FastifyRequest<{ Querystring: { email?: string } }>,+ request: FastifyRequest<{ Querystring: { email?: string; exp?: string; sig?: string } }>,reply: FastifyReply) => {try {const email = request.query.email;+ const { exp, sig } = request.query;const isGetRequest = request.method === "GET";+ if (email) {+ const validSignature = !!(sig && exp) && verifyExpiringPayload(`unsubscribe:${email}`, exp, sig);+ const legacyWindowOpen = DateTime.utc() < LEGACY_UNSIGNED_CUTOFF;+ const acceptableLegacy = !sig && !exp && legacyWindowOpen;+ if (!validSignature && !acceptableLegacy) {+ return reply.status(400).send({ error: "Invalid or expired unsubscribe link" });+ }+ }+if (!email) {if (isGetRequest) {return reply.status(400).type("text/html").send(`@@ -87,7 +111,7 @@ export const oneClickUnsubscribeMarketing = async (if (userData) {// Cancel scheduled tip emailsconst emailIds = (userData.scheduledTipEmailIds as string[]) || [];- await onboardingTipsService.cancelScheduledEmails(emailIds);+ await cancelLegacyScheduledTips(emailIds);// Clear the scheduled email IDsawait dbdiff --git a/server/src/cluster.ts b/server/src/cluster.tsindex f35ca29b0..2516351e3 100644--- a/server/src/cluster.ts+++ b/server/src/cluster.ts@@ -3,7 +3,7 @@ import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";import { initPostgres } from "./db/postgres/initPostgres.js";import { IS_CLOUD } from "./lib/const.js";import { createServiceLogger } from "./lib/logger/logger.js";-import { reengagementService } from "./services/reengagement/reengagementService.js";+import { lifecycleEmailService } from "./services/lifecycleEmails/lifecycleEmailService.js";import { sessionsService } from "./services/sessions/sessionsService.js";import { telemetryService } from "./services/telemetryService.js";import { usageService } from "./services/usageService.js";@@ -47,7 +47,7 @@ if (workerCount === 0) {usageService.startUsageCheckCron();if (IS_CLOUD && process.env.NODE_ENV !== "development") {weeklyReportService.startWeeklyReportCron();- reengagementService.startReengagementCron();+ lifecycleEmailService.startLifecycleCron();}// Broadcast usage state (sitesOverLimit + sitesWithoutReplay) to workers after each usage update@@ -119,7 +119,7 @@ if (workerCount === 0) {telemetryService.stopTelemetryCron();if (IS_CLOUD) {weeklyReportService.stopWeeklyReportCron();- reengagementService.stopReengagementCron();+ lifecycleEmailService.stopLifecycleCron();}// Attach exit listeners before sending SIGTERM to avoid a race wherediff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 67088983e..6cf906d59 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -42,6 +42,9 @@ export const user = pgTable(// deprecatedmonthlyEventCount: integer().default(0),sendAutoEmailReports: boolean().default(true),+ // deprecated - Resend email IDs from the retired pre-scheduled tip sequence; kept so+ // unsubscribe can still cancel tips already scheduled for users who signed up before+ // the lifecycle email system replaced itscheduledTipEmailIds: jsonb("scheduled_tip_email_ids").$type<string[]>().default([]),},table => [unique("user_username_unique").on(table.username), unique("user_email_unique").on(table.email)]@@ -100,6 +103,9 @@ export const sites = pgTable(apiKey: text("api_key"), // Format: rb_{64_hex_chars} = 67 chars totalprivateLinkKey: text("private_link_key"),tags: jsonb("tags").default([]).$type<string[]>(),+ // Platform fingerprinted from the site's homepage at creation time (e.g. "wordpress",+ // "next-js"); used to link the right install guide in lifecycle emails+ detectedPlatform: text("detected_platform"),},table => [check("sites_type_check", sql`${table.type} IS NULL OR ${table.type} IN ('web', 'mobile')`)]);@@ -622,3 +628,20 @@ export const importStatus = pgTable(}),]);++// One row per lifecycle email actually sent. The (userId, emailKey) unique index is the+// idempotency guard for the state-machine cron: per-site emails embed the siteId in the+// key (e.g. "site_live:42") so each fires at most once.+export const lifecycleEmailLog = pgTable(+ "lifecycle_email_log",+ {+ id: serial("id").primaryKey().notNull(),+ userId: text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ emailKey: text("email_key").notNull(),+ siteId: integer("site_id"),+ sentAt: timestamp("sent_at", { mode: "string" }).defaultNow().notNull(),+ },+ table => [unique("lifecycle_email_log_user_email_key_unique").on(table.userId, table.emailKey)]+);diff --git a/server/src/index.ts b/server/src/index.tsindex c8cd5a52d..288a0fbf9 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -132,6 +132,7 @@ import {getSiteExcludedASNs,getSiteExcludedQueryParams,getSiteHasData,+ checkInstall,getSiteImports,getSiteIsPublic,getSiteUsage,@@ -190,7 +191,7 @@ import { IS_CLOUD } from "./lib/const.js";import { logger } from "./lib/logger/logger.js";import { registerRequestLogging } from "./lib/logger/requestLogging.js";import { identityBackfillQueue } from "./services/tracker/identityBackfillQueue.js";-import { reengagementService } from "./services/reengagement/reengagementService.js";+import { lifecycleEmailService } from "./services/lifecycleEmails/lifecycleEmailService.js";import { telemetryService } from "./services/telemetryService.js";import { handleIdentify } from "./services/tracker/identifyService.js";import { trackEvent } from "./services/tracker/trackEvent.js";@@ -496,6 +497,7 @@ async function sitesRoutes(fastify: FastifyInstance) {fastify.get("/sites/:siteId/private-link-config", adminSitesWrite, getSitePrivateLinkConfig);fastify.post("/sites/:siteId/private-link-config", adminSitesWrite, updateSitePrivateLinkConfig);fastify.get("/site/tracking-config/:siteId", getTrackingConfig); // Public - used by tracking script+ fastify.get("/site/check-install", checkInstall); // Public (HMAC-signed) - linked from lifecycle emailsfastify.get("/sites/:siteId/embed-stats", { preHandler: [resolveSiteId] as any }, getEmbedStats); // Public - widget endpoint (handler checks site is public)fastify.get("/sites/:siteId/excluded-ips", authSitesRead, getSiteExcludedIPs);fastify.get("/sites/:siteId/excluded-countries", authSitesRead, getSiteExcludedCountries);@@ -637,7 +639,7 @@ const start = async () => {usageService.startUsageCheckCron();if (IS_CLOUD && process.env.NODE_ENV !== "development") {weeklyReportService.startWeeklyReportCron();- reengagementService.startReengagementCron();+ lifecycleEmailService.startLifecycleCron();}}diff --git a/server/src/lib/auth-utils.test.ts b/server/src/lib/auth-utils.test.tsindex bddb74c11..f6dd12ee6 100644--- a/server/src/lib/auth-utils.test.ts+++ b/server/src/lib/auth-utils.test.ts@@ -138,7 +138,8 @@ CREATE TABLE "sites" ("trackFormInteractions" boolean DEFAULT false,"api_key" text,"private_link_key" text,- "tags" jsonb DEFAULT '[]'+ "tags" jsonb DEFAULT '[]',+ "detected_platform" text);`;diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.tsindex a5bcdb64e..4bf88c255 100644--- a/server/src/lib/auth.ts+++ b/server/src/lib/auth.ts@@ -26,7 +26,6 @@ import {sendOtpEmail,sendWelcomeEmail,} from "./email/email.js";-import { onboardingTipsService } from "../services/onboardingTips/onboardingTipsService.js";import { getTrustedCorsOrigins } from "./cors.js";import { createServiceLogger } from "./logger/logger.js";@@ -361,18 +360,12 @@ export const auth = betterAuth({}sendWelcomeEmail(u.email, u.name);- // Add contact to marketing audience and schedule onboarding emails+ // Add contact to marketing audience; lifecycle emails are driven by the+ // state-machine cron (lifecycleEmailService), nothing is pre-scheduled heretry {await addContactToAudience(u.email, u.name);-- const emailIds = await onboardingTipsService.scheduleOnboardingEmails(u.email, u.name);-- // Store scheduled email IDs for potential cancellation- if (emailIds.length > 0) {- await db.update(user).set({ scheduledTipEmailIds: emailIds }).where(eq(user.id, u.id));- }} catch (error) {- authLogger.error({ err: error, userId: u.id }, "Error setting up onboarding emails");+ authLogger.error({ err: error, userId: u.id }, "Error adding contact to marketing audience");}},},diff --git a/server/src/lib/email/email.ts b/server/src/lib/email/email.tsindex d44be3b6d..5d96bbc54 100644--- a/server/src/lib/email/email.ts+++ b/server/src/lib/email/email.ts@@ -4,13 +4,10 @@ import { IS_CLOUD } from "../const.js";import { ApproachingLimitEmail } from "./templates/ApproachingLimitEmail.js";import { InvitationEmail } from "./templates/InvitationEmail.js";import { LimitExceededEmail } from "./templates/LimitExceededEmail.js";-import { OnboardingTipEmail } from "./templates/OnboardingTipEmail.js";import { OtpEmail, type OtpEmailType } from "./templates/OtpEmail.js";-import { ReengagementEmail } from "./templates/ReengagementEmail.js";import { WeeklyReportEmail } from "./templates/WeeklyReportEmail.js";import type { SiteReport } from "../../services/weekyReports/weeklyReportTypes.js";-import type { OnboardingTipContent } from "../../services/onboardingTips/onboardingTipsContent.js";-import type { ReengagementContent } from "../../services/reengagement/reengagementContent.js";+import { signExpiringPayload } from "../signedToken.js";let resend: Resend | undefined;let marketingAudienceId: string | null = null;@@ -245,47 +242,6 @@ Bill`;}};-// Scheduled onboarding tip email - returns the email ID for cancellation-export const scheduleOnboardingTipEmail = async (- email: string,- userName: string,- tipContent: OnboardingTipContent,- scheduledAt: string-): Promise<string | null> => {- if (!resend) return null;-- const unsubscribeUrl = `${process.env.BASE_URL}/api/user/unsubscribe-marketing-oneclick?email=${encodeURIComponent(email)}`;-- try {- const html = await render(- OnboardingTipEmail({- userName,- body: tipContent.body,- linkText: tipContent.linkText,- linkUrl: tipContent.linkUrl,- unsubscribeUrl,- })- );-- const response = await resend.emails.send({- from: "Rybbit <[email protected]>",- to: email,- subject: tipContent.subject,- html,- scheduledAt,- headers: {- "List-Unsubscribe": `<${unsubscribeUrl}>`,- "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",- },- });-- return response.data?.id ?? null;- } catch (error) {- console.error("Failed to schedule onboarding tip email:", error);- return null;- }-};-// Cancel a scheduled emailexport const cancelScheduledEmail = async (emailId: string): Promise<void> => {if (!resend) return;@@ -296,43 +252,58 @@ export const cancelScheduledEmail = async (emailId: string): Promise<void> => {}};-// Send re-engagement email-export const sendReengagementEmail = async (+/**+ * Signed one-click marketing unsubscribe URL used by all lifecycle emails.+ * Unsubscribe links must keep working from old emails, so the TTL is long+ * (2 years) - the expiry exists so a leaked link is not valid forever.+ */+export const marketingUnsubscribeUrl = (email: string): string => {+ const { exp, sig } = signExpiringPayload(`unsubscribe:${email}`, 2 * 365 * 24 * 3600);+ return `${process.env.BASE_URL}/api/user/unsubscribe-marketing-oneclick?email=${encodeURIComponent(email)}&exp=${exp}&sig=${sig}`;+};++/**+ * Plain-text lifecycle email from Bill with a monitored reply address.+ * All state-machine onboarding/retention emails go through here.+ *+ * Returns true only when Resend actually accepted the message: the SDK+ * resolves with { data: null, error } on HTTP/network failures rather than+ * throwing, so the response is checked explicitly. The caller passes a+ * stable idempotencyKey (the lifecycle email key) so a retry after an+ * "accepted but response lost" failure can't double-send.+ */+export const sendLifecycleEmail = async (email: string,- userName: string,- content: ReengagementContent,- siteId: number,- domain: string-): Promise<void> => {- if (!resend) return;+ subject: string,+ text: string,+ idempotencyKey?: string+): Promise<boolean> => {+ if (!resend) return false;- const unsubscribeUrl = `${process.env.BASE_URL}/api/user/unsubscribe-marketing-oneclick?email=${encodeURIComponent(email)}`;+ const unsubscribeUrl = marketingUnsubscribeUrl(email);try {- const html = await render(- ReengagementEmail({- userName,- day: content.day,- title: content.title,- message: content.message,- ctaText: content.ctaText,- siteId,- domain,- unsubscribeUrl,- })- );-- await resend.emails.send({- from: "Rybbit <[email protected]>",- to: email,- subject: content.subject,- html,- headers: {- "List-Unsubscribe": `<${unsubscribeUrl}>`,- "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",+ const response = await resend.emails.send(+ {+ from: "Bill from Rybbit <[email protected]>",+ replyTo: "[email protected]",+ to: email,+ subject,+ text: `${text}\n\n--\nUnsubscribe from these emails: ${unsubscribeUrl}`,+ headers: {+ "List-Unsubscribe": `<${unsubscribeUrl}>`,+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",+ },},- });+ idempotencyKey ? { idempotencyKey } : undefined+ );+ if (response.error || !response.data?.id) {+ console.error("Resend rejected lifecycle email:", response.error);+ return false;+ }+ return true;} catch (error) {- console.error("Failed to send re-engagement email:", error);+ console.error("Failed to send lifecycle email:", error);+ return false;}};diff --git a/server/src/lib/email/templates/OnboardingTipEmail.tsx b/server/src/lib/email/templates/OnboardingTipEmail.tsxdeleted file mode 100644index d95ed609b..000000000--- a/server/src/lib/email/templates/OnboardingTipEmail.tsx+++ /dev/null@@ -1,94 +0,0 @@-import {- Body,- Container,- Head,- Hr,- Html,- Img,- Link,- Preview,- Text,- Tailwind,- pixelBasedPreset,-} from "@react-email/components";-import * as React from "react";--interface OnboardingTipEmailProps {- userName: string;- body: string;- linkText?: string;- linkUrl?: string;- unsubscribeUrl: string;-}--export const OnboardingTipEmail = ({ userName, body, linkText, linkUrl, unsubscribeUrl }: OnboardingTipEmailProps) => {- const currentYear = new Date().getFullYear();- const greeting = userName ? `Hi ${userName}` : "Hi there";-- // Split body into paragraphs- const paragraphs = body.split("\n\n").filter(p => p.trim());-- return (- <Html>- <Head />- <Preview>{paragraphs[0]?.substring(0, 100) || "A message from Rybbit"}</Preview>- <Tailwind- config={{- presets: [pixelBasedPreset],- theme: {- extend: {- colors: {- brand: "#10b981",- darkText: "#111827",- mutedText: "#6b7280",- borderColor: "#e5e7eb",- },- },- },- }}- >- <Body className="bg-white font-sans">- <Container className="mx-auto py-8 px-6 max-w-[600px]">- <Img- src="https://app.rybbit.io/rybbit/horizontal_black.svg"- alt="Rybbit"- width="120"- height="28"- className="mb-8"- />-- <Text className="text-darkText text-base leading-relaxed mb-4">{greeting},</Text>-- {paragraphs.map((paragraph, index) => (- <Text key={index} className="text-darkText text-base leading-relaxed mb-4">- {paragraph}- </Text>- ))}-- {linkUrl && linkText && (- <Text className="text-darkText text-base leading-relaxed mb-4">- <Link href={linkUrl} className="text-brand underline">- {linkText}- </Link>- </Text>- )}-- <Text className="text-darkText text-base leading-relaxed mt-8">- You can reply to this email,- <br />- Bill – Founder of Rybbit- </Text>-- <Hr className="border-borderColor my-8" />-- <Text className="text-mutedText text-xs">- <Link href={unsubscribeUrl} className="text-mutedText underline">- Unsubscribe- </Link>- </Text>- </Container>- </Body>- </Tailwind>- </Html>- );-};diff --git a/server/src/lib/email/templates/ReengagementEmail.tsx b/server/src/lib/email/templates/ReengagementEmail.tsxdeleted file mode 100644index 164420a7d..000000000--- a/server/src/lib/email/templates/ReengagementEmail.tsx+++ /dev/null@@ -1,114 +0,0 @@-import {- Body,- Container,- Head,- Hr,- Html,- Img,- Link,- Preview,- Text,- Tailwind,- pixelBasedPreset,-} from "@react-email/components";-import * as React from "react";--interface ReengagementEmailProps {- userName: string;- day: number;- title: string;- message: string;- ctaText: string;- siteId: number;- domain: string;- unsubscribeUrl: string;-}--const DOCS_URL = "https://www.rybbit.io/docs";--export const ReengagementEmail = ({- userName,- day,- title,- message,- ctaText,- siteId,- domain,- unsubscribeUrl,-}: ReengagementEmailProps) => {- const greeting = userName ? `Hi ${userName}` : "Hi there";- const dashboardUrl = `https://app.rybbit.io/${siteId}`;- const messageWithDomain = message.replace("{domain}", domain);-- // Split message into paragraphs- const paragraphs = messageWithDomain.split("\n\n").filter(p => p.trim());-- return (- <Html>- <Head />- <Preview>{title}</Preview>- <Tailwind- config={{- presets: [pixelBasedPreset],- theme: {- extend: {- colors: {- brand: "#10b981",- darkText: "#111827",- mutedText: "#6b7280",- borderColor: "#e5e7eb",- },- },- },- }}- >- <Body className="bg-white font-sans">- <Container className="mx-auto py-8 px-6 max-w-[600px]">- <Img- src="https://app.rybbit.io/rybbit/horizontal_black.svg"- alt="Rybbit"- width="120"- height="28"- className="mb-8"- />-- <Text className="text-darkText text-base leading-relaxed mb-4">{greeting},</Text>-- {paragraphs.map((paragraph, index) => (- <Text key={index} className="text-darkText text-base leading-relaxed mb-4">- {paragraph}- </Text>- ))}-- <Text className="text-darkText text-base leading-relaxed mb-4">- <Link href={dashboardUrl} className="text-brand underline">- {ctaText}- </Link>- </Text>-- <Text className="text-mutedText text-sm leading-relaxed mb-4">- Need help?{" "}- <Link href={DOCS_URL} className="text-mutedText underline">- View our setup guide- </Link>- </Text>-- <Text className="text-darkText text-base leading-relaxed mt-8">- You can reply to this email,- <br />- Bill – Founder of Rybbit- </Text>-- <Hr className="border-borderColor my-8" />-- <Text className="text-mutedText text-xs">- <Link href={unsubscribeUrl} className="text-mutedText underline">- Unsubscribe- </Link>- </Text>- </Container>- </Body>- </Tailwind>- </Html>- );-};diff --git a/server/src/lib/signedToken.test.ts b/server/src/lib/signedToken.test.tsnew file mode 100644index 000000000..8a4694603--- /dev/null+++ b/server/src/lib/signedToken.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("./const.js", () => ({ SECRET: "test-secret" }));++import { signExpiringPayload, signPayload, verifyExpiringPayload, verifySignedPayload } from "./signedToken.js";++describe("signed tokens", () => {+ it("round-trips a plain payload and rejects tampering", () => {+ const sig = signPayload("unsubscribe:[email protected]");+ expect(verifySignedPayload("unsubscribe:[email protected]", sig)).toBe(true);+ expect(verifySignedPayload("unsubscribe:[email protected]", sig)).toBe(false);+ expect(verifySignedPayload("unsubscribe:[email protected]", sig + "x")).toBe(false);+ expect(verifySignedPayload("unsubscribe:[email protected]", "")).toBe(false);+ });++ it("expiring tokens verify within the TTL and fail after it", () => {+ const { exp, sig } = signExpiringPayload("check-install:42:acme.com", 3600);+ expect(verifyExpiringPayload("check-install:42:acme.com", exp, sig)).toBe(true);+ expect(verifyExpiringPayload("check-install:43:acme.com", exp, sig)).toBe(false);++ // A signature over an already-past expiry never verifies+ const past = Math.floor(Date.now() / 1000) - 10;+ const staleSig = signPayload(`check-install:42:acme.com:${past}`);+ expect(verifyExpiringPayload("check-install:42:acme.com", past, staleSig)).toBe(false);+ });++ it("rejects a forged expiry: exp is inside the signed payload", () => {+ const { exp, sig } = signExpiringPayload("unsubscribe:[email protected]", 60);+ expect(verifyExpiringPayload("unsubscribe:[email protected]", exp + 999999, sig)).toBe(false);+ expect(verifyExpiringPayload("unsubscribe:[email protected]", "not-a-number", sig)).toBe(false);+ });+});diff --git a/server/src/lib/signedToken.ts b/server/src/lib/signedToken.tsnew file mode 100644index 000000000..1d8b4dd78--- /dev/null+++ b/server/src/lib/signedToken.ts@@ -0,0 +1,31 @@+import { createHmac, timingSafeEqual } from "crypto";+import { SECRET } from "./const.js";++/**+ * HMAC signatures for links that leave the app in emails (unsubscribe,+ * install checks) so the endpoints can't be driven with arbitrary values.+ */+export function signPayload(payload: string): string {+ return createHmac("sha256", SECRET || "").update(payload).digest("base64url");+}++export function verifySignedPayload(payload: string, signature: string): boolean {+ const expected = Buffer.from(signPayload(payload));+ const provided = Buffer.from(signature);+ return expected.length === provided.length && timingSafeEqual(expected, provided);+}++/**+ * Expiring variant: the expiry is part of the signed payload and travels in+ * the URL, so a leaked link cannot be replayed indefinitely.+ */+export function signExpiringPayload(payload: string, ttlSeconds: number): { exp: number; sig: string } {+ const exp = Math.floor(Date.now() / 1000) + ttlSeconds;+ return { exp, sig: signPayload(`${payload}:${exp}`) };+}++export function verifyExpiringPayload(payload: string, exp: number | string, signature: string): boolean {+ const expNum = Number(exp);+ if (!Number.isFinite(expNum) || expNum < Date.now() / 1000) return false;+ return verifySignedPayload(`${payload}:${Math.floor(expNum)}`, signature);+}diff --git a/server/src/services/lifecycleEmails/lifecycleContent.ts b/server/src/services/lifecycleEmails/lifecycleContent.tsnew file mode 100644index 000000000..3c5c9c8dd--- /dev/null+++ b/server/src/services/lifecycleEmails/lifecycleContent.ts@@ -0,0 +1,178 @@+import type { PlatformInfo } from "./platformDetect.js";++export interface LifecycleEmail {+ subject: string;+ text: string;+}++const appUrl = () => (process.env.BASE_URL || "https://app.rybbit.io").replace(/\/$/, "");++const greeting = (name?: string | null) => {+ // Email-signup users have their email prefix stored as their name - don't greet with that+ const clean = name && !name.includes("@") ? name.split(" ")[0] : "";+ return clean ? `Hi ${clean},` : "Hi,";+};++const signoff = `\n\nBill\nFounder, Rybbit`;++export const snippetFor = (siteId: number) =>+ `<script src="${appUrl()}/api/script.js" data-site-id="${siteId}" defer></script>`;++// ---------------------------------------------------------------------------+// Stage 1: signed up, no site+// ---------------------------------------------------------------------------++export const noSite1 = (name?: string | null): LifecycleEmail => ({+ subject: "Finish setting up Rybbit",+ text: `${greeting(name)}++Looks like you haven't added your website yet. It takes about a minute - you give us the domain, we give you one script tag.++Pick up where you left off: ${appUrl()}++If anything was confusing or got in your way, just reply and tell me - I read every response.${signoff}`,+});++export const noSite2 = (name?: string | null): LifecycleEmail => ({+ subject: "Was something unclear?",+ text: `${greeting(name)}++You signed up for Rybbit a few days ago but haven't added a site. That usually means something got in the way - a question about pricing, self-hosting, privacy, or just timing.++Whatever it was, I'd genuinely like to know. Reply with one line and I'll help, or tell me what we could have done better.++This is the last email I'll send unless you start using Rybbit.${signoff}`,+});++// ---------------------------------------------------------------------------+// Stage 2: site created, no data+// ---------------------------------------------------------------------------++export const installSnippet = (+ domain: string,+ siteId: number,+ platform: PlatformInfo | null,+ name?: string | null+): LifecycleEmail => ({+ subject: `One step left for ${domain}`,+ text: `${greeting(name)}++${domain} is set up on Rybbit - it just needs the tracking snippet. Add this to the <head> of every page:++${snippetFor(siteId)}+${+ platform+ ? `\nYour site looks like it runs on ${platform.label}. Here's the exact guide for it:\n${platform.guideUrl}\n`+ : `\nUsing a framework or CMS? We have step-by-step guides for most of them:\nhttps://rybbit.com/docs/script\n`+}+As soon as the first pageview arrives you'll see it live on your dashboard. If it's not working after a few minutes, reply and I'll help you debug it.${signoff}`,+});++export const installCheck = (domain: string, checkInstallUrl: string, name?: string | null): LifecycleEmail => ({+ subject: `Still nothing from ${domain}`,+ text: `${greeting(name)}++Your Rybbit snippet hasn't sent any data from ${domain} yet. The three most common causes:++1. The snippet isn't in the <head> of the deployed site (check view-source on the live page)+2. The site hasn't been redeployed since you added it+3. An adblocker on your own browser is blocking your test visit - try a private window++Click here and we'll fetch ${domain} right now and tell you whether the snippet is there:+${checkInstallUrl}++Stuck? Reply to this email and I'll take a look personally.${signoff}`,+});++export const installFinal = (domain: string, name?: string | null): LifecycleEmail => ({+ subject: `Need a hand with ${domain}?`,+ text: `${greeting(name)}++${domain} still isn't sending data to Rybbit. I won't keep nudging you - this is the last one.++If you hit a technical wall, reply with your platform (WordPress, Next.js, Shopify...) and I'll send you exact instructions. If you decided Rybbit isn't for you, I'd honestly love to know why.++Either way, thanks for giving us a try.${signoff}`,+});++// ---------------------------------------------------------------------------+// Stage 3: data flowing+// ---------------------------------------------------------------------------++export const siteLive = (domain: string, siteId: number, country: string | null, name?: string | null): LifecycleEmail => ({+ subject: `Rybbit is live on ${domain}`,+ text: `${greeting(name)}++Rybbit just received its first pageview from ${domain}${country ? ` - a visitor from ${country}` : ""}. Everything is working.++Watch your traffic live: ${appUrl()}/${siteId}++Let it collect data for a couple of days, then I'll send you the first patterns worth looking at.${signoff}`,+});++export interface FirstDaysStats {+ sessions: number;+ pageviews: number;+ topReferrer: string | null;+ topPage: string | null;+}++export const firstDays = (domain: string, siteId: number, stats: FirstDaysStats, name?: string | null): LifecycleEmail => ({+ subject: `Your first days of data on ${domain}`,+ text: `${greeting(name)}++${domain} has been on Rybbit for a few days. So far:++- ${stats.sessions.toLocaleString()} visit${stats.sessions === 1 ? "" : "s"}, ${stats.pageviews.toLocaleString()} pageview${stats.pageviews === 1 ? "" : "s"}${+ stats.topReferrer ? `\n- Top source: ${stats.topReferrer}` : ""+ }${stats.topPage ? `\n- Most viewed page: ${stats.topPage}` : ""}++One thing worth knowing: adblockers hide roughly 10-30% of real visitors from Google Analytics, but they rarely block Rybbit. If these numbers look higher than what you're used to, that's your actual traffic.++See the full picture: ${appUrl()}/${siteId}${signoff}`,+});++export const nudgeEvents = (domain: string, siteId: number, name?: string | null): LifecycleEmail => ({+ subject: `See what visitors actually do on ${domain}`,+ text: `${greeting(name)}++Pageviews tell you where people go. Custom events tell you what they do - button clicks, signups, downloads. One line:++window.rybbit.event("signup_clicked")++Or straight from HTML, no code:++<button data-rybbit-event="signup_clicked">Sign up</button>++Events show up on your dashboard and work as funnel steps and goals.++Guide: https://rybbit.com/docs/track-events${signoff}`,+});++export const nudgeGoals = (domain: string, siteId: number, convertingPath: string, name?: string | null): LifecycleEmail => ({+ subject: `Visitors are reaching ${convertingPath} - measure it`,+ text: `${greeting(name)}++Visitors on ${domain} are landing on ${convertingPath}. That looks like a conversion - worth measuring properly.++Set a goal on that path and Rybbit shows your conversion rate broken down by source, country, and device. Funnels go further: define the steps leading up to it and see exactly where people drop off.++Create your first goal: ${appUrl()}/${siteId}/goals++Guide: https://rybbit.com/docs/goals${signoff}`,+});++// ---------------------------------------------------------------------------+// Stage 4: went quiet+// ---------------------------------------------------------------------------++export const wentQuiet = (domain: string, siteId: number, lastEventAt: string, name?: string | null): LifecycleEmail => ({+ subject: `We stopped hearing from ${domain}`,+ text: `${greeting(name)}++${domain} was sending data to Rybbit, but we haven't received anything since ${lastEventAt}. If you redeployed recently, the tracking snippet may have been dropped from the new build - that's the usual cause.++Check that the snippet is still in your <head>, or see your dashboard: ${appUrl()}/${siteId}++If you removed it on purpose, ignore this - I won't email about it again.${signoff}`,+});diff --git a/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts b/server/src/services/lifecycleEmails/lifecycleEmailService.test.tsnew file mode 100644index 000000000..dd233f81e--- /dev/null+++ b/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts@@ -0,0 +1,459 @@+import { DateTime } from "luxon";+import { beforeEach, describe, expect, it, vi } from "vitest";++/**+ * The lifecycle cron is a state machine: every email is triggered by a state+ * transition or a timeout inside a state, never by a timer from signup. These+ * tests drive the machine through its states with mocked Postgres/ClickHouse+ * and assert which single email (if any) each evaluation produces.+ */++const now = () => DateTime.utc();+const hoursAgo = (h: number) => now().minus({ hours: h }).toSQL({ includeOffset: false })!;+const daysAgo = (d: number) => now().minus({ days: d }).toSQL({ includeOffset: false })!;++const state = vi.hoisted(() => ({+ users: [] as Array<{ id: string; email: string; name: string; createdAt: string }>,+ legacyTipUsers: [] as Array<{ id: string; scheduledTipEmailIds: string[] }>,+ memberships: [] as Array<{ userId: string; organizationId: string; role: string }>,+ sites: [] as Array<{+ siteId: number;+ domain: string;+ createdAt: string;+ organizationId: string;+ detectedPlatform: string | null;+ }>,+ logs: [] as Array<{ userId: string; emailKey: string; sentAt: string }>,+ recentQuietLogs: [] as Array<{ siteId: number; emailKey: string }>,+ goals: [] as Array<{ siteId: number }>,+ owners: [] as Array<{ organizationId: string; userId: string; email: string; name: string }>,+ /** site_id -> aggregate stats returned by the ClickHouse batch query */+ siteStats: [] as Array<{+ site_id: number;+ first_event: string;+ last_event: string;+ total: number;+ pageviews: number;+ custom_events: number;+ }>,+ firstPageview: [] as Array<{ country: string }>,+ overview: [] as Array<{ sessions: number; pageviews: number }>,+ topRows: [] as Array<{ value: string }>,+ convertingPaths: [] as Array<{ pathname: string }>,+ quietCandidates: [] as Array<{ site_id: number; last_event: string }>,+ establishedSites: [] as Array<{ site_id: number; total: number }>,+ /** unique-key guard mirroring the DB constraint */+ sentKeys: new Set<string>(),+ clearedTipUsers: [] as string[],+}));++const mocks = vi.hoisted(() => ({+ sendLifecycleEmail: vi.fn(async (_email: string, _subject: string, _text: string, _idempotencyKey?: string) => true),+ isContactUnsubscribed: vi.fn(async (_email: string) => false),+ cancelScheduledEmail: vi.fn(async (_id: string) => undefined),+ detectPlatform: vi.fn(async () => null),+}));++const insertedStack = vi.hoisted(() => [] as string[]);++vi.mock("../../db/postgres/postgres.js", () => {+ function chain(rows: () => unknown[]) {+ const builder: any = {+ from: () => builder,+ innerJoin: () => builder,+ where: () => builder,+ then: (resolve: any, reject: any) => Promise.resolve(rows()).then(resolve, reject),+ };+ return builder;+ }++ return {+ db: {+ // Reads are told apart by the columns each one selects.+ select: (fields: Record<string, unknown>) =>+ chain(() => {+ if ("scheduledTipEmailIds" in fields) return state.legacyTipUsers;+ if ("emailKey" in fields && "userId" in fields) return state.logs;+ if ("emailKey" in fields && "siteId" in fields) return state.recentQuietLogs;+ if ("role" in fields) return state.memberships;+ if ("createdAt" in fields && "email" in fields) return state.users;+ if ("detectedPlatform" in fields) return state.sites;+ if ("email" in fields && "organizationId" in fields) return state.owners;+ if ("domain" in fields) return state.sites;+ return state.goals;+ }),+ insert: () => ({+ values: (row: { userId: string; emailKey: string }) => ({+ onConflictDoNothing: () => ({+ returning: async () => {+ const key = `${row.userId}:${row.emailKey}`;+ if (state.sentKeys.has(key)) return [];+ state.sentKeys.add(key);+ // Mirror the real table: the row is now visible to later reads+ state.logs.push({+ userId: row.userId,+ emailKey: row.emailKey,+ sentAt: new Date().toISOString(),+ });+ insertedStack.push(key);+ return [{ id: state.sentKeys.size }];+ },+ }),+ }),+ }),+ update: () => ({+ set: (values: Record<string, unknown>) => ({+ where: async () => {+ if ("scheduledTipEmailIds" in values) state.clearedTipUsers.push("cleared");+ },+ }),+ }),+ // The service only deletes the row it just inserted (send-failure+ // rollback), so LIFO removal mirrors the real behavior.+ delete: () => ({+ where: async () => {+ const key = insertedStack.pop();+ if (!key) return;+ state.sentKeys.delete(key);+ const [userId, ...rest] = key.split(":");+ const emailKey = rest.join(":");+ const idx = state.logs.findIndex(l => l.userId === userId && l.emailKey === emailKey);+ if (idx >= 0) state.logs.splice(idx, 1);+ },+ }),+ },+ };+});++vi.mock("../../db/clickhouse/clickhouse.js", () => ({+ clickhouse: {+ query: async ({ query }: { query: string }) => {+ const rows = (() => {+ if (query.includes("custom_events")) return state.siteStats;+ if (query.includes("ORDER BY timestamp ASC")) return state.firstPageview;+ if (query.includes("uniq(session_id)")) return state.overview;+ if (query.includes("GROUP BY value")) return state.topRows;+ if (query.includes("INTERVAL 14 DAY")) return state.convertingPaths;+ if (query.includes("HAVING last_event")) return state.quietCandidates;+ if (query.includes("INTERVAL 21 DAY")) return state.establishedSites;+ return [];+ })();+ return { json: async () => rows };+ },+ },+}));++vi.mock("../../lib/email/email.js", () => ({+ sendLifecycleEmail: mocks.sendLifecycleEmail,+ isContactUnsubscribed: mocks.isContactUnsubscribed,+ cancelScheduledEmail: mocks.cancelScheduledEmail,+}));++vi.mock("../../lib/const.js", () => ({ IS_CLOUD: true, SECRET: "test-secret" }));++vi.mock("./platformDetect.js", async importOriginal => {+ const original = await importOriginal<typeof import("./platformDetect.js")>();+ return { ...original, detectPlatform: mocks.detectPlatform };+});++import { lifecycleEmailService } from "./lifecycleEmailService.js";++const run = () => lifecycleEmailService.processLifecycleEmails();+const sentSubjects = () => mocks.sendLifecycleEmail.mock.calls.map(call => call[1]);++const addUser = (id: string, createdAt: string) => {+ state.users.push({ id, email: `${id}@example.com`, name: "Ada", createdAt });+};+const addOwnedSite = (userId: string, siteId: number, domain: string, createdAt: string) => {+ const orgId = `org-${userId}`;+ if (!state.memberships.some(m => m.userId === userId && m.organizationId === orgId)) {+ state.memberships.push({ userId, organizationId: orgId, role: "owner" });+ }+ state.sites.push({ siteId, domain, createdAt, organizationId: orgId, detectedPlatform: null });+};+const markSent = (userId: string, emailKey: string, sentAt: string) => {+ state.logs.push({ userId, emailKey, sentAt });+ state.sentKeys.add(`${userId}:${emailKey}`);+};++beforeEach(() => {+ process.env.BASE_URL = "https://app.rybbit.io";+ for (const value of Object.values(state)) {+ if (Array.isArray(value)) value.length = 0;+ else if (value instanceof Set) value.clear();+ }+ vi.clearAllMocks();+ mocks.sendLifecycleEmail.mockResolvedValue(true);+ mocks.isContactUnsubscribed.mockResolvedValue(false);+ insertedStack.length = 0;+ // Reset singleton run-state between tests+ (lifecycleEmailService as any).lastWentQuietAt = null;+ (lifecycleEmailService as any).legacyTipsCancelled = true;+ (lifecycleEmailService as any).negativeCache.clear();+});++describe("state: signed up, no site", () => {+ it("sends the finish-setup email once the 2h timeout passes", async () => {+ addUser("u1", hoursAgo(3));+ await run();+ expect(sentSubjects()).toEqual(["Finish setting up Rybbit"]);+ });++ it("sends nothing before the timeout", async () => {+ addUser("u1", hoursAgo(1));+ await run();+ expect(mocks.sendLifecycleEmail).not.toHaveBeenCalled();+ });++ it("never sends the same email twice", async () => {+ addUser("u1", hoursAgo(3));+ await run();+ await run();+ expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(1);+ });++ it("escalates to the reply-based ask after 3 days, then stops without touching the provider", async () => {+ addUser("u1", daysAgo(4));+ markSent("u1", "no_site_1", daysAgo(3));+ await run();+ expect(sentSubjects()).toEqual(["Was something unclear?"]);++ // Once both terminal keys exist, later ticks must be provider-silent:+ // no unsubscribe lookup, no conflicting insert, no send attempt.+ mocks.isContactUnsubscribed.mockClear();+ await run();+ expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(1);+ expect(mocks.isContactUnsubscribed).not.toHaveBeenCalled();+ });++ it("includes unverified users (this app doesn't require email verification)", async () => {+ // The query-level fix can't be seen through the mock, but the behavior+ // contract is documented here: eligibility is not gated on emailVerified.+ addUser("u1", hoursAgo(3));+ await run();+ expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(1);+ });++ it("skips invited teammates who own no organization", async () => {+ addUser("u1", hoursAgo(5));+ state.memberships.push({ userId: "u1", organizationId: "someone-elses-org", role: "member" });+ await run();+ expect(mocks.sendLifecycleEmail).not.toHaveBeenCalled();+ });++ it("skips unsubscribed users entirely", async () => {+ addUser("u1", hoursAgo(3));+ mocks.isContactUnsubscribed.mockResolvedValue(true);+ await run();+ expect(mocks.sendLifecycleEmail).not.toHaveBeenCalled();+ });+});++describe("state: site created, no data", () => {+ it("sends the snippet email an hour after site creation", async () => {+ addUser("u1", hoursAgo(4));+ addOwnedSite("u1", 42, "acme.com", hoursAgo(2));+ await run();+ expect(sentSubjects()).toEqual(["One step left for acme.com"]);+ const body = mocks.sendLifecycleEmail.mock.calls[0][2];+ expect(body).toContain('data-site-id="42"');+ });++ it("times the install check from the snippet send, not site age", async () => {+ // Pre-existing site picked up at rollout: 30h old, snippet sent on the+ // previous tick. The check must NOT follow ten minutes later.+ addUser("u1", daysAgo(2));+ addOwnedSite("u1", 42, "acme.com", hoursAgo(30));+ markSent("u1", "install_snippet:42", hoursAgo(0.2));+ await run();+ expect(mocks.sendLifecycleEmail).not.toHaveBeenCalled();++ // 24h after the snippet, the check goes out.+ state.logs.length = 0;+ markSent("u1", "install_snippet:42", hoursAgo(25));+ await run();+ expect(sentSubjects()).toEqual(["Still nothing from acme.com"]);+ const body = mocks.sendLifecycleEmail.mock.calls[0][2];+ expect(body).toContain("/api/site/check-install?siteId=42&domain=acme.com&exp=");+ });++ it("sends the final reply-based email 4 days after the check and nothing after", async () => {+ addUser("u1", daysAgo(7));+ addOwnedSite("u1", 42, "acme.com", daysAgo(6));+ markSent("u1", "install_snippet:42", daysAgo(6));+ markSent("u1", "install_check:42", daysAgo(5));+ await run();+ expect(sentSubjects()).toEqual(["Need a hand with acme.com?"]);++ mocks.isContactUnsubscribed.mockClear();+ await run();+ expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(1);+ expect(mocks.isContactUnsubscribed).not.toHaveBeenCalled();+ });++ it("still helps install a new site when another site already has data", async () => {+ addUser("u1", daysAgo(20));+ addOwnedSite("u1", 1, "working.com", daysAgo(20));+ addOwnedSite("u1", 2, "newsite.com", hoursAgo(3));+ state.siteStats.push({ site_id: 1, first_event: daysAgo(19), last_event: hoursAgo(1), total: 9000, pageviews: 8500, custom_events: 40 });+ markSent("u1", "site_live:1", daysAgo(19));+ await run();+ expect(sentSubjects()).toEqual(["One step left for newsite.com"]);+ });+});++describe("transition: first data arrives", () => {+ it("sends 'you're live' immediately, bypassing the educational gap", async () => {+ addUser("u1", daysAgo(1));+ addOwnedSite("u1", 42, "acme.com", hoursAgo(20));+ // snippet email went out an hour ago - the gap must not delay the transition email+ markSent("u1", "install_snippet:42", hoursAgo(1));+ state.siteStats.push({ site_id: 42, first_event: hoursAgo(1), last_event: hoursAgo(1), total: 5, pageviews: 5, custom_events: 0 });+ state.firstPageview.push({ country: "DE" });+ await run();+ expect(sentSubjects()).toEqual(["Rybbit is live on acme.com"]);+ const body = mocks.sendLifecycleEmail.mock.calls[0][2];+ expect(body).toContain("Germany");+ });++ it("passes a stable idempotency key to the provider", async () => {+ addUser("u1", daysAgo(1));+ addOwnedSite("u1", 42, "acme.com", hoursAgo(20));+ state.siteStats.push({ site_id: 42, first_event: hoursAgo(1), last_event: hoursAgo(1), total: 5, pageviews: 5, custom_events: 0 });+ await run();+ expect(mocks.sendLifecycleEmail.mock.calls[0][3]).toBe("lifecycle:u1:site_live:42");+ });++ it("does not send it for sites whose first event is old (pre-existing traffic)", async () => {+ addUser("u1", daysAgo(20));+ addOwnedSite("u1", 42, "acme.com", daysAgo(20));+ state.siteStats.push({ site_id: 42, first_event: daysAgo(15), last_event: hoursAgo(1), total: 900, pageviews: 850, custom_events: 3 });+ await run();+ expect(sentSubjects()).not.toContain("Rybbit is live on acme.com");+ });++ it("retries next tick when the provider rejects the send", async () => {+ addUser("u1", daysAgo(1));+ addOwnedSite("u1", 42, "acme.com", hoursAgo(20));+ state.siteStats.push({ site_id: 42, first_event: hoursAgo(1), last_event: hoursAgo(1), total: 5, pageviews: 5, custom_events: 0 });+ mocks.sendLifecycleEmail.mockResolvedValueOnce(false);+ await run();+ // First run: attempted but rejected; the log row is rolled back, so the+ // next run attempts the same key again.+ await run();+ expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(2);+ expect(mocks.sendLifecycleEmail.mock.calls[1][1]).toBe("Rybbit is live on acme.com");+ });+});++describe("state: data flowing", () => {+ const flowingSite = (customEvents = 0) => {+ addUser("u1", daysAgo(10));+ addOwnedSite("u1", 42, "acme.com", daysAgo(10));+ state.siteStats.push({ site_id: 42, first_event: daysAgo(4), last_event: hoursAgo(2), total: 500, pageviews: 450, custom_events: customEvents });+ markSent("u1", "site_live:42", daysAgo(4));+ };++ it("sends the first-days report keyed to data age, with real numbers", async () => {+ flowingSite();+ state.overview.push({ sessions: 120, pageviews: 340 });+ state.topRows.push({ value: "google.com" });+ await run();+ expect(sentSubjects()).toEqual(["Your first days of data on acme.com"]);+ const body = mocks.sendLifecycleEmail.mock.calls[0][2];+ expect(body).toContain("120 visits");+ expect(body).toContain("google.com");+ });++ it("holds educational emails until the 48h gap has passed", async () => {+ addUser("u1", daysAgo(10));+ addOwnedSite("u1", 42, "acme.com", daysAgo(10));+ state.siteStats.push({ site_id: 42, first_event: daysAgo(4), last_event: hoursAgo(2), total: 500, pageviews: 450, custom_events: 0 });+ markSent("u1", "site_live:42", hoursAgo(10));+ await run();+ expect(mocks.sendLifecycleEmail).not.toHaveBeenCalled();+ });++ it("nudges goals only when the data shows a converting path and no goal exists", async () => {+ addUser("u1", daysAgo(15));+ addOwnedSite("u1", 42, "acme.com", daysAgo(15));+ state.siteStats.push({ site_id: 42, first_event: daysAgo(8), last_event: hoursAgo(2), total: 2000, pageviews: 1900, custom_events: 4 });+ markSent("u1", "site_live:42", daysAgo(4));+ markSent("u1", "first_days:42", daysAgo(4));+ state.convertingPaths.push({ pathname: "/thank-you" });+ await run();+ expect(sentSubjects()).toEqual(["Visitors are reaching /thank-you - measure it"]);++ // With a goal already configured, the nudge never fires+ state.sentKeys.delete("u1:nudge_goals:42");+ mocks.sendLifecycleEmail.mockClear();+ state.goals.push({ siteId: 42 });+ await run();+ expect(sentSubjects()).not.toContain("Visitors are reaching /thank-you - measure it");+ });++ it("nudges custom events only when the site has none", async () => {+ addUser("u1", daysAgo(20));+ addOwnedSite("u1", 42, "acme.com", daysAgo(20));+ state.siteStats.push({ site_id: 42, first_event: daysAgo(11), last_event: hoursAgo(2), total: 2000, pageviews: 1900, custom_events: 0 });+ markSent("u1", "site_live:42", daysAgo(5));+ markSent("u1", "first_days:42", daysAgo(5));+ await run();+ expect(sentSubjects()).toEqual(["See what visitors actually do on acme.com"]);+ });+});++describe("state: went quiet", () => {+ const quietSite = () => {+ state.quietCandidates.push({ site_id: 7, last_event: hoursAgo(50) });+ state.establishedSites.push({ site_id: 7, total: 5000 });+ state.sites.push({ siteId: 7, domain: "quiet.com", createdAt: daysAgo(200), organizationId: "org-x", detectedPlatform: null });+ state.owners.push({ organizationId: "org-x", userId: "owner1", email: "[email protected]", name: "Ada" });+ };++ it("alerts the owner when an established site stops sending data, once per outage", async () => {+ quietSite();+ await run();+ expect(sentSubjects()).toEqual(["We stopped hearing from quiet.com"]);+ // Hourly cadence: force the next run to include the went-quiet pass again.+ (lifecycleEmailService as any).lastWentQuietAt = null;+ await run();+ expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(1);+ });++ it("skips sites without an established baseline", async () => {+ state.quietCandidates.push({ site_id: 7, last_event: hoursAgo(50) });+ // establishedSites empty: only a handful of test events, no alert+ state.sites.push({ siteId: 7, domain: "quiet.com", createdAt: daysAgo(200), organizationId: "org-x", detectedPlatform: null });+ state.owners.push({ organizationId: "org-x", userId: "owner1", email: "[email protected]", name: "Ada" });+ await run();+ expect(mocks.sendLifecycleEmail).not.toHaveBeenCalled();+ });++ it("respects the 30-day per-site cooldown for repeat outages", async () => {+ quietSite();+ state.recentQuietLogs.push({ siteId: 7, emailKey: "went_quiet:7:2026-08-15" });+ await run();+ expect(mocks.sendLifecycleEmail).not.toHaveBeenCalled();+ });++ it("sends one owner at most one alert per run even with several quiet sites", async () => {+ quietSite();+ state.quietCandidates.push({ site_id: 8, last_event: hoursAgo(52) });+ state.establishedSites.push({ site_id: 8, total: 3000 });+ state.sites.push({ siteId: 8, domain: "quiet2.com", createdAt: daysAgo(200), organizationId: "org-x", detectedPlatform: null });+ await run();+ expect(mocks.sendLifecycleEmail).toHaveBeenCalledTimes(1);+ });+});++describe("rollout", () => {+ it("cancels tips the retired drip already scheduled in Resend", async () => {+ (lifecycleEmailService as any).legacyTipsCancelled = false;+ state.legacyTipUsers.push({ id: "u9", scheduledTipEmailIds: ["re_1", "re_2", "re_3"] });+ await run();+ expect(mocks.cancelScheduledEmail).toHaveBeenCalledTimes(3);+ expect(mocks.cancelScheduledEmail).toHaveBeenCalledWith("re_1");+ expect(state.clearedTipUsers.length).toBe(1);+ });+});diff --git a/server/src/services/lifecycleEmails/lifecycleEmailService.ts b/server/src/services/lifecycleEmails/lifecycleEmailService.tsnew file mode 100644index 000000000..11f585639--- /dev/null+++ b/server/src/services/lifecycleEmails/lifecycleEmailService.ts@@ -0,0 +1,660 @@+import { and, eq, gt, inArray, like } from "drizzle-orm";+import { DateTime } from "luxon";+import * as cron from "node-cron";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";+import { db } from "../../db/postgres/postgres.js";+import { goals, lifecycleEmailLog, member, sites, user } from "../../db/postgres/schema.js";+import { IS_CLOUD } from "../../lib/const.js";+import { cancelScheduledEmail, isContactUnsubscribed, sendLifecycleEmail } from "../../lib/email/email.js";+import { createServiceLogger } from "../../lib/logger/logger.js";+import { signExpiringPayload } from "../../lib/signedToken.js";+import * as content from "./lifecycleContent.js";+import { detectPlatform, platformForKey, type PlatformInfo } from "./platformDetect.js";++/**+ * State-machine lifecycle emails. Every email is triggered by a state+ * transition or a timeout inside a state - never by a timer from signup.+ * The cron re-evaluates real state (Postgres + ClickHouse) at send time, and+ * the unique (userId, emailKey) index on lifecycle_email_log makes each email+ * fire at most once. At most one email per user per run (enforced across both+ * passes via a per-run set), with a minimum gap between educational sends.+ *+ * Concurrency: the cron runs on the cluster primary only, so a single+ * evaluator holds the "one email per user per run" invariant. If this ever+ * moves to multiple replicas, the per-run set must become a distributed+ * claim - the unique key alone only dedupes per emailKey, not per user.+ */++const COHORT_DAYS = 30; // users/sites older than this never enter the onboarding flow+const MIN_GAP_HOURS = 48; // between non-transition emails to the same user+const CHECK_INSTALL_TTL_SECONDS = 30 * 24 * 3600;+const NEGATIVE_CACHE_TTL_MS = 12 * 3600 * 1000; // don't re-run a no-result ClickHouse probe for this long++interface SiteStats {+ firstEvent: DateTime;+ lastEvent: DateTime;+ total: number;+ pageviews: number;+ customEvents: number;+}++interface OwnedSite {+ siteId: number;+ domain: string;+ createdAt: DateTime;+ detectedPlatform: string | null;+}++const parseTs = (value: string): DateTime => {+ const sql = DateTime.fromSQL(value, { zone: "utc" });+ return sql.isValid ? sql : DateTime.fromISO(value, { zone: "utc" });+};++const countryName = (code: string | null): string | null => {+ if (!code) return null;+ try {+ return new Intl.DisplayNames(["en"], { type: "region" }).of(code) ?? code;+ } catch {+ return code;+ }+};++class LifecycleEmailService {+ private cronTask: cron.ScheduledTask | null = null;+ private logger = createServiceLogger("lifecycle-emails");+ private running = false;+ private legacyTipsCancelled = false;+ private lastWentQuietAt: DateTime | null = null;+ /** cacheKey -> epoch ms until which a known-negative ClickHouse probe is not repeated */+ private negativeCache = new Map<string, number>();+ /** users already sent an email in the current run, shared across both passes */+ private emailedThisRun = new Set<string>();++ // -------------------------------------------------------------------------+ // Data helpers+ // -------------------------------------------------------------------------++ private async fetchSiteStats(siteIds: number[]): Promise<Map<number, SiteStats>> {+ const stats = new Map<number, SiteStats>();+ if (siteIds.length === 0) return stats;++ // Cohort sites are < COHORT_DAYS old, so a bounded time predicate covers+ // their full history and keeps the scan on the primary-key index.+ const result = await clickhouse.query({+ query: `+ SELECT+ site_id,+ min(timestamp) AS first_event,+ max(timestamp) AS last_event,+ count() AS total,+ countIf(type = 'pageview') AS pageviews,+ countIf(type = 'custom_event') AS custom_events+ FROM events+ WHERE site_id IN ({siteIds:Array(Int32)})+ AND timestamp > now() - INTERVAL ${COHORT_DAYS + 10} DAY+ GROUP BY site_id+ `,+ format: "JSONEachRow",+ query_params: { siteIds },+ });++ const rows = await result.json<{+ site_id: number;+ first_event: string;+ last_event: string;+ total: string | number;+ pageviews: string | number;+ custom_events: string | number;+ }>();++ for (const row of rows) {+ stats.set(Number(row.site_id), {+ firstEvent: parseTs(row.first_event),+ lastEvent: parseTs(row.last_event),+ total: Number(row.total),+ pageviews: Number(row.pageviews),+ customEvents: Number(row.custom_events),+ });+ }+ return stats;+ }++ private async fetchFirstPageview(siteId: number): Promise<{ country: string | null } | null> {+ const result = await clickhouse.query({+ query: `+ SELECT country FROM events+ WHERE site_id = {siteId:Int32} AND type = 'pageview'+ AND timestamp > now() - INTERVAL 7 DAY+ ORDER BY timestamp ASC+ LIMIT 1+ `,+ format: "JSONEachRow",+ query_params: { siteId },+ });+ const rows = await result.json<{ country: string }>();+ if (rows.length === 0) return null;+ return { country: rows[0].country || null };+ }++ private async fetchFirstDaysStats(siteId: number): Promise<content.FirstDaysStats | null> {+ const overviewResult = await clickhouse.query({+ query: `+ SELECT uniq(session_id) AS sessions, countIf(type = 'pageview') AS pageviews+ FROM events+ WHERE site_id = {siteId:Int32}+ AND timestamp > now() - INTERVAL ${COHORT_DAYS + 10} DAY+ `,+ format: "JSONEachRow",+ query_params: { siteId },+ });+ const [overview] = await overviewResult.json<{ sessions: string | number; pageviews: string | number }>();+ if (!overview || Number(overview.pageviews) === 0) return null;++ const topOf = async (expression: string, condition: string): Promise<string | null> => {+ const result = await clickhouse.query({+ query: `+ SELECT ${expression} AS value, count() AS c+ FROM events+ WHERE site_id = {siteId:Int32} AND type = 'pageview' AND ${condition}+ AND timestamp > now() - INTERVAL ${COHORT_DAYS + 10} DAY+ GROUP BY value+ ORDER BY c DESC+ LIMIT 1+ `,+ format: "JSONEachRow",+ query_params: { siteId },+ });+ const rows = await result.json<{ value: string }>();+ return rows[0]?.value || null;+ };++ return {+ sessions: Number(overview.sessions),+ pageviews: Number(overview.pageviews),+ topReferrer: await topOf("domainWithoutWWW(referrer)", "referrer != ''"),+ topPage: await topOf("pathname", "pathname != ''"),+ };+ }++ private async fetchConvertingPath(siteId: number): Promise<string | null> {+ const cacheKey = `conv:${siteId}`;+ const retryAfter = this.negativeCache.get(cacheKey);+ if (retryAfter && retryAfter > Date.now()) return null;++ const result = await clickhouse.query({+ query: `+ SELECT pathname, count() AS c+ FROM events+ WHERE site_id = {siteId:Int32}+ AND type = 'pageview'+ AND timestamp > now() - INTERVAL 14 DAY+ AND match(pathname, '(thank|success|checkout|confirmation|purchase|order-complete|welcome)')+ GROUP BY pathname+ ORDER BY c DESC+ LIMIT 1+ `,+ format: "JSONEachRow",+ query_params: { siteId },+ });+ const rows = await result.json<{ pathname: string }>();+ const path = rows[0]?.pathname || null;+ if (!path) this.negativeCache.set(cacheKey, Date.now() + NEGATIVE_CACHE_TTL_MS);+ return path;+ }++ private async resolvePlatform(site: OwnedSite): Promise<PlatformInfo | null> {+ const known = platformForKey(site.detectedPlatform);+ if (known) return known;++ const detected = await detectPlatform(site.domain);+ if (detected) {+ await db.update(sites).set({ detectedPlatform: detected.key }).where(eq(sites.siteId, site.siteId));+ }+ return detected;+ }++ private checkInstallUrl(siteId: number, domain: string): string {+ const { exp, sig } = signExpiringPayload(`check-install:${siteId}:${domain}`, CHECK_INSTALL_TTL_SECONDS);+ return `${process.env.BASE_URL}/api/site/check-install?siteId=${siteId}&domain=${encodeURIComponent(domain)}&exp=${exp}&sig=${sig}`;+ }++ /**+ * Record + send. The insert happens first with the unique index as the guard,+ * so a re-entrant run can never double-send; if the send then fails, the row+ * is removed so the next tick retries. The lifecycle key doubles as the+ * Resend idempotency key so an "accepted but response lost" retry can't+ * deliver twice.+ */+ private async sendOnce(+ userId: string,+ email: string,+ emailKey: string,+ siteId: number | null,+ build: () => Promise<content.LifecycleEmail | null> | content.LifecycleEmail | null+ ): Promise<boolean> {+ const [inserted] = await db+ .insert(lifecycleEmailLog)+ .values({ userId, emailKey, siteId })+ .onConflictDoNothing()+ .returning({ id: lifecycleEmailLog.id });+ if (!inserted) return false; // already sent++ try {+ const message = await build();+ if (!message) {+ await db.delete(lifecycleEmailLog).where(eq(lifecycleEmailLog.id, inserted.id));+ return false;+ }+ const sent = await sendLifecycleEmail(email, message.subject, message.text, `lifecycle:${userId}:${emailKey}`);+ if (!sent) {+ await db.delete(lifecycleEmailLog).where(eq(lifecycleEmailLog.id, inserted.id));+ return false;+ }+ this.emailedThisRun.add(userId);+ this.logger.info({ userId, emailKey, siteId }, "Sent lifecycle email");+ return true;+ } catch (error) {+ this.logger.error({ err: error, userId, emailKey }, "Error sending lifecycle email");+ await db.delete(lifecycleEmailLog).where(eq(lifecycleEmailLog.id, inserted.id));+ return false;+ }+ }++ // -------------------------------------------------------------------------+ // Rollout: cancel tips the retired drip already scheduled in Resend+ // -------------------------------------------------------------------------++ private async cancelLegacyScheduledTips(): Promise<void> {+ if (this.legacyTipsCancelled) return;+ this.legacyTipsCancelled = true;++ try {+ // The old drip scheduled at most 5 days out, so only recent signups can+ // still have pending sends worth cancelling.+ const cutoff = DateTime.utc().minus({ days: 10 }).toSQL({ includeOffset: false })!;+ const users = await db+ .select({ id: user.id, scheduledTipEmailIds: user.scheduledTipEmailIds })+ .from(user)+ .where(gt(user.createdAt, cutoff));++ for (const u of users) {+ const ids = (u.scheduledTipEmailIds as string[]) || [];+ if (ids.length === 0) continue;+ for (const emailId of ids) {+ await cancelScheduledEmail(emailId);+ }+ await db.update(user).set({ scheduledTipEmailIds: [] }).where(eq(user.id, u.id));+ this.logger.info({ userId: u.id, cancelled: ids.length }, "Cancelled legacy scheduled tip emails");+ }+ } catch (error) {+ this.legacyTipsCancelled = false; // retry next run+ this.logger.error({ err: error }, "Error cancelling legacy scheduled tips");+ }+ }++ // -------------------------------------------------------------------------+ // Onboarding pass: users in their first COHORT_DAYS+ // -------------------------------------------------------------------------++ private async processOnboarding(now: DateTime): Promise<void> {+ const cohortStart = now.minus({ days: COHORT_DAYS });++ // No emailVerified filter: this app doesn't require (or send) email+ // verification on password signup, so gating on it would exclude nearly+ // every normal signup. Bounce protection comes from Resend suppression+ // (isContactUnsubscribed) checked before every send.+ const users = await db+ .select({ id: user.id, email: user.email, name: user.name, createdAt: user.createdAt })+ .from(user)+ .where(gt(user.createdAt, cohortStart.toSQL({ includeOffset: false })!));+ if (users.length === 0) return;++ const userIds = users.map(u => u.id);+ const memberships = await db+ .select({ userId: member.userId, organizationId: member.organizationId, role: member.role })+ .from(member)+ .where(inArray(member.userId, userIds));++ const ownedOrgsByUser = new Map<string, string[]>();+ const anyMembership = new Set<string>();+ for (const m of memberships) {+ anyMembership.add(m.userId);+ if (m.role === "owner") {+ ownedOrgsByUser.set(m.userId, [...(ownedOrgsByUser.get(m.userId) ?? []), m.organizationId]);+ }+ }++ const allOwnedOrgIds = [...new Set([...ownedOrgsByUser.values()].flat())];+ const orgSites =+ allOwnedOrgIds.length > 0+ ? await db+ .select({+ siteId: sites.siteId,+ domain: sites.domain,+ createdAt: sites.createdAt,+ organizationId: sites.organizationId,+ detectedPlatform: sites.detectedPlatform,+ })+ .from(sites)+ .where(inArray(sites.organizationId, allOwnedOrgIds))+ : [];++ const sitesByOrg = new Map<string, OwnedSite[]>();+ for (const s of orgSites) {+ if (!s.organizationId || !s.createdAt) continue;+ const entry: OwnedSite = {+ siteId: s.siteId,+ domain: s.domain,+ createdAt: parseTs(s.createdAt),+ detectedPlatform: s.detectedPlatform,+ };+ sitesByOrg.set(s.organizationId, [...(sitesByOrg.get(s.organizationId) ?? []), entry]);+ }++ const allSiteIds = orgSites.map(s => s.siteId);+ const [stats, logs, siteGoals] = await Promise.all([+ this.fetchSiteStats(allSiteIds),+ db+ .select({ userId: lifecycleEmailLog.userId, emailKey: lifecycleEmailLog.emailKey, sentAt: lifecycleEmailLog.sentAt })+ .from(lifecycleEmailLog)+ .where(inArray(lifecycleEmailLog.userId, userIds)),+ allSiteIds.length > 0+ ? db.select({ siteId: goals.siteId }).from(goals).where(inArray(goals.siteId, allSiteIds))+ : Promise.resolve([]),+ ]);++ const logsByUser = new Map<string, Map<string, DateTime>>();+ for (const log of logs) {+ const map = logsByUser.get(log.userId) ?? new Map<string, DateTime>();+ map.set(log.emailKey, parseTs(log.sentAt));+ logsByUser.set(log.userId, map);+ }+ const sitesWithGoals = new Set(siteGoals.map(g => g.siteId));++ for (const u of users) {+ try {+ const ownedOrgs = ownedOrgsByUser.get(u.id) ?? [];+ // Invited teammates (members of someone else's org, owners of none) get no onboarding+ if (ownedOrgs.length === 0 && anyMembership.has(u.id)) continue;++ const userSites = ownedOrgs.flatMap(orgId => sitesByOrg.get(orgId) ?? []);+ await this.processUser(now, u, userSites, stats, logsByUser.get(u.id) ?? new Map(), sitesWithGoals);+ } catch (error) {+ this.logger.error({ err: error, userId: u.id }, "Error processing user lifecycle state");+ }+ }+ }++ /** Evaluate one user's state and send at most one email. */+ private async processUser(+ now: DateTime,+ u: { id: string; email: string; name: string; createdAt: string },+ userSites: OwnedSite[],+ stats: Map<number, SiteStats>,+ sentLog: Map<string, DateTime>,+ sitesWithGoals: Set<number>+ ): Promise<void> {+ const lastSent = [...sentLog.values()].sort((a, b) => b.toMillis() - a.toMillis())[0] ?? null;+ const gapElapsed = !lastSent || now.diff(lastSent, "hours").hours >= MIN_GAP_HOURS;+ const signupAge = now.diff(parseTs(u.createdAt), "hours").hours;++ const unsubscribed = () => isContactUnsubscribed(u.email);++ // --- Transition: a site just received its first data -> "you're live" ---+ // Exempt from the gap; it's a confirmation, not education. Only fires while+ // the first event is fresh so pre-existing sites don't get it late.+ for (const site of userSites) {+ const s = stats.get(site.siteId);+ if (!s || s.total === 0) continue;+ const firstEventAge = now.diff(s.firstEvent, "hours").hours;+ if (firstEventAge > 72) continue;+ if (sentLog.has(`site_live:${site.siteId}`)) continue;+ if (await unsubscribed()) return;++ const sent = await this.sendOnce(u.id, u.email, `site_live:${site.siteId}`, site.siteId, async () => {+ const first = await this.fetchFirstPageview(site.siteId);+ return content.siteLive(site.domain, site.siteId, countryName(first?.country ?? null), u.name);+ });+ if (sent) return;+ }++ // --- State: no site created ---+ if (userSites.length === 0) {+ if (!sentLog.has("no_site_1")) {+ if (signupAge < 2) return;+ if (await unsubscribed()) return;+ await this.sendOnce(u.id, u.email, "no_site_1", null, () => content.noSite1(u.name));+ } else if (!sentLog.has("no_site_2") && signupAge >= 72 && gapElapsed) {+ if (await unsubscribed()) return;+ await this.sendOnce(u.id, u.email, "no_site_2", null, () => content.noSite2(u.name));+ }+ return;+ }++ // --- Install track: evaluated per site, so a working site doesn't+ // suppress install help for the owner's other new sites ---+ const noDataSites = userSites+ .filter(site => !stats.get(site.siteId) && now.diff(site.createdAt, "days").days < COHORT_DAYS)+ .sort((a, b) => a.createdAt.toMillis() - b.createdAt.toMillis());++ for (const site of noDataSites) {+ const siteAge = now.diff(site.createdAt, "hours").hours;+ const snippetKey = `install_snippet:${site.siteId}`;+ const checkKey = `install_check:${site.siteId}`;+ const finalKey = `install_final:${site.siteId}`;+ const snippetSentAt = sentLog.get(snippetKey);+ const checkSentAt = sentLog.get(checkKey);++ if (!sentLog.has(snippetKey)) {+ // The snippet email is the user's next step right after creating a+ // site; it is exempt from the educational gap.+ if (siteAge < 1) continue;+ if (await unsubscribed()) return;+ const sent = await this.sendOnce(u.id, u.email, snippetKey, site.siteId, async () => {+ const platform = await this.resolvePlatform(site);+ return content.installSnippet(site.domain, site.siteId, platform, u.name);+ });+ if (sent) return;+ } else if (!sentLog.has(checkKey) && snippetSentAt && now.diff(snippetSentAt, "hours").hours >= 24) {+ // Timed from the snippet email, not site age, so a pre-existing site+ // picked up at rollout doesn't get two install emails in one hour.+ if (await unsubscribed()) return;+ const sent = await this.sendOnce(u.id, u.email, checkKey, site.siteId, () =>+ content.installCheck(site.domain, this.checkInstallUrl(site.siteId, site.domain), u.name)+ );+ if (sent) return;+ } else if (!sentLog.has(finalKey) && checkSentAt && now.diff(checkSentAt, "hours").hours >= 96 && gapElapsed) {+ if (await unsubscribed()) return;+ const sent = await this.sendOnce(u.id, u.email, finalKey, site.siteId, () =>+ content.installFinal(site.domain, u.name)+ );+ if (sent) return;+ }+ }++ // --- State: data flowing. Value emails keyed to data age, not signup age ---+ if (!gapElapsed) return;++ for (const site of userSites) {+ const s = stats.get(site.siteId);+ if (!s || s.total === 0) continue;+ const dataAgeDays = now.diff(s.firstEvent, "days").days;++ // Pageview count comes from the batched stats, so a custom-event-only+ // site is skipped without a per-tick ClickHouse probe.+ if (dataAgeDays >= 3 && dataAgeDays < 14 && s.pageviews > 0 && !sentLog.has(`first_days:${site.siteId}`)) {+ if (await unsubscribed()) return;+ const sent = await this.sendOnce(u.id, u.email, `first_days:${site.siteId}`, site.siteId, async () => {+ const report = await this.fetchFirstDaysStats(site.siteId);+ return report ? content.firstDays(site.domain, site.siteId, report, u.name) : null;+ });+ if (sent) return;+ }++ // Evidence-based nudges: only when their data shows the feature applies+ if (dataAgeDays >= 7 && dataAgeDays < COHORT_DAYS && !sitesWithGoals.has(site.siteId) && !sentLog.has(`nudge_goals:${site.siteId}`)) {+ const path = await this.fetchConvertingPath(site.siteId);+ if (path) {+ if (await unsubscribed()) return;+ const sent = await this.sendOnce(u.id, u.email, `nudge_goals:${site.siteId}`, site.siteId, () =>+ content.nudgeGoals(site.domain, site.siteId, path, u.name)+ );+ if (sent) return;+ }+ }++ if (dataAgeDays >= 10 && dataAgeDays < COHORT_DAYS && s.customEvents === 0 && !sentLog.has(`nudge_events:${site.siteId}`)) {+ if (await unsubscribed()) return;+ const sent = await this.sendOnce(u.id, u.email, `nudge_events:${site.siteId}`, site.siteId, () =>+ content.nudgeEvents(site.domain, site.siteId, u.name)+ );+ if (sent) return;+ }+ }+ }++ // -------------------------------------------------------------------------+ // Went-quiet pass: any site (not just new ones) that stopped sending data+ // -------------------------------------------------------------------------++ private async processWentQuiet(now: DateTime): Promise<void> {+ // Candidates: sites with events in the last 7 days whose latest event is+ // older than 48h. The 7-day window (vs a hard 48-60h band) means a cron+ // outage longer than the band can't silently skip an alert; the per-outage+ // email key plus the 30-day per-site cooldown below prevent repeats.+ const result = await clickhouse.query({+ query: `+ SELECT site_id, max(timestamp) AS last_event+ FROM events+ WHERE timestamp > now() - INTERVAL 7 DAY+ GROUP BY site_id+ HAVING last_event < now() - INTERVAL 48 HOUR+ `,+ format: "JSONEachRow",+ });+ const quietRows = await result.json<{ site_id: number; last_event: string }>();+ if (quietRows.length === 0) return;++ const quietSiteIds = quietRows.map(r => Number(r.site_id));++ // "Established" check, bounded: at least 100 events in the 3 weeks before+ // going quiet - a scratch site with a handful of test hits gets no alert.+ const volumeResult = await clickhouse.query({+ query: `+ SELECT site_id, count() AS total+ FROM events+ WHERE site_id IN ({siteIds:Array(Int32)})+ AND timestamp > now() - INTERVAL 21 DAY+ GROUP BY site_id+ HAVING total >= 100+ `,+ format: "JSONEachRow",+ query_params: { siteIds: quietSiteIds },+ });+ const establishedIds = new Set((await volumeResult.json<{ site_id: number }>()).map(r => Number(r.site_id)));++ const candidates = quietRows.filter(r => establishedIds.has(Number(r.site_id)));+ if (candidates.length === 0) return;++ const quietSites = await db+ .select({ siteId: sites.siteId, domain: sites.domain, organizationId: sites.organizationId })+ .from(sites)+ .where(inArray(sites.siteId, candidates.map(r => Number(r.site_id))));+ if (quietSites.length === 0) return;++ // 30-day per-site cooldown: a recovered-then-quiet-again site alerts at+ // most monthly even though each outage gets its own email key.+ const recentQuietLogs = await db+ .select({ siteId: lifecycleEmailLog.siteId, emailKey: lifecycleEmailLog.emailKey })+ .from(lifecycleEmailLog)+ .where(+ and(+ like(lifecycleEmailLog.emailKey, "went_quiet:%"),+ gt(lifecycleEmailLog.sentAt, now.minus({ days: 30 }).toSQL({ includeOffset: false })!)+ )+ );+ const recentlyAlerted = new Set(recentQuietLogs.map(r => r.siteId));++ const orgIds = [...new Set(quietSites.map(s => s.organizationId).filter((id): id is string => !!id))];+ const owners =+ orgIds.length > 0+ ? await db+ .select({ organizationId: member.organizationId, userId: user.id, email: user.email, name: user.name })+ .from(member)+ .innerJoin(user, eq(member.userId, user.id))+ .where(and(inArray(member.organizationId, orgIds), eq(member.role, "owner")))+ : [];++ const ownerByOrg = new Map(owners.map(o => [o.organizationId, o]));+ const lastEventBySite = new Map(quietRows.map(r => [Number(r.site_id), parseTs(r.last_event)]));++ for (const site of quietSites) {+ if (recentlyAlerted.has(site.siteId)) continue;+ const owner = site.organizationId ? ownerByOrg.get(site.organizationId) : null;+ if (!owner) continue;+ // One email per user per run, across both passes: an owner with five+ // quiet sites (or one who just got an onboarding email) gets one message.+ if (this.emailedThisRun.has(owner.userId)) continue;+ try {+ if (await isContactUnsubscribed(owner.email)) continue;+ const lastEvent = lastEventBySite.get(site.siteId);+ // Per-outage key: the date of the last event identifies the outage, so+ // a site that recovers and goes quiet again next month can alert again.+ const outageKey = `went_quiet:${site.siteId}:${lastEvent?.toFormat("yyyy-MM-dd") ?? "unknown"}`;+ await this.sendOnce(owner.userId, owner.email, outageKey, site.siteId, () =>+ content.wentQuiet(site.domain, site.siteId, lastEvent?.toFormat("MMMM d 'at' HH:mm 'UTC'") ?? "two days ago", owner.name)+ );+ } catch (error) {+ this.logger.error({ err: error, siteId: site.siteId }, "Error processing went-quiet email");+ }+ }+ }++ // -------------------------------------------------------------------------+ // Entry points+ // -------------------------------------------------------------------------++ async processLifecycleEmails(): Promise<void> {+ if (this.running) return;+ this.running = true;+ this.emailedThisRun = new Set();+ const now = DateTime.utc();+ try {+ await this.cancelLegacyScheduledTips();+ await this.processOnboarding(now);+ // The went-quiet scan covers the whole events table (bounded to 7 days);+ // hourly is plenty for a 48h-silence alert.+ if (!this.lastWentQuietAt || now.diff(this.lastWentQuietAt, "minutes").minutes >= 55) {+ this.lastWentQuietAt = now;+ await this.processWentQuiet(now);+ }+ } catch (error) {+ this.logger.error({ err: error }, "Error in lifecycle email run");+ } finally {+ this.running = false;+ }+ }++ startLifecycleCron(): void {+ if (!IS_CLOUD) return;+ if (this.cronTask) {+ this.logger.warn("Lifecycle email cron already running");+ return;+ }++ // Every 10 minutes: state transitions like "first pageview arrived" should+ // reach the user while they're still at their desk.+ this.cronTask = cron.schedule("*/10 * * * *", () => void this.processLifecycleEmails(), { timezone: "UTC" });+ this.logger.info("Lifecycle email cron started - runs every 10 minutes");+ }++ stopLifecycleCron(): void {+ if (this.cronTask) {+ this.cronTask.stop();+ this.cronTask = null;+ this.logger.info("Lifecycle email cron stopped");+ }+ }+}++export const lifecycleEmailService = new LifecycleEmailService();diff --git a/server/src/services/lifecycleEmails/platformDetect.test.ts b/server/src/services/lifecycleEmails/platformDetect.test.tsnew file mode 100644index 000000000..41961f65f--- /dev/null+++ b/server/src/services/lifecycleEmails/platformDetect.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vitest";+import { detectPlatformFromHtml, hasRybbitScript, isPublicUnicastAddress } from "./platformDetect.js";++describe("isPublicUnicastAddress (SSRF guard)", () => {+ it.each([+ "127.0.0.1",+ "10.0.0.5",+ "172.16.0.1",+ "172.31.255.255",+ "192.168.1.1",+ "169.254.169.254", // cloud metadata+ "100.64.0.1", // CGNAT+ "0.0.0.0",+ "198.18.0.1",+ "224.0.0.1",+ "255.255.255.255",+ "::1",+ "::",+ "fc00::1",+ "fd12::1",+ "fe80::1",+ "::ffff:127.0.0.1", // v4-mapped loopback+ "::ffff:10.0.0.1",+ ])("rejects %s", address => {+ expect(isPublicUnicastAddress(address)).toBe(false);+ });++ it.each(["8.8.8.8", "1.1.1.1", "93.184.216.34", "2606:4700:4700::1111", "::ffff:8.8.8.8"])(+ "allows public %s",+ address => {+ expect(isPublicUnicastAddress(address)).toBe(true);+ }+ );++ it("rejects garbage", () => {+ expect(isPublicUnicastAddress("not-an-ip")).toBe(false);+ expect(isPublicUnicastAddress("")).toBe(false);+ });+});++describe("hasRybbitScript", () => {+ it("requires the script AND a matching site id", () => {+ const html = '<script src="https://app.rybbit.io/api/script.js" data-site-id="42" defer></script>';+ expect(hasRybbitScript(html, 42)).toBe(true);+ // A leftover snippet for a different site must not report success+ expect(hasRybbitScript(html, 43)).toBe(false);+ });++ it("does not match a prefix of a longer site id", () => {+ const html = '<script src="/api/script.js" data-site-id="421"></script>';+ expect(hasRybbitScript(html, 42)).toBe(false);+ });++ it("rejects pages without the script", () => {+ expect(hasRybbitScript('<span data-site-id="42"></span>', 42)).toBe(false);+ });+});++describe("detectPlatformFromHtml", () => {+ it("prefers the more specific marker (WooCommerce over WordPress)", () => {+ const html = '<link href="/wp-content/x.css"><body class="woocommerce">';+ expect(detectPlatformFromHtml(html)?.key).toBe("woocommerce");+ });++ it("detects Next.js", () => {+ expect(detectPlatformFromHtml('<script id="__NEXT_DATA__">{}</script>')?.key).toBe("next-js");+ });++ it("returns null for unknown stacks", () => {+ expect(detectPlatformFromHtml("<html><body>plain</body></html>")).toBeNull();+ });+});diff --git a/server/src/services/lifecycleEmails/platformDetect.ts b/server/src/services/lifecycleEmails/platformDetect.tsnew file mode 100644index 000000000..f42a978c8--- /dev/null+++ b/server/src/services/lifecycleEmails/platformDetect.ts@@ -0,0 +1,200 @@+import { lookup } from "node:dns/promises";+import { isIP } from "node:net";+import { createServiceLogger } from "../../lib/logger/logger.js";++const logger = createServiceLogger("platform-detect");++export interface PlatformInfo {+ key: string;+ label: string;+ guideUrl: string;+}++const GUIDE_BASE = "https://rybbit.com/docs/guides";++// Ordered: more specific markers first (e.g. WooCommerce implies WordPress, Nuxt implies Vue)+const PLATFORM_MARKERS: Array<{ pattern: RegExp; platform: PlatformInfo }> = [+ { pattern: /woocommerce/i, platform: { key: "woocommerce", label: "WooCommerce", guideUrl: `${GUIDE_BASE}/woocommerce` } },+ { pattern: /wp-content|wp-includes|content="WordPress/i, platform: { key: "wordpress", label: "WordPress", guideUrl: `${GUIDE_BASE}/wordpress` } },+ { pattern: /cdn\.shopify\.com|Shopify\.theme/i, platform: { key: "shopify", label: "Shopify", guideUrl: `${GUIDE_BASE}/shopify` } },+ { pattern: /data-wf-domain|assets\.website-files\.com|assets-global\.website-files\.com/i, platform: { key: "webflow", label: "Webflow", guideUrl: `${GUIDE_BASE}/webflow` } },+ { pattern: /framerusercontent\.com|framerstatic/i, platform: { key: "framer", label: "Framer", guideUrl: `${GUIDE_BASE}/framer` } },+ { pattern: /static\.parastorage\.com|wix\.com\/website/i, platform: { key: "wix", label: "Wix", guideUrl: `${GUIDE_BASE}/wix` } },+ { pattern: /squarespace\.com|content="Squarespace/i, platform: { key: "squarespace", label: "Squarespace", guideUrl: `${GUIDE_BASE}/squarespace` } },+ { pattern: /content="Ghost/i, platform: { key: "ghost", label: "Ghost", guideUrl: `${GUIDE_BASE}/ghost` } },+ { pattern: /content="Docusaurus/i, platform: { key: "docusaurus", label: "Docusaurus", guideUrl: `${GUIDE_BASE}/docusaurus` } },+ { pattern: /content="Astro|astro-island/i, platform: { key: "astro", label: "Astro", guideUrl: `${GUIDE_BASE}/astro` } },+ { pattern: /__NUXT__|nuxt\./i, platform: { key: "nuxt", label: "Nuxt", guideUrl: `${GUIDE_BASE}/vue/nuxt` } },+ { pattern: /__remixContext/i, platform: { key: "remix", label: "Remix", guideUrl: `${GUIDE_BASE}/react/remix` } },+ { pattern: /___gatsby/i, platform: { key: "gatsby", label: "Gatsby", guideUrl: `${GUIDE_BASE}/react/gatsby` } },+ { pattern: /__NEXT_DATA__|\/_next\//i, platform: { key: "next-js", label: "Next.js", guideUrl: `${GUIDE_BASE}/react/next-js` } },+ { pattern: /sveltekit/i, platform: { key: "sveltekit", label: "SvelteKit", guideUrl: `${GUIDE_BASE}/svelte/sveltekit` } },+ { pattern: /content="Hugo/i, platform: { key: "hugo", label: "Hugo", guideUrl: `${GUIDE_BASE}/hugo` } },+ { pattern: /content="Drupal/i, platform: { key: "drupal", label: "Drupal", guideUrl: `${GUIDE_BASE}/drupal` } },+ { pattern: /content="Joomla/i, platform: { key: "joomla", label: "Joomla", guideUrl: `${GUIDE_BASE}/joomla` } },+];++export function platformForKey(key: string | null | undefined): PlatformInfo | null {+ if (!key) return null;+ return PLATFORM_MARKERS.find(m => m.platform.key === key)?.platform ?? null;+}++const MAX_BODY_BYTES = 512 * 1024;+const FETCH_TIMEOUT_MS = 8000;+const MAX_REDIRECTS = 3;++/**+ * SSRF guard: reject any address that is not publicly routable. Covers+ * loopback, RFC1918, link-local (incl. cloud metadata 169.254.169.254),+ * CGNAT, benchmarking/documentation ranges, multicast/reserved, and their+ * IPv6 equivalents including v4-mapped forms.+ */+export function isPublicUnicastAddress(address: string): boolean {+ const family = isIP(address);+ if (family === 4) return isPublicV4(address);+ if (family === 6) {+ const lower = address.toLowerCase();+ // v4-mapped / v4-translated: judge the embedded v4+ const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/) || lower.match(/^64:ff9b::(\d+\.\d+\.\d+\.\d+)$/);+ if (mapped) return isPublicV4(mapped[1]);+ if (lower === "::" || lower === "::1") return false;+ if (/^(fc|fd)/.test(lower)) return false; // unique local fc00::/7+ if (/^fe[89ab]/.test(lower)) return false; // link-local fe80::/10+ if (/^ff/.test(lower)) return false; // multicast+ return true;+ }+ return false;+}++function isPublicV4(address: string): boolean {+ const parts = address.split(".").map(Number);+ if (parts.length !== 4 || parts.some(p => Number.isNaN(p) || p < 0 || p > 255)) return false;+ const [a, b] = parts;+ if (a === 0 || a === 10 || a === 127) return false;+ if (a === 100 && b >= 64 && b <= 127) return false; // CGNAT 100.64/10+ if (a === 169 && b === 254) return false; // link-local / metadata+ if (a === 172 && b >= 16 && b <= 31) return false;+ if (a === 192 && b === 168) return false;+ if (a === 192 && b === 0) return false; // 192.0.0/24 + 192.0.2/24 (docs)+ if (a === 198 && (b === 18 || b === 19)) return false; // benchmarking+ if (a === 198 && b === 51) return false; // 198.51.100/24 docs+ if (a === 203 && b === 113) return false; // 203.0.113/24 docs+ if (a >= 224) return false; // multicast + reserved + broadcast+ return true;+}++/** Resolve a hostname and confirm every address it maps to is public. */+async function isSafeTarget(url: URL): Promise<boolean> {+ if (url.protocol !== "https:" && url.protocol !== "http:") return false;+ if (url.port && url.port !== "80" && url.port !== "443") return false;+ if (url.username || url.password) return false;++ const host = url.hostname.replace(/^\[|\]$/g, "");+ if (isIP(host)) return isPublicUnicastAddress(host);+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {+ return false;+ }+ try {+ const addresses = await lookup(host, { all: true, verbatim: true });+ return addresses.length > 0 && addresses.every(a => isPublicUnicastAddress(a.address));+ } catch {+ return false;+ }+}++async function readBody(response: Response): Promise<string | null> {+ if (!response.body) return null;+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let received = 0;+ while (received < MAX_BODY_BYTES) {+ const { done, value } = await reader.read();+ if (done) break;+ chunks.push(value);+ received += value.length;+ }+ reader.cancel().catch(() => {});+ return Buffer.concat(chunks).toString("utf-8");+}++/**+ * Fetch a site's homepage HTML. Returns null when the site is unreachable.+ * Shared by platform fingerprinting and the install checker.+ *+ * Every hop (initial and each redirect) is validated against the SSRF guard+ * before it is fetched, redirects are followed manually with a hop cap, only+ * http/https on default ports are allowed, and the body read is size-capped.+ * (DNS is re-resolved by fetch after validation, so a fast-rebinding attacker+ * retains a narrow TOCTOU window; combined with the response never being+ * echoed back raw, the primitive is reduced to a coarse reachability oracle.)+ */+export async function fetchHomepage(domain: string): Promise<string | null> {+ // A site "domain" must be a bare hostname - anything else is refused outright.+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i.test(domain)) return null;++ for (const scheme of ["https", "http"]) {+ let url: URL;+ try {+ url = new URL(`${scheme}://${domain}/`);+ } catch {+ return null;+ }++ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {+ if (!(await isSafeTarget(url))) {+ logger.debug({ domain, target: url.href }, "Blocked non-public fetch target");+ break;+ }+ let response: Response;+ try {+ response = await fetch(url, {+ redirect: "manual",+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),+ headers: {+ "User-Agent": "Mozilla/5.0 (compatible; RybbitSetupCheck/1.0; +https://rybbit.com)",+ Accept: "text/html",+ },+ });+ } catch (error) {+ logger.debug({ domain, scheme, err: error }, "Homepage fetch failed");+ break;+ }++ if (response.status >= 300 && response.status < 400) {+ const location = response.headers.get("location");+ response.body?.cancel().catch(() => {});+ if (!location) break;+ try {+ url = new URL(location, url);+ } catch {+ break;+ }+ continue;+ }++ if (!response.ok) break;+ return await readBody(response);+ }+ }+ return null;+}++export function detectPlatformFromHtml(html: string): PlatformInfo | null {+ return PLATFORM_MARKERS.find(m => m.pattern.test(html))?.platform ?? null;+}++export async function detectPlatform(domain: string): Promise<PlatformInfo | null> {+ const html = await fetchHomepage(domain);+ if (!html) return null;+ return detectPlatformFromHtml(html);+}++/**+ * Whether the fetched homepage loads the Rybbit tracking script *for this+ * site*: a script reference plus a matching data-site-id, so a leftover+ * snippet for a different site doesn't report success.+ */+export function hasRybbitScript(html: string, siteId: number): boolean {+ if (!/api\/script\.js|rybbit\.js/i.test(html)) return false;+ return new RegExp(`data-site-id=["']?${siteId}["'\\s>]`, "i").test(html);+}diff --git a/server/src/services/onboardingTips/onboardingTipsContent.ts b/server/src/services/onboardingTips/onboardingTipsContent.tsdeleted file mode 100644index 9e36acd87..000000000--- a/server/src/services/onboardingTips/onboardingTipsContent.ts+++ /dev/null@@ -1,73 +0,0 @@-export interface OnboardingTipContent {- day: number;- subject: string;- body: string;- linkText?: string;- linkUrl?: string;-}--export const ONBOARDING_TIPS: OnboardingTipContent[] = [- {- day: 1,- subject: "You made the right choice",- body: `Thanks for signing up for Rybbit. You've joined thousands of developers who care about respecting their users' privacy.--Unlike traditional analytics tools, Rybbit doesn't use cookies, doesn't track users across websites, and doesn't sell your data to advertisers. Your visitors stay anonymous, and you still get the insights you need.--We built Rybbit because we were tired of tools that treat users as products. Privacy shouldn't mean giving up on understanding your audience.--If you're curious how we compare to other tools, check out our comparison page.`,- linkText: "View comparison",- linkUrl: "https://rybbit.com/docs/comparison",- },- {- day: 2,- subject: "Why your metrics might look different than GA",- body: `If you've been using Google Analytics before, you might notice your Rybbit numbers look different. That's actually a good thing.--Adblockers block Google Analytics. They rarely block Rybbit. So for the first time, you're probably seeing your real traffic - and it's likely higher than GA ever showed you.--We're also lightweight and privacy-focused, which means browsers and privacy tools treat us differently than traditional trackers.--Those missing visitors in GA? They were always there. You just couldn't see them.`,- },- {- day: 3,- subject: "Track what matters with custom events",- body: `Pageviews tell you what pages people visit. Custom events tell you what they actually do.--Track button clicks, form submissions, video plays - anything that matters to your business. It's one line of code:--window.rybbit.event("signup_clicked")--Or use data attributes directly in your HTML:--<button data-rybbit-event="signup_clicked">Sign Up</button>--Events show up in your dashboard and can be used as funnel steps or goal triggers.`,- linkText: "Read the full guide",- linkUrl: "https://rybbit.com/docs/track-events",- },- {- day: 4,- subject: "Turn pageviews into insights",- body: `Raw traffic numbers are interesting, but conversions are what matter.--Goals let you track specific outcomes - signups, purchases, downloads. Set a goal for "/thank-you" and see how many visitors actually convert, broken down by source, device, and more.--Funnels go deeper. Define a multi-step process (view product -> add to cart -> checkout -> purchase) and see exactly where users drop off. Finding a 60% drop-off at checkout? Now you know where to focus.`,- linkText: "Set up your first goal",- linkUrl: "https://rybbit.com/docs/web-analytics/goals-tab",- },- {- day: 5,- subject: "Build with your data",- body: `Everything in your Rybbit dashboard is available through our API.--Build custom dashboards, set up alerts when traffic spikes, pipe data into your own tools, create reports for clients - the data is yours to use however you want.--Authentication is simple (API key in header), and the endpoints mirror what you see in the UI. Query pageviews, events, sessions, funnels - whatever you need.`,- linkText: "Get started with the API",- linkUrl: "https://rybbit.com/docs/api/getting-started",- },-];diff --git a/server/src/services/onboardingTips/onboardingTipsService.test.ts b/server/src/services/onboardingTips/onboardingTipsService.test.tsdeleted file mode 100644index 4acce3251..000000000--- a/server/src/services/onboardingTips/onboardingTipsService.test.ts+++ /dev/null@@ -1,117 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { ONBOARDING_TIPS } from "./onboardingTipsContent.js";--const mocks = vi.hoisted(() => ({- schedule: vi.fn(),- cancel: vi.fn(),-}));--vi.mock("../../lib/email/email.js", () => ({- scheduleOnboardingTipEmail: mocks.schedule,- cancelScheduledEmail: mocks.cancel,-}));--import { onboardingTipsService } from "./onboardingTipsService.js";--beforeEach(() => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-08-29T15:45:30.123Z"));- mocks.schedule.mockReset();- mocks.cancel.mockReset();-});--afterEach(() => {- vi.useRealTimers();-});--describe("onboardingTipsService.scheduleOnboardingEmails", () => {- it("schedules every configured tip for 9am UTC on its signup-relative day", async () => {- mocks.schedule.mockImplementation(async (_email, _name, tip) => `email-day-${tip.day}`);-- await expect(onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Ada")).resolves.toEqual(- ONBOARDING_TIPS.map(tip => `email-day-${tip.day}`)- );-- expect(mocks.schedule).toHaveBeenCalledTimes(ONBOARDING_TIPS.length);- const expectedSchedule = [- "2026-08-30T09:00:00.000Z",- "2026-08-31T09:00:00.000Z",- "2026-09-01T09:00:00.000Z",- "2026-09-02T09:00:00.000Z",- "2026-09-03T09:00:00.000Z",- ];- for (const [index, tip] of ONBOARDING_TIPS.entries()) {- expect(mocks.schedule).toHaveBeenNthCalledWith(- index + 1,- "[email protected]",- "Ada",- tip,- expectedSchedule[index]- );- }- });-- it("passes an empty display name and omits provider calls that return no id", async () => {- mocks.schedule- .mockResolvedValueOnce("email-1")- .mockResolvedValueOnce(null)- .mockResolvedValueOnce("email-3")- .mockResolvedValue(null);-- await expect(onboardingTipsService.scheduleOnboardingEmails("[email protected]")).resolves.toEqual([- "email-1",- "email-3",- ]);- expect(mocks.schedule.mock.calls.every(call => call[1] === "")).toBe(true);- expect(mocks.schedule).toHaveBeenCalledTimes(ONBOARDING_TIPS.length);- });-- it("propagates a scheduling failure and does not schedule later tips", async () => {- const providerError = new Error("provider unavailable");- mocks.schedule.mockResolvedValueOnce("email-1").mockRejectedValueOnce(providerError);-- await expect(onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Ada")).rejects.toBe(- providerError- );- expect(mocks.schedule).toHaveBeenCalledTimes(2);- });-- it("keeps results isolated across overlapping scheduling requests", async () => {- mocks.schedule.mockImplementation(async (email, _name, tip) => `${email}:day-${tip.day}`);-- const [adaIds, graceIds] = await Promise.all([- onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Ada"),- onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Grace"),- ]);-- expect(adaIds).toEqual(ONBOARDING_TIPS.map(tip => `[email protected]:day-${tip.day}`));- expect(graceIds).toEqual(ONBOARDING_TIPS.map(tip => `[email protected]:day-${tip.day}`));- });-});--describe("onboardingTipsService.cancelScheduledEmails", () => {- it("cancels each provider id in order", async () => {- mocks.cancel.mockResolvedValue(undefined);-- await expect(- onboardingTipsService.cancelScheduledEmails(["email-1", "email-2", "email-3"])- ).resolves.toBeUndefined();-- expect(mocks.cancel.mock.calls).toEqual([["email-1"], ["email-2"], ["email-3"]]);- });-- it("does nothing for an empty id list", async () => {- await expect(onboardingTipsService.cancelScheduledEmails([])).resolves.toBeUndefined();- expect(mocks.cancel).not.toHaveBeenCalled();- });-- it("stops after the first cancellation failure", async () => {- const providerError = new Error("cancellation failed");- mocks.cancel.mockResolvedValueOnce(undefined).mockRejectedValueOnce(providerError);-- await expect(onboardingTipsService.cancelScheduledEmails(["email-1", "email-2", "email-3"])).rejects.toBe(- providerError- );- expect(mocks.cancel.mock.calls).toEqual([["email-1"], ["email-2"]]);- });-});diff --git a/server/src/services/onboardingTips/onboardingTipsService.ts b/server/src/services/onboardingTips/onboardingTipsService.tsdeleted file mode 100644index 9405c3515..000000000--- a/server/src/services/onboardingTips/onboardingTipsService.ts+++ /dev/null@@ -1,40 +0,0 @@-import { DateTime } from "luxon";-import { scheduleOnboardingTipEmail, cancelScheduledEmail } from "../../lib/email/email.js";-import { ONBOARDING_TIPS } from "./onboardingTipsContent.js";--class OnboardingTipsService {- /**- * Schedule all 7 onboarding tip emails at signup- * Returns array of Resend email IDs for cancellation- */- async scheduleOnboardingEmails(email: string, name?: string): Promise<string[]> {- const emailIds: string[] = [];- const now = DateTime.utc();-- for (const tip of ONBOARDING_TIPS) {- // Schedule email for day N at 9am UTC- const scheduledAt = now.plus({ days: tip.day }).set({ hour: 9, minute: 0, second: 0, millisecond: 0 }).toISO();-- if (!scheduledAt) continue;-- const emailId = await scheduleOnboardingTipEmail(email, name || "", tip, scheduledAt);-- if (emailId) {- emailIds.push(emailId);- }- }-- return emailIds;- }-- /**- * Cancel all scheduled tip emails for a user- */- async cancelScheduledEmails(emailIds: string[]): Promise<void> {- for (const emailId of emailIds) {- await cancelScheduledEmail(emailId);- }- }-}--export const onboardingTipsService = new OnboardingTipsService();diff --git a/server/src/services/reengagement/reengagementContent.ts b/server/src/services/reengagement/reengagementContent.tsdeleted file mode 100644index 2a74002fb..000000000--- a/server/src/services/reengagement/reengagementContent.ts+++ /dev/null@@ -1,34 +0,0 @@-export interface ReengagementContent {- day: number;- subject: string;- title: string;- message: string;- ctaText: string;-}--export const REENGAGEMENT_EMAILS: Record<number, ReengagementContent> = {- 3: {- day: 3,- subject: "Need help getting started with Rybbit?",- title: "We noticed you haven't added your tracking script yet",- message:- "It looks like we haven't received any data from {domain} yet. Adding Rybbit is quick and easy - just one line of code. If you're running into any issues or have questions, just reply to this email and we'll help you get set up.",- ctaText: "Go to Dashboard",- },- 7: {- day: 7,- subject: "Your Rybbit analytics are waiting",- title: "It's been a week - let's get you started",- message:- "You signed up for Rybbit a week ago but we still haven't received any analytics data for {domain}. We'd hate for you to miss out on understanding your website traffic. Need help with installation? Our setup takes less than 5 minutes.",- ctaText: "Go to Dashboard",- },- 14: {- day: 14,- subject: "Last chance: Start tracking your analytics",- title: "We're here to help",- message:- "It's been two weeks since you signed up and we haven't seen any data from {domain}. If you're having trouble with the setup or if Rybbit isn't the right fit, we'd love to know. Reply to this email and let us know how we can help.",- ctaText: "Go to Dashboard",- },-};diff --git a/server/src/services/reengagement/reengagementService.ts b/server/src/services/reengagement/reengagementService.tsdeleted file mode 100644index 82a4d0b50..000000000--- a/server/src/services/reengagement/reengagementService.ts+++ /dev/null@@ -1,186 +0,0 @@-import { and, between, eq, inArray } from "drizzle-orm";-import { DateTime } from "luxon";-import * as cron from "node-cron";-import { clickhouse } from "../../db/clickhouse/clickhouse.js";-import { db } from "../../db/postgres/postgres.js";-import { member, sites, user } from "../../db/postgres/schema.js";-import { IS_CLOUD } from "../../lib/const.js";-import { isContactUnsubscribed, sendReengagementEmail } from "../../lib/email/email.js";-import { createServiceLogger } from "../../lib/logger/logger.js";-import { REENGAGEMENT_EMAILS } from "./reengagementContent.js";--class ReengagementService {- private cronTask: cron.ScheduledTask | null = null;- private logger = createServiceLogger("reengagement");-- constructor() {}-- /**- * Get a site for reengagement email- * Only returns a siteId if ALL sites have no events (user hasn't started tracking at all)- */- private async getSiteWithoutEvents(- userId: string- ): Promise<{ hasEvents: boolean; siteId: number | null; domain: string | null }> {- try {- // Find organizations where the user is an owner- const userOrgs = await db- .select({ organizationId: member.organizationId })- .from(member)- .where(and(eq(member.userId, userId), eq(member.role, "owner")));-- if (userOrgs.length === 0) {- return { hasEvents: false, siteId: null, domain: null };- }-- const orgIds = userOrgs.map(o => o.organizationId);-- // Find sites belonging to these organizations- const userSites = await db- .select({ siteId: sites.siteId, domain: sites.domain })- .from(sites)- .where(inArray(sites.organizationId, orgIds));-- if (userSites.length === 0) {- return { hasEvents: false, siteId: null, domain: null };- }-- const siteIds = userSites.map(s => s.siteId);-- // Check if ANY site has events- const result = await clickhouse.query({- query: `- SELECT 1 FROM events- WHERE site_id IN ({siteIds:Array(Int32)})- LIMIT 1- `,- format: "JSONEachRow",- query_params: {- siteIds,- },- });-- const data = await result.json<{ 1: number }>();-- // If any site has events, don't send reengagement email- if (data.length > 0) {- return { hasEvents: true, siteId: null, domain: null };- }-- // No sites have events - return the first site for the dashboard link- return { hasEvents: false, siteId: userSites[0].siteId, domain: userSites[0].domain };- } catch (error) {- this.logger.error({ err: error, userId }, "Error checking user sites for events");- return { hasEvents: true, siteId: null, domain: null }; // On error, assume they have events (don't send email)- }- }-- /**- * Process re-engagement emails for a specific day- */- private async processDay(targetDay: 3 | 7 | 14): Promise<void> {- const now = DateTime.utc();- const content = REENGAGEMENT_EMAILS[targetDay];-- if (!content) {- this.logger.error({ targetDay }, "No content found for target day");- return;- }-- // Find users who signed up exactly targetDay days ago- const targetStart = now.minus({ days: targetDay }).startOf("day");- const targetEnd = targetStart.endOf("day");-- try {- const users = await db- .select({- id: user.id,- email: user.email,- name: user.name,- })- .from(user)- .where(and(between(user.createdAt, targetStart.toSQL()!, targetEnd.toSQL()!)));-- this.logger.info({ targetDay, userCount: users.length }, "Processing re-engagement emails");-- for (const userData of users) {- // Check if user has a site without events- const { hasEvents, siteId, domain } = await this.getSiteWithoutEvents(userData.id);- if (hasEvents) {- this.logger.debug({ userId: userData.id }, "User has events, skipping");- continue;- }-- if (!siteId || !domain) {- this.logger.debug({ userId: userData.id }, "User has no sites, skipping");- continue;- }-- // Check if contact is unsubscribed- const unsubscribed = await isContactUnsubscribed(userData.email);- if (unsubscribed) {- this.logger.debug({ userId: userData.id }, "User is unsubscribed, skipping");- continue;- }-- // Send re-engagement email- await sendReengagementEmail(userData.email, userData.name, content, siteId, domain);- this.logger.info({ userId: userData.id, day: targetDay, siteId, domain }, "Sent re-engagement email");- break;- }- } catch (error) {- this.logger.error({ err: error, targetDay }, "Error processing re-engagement emails");- }- }-- /**- * Process all re-engagement emails (days 3, 7, 14)- */- async processReengagementEmails(): Promise<void> {- this.logger.info("Starting re-engagement email processing");-- await this.processDay(3);- await this.processDay(7);- await this.processDay(14);-- this.logger.info("Completed re-engagement email processing");- }-- /**- * Start the daily cron job (10am UTC)- */- startReengagementCron(): void {- if (!IS_CLOUD) {- return;- }-- if (this.cronTask) {- this.logger.warn("Re-engagement cron already running");- return;- }-- // Run daily at 10am UTC- this.cronTask = cron.schedule(- "0 10 * * *",- async () => {- await this.processReengagementEmails();- },- { timezone: "UTC" }- );-- this.logger.info("Re-engagement cron started - runs daily at 10am UTC");- }-- /**- * Stop the cron job- */- stopReengagementCron(): void {- if (this.cronTask) {- this.cronTask.stop();- this.cronTask = null;- this.logger.info("Re-engagement cron stopped");- }- }-}--export const reengagementService = new ReengagementService();diff --git a/server/src/services/sites/siteConfigurationLifecycle.ts b/server/src/services/sites/siteConfigurationLifecycle.tsindex 3b82918c2..fbb9e68cc 100644--- a/server/src/services/sites/siteConfigurationLifecycle.ts+++ b/server/src/services/sites/siteConfigurationLifecycle.ts@@ -6,6 +6,7 @@ import { db } from "../../db/postgres/postgres.js";import { sites } from "../../db/postgres/schema.js";import { IS_CLOUD } from "../../lib/const.js";import { validateIPPattern } from "../../lib/ipUtils.js";+import { detectPlatform } from "../lifecycleEmails/platformDetect.js";import { siteConfig, type SiteConfigData } from "../../lib/siteConfig.js";type SiteRow = typeof sites.$inferSelect;@@ -273,6 +274,18 @@ class SiteConfigurationLifecycle {throw new Error("Site insert returned no row");}+ // Fingerprint the site's platform in the background so the lifecycle+ // install email can link the right guide. Best-effort only.+ if (siteType === "web") {+ void detectPlatform(domain)+ .then(platform =>+ platform+ ? db.update(sites).set({ detectedPlatform: platform.key }).where(eq(sites.siteId, createdSite.siteId))+ : undefined+ )+ .catch(() => {});+ }+return createdSite;} catch (error) {if (isUniqueConstraintViolation(error)) {