Beautiful Open-Source Form Builder
Telemetry (#956)
Julien Nahum9a5f39105131
diff --git a/api/.env.example b/api/.env.exampleindex 70c2e77ea..1e0c95d04 100644--- a/api/.env.example+++ b/api/.env.example@@ -96,4 +96,4 @@ STRIPE_CLIENT_SECRET=SLACK_BOT_TOKEN=-IPINFO_TOKEN=\ No newline at end of file+IPINFO_TOKEN=diff --git a/api/app/Console/Commands/InitializeInstance.php b/api/app/Console/Commands/InitializeInstance.phpnew file mode 100644index 000000000..a77c3be73--- /dev/null+++ b/api/app/Console/Commands/InitializeInstance.php@@ -0,0 +1,59 @@+<?php++namespace App\Console\Commands;++use App\Enums\SettingsKey;+use App\Models\Setting;+use Illuminate\Console\Command;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Str;++class InitializeInstance extends Command+{+ /**+ * The name and signature of the console command.+ *+ * @var string+ */+ protected $signature = 'telemetry:initialize-instance';++ /**+ * The console command description.+ *+ * @var string+ */+ protected $description = 'Initialize instance ID and creation timestamp for telemetry tracking';++ /**+ * Execute the console command.+ */+ public function handle(): int+ {+ // Check if instance_id already exists+ $instanceId = Setting::get(SettingsKey::INSTANCE_ID);++ if ($instanceId) {+ $this->info('Instance ID already initialized: ' . $instanceId);+ return Command::SUCCESS;+ }++ // Generate UUID+ $uuid = (string) Str::uuid();++ // Store instance_id+ Setting::set(SettingsKey::INSTANCE_ID, $uuid);++ // Store instance_created_at timestamp+ Setting::set(SettingsKey::INSTANCE_CREATED_AT, now()->toIso8601String());++ // Clear cache so the new instance ID is picked up immediately+ Cache::forget('telemetry.instance_id');++ $this->info('Instance initialized successfully. Instance ID: ' . $uuid);++ // Track instance creation+ telemetry(\App\Service\Telemetry\TelemetryEvent::INSTANCE_CREATED);++ return Command::SUCCESS;+ }+}diff --git a/api/app/Enums/SettingsKey.php b/api/app/Enums/SettingsKey.phpnew file mode 100644index 000000000..530061514--- /dev/null+++ b/api/app/Enums/SettingsKey.php@@ -0,0 +1,14 @@+<?php++namespace App\Enums;++enum SettingsKey: string+{+ case INSTANCE_ID = 'instance_id';+ case INSTANCE_CREATED_AT = 'instance_created_at';++ public function value(): string+ {+ return $this->value;+ }+}diff --git a/api/app/Events/Models/UserCreated.php b/api/app/Events/Models/UserCreated.phpnew file mode 100644index 000000000..9aef5ead4--- /dev/null+++ b/api/app/Events/Models/UserCreated.php@@ -0,0 +1,24 @@+<?php++namespace App\Events\Models;++use App\Models\User;+use Illuminate\Broadcasting\InteractsWithSockets;+use Illuminate\Foundation\Events\Dispatchable;+use Illuminate\Queue\SerializesModels;++class UserCreated+{+ use Dispatchable;+ use InteractsWithSockets;+ use SerializesModels;++ /**+ * Create a new event instance.+ *+ * @return void+ */+ public function __construct(public User $user)+ {+ }+}diff --git a/api/app/Events/Models/WorkspaceCreated.php b/api/app/Events/Models/WorkspaceCreated.phpnew file mode 100644index 000000000..ab430916d--- /dev/null+++ b/api/app/Events/Models/WorkspaceCreated.php@@ -0,0 +1,24 @@+<?php++namespace App\Events\Models;++use App\Models\Workspace;+use Illuminate\Broadcasting\InteractsWithSockets;+use Illuminate\Foundation\Events\Dispatchable;+use Illuminate\Queue\SerializesModels;++class WorkspaceCreated+{+ use Dispatchable;+ use InteractsWithSockets;+ use SerializesModels;++ /**+ * Create a new event instance.+ *+ * @return void+ */+ public function __construct(public Workspace $workspace)+ {+ }+}diff --git a/api/app/Models/Setting.php b/api/app/Models/Setting.phpnew file mode 100644index 000000000..39f693788--- /dev/null+++ b/api/app/Models/Setting.php@@ -0,0 +1,52 @@+<?php++namespace App\Models;++use App\Enums\SettingsKey;+use Illuminate\Database\Eloquent\Factories\HasFactory;+use Illuminate\Database\Eloquent\Model;++class Setting extends Model+{+ use HasFactory;++ protected $fillable = [+ 'key',+ 'value',+ ];++ protected function casts(): array+ {+ return [+ 'value' => 'json',+ ];+ }++ /**+ * Get a setting value by key.+ *+ * @param SettingsKey $key+ * @return mixed|null+ */+ public static function get(SettingsKey $key): mixed+ {+ $setting = static::where('key', $key->value)->first();++ return $setting?->value;+ }++ /**+ * Set a setting value by key.+ *+ * @param SettingsKey $key+ * @param mixed $value+ * @return void+ */+ public static function set(SettingsKey $key, mixed $value): void+ {+ static::updateOrCreate(+ ['key' => $key->value],+ ['value' => $value]+ );+ }+}diff --git a/api/app/Models/User.php b/api/app/Models/User.phpindex f172666c9..04a5dd816 100644--- a/api/app/Models/User.php+++ b/api/app/Models/User.php@@ -48,6 +48,10 @@ class User extends Authenticatable implements JWTSubject, CachableAttributes'blocked_at'];+ protected $dispatchesEvents = [+ 'created' => \App\Events\Models\UserCreated::class,+ ];+/*** The attributes that should be hidden for arrays.*diff --git a/api/app/Models/Workspace.php b/api/app/Models/Workspace.phpindex fb5ada6fa..cd60e8963 100644--- a/api/app/Models/Workspace.php+++ b/api/app/Models/Workspace.php@@ -28,6 +28,10 @@ class Workspace extends Model implements CachableAttributes'settings'];+ protected $dispatchesEvents = [+ 'created' => \App\Events\Models\WorkspaceCreated::class,+ ];+protected $appends = ['is_pro','is_trialing',diff --git a/api/app/Providers/EventServiceProvider.php b/api/app/Providers/EventServiceProvider.phpindex e0a0dedda..ee93d3662 100644--- a/api/app/Providers/EventServiceProvider.php+++ b/api/app/Providers/EventServiceProvider.php@@ -65,6 +65,15 @@ class EventServiceProvider extends ServiceProvider]];+ /**+ * The subscriber classes to register.+ *+ * @var array+ */+ protected $subscribe = [+ \App\Service\Telemetry\TelemetrySubscriber::class,+ ];+/*** Register any events for your application.*diff --git a/api/app/Service/Telemetry/OpenPanelClient.php b/api/app/Service/Telemetry/OpenPanelClient.phpnew file mode 100644index 000000000..7bbf9c14f--- /dev/null+++ b/api/app/Service/Telemetry/OpenPanelClient.php@@ -0,0 +1,78 @@+<?php++namespace App\Service\Telemetry;++use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Log;++class OpenPanelClient+{+ public function __construct(+ private string $endpoint,+ private ?string $clientId,+ private ?string $clientSecret+ ) {+ }++ /**+ * Send an event to OpenPanel.+ *+ * @param string $eventName+ * @param array $properties+ * @param string|null $instanceId+ * @return bool+ */+ public function sendEvent(+ string $eventName,+ array $properties,+ ?string $instanceId+ ): bool {+ if (!$this->clientId || !$this->clientSecret) {+ Log::warning('Telemetry skipped: missing client credentials');+ return false;+ }++ if (!$instanceId) {+ Log::warning('Telemetry skipped: instance_id not found');+ return false;+ }++ try {+ $payload = [+ 'type' => 'track',+ 'payload' => [+ 'name' => $eventName,+ 'properties' => array_merge($properties, [+ 'instance_id' => $instanceId,+ ]),+ ],+ ];++ $response = Http::timeout(5)+ ->withHeaders([+ 'openpanel-client-id' => $this->clientId,+ 'openpanel-client-secret' => $this->clientSecret,+ ])+ ->post($this->endpoint, $payload);++ if (!$response->successful()) {+ Log::warning('Telemetry event failed to send', [+ 'event' => $eventName,+ 'status' => $response->status(),+ 'response' => $response->body(),+ ]);++ return false;+ }++ return true;+ } catch (\Exception $e) {+ Log::warning('Telemetry event error', [+ 'event' => $eventName,+ 'error' => $e->getMessage(),+ ]);++ return false;+ }+ }+}diff --git a/api/app/Service/Telemetry/SendTelemetryJob.php b/api/app/Service/Telemetry/SendTelemetryJob.phpnew file mode 100644index 000000000..4c3794595--- /dev/null+++ b/api/app/Service/Telemetry/SendTelemetryJob.php@@ -0,0 +1,73 @@+<?php++namespace App\Service\Telemetry;++use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\Log;++class SendTelemetryJob implements ShouldQueue+{+ use Dispatchable;+ use InteractsWithQueue;+ use Queueable;+ use SerializesModels;++ /**+ * The number of times the job may be attempted.+ *+ * @var int+ */+ public $tries = 1;++ /**+ * The number of seconds the job can run before timing out.+ *+ * @var int+ */+ public $timeout = 10;++ /**+ * Create a new job instance.+ */+ public function __construct(+ public string $eventName,+ public array $properties+ ) {+ }++ /**+ * Execute the job.+ */+ public function handle(TelemetryService $telemetryService): void+ {+ if (!$telemetryService->shouldSendTelemetry()) {+ return;+ }++ try {+ $instanceId = $telemetryService->getInstanceId();++ if (!$instanceId) {+ Log::warning('Telemetry skipped: instance_id not found');+ return;+ }++ $client = $telemetryService->createClient();++ $client->sendEvent(+ $this->eventName,+ $this->properties,+ $instanceId+ );+ } catch (\Exception $e) {+ Log::warning('Telemetry job error', [+ 'event' => $this->eventName,+ 'error' => $e->getMessage(),+ ]);+ }+ }+}diff --git a/api/app/Service/Telemetry/TelemetryEvent.php b/api/app/Service/Telemetry/TelemetryEvent.phpnew file mode 100644index 000000000..d7bbe0ac9--- /dev/null+++ b/api/app/Service/Telemetry/TelemetryEvent.php@@ -0,0 +1,17 @@+<?php++namespace App\Service\Telemetry;++enum TelemetryEvent: string+{+ case INSTANCE_CREATED = 'instance.created';+ case USER_CREATED = 'user.created';+ case FORM_CREATED = 'form.created';+ case WORKSPACE_CREATED = 'workspace.created';+ case FORM_SUBMISSION = 'form.submission';++ public function value(): string+ {+ return $this->value;+ }+}diff --git a/api/app/Service/Telemetry/TelemetryService.php b/api/app/Service/Telemetry/TelemetryService.phpnew file mode 100644index 000000000..df8d896ab--- /dev/null+++ b/api/app/Service/Telemetry/TelemetryService.php@@ -0,0 +1,92 @@+<?php++namespace App\Service\Telemetry;++use App\Enums\SettingsKey;+use App\Models\Setting;+use Illuminate\Support\Facades\App;+use Illuminate\Support\Facades\Cache;++class TelemetryService+{+ /**+ * Check if telemetry should be sent.+ *+ * Telemetry only runs when BOTH production environment AND self-hosted mode+ * are enabled. It can be explicitly disabled via OPNFORM_ANONYMOUS_TELEMETRY_DISABLED.+ *+ * @return bool+ */+ public function shouldSendTelemetry(): bool+ {+ // Explicitly disabled via environment variable+ if (!config('telemetry.enabled', true)) {+ return false;+ }++ // Only enable in production AND self-hosted mode+ $isProduction = App::isProduction();+ $isSelfHosted = config('app.self_hosted', false);++ return $isProduction && $isSelfHosted;+ }++ /**+ * Get the instance ID from settings.+ *+ * Instance ID is cached since it's read frequently (on every telemetry event)+ * but only set once during initialization and never changes.+ *+ * @return string|null+ */+ public function getInstanceId(): ?string+ {+ return Cache::rememberForever('telemetry.instance_id', function () {+ return Setting::get(SettingsKey::INSTANCE_ID);+ });+ }++ /**+ * Get the telemetry endpoint URL.+ *+ * @return string+ */+ public function getEndpoint(): string+ {+ return config('telemetry.endpoint');+ }++ /**+ * Get the OpenPanel client ID.+ *+ * @return string|null+ */+ public function getClientId(): ?string+ {+ return config('telemetry.client_id');+ }++ /**+ * Get the OpenPanel client secret.+ *+ * @return string|null+ */+ public function getClientSecret(): ?string+ {+ return config('telemetry.client_secret');+ }++ /**+ * Create a configured OpenPanel client instance.+ *+ * @return OpenPanelClient+ */+ public function createClient(): OpenPanelClient+ {+ return new OpenPanelClient(+ $this->getEndpoint(),+ $this->getClientId(),+ $this->getClientSecret()+ );+ }+}diff --git a/api/app/Service/Telemetry/TelemetrySubscriber.php b/api/app/Service/Telemetry/TelemetrySubscriber.phpnew file mode 100644index 000000000..8519fe7e5--- /dev/null+++ b/api/app/Service/Telemetry/TelemetrySubscriber.php@@ -0,0 +1,47 @@+<?php++namespace App\Service\Telemetry;++use App\Events\Forms\FormSubmitted;+use App\Events\Models\FormCreated;+use App\Events\Models\UserCreated;+use App\Events\Models\WorkspaceCreated;+use Illuminate\Events\Dispatcher;++class TelemetrySubscriber+{+ /**+ * Register the listeners for the subscriber.+ *+ * @param Dispatcher $events+ * @return void+ */+ public function subscribe(Dispatcher $events): void+ {+ $events->listen(FormCreated::class, [self::class, 'handleEvent']);+ $events->listen(WorkspaceCreated::class, [self::class, 'handleEvent']);+ $events->listen(UserCreated::class, [self::class, 'handleEvent']);+ $events->listen(FormSubmitted::class, [self::class, 'handleEvent']);+ }++ /**+ * Handle all telemetry events.+ *+ * @param mixed $event+ * @return void+ */+ public function handleEvent(mixed $event): void+ {+ $telemetryEvent = match (true) {+ $event instanceof FormCreated => TelemetryEvent::FORM_CREATED,+ $event instanceof WorkspaceCreated => TelemetryEvent::WORKSPACE_CREATED,+ $event instanceof UserCreated => TelemetryEvent::USER_CREATED,+ $event instanceof FormSubmitted => TelemetryEvent::FORM_SUBMISSION,+ default => null,+ };++ if ($telemetryEvent) {+ telemetry($telemetryEvent);+ }+ }+}diff --git a/api/app/helpers.php b/api/app/helpers.phpindex a8a57ccd0..321252071 100644--- a/api/app/helpers.php+++ b/api/app/helpers.php@@ -37,3 +37,20 @@ if (!function_exists('pricing_enabled')) {return !is_null(config('cashier.key')) && !config('app.self_hosted');}}++if (!function_exists('telemetry')) {+ /**+ * Send a telemetry event asynchronously.+ *+ * @param \App\Service\Telemetry\TelemetryEvent $event+ * @param array $properties+ * @return void+ */+ function telemetry(\App\Service\Telemetry\TelemetryEvent $event, array $properties = []): void+ {+ \App\Service\Telemetry\SendTelemetryJob::dispatch(+ $event->value(),+ $properties+ );+ }+}diff --git a/api/config/telemetry.php b/api/config/telemetry.phpnew file mode 100644index 000000000..dea615c44--- /dev/null+++ b/api/config/telemetry.php@@ -0,0 +1,64 @@+<?php++return [+ /*+ |--------------------------------------------------------------------------+ | Anonymous Telemetry Enabled+ |--------------------------------------------------------------------------+ |+ | OpnForm collects anonymous usage data to help improve the product. This+ | telemetry is completely anonymous and contains no personally identifiable+ | information (PII). None of your customer data, form content, submission+ | data, or user emails are ever transmitted.+ |+ | It can be explicitly disabled by setting+ | OPNFORM_ANONYMOUS_TELEMETRY_DISABLED to true.+ |+ | What is collected:+ | - Basic usage metrics (form creation, submissions, workspace creation, user additions)+ | - Anonymous instance identifier (UUID)+ | - No PII, form content, submission data, or user emails+ |+ | Note: The actual check for production/self-hosted is done in+ | TelemetryService::shouldSendTelemetry().+ |+ */++ 'enabled' => !env('OPNFORM_ANONYMOUS_TELEMETRY_DISABLED', false),++ /*+ |--------------------------------------------------------------------------+ | Telemetry Endpoint+ |--------------------------------------------------------------------------+ |+ | The OpenPanel endpoint URL where telemetry events will be sent.+ | This is hardcoded for OpnForm's telemetry collection.+ |+ */++ 'endpoint' => 'https://telemetry.opnform.com/track',++ /*+ |--------------------------------------------------------------------------+ | OpenPanel Client ID+ |--------------------------------------------------------------------------+ |+ | OpenPanel client ID for OpnForm telemetry authentication.+ | Hardcoded - users do not need to configure this.+ |+ */++ 'client_id' => 'd6d85ed5-723f-48de-894e-db2de1a0c7c1', // NOSONAR - This is a public client ID for telemetry++ /*+ |--------------------------------------------------------------------------+ | OpenPanel Client Secret+ |--------------------------------------------------------------------------+ |+ | OpenPanel client secret for OpnForm telemetry authentication.+ | Hardcoded - users do not need to configure this.+ |+ */++ 'client_secret' => 'sec_236ae00cc86099409ee2', // NOSONAR - This is a public client secret for telemetry+];diff --git a/api/database/migrations/2025_11_18_154325_create_settings_table.php b/api/database/migrations/2025_11_18_154325_create_settings_table.phpnew file mode 100644index 000000000..591d4da94--- /dev/null+++ b/api/database/migrations/2025_11_18_154325_create_settings_table.php@@ -0,0 +1,28 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class () extends Migration {+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::create('settings', function (Blueprint $table) {+ $table->id();+ $table->string('key')->unique();+ $table->json('value')->nullable();+ $table->timestamps();+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::dropIfExists('settings');+ }+};diff --git a/api/tests/Feature/Console/InitializeInstanceCommandTest.php b/api/tests/Feature/Console/InitializeInstanceCommandTest.phpnew file mode 100644index 000000000..6acc40488--- /dev/null+++ b/api/tests/Feature/Console/InitializeInstanceCommandTest.php@@ -0,0 +1,79 @@+<?php++use App\Enums\SettingsKey;+use App\Models\Setting;+use Illuminate\Support\Facades\Artisan;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Queue;++describe('InitializeInstance Command', function () {+ beforeEach(function () {+ Queue::fake();+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', true); // Enable self-hosted for tests+ // Clean up before each test+ Setting::whereIn('key', [+ SettingsKey::INSTANCE_ID->value,+ SettingsKey::INSTANCE_CREATED_AT->value,+ ])->delete();+ });++ it('creates instance id when it does not exist', function () {+ Artisan::call('telemetry:initialize-instance');++ $instanceId = Setting::get(SettingsKey::INSTANCE_ID);+ expect($instanceId)->not->toBeNull();+ expect($instanceId)->toBeString();+ expect(strlen($instanceId))->toBeGreaterThan(0);+ });++ it('creates instance created at timestamp', function () {+ Artisan::call('telemetry:initialize-instance');++ $createdAt = Setting::get(SettingsKey::INSTANCE_CREATED_AT);+ expect($createdAt)->not->toBeNull();+ expect($createdAt)->toBeString();+ // Should be ISO8601 format+ expect($createdAt)->toMatch('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/');+ });++ it('does not overwrite existing instance id', function () {+ $existingId = 'existing-instance-id';+ Setting::set(SettingsKey::INSTANCE_ID, $existingId);++ Artisan::call('telemetry:initialize-instance');++ $instanceId = Setting::get(SettingsKey::INSTANCE_ID);+ expect($instanceId)->toBe($existingId);+ });++ it('tracks instance created event on first initialization', function () {+ Artisan::call('telemetry:initialize-instance');++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return $job->eventName === 'instance.created';+ });+ });++ it('does not track instance created event when instance already exists', function () {+ Setting::set(SettingsKey::INSTANCE_ID, 'existing-id');++ Artisan::call('telemetry:initialize-instance');++ Queue::assertNothingPushed();+ });++ it('returns success status', function () {+ $exitCode = Artisan::call('telemetry:initialize-instance');++ expect($exitCode)->toBe(0);+ });++ it('generates valid UUID format', function () {+ Artisan::call('telemetry:initialize-instance');++ $instanceId = Setting::get(SettingsKey::INSTANCE_ID);+ // UUID v4 format: 8-4-4-4-12 hex characters+ expect($instanceId)->toMatch('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i');+ });+});diff --git a/api/tests/Feature/Telemetry/SendTelemetryJobTest.php b/api/tests/Feature/Telemetry/SendTelemetryJobTest.phpnew file mode 100644index 000000000..bd3103a9e--- /dev/null+++ b/api/tests/Feature/Telemetry/SendTelemetryJobTest.php@@ -0,0 +1,126 @@+<?php++use App\Enums\SettingsKey;+use App\Models\Setting;+use App\Service\Telemetry\SendTelemetryJob;+use App\Service\Telemetry\TelemetryEvent;+use App\Service\Telemetry\TelemetryService;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Http;++describe('SendTelemetryJob', function () {+ beforeEach(function () {+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', true); // Enable self-hosted for tests+ Config::set('telemetry.endpoint', 'https://test-endpoint.com/track');+ Config::set('telemetry.client_id', 'test-client-id');+ Config::set('telemetry.client_secret', 'test-client-secret');+ // Set production environment (telemetry requires both production AND self-hosted)+ app()->detectEnvironment(fn () => 'production');+ });++ it('sends event when telemetry is enabled', function () {+ $instanceId = 'test-instance-id';+ Setting::set(SettingsKey::INSTANCE_ID, $instanceId);++ Http::fake([+ 'test-endpoint.com/track' => Http::response([], 200),+ ]);++ $job = new SendTelemetryJob(+ TelemetryEvent::FORM_CREATED->value(),+ []+ );++ $job->handle(+ app(TelemetryService::class)+ );++ Http::assertSent(function ($request) {+ return $request->url() === 'https://test-endpoint.com/track'+ && $request['type'] === 'track'+ && $request['payload']['name'] === TelemetryEvent::FORM_CREATED->value();+ });+ });++ it('does not send event when telemetry is disabled', function () {+ Config::set('telemetry.enabled', false);+ $instanceId = 'test-instance-id';+ Setting::set(SettingsKey::INSTANCE_ID, $instanceId);++ Http::fake();++ $job = new SendTelemetryJob(+ TelemetryEvent::FORM_CREATED->value(),+ []+ );++ $job->handle(+ app(TelemetryService::class)+ );++ Http::assertNothingSent();+ });++ it('does not send event when instance id is missing', function () {+ Setting::where('key', SettingsKey::INSTANCE_ID->value)->delete();++ Http::fake();++ $job = new SendTelemetryJob(+ TelemetryEvent::FORM_CREATED->value(),+ []+ );++ $job->handle(+ app(TelemetryService::class)+ );++ Http::assertNothingSent();+ });++ it('includes instance id in event properties', function () {+ $instanceId = 'test-instance-id';+ Setting::set(SettingsKey::INSTANCE_ID, $instanceId);++ Http::fake([+ 'test-endpoint.com/track' => Http::response([], 200),+ ]);++ $job = new SendTelemetryJob(+ TelemetryEvent::FORM_CREATED->value(),+ ['custom' => 'property']+ );++ $job->handle(+ app(TelemetryService::class)+ );++ Http::assertSent(function ($request) use ($instanceId) {+ $properties = $request['payload']['properties'];+ return $properties['instance_id'] === $instanceId+ && $properties['custom'] === 'property';+ });+ });++ it('handles errors gracefully', function () {+ $instanceId = 'test-instance-id';+ Setting::set(SettingsKey::INSTANCE_ID, $instanceId);++ Http::fake(function () {+ throw new \Exception('Network error');+ });++ $job = new SendTelemetryJob(+ TelemetryEvent::FORM_CREATED->value(),+ []+ );++ $job->handle(+ app(TelemetryService::class)+ );++ // Should not throw exception+ expect(true)->toBeTrue();+ });+});diff --git a/api/tests/Feature/Telemetry/TelemetryHelperTest.php b/api/tests/Feature/Telemetry/TelemetryHelperTest.phpnew file mode 100644index 000000000..449befaea--- /dev/null+++ b/api/tests/Feature/Telemetry/TelemetryHelperTest.php@@ -0,0 +1,59 @@+<?php++use App\Service\Telemetry\TelemetryEvent;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Queue;++describe('telemetry helper function', function () {+ beforeEach(function () {+ Queue::fake();+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', true); // Enable self-hosted for tests+ });++ it('dispatches job when telemetry is enabled', function () {+ telemetry(TelemetryEvent::FORM_CREATED);++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return $job->eventName === TelemetryEvent::FORM_CREATED->value()+ && empty($job->properties);+ });+ });++ it('dispatches job with properties', function () {+ $properties = ['foo' => 'bar', 'baz' => 'qux'];+ telemetry(TelemetryEvent::FORM_CREATED, $properties);++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) use ($properties) {+ return $job->eventName === TelemetryEvent::FORM_CREATED->value()+ && $job->properties === $properties;+ });+ });++ it('dispatches job even when telemetry is disabled (job handles the check)', function () {+ Config::set('telemetry.enabled', false);++ telemetry(TelemetryEvent::FORM_CREATED);++ // Job is dispatched, but will check and return early in handle()+ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return $job->eventName === TelemetryEvent::FORM_CREATED->value();+ });+ });++ it('works with all event types', function () {+ $events = [+ TelemetryEvent::INSTANCE_CREATED,+ TelemetryEvent::USER_CREATED,+ TelemetryEvent::FORM_CREATED,+ TelemetryEvent::WORKSPACE_CREATED,+ TelemetryEvent::FORM_SUBMISSION,+ ];++ foreach ($events as $event) {+ telemetry($event);+ }++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, 5);+ });+});diff --git a/api/tests/Feature/Telemetry/TelemetrySubscriberTest.php b/api/tests/Feature/Telemetry/TelemetrySubscriberTest.phpnew file mode 100644index 000000000..97a31c72d--- /dev/null+++ b/api/tests/Feature/Telemetry/TelemetrySubscriberTest.php@@ -0,0 +1,80 @@+<?php++use App\Events\Forms\FormSubmitted;+use App\Events\Models\FormCreated;+use App\Events\Models\UserCreated;+use App\Events\Models\WorkspaceCreated;+use App\Models\User;+use App\Models\Workspace;+use App\Service\Telemetry\TelemetryEvent;+use Illuminate\Support\Facades\Config;+use Illuminate\Support\Facades\Queue;++describe('TelemetrySubscriber', function () {+ beforeEach(function () {+ Queue::fake();+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', true); // Enable self-hosted for tests+ });++ it('handles FormCreated event', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);+ $event = new FormCreated($form);++ event($event);++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return $job->eventName === TelemetryEvent::FORM_CREATED->value();+ });+ });++ it('handles WorkspaceCreated event', function () {+ $workspace = Workspace::factory()->create();+ $event = new WorkspaceCreated($workspace);++ event($event);++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return $job->eventName === TelemetryEvent::WORKSPACE_CREATED->value();+ });+ });++ it('handles UserCreated event', function () {+ $user = User::factory()->create();+ $event = new UserCreated($user);++ event($event);++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return $job->eventName === TelemetryEvent::USER_CREATED->value();+ });+ });++ it('handles FormSubmitted event', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);+ $event = new FormSubmitted($form, []);++ event($event);++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return $job->eventName === TelemetryEvent::FORM_SUBMISSION->value();+ });+ });++ it('sends events without properties for anonymous telemetry', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);+ $event = new FormCreated($form);++ event($event);++ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {+ return empty($job->properties);+ });+ });+});diff --git a/api/tests/Unit/Models/SettingTest.php b/api/tests/Unit/Models/SettingTest.phpnew file mode 100644index 000000000..9ae8b1917--- /dev/null+++ b/api/tests/Unit/Models/SettingTest.php@@ -0,0 +1,70 @@+<?php++use App\Enums\SettingsKey;+use App\Models\Setting;+use Tests\TestCase;++uses(TestCase::class);++describe('Setting', function () {+ beforeEach(function () {+ // Clean up before each test+ Setting::whereIn('key', [+ SettingsKey::INSTANCE_ID->value,+ SettingsKey::INSTANCE_CREATED_AT->value,+ ])->delete();+ });++ describe('get', function () {+ it('returns null when key does not exist', function () {+ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBeNull();+ });++ it('returns value when key exists', function () {+ $value = 'test-value';+ Setting::set(SettingsKey::INSTANCE_ID, $value);++ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe($value);+ });++ it('handles string values', function () {+ $value = 'test-uuid-string';+ Setting::set(SettingsKey::INSTANCE_ID, $value);++ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe($value);+ });++ it('handles array values', function () {+ $value = ['key1' => 'value1', 'key2' => 'value2'];+ Setting::set(SettingsKey::INSTANCE_ID, $value);++ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe($value);+ });+ });++ describe('set', function () {+ it('creates new setting when key does not exist', function () {+ Setting::set(SettingsKey::INSTANCE_ID, 'new-value');++ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe('new-value');+ });++ it('updates existing setting when key exists', function () {+ Setting::set(SettingsKey::INSTANCE_ID, 'initial-value');+ Setting::set(SettingsKey::INSTANCE_ID, 'updated-value');++ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe('updated-value');+ });++ it('handles different value types', function () {+ Setting::set(SettingsKey::INSTANCE_ID, 'string-value');+ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe('string-value');++ Setting::set(SettingsKey::INSTANCE_ID, ['array' => 'value']);+ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe(['array' => 'value']);++ Setting::set(SettingsKey::INSTANCE_ID, 123);+ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe(123);+ });+ });+});diff --git a/api/tests/Unit/Service/Telemetry/OpenPanelClientTest.php b/api/tests/Unit/Service/Telemetry/OpenPanelClientTest.phpnew file mode 100644index 000000000..d7f8496c6--- /dev/null+++ b/api/tests/Unit/Service/Telemetry/OpenPanelClientTest.php@@ -0,0 +1,174 @@+<?php++use App\Service\Telemetry\OpenPanelClient;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Log;+use Tests\TestCase;++uses(TestCase::class);++describe('OpenPanelClient', function () {+ it('can be instantiated', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ 'client-id',+ 'client-secret'+ );++ expect($client)->toBeInstanceOf(OpenPanelClient::class);+ });++ it('sends event successfully with valid credentials', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ 'client-id',+ 'client-secret'+ );++ Http::fake([+ 'test-endpoint.com/track' => Http::response([], 200),+ ]);++ $result = $client->sendEvent(+ 'test.event',+ ['foo' => 'bar'],+ 'instance-id'+ );++ expect($result)->toBeTrue();++ Http::assertSent(function ($request) {+ return $request->url() === 'https://test-endpoint.com/track'+ && $request->hasHeader('openpanel-client-id', 'client-id')+ && $request->hasHeader('openpanel-client-secret', 'client-secret')+ && $request['type'] === 'track'+ && $request['payload']['name'] === 'test.event'+ && $request['payload']['properties']['foo'] === 'bar'+ && $request['payload']['properties']['instance_id'] === 'instance-id';+ });+ });++ it('returns false when client id is missing', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ null,+ 'client-secret'+ );++ $result = $client->sendEvent(+ 'test.event',+ [],+ 'instance-id'+ );++ expect($result)->toBeFalse();+ });++ it('returns false when client secret is missing', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ 'client-id',+ null+ );++ $result = $client->sendEvent(+ 'test.event',+ [],+ 'instance-id'+ );++ expect($result)->toBeFalse();+ });++ it('handles HTTP errors gracefully', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ 'client-id',+ 'client-secret'+ );++ Log::spy();++ Http::fake([+ 'test-endpoint.com/track' => Http::response(['error' => 'Unauthorized'], 401),+ ]);++ $result = $client->sendEvent(+ 'test.event',+ [],+ 'instance-id'+ );++ expect($result)->toBeFalse();+ Log::shouldHaveReceived('warning')+ ->with('Telemetry event failed to send', \Mockery::type('array'))+ ->once();+ });++ it('handles exceptions gracefully', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ 'client-id',+ 'client-secret'+ );++ Log::spy();++ Http::fake(function () {+ throw new \Exception('Network error');+ });++ $result = $client->sendEvent(+ 'test.event',+ [],+ 'instance-id'+ );++ expect($result)->toBeFalse();+ Log::shouldHaveReceived('warning')+ ->with('Telemetry event error', \Mockery::type('array'))+ ->once();+ });++ it('includes instance id in event properties', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ 'client-id',+ 'client-secret'+ );++ Http::fake([+ 'test-endpoint.com/track' => Http::response([], 200),+ ]);++ $client->sendEvent(+ 'test.event',+ ['custom' => 'property'],+ 'test-instance-id'+ );++ Http::assertSent(function ($request) {+ $properties = $request['payload']['properties'];+ return $properties['instance_id'] === 'test-instance-id'+ && $properties['custom'] === 'property';+ });+ });++ it('returns false when instance id is missing', function () {+ $client = new OpenPanelClient(+ 'https://test-endpoint.com/track',+ 'client-id',+ 'client-secret'+ );++ Http::fake();++ $result = $client->sendEvent(+ 'test.event',+ [],+ null+ );++ expect($result)->toBeFalse();+ });+});diff --git a/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php b/api/tests/Unit/Service/Telemetry/TelemetryEventTest.phpnew file mode 100644index 000000000..a03cd3f5b--- /dev/null+++ b/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php@@ -0,0 +1,34 @@+<?php++use App\Service\Telemetry\TelemetryEvent;++describe('TelemetryEvent', function () {+ it('has all required event cases', function () {+ expect(TelemetryEvent::cases())->toHaveCount(5);+ });++ it('has INSTANCE_CREATED case with correct value', function () {+ expect(TelemetryEvent::INSTANCE_CREATED->value)->toBe('instance.created');+ });++ it('has USER_CREATED case with correct value', function () {+ expect(TelemetryEvent::USER_CREATED->value)->toBe('user.created');+ });++ it('has FORM_CREATED case with correct value', function () {+ expect(TelemetryEvent::FORM_CREATED->value)->toBe('form.created');+ });++ it('has WORKSPACE_CREATED case with correct value', function () {+ expect(TelemetryEvent::WORKSPACE_CREATED->value)->toBe('workspace.created');+ });++ it('has FORM_SUBMISSION case with correct value', function () {+ expect(TelemetryEvent::FORM_SUBMISSION->value)->toBe('form.submission');+ });++ it('value method returns the enum value', function () {+ expect(TelemetryEvent::INSTANCE_CREATED->value())->toBe('instance.created');+ expect(TelemetryEvent::USER_CREATED->value())->toBe('user.created');+ });+});diff --git a/api/tests/Unit/Service/Telemetry/TelemetryServiceTest.php b/api/tests/Unit/Service/Telemetry/TelemetryServiceTest.phpnew file mode 100644index 000000000..2dac9e172--- /dev/null+++ b/api/tests/Unit/Service/Telemetry/TelemetryServiceTest.php@@ -0,0 +1,91 @@+<?php++use App\Enums\SettingsKey;+use App\Models\Setting;+use App\Service\Telemetry\TelemetryService;+use Illuminate\Support\Facades\Config;+use Tests\TestCase;++uses(TestCase::class);++describe('TelemetryService', function () {+ beforeEach(function () {+ $this->service = new TelemetryService();+ });++ it('can be instantiated', function () {+ expect($this->service)->toBeInstanceOf(TelemetryService::class);+ });++ it('returns false when telemetry config is disabled', function () {+ Config::set('telemetry.enabled', false);++ expect($this->service->shouldSendTelemetry())->toBeFalse();+ });++ it('returns false when not in production and not self-hosted', function () {+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', false);+ app()->detectEnvironment(fn () => 'local');++ expect($this->service->shouldSendTelemetry())->toBeFalse();+ });++ it('returns false when only in production environment (needs self-hosted too)', function () {+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', false);+ app()->detectEnvironment(fn () => 'production');++ expect($this->service->shouldSendTelemetry())->toBeFalse();+ });++ it('returns false when only self-hosted mode is enabled (needs production too)', function () {+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', true);+ app()->detectEnvironment(fn () => 'local');++ expect($this->service->shouldSendTelemetry())->toBeFalse();+ });++ it('returns true when both production and self-hosted', function () {+ Config::set('telemetry.enabled', true);+ Config::set('app.self_hosted', true);+ app()->detectEnvironment(fn () => 'production');++ expect($this->service->shouldSendTelemetry())->toBeTrue();+ });++ it('returns instance id when set', function () {+ $instanceId = 'test-instance-id';+ Setting::set(SettingsKey::INSTANCE_ID, $instanceId);++ expect($this->service->getInstanceId())->toBe($instanceId);+ });++ it('returns null when instance id is not set', function () {+ Setting::where('key', SettingsKey::INSTANCE_ID->value)->delete();++ expect($this->service->getInstanceId())->toBeNull();+ });++ it('returns configured endpoint', function () {+ $endpoint = 'https://test-endpoint.com/track';+ Config::set('telemetry.endpoint', $endpoint);++ expect($this->service->getEndpoint())->toBe($endpoint);+ });++ it('returns configured client id', function () {+ $clientId = 'test-client-id';+ Config::set('telemetry.client_id', $clientId);++ expect($this->service->getClientId())->toBe($clientId);+ });++ it('returns configured client secret', function () {+ $clientSecret = 'test-client-secret';+ Config::set('telemetry.client_secret', $clientSecret);++ expect($this->service->getClientSecret())->toBe($clientSecret);+ });+});diff --git a/docker/php-fpm-entrypoint b/docker/php-fpm-entrypointindex e25ca9da5..84f41c94b 100644--- a/docker/php-fpm-entrypoint+++ b/docker/php-fpm-entrypoint@@ -27,6 +27,7 @@ main() {if [ "$ROLE" = "api" ]; thenecho "Running setup for API role..."apply_db_migrations+ initialize_instanceoptimize_applicationecho "Starting server for API role with command: $@"exec "$@"@@ -124,6 +125,11 @@ apply_db_migrations() {php ./artisan migrate --force}+initialize_instance() {+ echo "Initializing instance for telemetry"+ php ./artisan telemetry:initialize-instance+}+optimize_application() {echo "Clearing application cache"php ./artisan optimize:cleardiff --git a/docs/configuration/environment-variables.mdx b/docs/configuration/environment-variables.mdxindex 1aacc7e91..e359592a9 100644--- a/docs/configuration/environment-variables.mdx+++ b/docs/configuration/environment-variables.mdx@@ -89,6 +89,38 @@ These variables are essential for connecting the Laravel backend to your databas| `DB_USERNAME` | The username for connecting to the database. || `DB_PASSWORD` | The password for the database user. |+### Anonymous Telemetry++OpnForm tracks usage of its products which helps the team to improve and deliver better software. You can opt-out of this telemetry at any time.++**What data is collected?**++None of your customer data is ever transmitted by OpnForm installation. The telemetry data collected are purely usage statistics of various software features:++- Basic usage metrics (form creation, submissions, workspace creation, user additions)+- Anonymous instance identifier (UUID)+- Distribution of forms by type+- No personally identifiable information (PII)+- No form content, submission data, or user emails++**How is the data used?**++This data will only be used by OpnForm team for:++- Directly improving the product and identifying the parts of product which are popular+- Identifying areas with limited usage or where our users get stuck+- Prioritizing the next set of features to be developed++**When is telemetry active?**++- Production environments (`APP_ENV=production`)+- Self-hosted deployments (`SELF_HOSTED=true`)+- Disabled in local/development environments++**How to opt-out:**++Set `OPNFORM_ANONYMOUS_TELEMETRY_DISABLED=true` in your environment variables to disable data collection.+## Front-end Environment Variables| Variable Name | Description |