A free open source IT asset/license management system
Added adapters+clients
snipe2688b9684bb9
diff --git a/app/SyncAdapters/AdapterRegistry.php b/app/SyncAdapters/AdapterRegistry.phpnew file mode 100644index 0000000000..896098cee2--- /dev/null+++ b/app/SyncAdapters/AdapterRegistry.php@@ -0,0 +1,110 @@+<?php++namespace App\SyncAdapters;++use App\Models\SyncAdapterInstance;+use App\SyncAdapters\Addigy\AddigyAdapter;+use App\SyncAdapters\Fleet\FleetAdapter;+use App\SyncAdapters\Intune\IntuneAdapter;+use App\SyncAdapters\Jamf\JamfAdapter;+use App\SyncAdapters\JamfSchool\JamfSchoolAdapter;+use App\SyncAdapters\JumpCloud\JumpCloudAdapter;+use App\SyncAdapters\Kandji\KandjiAdapter;+use App\SyncAdapters\MerakiSystemsManager\MerakiSystemsManagerAdapter;+use App\SyncAdapters\Mosyle\MosyleAdapter;+use App\SyncAdapters\NinjaOne\NinjaOneAdapter;+use App\SyncAdapters\Osctrl\OsctrlAdapter;+use App\SyncAdapters\Unifi\UnifiAdapter;+use App\SyncAdapters\WorkspaceOne\WorkspaceOneAdapter;+use App\SyncAdapters\Zentral\ZentralAdapter;++/**+ * Registry of adapter TYPES Snipe-IT ships. Instances are stored in the+ * sync_adapter_instances table and multiple instances of the same type+ * are allowed (e.g., two Fleet installs). This registry only tells the+ * app which class handles which adapter_type slug.+ *+ * Kept as a static map for now. Migrating to service-container tagged+ * bindings later would let third-party adapter packages register their+ * own types via a service provider without touching this file.+ */+class AdapterRegistry+{+ /**+ * @var array<string, class-string<HostInventoryAdapter>>+ */+ private const TYPES = [+ 'fleet' => FleetAdapter::class,+ 'addigy' => AddigyAdapter::class,+ 'intune' => IntuneAdapter::class,+ 'jamf' => JamfAdapter::class,+ 'jamf_school' => JamfSchoolAdapter::class,+ 'kandji' => KandjiAdapter::class,+ 'meraki_sm' => MerakiSystemsManagerAdapter::class,+ 'mosyle' => MosyleAdapter::class,+ 'ninjaone' => NinjaOneAdapter::class,+ 'osctrl' => OsctrlAdapter::class,+ 'unifi' => UnifiAdapter::class,+ 'workspace_one' => WorkspaceOneAdapter::class,+ 'zentral' => ZentralAdapter::class,+ 'jumpcloud' => JumpCloudAdapter::class,+ ];++ /**+ * Build an instance-aware adapter from a SyncAdapterInstance row.+ * Returns null when the instance's adapter_type is not registered+ * (which can happen if an adapter class was removed but instances+ * still reference it).+ */+ public static function hydrate(SyncAdapterInstance $instance): ?HostInventoryAdapter+ {+ $class = self::TYPES[$instance->adapter_type] ?? null;+ if ($class === null) {+ return null;+ }++ return new $class($instance);+ }++ /**+ * Load every configured instance and hydrate it as a live adapter.+ * Instances whose adapter_type isn't registered are skipped.+ *+ * @return array<int, HostInventoryAdapter>+ */+ public static function allInstances(): array+ {+ return SyncAdapterInstance::query()+ ->orderBy('label')+ ->get()+ ->map(fn (SyncAdapterInstance $i) => self::hydrate($i))+ ->filter()+ ->values()+ ->all();+ }++ /**+ * @return array<int, string>+ */+ public static function typeNames(): array+ {+ return array_keys(self::TYPES);+ }++ /**+ * Human-readable labels for each registered adapter type. Used by+ * the "Add adapter" flow's type picker. Falls back to the type slug+ * when the class doesn't declare a static typeLabel().+ *+ * @return array<string, string>+ */+ public static function typeLabels(): array+ {+ $out = [];+ foreach (self::TYPES as $type => $class) {+ $out[$type] = method_exists($class, 'typeLabel') ? $class::typeLabel() : ucfirst($type);+ }++ return $out;+ }+}diff --git a/app/SyncAdapters/Addigy/AddigyAdapter.php b/app/SyncAdapters/Addigy/AddigyAdapter.phpnew file mode 100644index 0000000000..bdc59107e6--- /dev/null+++ b/app/SyncAdapters/Addigy/AddigyAdapter.php@@ -0,0 +1,135 @@+<?php++namespace App\SyncAdapters\Addigy;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * Addigy adapter. Pulls device inventory from the Addigy API and+ * normalizes it into HostInventoryRecord objects. Uses Addigy's+ * client-id + client-secret header pair (not bearer-token auth).+ */+class AddigyAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'Addigy';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://prod.addigy.com';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'key_id',+ 'label' => 'Client ID',+ 'help' => trans('admin/settings/general.sync_adapter_addigy_key_id_help'),+ ],+ [+ 'key' => 'key_secret',+ 'label' => 'Client Secret',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_addigy_key_secret_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'addigy_policy_id' => 'Addigy Policy ID',+ 'addigy_supervised' => ['label' => 'Addigy Supervised', 'type' => 'boolean'],+ 'addigy_agent_version' => 'Addigy Agent Version',+ ];+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return 'Addigy Policy';+ }++ public function fetchGroups(): array+ {+ $client = new AddigyClient(+ baseUrl: $this->url(),+ clientId: $this->credential('key_id'),+ clientSecret: $this->credential('key_secret'),+ );++ return array_map(+ fn (array $policy) => [+ 'id' => (string) ($policy['policyId'] ?? $policy['id'] ?? ''),+ 'label' => (string) ($policy['name'] ?? $policy['policyId'] ?? '?'),+ ],+ $client->policies(),+ );+ }++ public function pull(): iterable+ {+ $client = new AddigyClient(+ baseUrl: $this->url(),+ clientId: $this->credential('key_id'),+ clientSecret: $this->credential('key_secret'),+ );++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert an Addigy device payload into the normalized record+ * shape. Addigy's `agentid` is stable per enrolled device and is+ * what we key asset_external_sources on.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'agentid'),+ hostname: Arr::get($device, 'name'),+ hardwareSerial: Arr::get($device, 'serial_number'),+ hardwareModel: Arr::get($device, 'hardware_model'),+ manufacturer: 'Apple',+ primaryMac: Arr::get($device, 'network_mac_address'),+ primaryIp: Arr::get($device, 'network_ip_address'),+ os: Arr::get($device, 'os_type'),+ osVersion: Arr::get($device, 'os_version'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'last_online')),+ // Addigy's "asset_tag" is the operator-assigned tag from+ // their inventory settings, distinct from the Snipe-IT one.+ assetTag: Arr::get($device, 'asset_tag'),+ assignedUserEmail: Arr::get($device, 'user_email'),+ vendorGroupId: Arr::has($device, 'policy_id') ? (string) Arr::get($device, 'policy_id') : null,+ extra: [+ 'addigy_policy_id' => Arr::get($device, 'policy_id'),+ 'addigy_supervised' => Arr::get($device, 'is_supervised'),+ 'addigy_agent_version' => Arr::get($device, 'agent_version'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/Addigy/AddigyClient.php b/app/SyncAdapters/Addigy/AddigyClient.phpnew file mode 100644index 0000000000..cdc8e35cdf--- /dev/null+++ b/app/SyncAdapters/Addigy/AddigyClient.php@@ -0,0 +1,84 @@+<?php++namespace App\SyncAdapters\Addigy;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Addigy API. Owns auth for the devices+ * endpoint the sync adapter uses. Yields raw decoded JSON, no+ * normalization (that's the adapter's job).+ *+ * Auth model: a header pair generated in the Addigy admin console+ * under Integrations -> Addigy API. Both are treated as secrets by+ * the framework and pass in the `client-id` and `client-secret`+ * headers on every request (Addigy's own naming, lowercase). Distinct+ * from the bearer-token pattern the other adapters use.+ *+ * The v1 devices endpoint returns the full device list in one call,+ * so this client is single-request. Large tenants (thousands of+ * devices) can extend later to page through /api/v2/devices with the+ * cursor-based response shape.+ *+ * Addigy API reference: https://addigy.freshdesk.com/support/solutions/folders/8000078965+ */+class AddigyClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $clientId,+ private readonly string $clientSecret,+ ) {}++ /**+ * List every enrolled device in the Addigy tenant. Returned as a+ * generator for consistency with the other adapters, even though+ * the underlying endpoint is single-response.+ *+ * @return iterable<array<string, mixed>>+ */+ public function devices(): iterable+ {+ $response = $this->request()+ ->get('/api/devices')+ ->throw()+ ->json();++ // v1 returns a bare array of device objects on this endpoint.+ $devices = is_array($response) ? $response : [];++ foreach ($devices as $device) {+ yield $device;+ }+ }++ /**+ * List every Policy in the Addigy tenant. Used by the adapter's+ * fetchGroups() so admins can map Policies to Snipe-IT companies.+ * Policies are Addigy's device-grouping concept. MSPs often use+ * them as customer proxies.+ *+ * @return array<int, array<string, mixed>>+ */+ public function policies(): array+ {+ $response = $this->request()+ ->get('/api/policies')+ ->throw()+ ->json();++ return is_array($response) ? $response : [];+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withHeaders([+ 'client-id' => $this->clientId,+ 'client-secret' => $this->clientSecret,+ ])+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/Fleet/FleetAdapter.php b/app/SyncAdapters/Fleet/FleetAdapter.phpnew file mode 100644index 0000000000..c0b05d9536--- /dev/null+++ b/app/SyncAdapters/Fleet/FleetAdapter.php@@ -0,0 +1,362 @@+<?php++namespace App\SyncAdapters\Fleet;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * Fleet adapter. Pulls host inventory from a Fleet (FleetDM) instance+ * and normalizes it into HostInventoryRecord objects.+ *+ * Push (Snipe-IT -> Fleet) is not implemented because Fleet has no+ * first-class per-host writable metadata field that maps to Snipe-IT+ * concepts like asset_tag or notes. Fleet labels are group membership+ * (targeting devices for policies / reports / software), not a+ * per-host key-value store, so encoding an asset_tag as a label was a+ * semantic mismatch. Revisit if Fleet exposes per-host Custom+ * Attributes on a future release.+ */+class FleetAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'Fleet';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => 'API Token',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_fleet_token_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'fleet_team' => 'Fleet Team',+ 'fleet_labels' => 'Fleet Labels',+ 'fleet_uuid' => 'Fleet UUID',+ 'fleet_status' => 'Fleet Status',+ ];+ }++ /**+ * Fleet accepts label writes on any Admin-role API token. No+ * tier gate: label endpoints are on Free (unlike Teams, which+ * 402s). Push availability is purely a permissions question,+ * enforced by Fleet on the individual request.+ */+ public function canPush(): bool+ {+ return true;+ }++ public function supportsGroupScoping(): bool+ {+ // Fleet Teams is a Fleet Premium feature. When the cached+ // license tier (populated by afterSaveConfig() below) is+ // "free" we hide the group-mapping UI entirely so admins+ // don't try to Refresh and hit a 402. Any other value+ // (premium, unknown, or absent) shows it. Unknown covers+ // fresh installs before the first save and pre-existing+ // instances upgraded from earlier versions.+ return \App\Models\SyncAdapterConfig::get($this->instance->id, 'fleet_license_tier') !== 'free';+ }++ /**+ * After the admin saves credentials, probe the Fleet /config+ * endpoint to learn the license tier and cache it. Called only+ * when a URL + token are present since the endpoint requires auth.+ * Silent on failure so a misconfigured / offline Fleet doesn't+ * block the save.+ */+ protected function afterSaveConfig(): void+ {+ $url = $this->url();+ $token = $this->credential('token');+ if ($url === null || $url === '' || $token === null || $token === '') {+ return;+ }++ $tier = (new FleetClient(baseUrl: $url, token: $token))->licenseTier();++ if ($tier !== null) {+ \App\Models\SyncAdapterConfig::put(+ $this->instance->id,+ 'fleet_license_tier',+ $tier,+ );+ }+ }++ public function vendorGroupLabel(): string+ {+ return 'Fleet Team';+ }++ public function fetchGroups(): array+ {+ $client = new FleetClient(baseUrl: $this->url(), token: $this->credential('token'));++ return array_map(+ fn (array $team) => [+ 'id' => (string) ($team['id'] ?? ''),+ 'label' => (string) ($team['name'] ?? $team['id'] ?? '?'),+ ],+ $client->teams(),+ );+ }++ public function pull(): iterable+ {+ $client = new FleetClient(baseUrl: $this->url(), token: $this->credential('token'));++ // Fleet's list endpoint returns a slimmed-down host summary+ // that omits device_mapping and end_users. When the admin has+ // configured user matching, hydrate each host with the detail+ // endpoint so the assigned-user extractors have something to+ // work with. Pays an N+1 API cost per sync, only when needed.+ $needsDetail = $this->userMatchStrategy() !== 'none';++ foreach ($client->hosts() as $host) {+ if ($needsDetail && isset($host['id'])) {+ $detail = $client->hostDetail((int) $host['id']);+ if ($detail !== null) {+ $host = $detail;+ }+ }++ yield $this->normalize($host);+ }+ }++ /**+ * Convert a Fleet host payload into the normalized record shape.+ * Fleet's `id` field is stable per host enrollment and is what we+ * key asset_external_sources on. The sourceKey is the instance slug so+ * hosts from different Fleet instances stay distinct.+ *+ * @param array<string, mixed> $host+ */+ private function normalize(array $host): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($host, 'id'),+ hostname: Arr::get($host, 'hostname'),+ hardwareSerial: Arr::get($host, 'hardware_serial'),+ hardwareModel: Arr::get($host, 'hardware_model'),+ manufacturer: Arr::get($host, 'hardware_vendor'),+ primaryMac: Arr::get($host, 'primary_mac'),+ primaryIp: Arr::get($host, 'primary_ip'),+ os: Arr::get($host, 'platform'),+ osVersion: Arr::get($host, 'os_version'),+ lastSeen: $this->parseTimestamp(Arr::get($host, 'seen_time')),+ assignedUserEmail: $this->extractUserEmail($host),+ assignedUserName: $this->extractUserName($host),+ vendorGroupId: Arr::has($host, 'team_id') ? (string) Arr::get($host, 'team_id') : null,+ extra: [+ 'fleet_team' => Arr::get($host, 'team_name'),+ 'fleet_labels' => Arr::get($host, 'labels'),+ 'fleet_uuid' => Arr::get($host, 'uuid'),+ 'fleet_status' => Arr::get($host, 'status'),+ ],+ );+ }++ /**+ * Fleet doesn't have one canonical "primary user email" field.+ * The Fleet Premium IdP / SCIM sync populates end_users[] with+ * idp_info[].email and other_emails[]. Some Fleet builds expose+ * a top-level primary_user_email on the detailed host endpoint.+ * Walk the known locations in preference order and return the+ * first one that yields something email-shaped.+ *+ * @param array<string, mixed> $host+ */+ private function extractUserEmail(array $host): ?string+ {+ $candidates = [+ // device_mapping is the Fleet Free feature that surfaces+ // Google Chrome sync email associations. Only present on+ // the detailed host endpoint with ?device_mapping=true.+ Arr::get($host, 'device_mapping.0.email'),+ Arr::get($host, 'primary_user_email'),+ Arr::get($host, 'end_users.0.idp_info.0.email'),+ Arr::get($host, 'end_users.0.other_emails.0.email'),+ Arr::get($host, 'end_users.0.other_emails.0'),+ Arr::get($host, 'end_users.0.email'),+ ];++ foreach ($candidates as $candidate) {+ if (is_string($candidate) && str_contains($candidate, '@')) {+ return $candidate;+ }+ }++ return null;+ }++ /**+ * Fleet returns a `users[]` array of every local UNIX account on+ * the host, including system daemons (`_installassistant`, `root`,+ * `nobody`, macOS's underscore-prefixed service accounts, etc.).+ * Filter those out and return the first remaining username. When+ * the host has exactly one real user account, that's almost always+ * the "primary user" for asset-management purposes. When multiple+ * real users exist we still pick the first, which is imperfect but+ * matches how vendors like Kandji surface primary user too.+ *+ * @param array<string, mixed> $host+ */+ private function extractUserName(array $host): ?string+ {+ $users = Arr::get($host, 'users');+ if (! is_array($users)) {+ return null;+ }++ foreach ($users as $user) {+ $username = Arr::get($user, 'username');+ if (! is_string($username) || $username === '') {+ continue;+ }++ // Skip macOS system accounts (all start with underscore),+ // Linux daemon accounts (root, daemon, bin, sys, sync, etc.),+ // and Windows built-ins that Fleet reports.+ if ($this->looksLikeSystemAccount($username)) {+ continue;+ }++ return $username;+ }++ return null;+ }++ /**+ * Heuristic system-account filter. Underscore-prefix catches every+ * macOS service account. The explicit deny-list catches the well-+ * known Linux and Windows accounts that Fleet reports alongside+ * real users.+ */+ private function looksLikeSystemAccount(string $username): bool+ {+ if (str_starts_with($username, '_')) {+ return true;+ }++ return in_array($username, [+ 'root', 'daemon', 'bin', 'sys', 'sync', 'games', 'man', 'lp',+ 'mail', 'news', 'uucp', 'proxy', 'www-data', 'backup', 'list',+ 'irc', 'gnats', 'nobody', 'systemd-network', 'systemd-resolve',+ 'messagebus', 'sshd', 'shutdown', 'halt', 'operator',+ 'DefaultAccount', 'Guest', 'WDAGUtilityAccount', 'SYSTEM',+ ], true);+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }++ /**+ * Push Snipe-IT-authoritative fields to Fleet as manual labels.+ * Fleet has no native asset_tag / notes columns, so each push-+ * directed field becomes a per-host manual label named+ * `snipeit_{field}_{value}`. Membership is set via label-spec so+ * one API call creates the label (if new) and sets its member+ * host in a single round trip.+ *+ * Uses the asset's serial number to identify the host to Fleet+ * because serial is more stable than hostname across renames+ * and re-enrollments. Silently no-ops when the asset has no+ * serial (nothing to identify the Fleet host with).+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): void+ {+ $pushFields = $this->pushDirectedFields();+ if ($pushFields === []) {+ return;+ }++ if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {+ return;+ }++ $externalSource = AssetExternalSource::query()+ ->where('asset_id', $asset->id)+ ->where('source', $this->name())+ ->first();++ if ($externalSource === null) {+ return;+ }++ $serial = $asset->serial;+ if ($serial === null || $serial === '') {+ return;+ }++ $client = new FleetClient(baseUrl: $this->url(), token: $this->credential('token'));++ foreach ($pushFields as $field) {+ $value = $this->assetValueForSourceField($asset, $field);+ if ($value === null || $value === '') {+ continue;+ }++ $labelName = self::labelNameFor($field, $value);+ $client->upsertManualLabelForHost($labelName, $serial);++ Log::channel('sync-adapters')->info(sprintf(+ '%s push: set label "%s" on Fleet host serial=%s',+ $this->name(),+ $labelName,+ $serial,+ ));+ }+ }++ /**+ * Build the Fleet label name for a Snipe-IT source-field / value+ * pair. `snipeit_` prefix so admins can filter Fleet's label list+ * down to the sync-managed ones. Underscore separator between+ * field name and value because Fleet's label names allow letters,+ * digits, underscores, and hyphens but not colons or slashes.+ * Value is sanitized to the same charset.+ */+ private static function labelNameFor(string $field, string $value): string+ {+ return 'snipeit_'.$field.'_'.preg_replace('/[^A-Za-z0-9_\\-]/', '_', $value);+ }++ /**+ * Resolve a Snipe-IT source of truth for a given source-field+ * name. Currently only asset_tag is push-supported for Fleet+ * (the vendor field most commonly requested); additional fields+ * add cases here as we wire them.+ */+ private function assetValueForSourceField(Asset $asset, string $field): ?string+ {+ return match ($field) {+ 'asset_tag' => $asset->asset_tag,+ default => null,+ };+ }+}diff --git a/app/SyncAdapters/Fleet/FleetClient.php b/app/SyncAdapters/Fleet/FleetClient.phpnew file mode 100644index 0000000000..bcc29c635a--- /dev/null+++ b/app/SyncAdapters/Fleet/FleetClient.php@@ -0,0 +1,189 @@+<?php++namespace App\SyncAdapters\Fleet;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Fleet REST API. Owns auth + pagination for the+ * endpoints the sync adapter uses. Yields raw decoded JSON, no normalization+ * (that's the adapter's job).+ *+ * Fleet API reference: https://fleetdm.com/docs/rest-api/rest-api+ */+class FleetClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $token,+ ) {}++ /**+ * Iterate over every host in Fleet, one page at a time. Returns a+ * generator so callers can stream through large fleets without holding+ * the whole list in memory.+ *+ * @return iterable<array<string, mixed>>+ */+ public function hosts(int $perPage = 100): iterable+ {+ $page = 0;++ do {+ $response = $this->request()+ ->get('/api/latest/fleet/hosts', [+ 'page' => $page,+ 'per_page' => $perPage,+ ])+ ->throw()+ ->json();++ $hosts = $response['hosts'] ?? [];+ foreach ($hosts as $host) {+ yield $host;+ }++ // Fleet doesn't return a total-pages count on this endpoint.+ // The accepted convention is to keep asking until a short page+ // comes back.+ $done = count($hosts) < $perPage;+ $page++;+ } while (! $done);+ }++ /**+ * List every Fleet Team on the instance. Used by the adapter's+ * fetchGroups() so admins can map Fleet Teams to Snipe-IT+ * companies. Teams endpoint returns the full list in one call.+ *+ * @return array<int, array<string, mixed>>+ */+ public function teams(): array+ {+ $response = $this->request()+ ->get('/api/latest/fleet/teams')+ ->throw()+ ->json();++ return $response['teams'] ?? [];+ }++ /**+ * Fetch the detailed host payload for a single host, including+ * device_mapping (the Fleet Free feature that surfaces email+ * associations from Google Chrome sync data). The list endpoint+ * used by hosts() returns a slimmed-down summary. Anything user-+ * assignment-related lives on this detail endpoint.+ *+ * @return array<string, mixed>|null+ */+ public function hostDetail(int $id): ?array+ {+ $response = $this->request()+ ->get('/api/latest/fleet/hosts/'.$id, ['device_mapping' => 'true'])+ ->throw()+ ->json();++ $host = $response['host'] ?? null;++ return is_array($host) ? $host : null;+ }++ /**+ * Fetch the instance's license tier by hitting /api/latest/fleet/config,+ * which returns a `license.tier` field ("free" or "premium"). Free+ * to call regardless of tier. Returns null when the config endpoint+ * is unreachable or returns an unrecognized shape so callers can+ * distinguish "confirmed free" from "we don't know" and default+ * conservatively.+ */+ public function licenseTier(): ?string+ {+ try {+ $config = $this->request()+ ->get('/api/latest/fleet/config')+ ->throw()+ ->json();+ } catch (\Throwable) {+ return null;+ }++ $tier = $config['license']['tier'] ?? null;++ return is_string($tier) ? strtolower($tier) : null;+ }++ /**+ * Upsert a manual label with the specified host as its sole member.+ * Fleet's spec-apply endpoint is gated behind Premium / gitops mode+ * on some builds, so this uses the individual /labels endpoints+ * instead: GET to find an existing label by name, PATCH to update+ * host membership, or POST to create when absent. Two API calls in+ * the update path, three in the create path (list + create + noop).+ *+ * Fleet identifies label hosts by "identifier" (hostname, hardware+ * serial, or UUID). Serial is the most stable of the three across+ * renames and re-enrollments, so callers pass that.+ *+ * Silently no-ops when either arg is blank so a partial-config+ * push doesn't punch a random label into the fleet.+ */+ public function upsertManualLabelForHost(string $labelName, string $hostIdentifier): void+ {+ if ($labelName === '' || $hostIdentifier === '') {+ return;+ }++ $existingId = $this->findLabelIdByName($labelName);++ if ($existingId !== null) {+ $this->request()+ ->patch('/api/latest/fleet/labels/'.$existingId, [+ 'hosts' => [$hostIdentifier],+ ])+ ->throw();++ return;+ }++ $this->request()+ ->post('/api/latest/fleet/labels', [+ 'name' => $labelName,+ 'description' => 'Managed by Snipe-IT sync push',+ 'label_membership_type' => 'manual',+ 'hosts' => [$hostIdentifier],+ ])+ ->throw();+ }++ /**+ * Look up a Fleet label id by its exact name. Fleet's /labels+ * endpoint doesn't support server-side name filtering, so we page+ * through and match client-side. Returns null when no label with+ * that name exists.+ */+ private function findLabelIdByName(string $name): ?int+ {+ $response = $this->request()+ ->get('/api/latest/fleet/labels', ['per_page' => 500])+ ->throw()+ ->json();++ foreach ($response['labels'] ?? [] as $label) {+ if (($label['name'] ?? null) === $name) {+ return (int) $label['id'];+ }+ }++ return null;+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withToken($this->token)+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/HostInventoryAdapter.php b/app/SyncAdapters/HostInventoryAdapter.phpnew file mode 100644index 0000000000..525198b5f0--- /dev/null+++ b/app/SyncAdapters/HostInventoryAdapter.php@@ -0,0 +1,115 @@+<?php++namespace App\SyncAdapters;++use App\Models\SyncAdapterInstance;+use Carbon\CarbonInterface;+use Illuminate\Http\Request;++/**+ * Contract every host-inventory sync adapter implements. An adapter is+ * always constructed against a specific SyncAdapterInstance so multiple+ * instances of the same adapter TYPE (two Fleet installs, one Fleet ++ * one Kandji, etc.) each get their own credentials, own settings tab,+ * own asset_external_sources.source value.+ *+ * The asset-side upsert code is shared across adapters+ * (SyncHostFromAdapter action). Adapters also own their own settings+ * view partial and save handler so the generic /admin/adapters page+ * can render every instance's section without the controller knowing+ * anything vendor-specific.+ */+interface HostInventoryAdapter+{+ /**+ * Bind the adapter to the given instance. Every adapter subclass+ * accepts a SyncAdapterInstance in its constructor via this contract+ * so AdapterRegistry::hydrate() can build one uniformly.+ */+ public function __construct(SyncAdapterInstance $instance);++ /**+ * The instance's slug. Used as the `source` value in+ * asset_external_sources and as the route parameter for the sync+ * trigger. Example: 'fleet-prod', 'jamf-staging', 'kandji'.+ */+ public function name(): string;++ /**+ * Human-readable name shown on the settings-page tab. Pulled from+ * the instance's `label` column, which is user-editable per instance.+ */+ public function label(): string;++ /**+ * Whether this instance is configured, active, and available to run.+ * Adapters check their required credentials, the instance's `active`+ * flag, and any adapter-specific readiness here.+ */+ public function isEnabled(): bool;++ /**+ * Whether this instance's `active` toggle is on. Distinct from+ * isEnabled(), which also requires config to be present. The blade+ * uses this to render the checkbox state.+ */+ public function isActive(): bool;++ /**+ * Whether this instance is a shipped built-in (undeletable). The+ * blade uses this to hide the delete control.+ */+ public function isBuiltIn(): bool;++ /**+ * View name for the adapter's settings section, rendered inside a+ * tab-pane on the shared /admin/adapters page. The view is included+ * with the current adapter instance available so it can read its own+ * state (e.g. getUrl(), credentialForDisplay(), isActive(), etc.).+ */+ public function settingsView(): string;++ /**+ * Validation rules the controller runs against the save request+ * BEFORE handing it to saveConfig. Adapters declare their own+ * required fields + SSRF guards here (e.g. the ExternalUrl rule on+ * the URL field to block loopback / RFC-1918 / metadata targets).+ *+ * @return array<string, array<int, mixed>>+ */+ public function validationRules(): array;++ /**+ * Persist this instance's settings from a save request. The generic+ * postAdapters controller iterates the registered instances and+ * calls this for the one whose slug matches the form's hidden+ * `adapter` input. Keeps every adapter's config-storage details+ * inside the adapter class instead of leaking into shared+ * controller code.+ */+ public function saveConfig(Request $request): void;++ /**+ * Pull the current host inventory from the vendor. Returns a+ * generator so adapters can page through large inventories without+ * buffering everything in memory.+ *+ * @return iterable<HostInventoryRecord>+ */+ public function pull(): iterable;++ /**+ * When the last sync ran, or null if this instance has never been+ * synced. Written by both the interactive Sync Now button and the+ * CLI command so the settings page can surface the most recent+ * outcome regardless of trigger source.+ */+ public function lastSyncedAt(): ?CarbonInterface;++ /**+ * Human-readable summary of the last sync's outcome (e.g.+ * "Sync complete. Synced 847 host(s), 3 error(s).") or null if+ * this instance has never been synced.+ */+ public function lastSyncResult(): ?string;+}diff --git a/app/SyncAdapters/HostInventoryRecord.php b/app/SyncAdapters/HostInventoryRecord.phpnew file mode 100644index 0000000000..f7226d1885--- /dev/null+++ b/app/SyncAdapters/HostInventoryRecord.php@@ -0,0 +1,49 @@+<?php++namespace App\SyncAdapters;++use Carbon\CarbonInterface;++/**+ * Normalized host record produced by every adapter. Universal currency of+ * the host-inventory ingestion pipeline. Adapters convert vendor-specific+ * payloads into this shape, the sync action reads only this shape.+ */+final readonly class HostInventoryRecord+{+ /**+ * @param array<string, mixed> $extra source-specific data that per-adapter+ * fieldsets can surface as custom fields+ */+ public function __construct(+ public string $sourceKey,+ public string $sourceId,+ public ?string $hostname = null,+ public ?string $hardwareSerial = null,+ public ?string $hardwareModel = null,+ public ?string $manufacturer = null,+ public ?string $primaryMac = null,+ public ?string $primaryIp = null,+ public ?string $os = null,+ public ?string $osVersion = null,+ public ?CarbonInterface $lastSeen = null,+ // Vendor-provided asset tag when the source has one (Kandji,+ // Jamf School, Mosyle, Addigy). Never overwrites Snipe-IT's+ // asset_tag by default. Admins opt in via the mapping UI by+ // picking `native:asset_tag` as the target for this field.+ public ?string $assetTag = null,+ // Vendor-side identifiers for whoever the device is assigned+ // to. Adapters populate whichever the vendor emits. The sync+ // path's user-lookup uses one of these per the adapter's+ // configured match strategy (email or username).+ public ?string $assignedUserEmail = null,+ public ?string $assignedUserName = null,+ // Vendor's group identifier (Fleet Team id, Jamf Site id,+ // Kandji Blueprint id, etc). Sync path uses this to resolve+ // the asset's Snipe-IT company via the adapter's per-group+ // company mapping. Null when the vendor doesn't group the+ // device or the adapter doesn't emit group data.+ public ?string $vendorGroupId = null,+ public array $extra = [],+ ) {}+}diff --git a/app/SyncAdapters/Intune/IntuneAdapter.php b/app/SyncAdapters/Intune/IntuneAdapter.phpnew file mode 100644index 0000000000..912d60bec5--- /dev/null+++ b/app/SyncAdapters/Intune/IntuneAdapter.php@@ -0,0 +1,233 @@+<?php++namespace App\SyncAdapters\Intune;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\Support\ConfigurableAdapter;+use App\SyncAdapters\Support\NotesComposer;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * Microsoft Intune adapter. Pulls managed devices from Microsoft Graph+ * (/v1.0/deviceManagement/managedDevices) via an OAuth 2.0+ * client-credentials app registration and normalizes them into+ * HostInventoryRecord objects. Also pushes composed notes back to+ * Intune's managed-device notes field via Graph beta, matching what+ * community integrations like Brady Widener's PowerShell script do.+ *+ * Sovereign clouds change both the Graph URL and the token endpoint+ * (US Gov uses graph.microsoft.us + login.microsoftonline.us). The+ * Base URL field on the settings page controls the Graph endpoint.+ * The login host is derived from it by swapping the second-level+ * label so a single URL config drives both.+ *+ * Non-secret credentials (tenant + client id) stay plain-text at rest+ * so admins can audit which Azure app registration a Snipe-IT instance+ * is talking to without a decrypt step. Only client_secret is encrypted.+ */+class IntuneAdapter extends ConfigurableAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'Microsoft Intune';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://graph.microsoft.com';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'tenant_id',+ 'label' => 'Tenant ID',+ 'help' => trans('admin/settings/general.sync_adapter_intune_tenant_id_help'),+ ],+ [+ 'key' => 'client_id',+ 'label' => 'Client ID',+ 'help' => trans('admin/settings/general.sync_adapter_intune_client_id_help'),+ ],+ [+ 'key' => 'client_secret',+ 'label' => 'Client Secret',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_intune_client_secret_help'),+ ],+ ];+ }++ public function pull(): iterable+ {+ $graphBaseUrl = $this->url();++ $client = new IntuneClient(+ graphBaseUrl: $graphBaseUrl,+ loginBaseUrl: $this->deriveLoginBaseUrl($graphBaseUrl),+ tenantId: $this->credential('tenant_id'),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ );++ foreach ($client->managedDevices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Derive the OAuth login host from the Graph host so sovereign+ * clouds (US Gov, China) work off a single URL config. Falls+ * back to the public Microsoft login endpoint when the base URL+ * doesn't parse cleanly.+ */+ private function deriveLoginBaseUrl(string $graphBaseUrl): string+ {+ $host = parse_url($graphBaseUrl, PHP_URL_HOST);+ if (! is_string($host)) {+ return 'https://login.microsoftonline.com';+ }++ $tld = substr($host, strrpos($host, '.') + 1);++ return match ($tld) {+ 'us' => 'https://login.microsoftonline.us',+ 'cn' => 'https://login.chinacloudapi.cn',+ default => 'https://login.microsoftonline.com',+ };+ }++ /**+ * Convert a Graph managedDevice payload into the normalized record+ * shape. Graph's stable id is `id` (a GUID); we key+ * asset_external_sources on it. Ethernet MAC is preferred over+ * WiFi because it's more likely to be a hardware-inventory MAC+ * that survives OS reinstall.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'id'),+ hostname: Arr::get($device, 'deviceName'),+ hardwareSerial: Arr::get($device, 'serialNumber'),+ hardwareModel: Arr::get($device, 'model'),+ manufacturer: Arr::get($device, 'manufacturer'),+ primaryMac: Arr::get($device, 'ethernetMacAddress')+ ?? Arr::get($device, 'wiFiMacAddress'),+ primaryIp: null,+ os: Arr::get($device, 'operatingSystem'),+ osVersion: Arr::get($device, 'osVersion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'lastSyncDateTime')),+ assignedUserEmail: Arr::get($device, 'userPrincipalName')+ ?? Arr::get($device, 'emailAddress'),+ extra: [+ 'intune_compliance_state' => Arr::get($device, 'complianceState'),+ 'intune_enrolled_at' => Arr::get($device, 'enrolledDateTime'),+ 'intune_management_agent' => Arr::get($device, 'managementAgent'),+ 'intune_ownership' => Arr::get($device, 'managedDeviceOwnerType'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }++ /**+ * Push always available for a configured Intune instance. The+ * Graph beta endpoint requires the app registration to have the+ * DeviceManagementManagedDevices.ReadWrite.All permission+ * (admin consent required, same as the read scope but broader).+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * Intune managed devices carry a freeform `notes` field on the+ * Graph beta endpoint. That's the field Brady Widener's community+ * PowerShell script targets and is the most-asked-for Intune+ * push shape.+ */+ public function notesFieldTarget(): ?string+ {+ return 'notes';+ }++ /**+ * Push composed notes to Intune's managed-device notes field.+ * asset_tag isn't first-class-writable on Intune (Graph v1.0+ * doesn't expose it and the beta shape varies), so v1 supports+ * composed notes only. Admins who want asset_tag on Intune+ * embed it in the notes template.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): void+ {+ $template = $this->pushNotesTemplate();+ $target = $this->effectiveNotesTarget();+ if ($template === '' || $target === null) {+ return;+ }++ $externalSource = AssetExternalSource::query()+ ->where('asset_id', $asset->id)+ ->where('source', $this->name())+ ->first();++ if ($externalSource === null) {+ return;+ }++ $composed = NotesComposer::compose($asset, $template);+ if ($composed === '') {+ return;+ }++ $payload = [$target => $composed];++ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would PATCH Intune managed device %s with %s',+ $this->name(),+ $externalSource->external_id,+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ ));++ return;+ }++ $graphBaseUrl = $this->url();+ $client = new IntuneClient(+ graphBaseUrl: $graphBaseUrl,+ loginBaseUrl: $this->deriveLoginBaseUrl($graphBaseUrl),+ tenantId: $this->credential('tenant_id'),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ );+ $client->updateManagedDevice($externalSource->external_id, $payload);++ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Intune managed device %s (%s)',+ $this->name(),+ $externalSource->external_id,+ $target,+ ));+ }+}diff --git a/app/SyncAdapters/Intune/IntuneClient.php b/app/SyncAdapters/Intune/IntuneClient.phpnew file mode 100644index 0000000000..10dd5d7c68--- /dev/null+++ b/app/SyncAdapters/Intune/IntuneClient.php@@ -0,0 +1,114 @@+<?php++namespace App\SyncAdapters\Intune;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around Microsoft Graph for the Intune Managed Devices+ * endpoint. Handles OAuth 2.0 client-credentials token exchange and+ * Graph cursor pagination (via the `@odata.nextLink` response field).+ *+ * Auth model: Azure app registration with a tenant + client_id ++ * client_secret. Token exchange POSTs to the tenant-scoped OAuth 2.0+ * token endpoint with scope `https://graph.microsoft.com/.default`.+ * The returned bearer is valid for ~60 minutes. A single sync run+ * stays inside that window so we don't refresh mid-run.+ *+ * Sovereign clouds swap both hosts. The `graphBaseUrl` and+ * `loginBaseUrl` constructor args let the adapter derive the login+ * host from the Graph host so the settings-page URL field controls+ * both endpoints.+ */+class IntuneClient+{+ private ?string $token = null;++ public function __construct(+ private readonly string $graphBaseUrl,+ private readonly string $loginBaseUrl,+ private readonly string $tenantId,+ private readonly string $clientId,+ private readonly string $clientSecret,+ ) {}++ /**+ * Iterate every managed device visible to the app registration.+ * Uses Graph's `@odata.nextLink` for cursor pagination. The+ * cursor URL is absolute and includes the base host, so we hand+ * it straight to Http::get() rather than composing against+ * $graphBaseUrl a second time.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function managedDevices(): iterable+ {+ $url = rtrim($this->graphBaseUrl, '/').'/v1.0/deviceManagement/managedDevices';++ do {+ $response = $this->request()->get($url)->throw()->json();++ foreach (($response['value'] ?? []) as $device) {+ yield $device;+ }++ $url = $response['@odata.nextLink'] ?? null;+ } while ($url !== null);+ }++ /**+ * Fetch (or reuse) a bearer token via OAuth 2.0 client-credentials+ * against the tenant-scoped token endpoint. Token is cached on+ * this instance for the life of the sync run.+ */+ private function bearer(): string+ {+ if ($this->token !== null) {+ return $this->token;+ }++ $tokenUrl = rtrim($this->loginBaseUrl, '/').'/'.$this->tenantId.'/oauth2/v2.0/token';++ $response = Http::asForm()+ ->timeout(30)+ ->post($tokenUrl, [+ 'grant_type' => 'client_credentials',+ 'client_id' => $this->clientId,+ 'client_secret' => $this->clientSecret,+ 'scope' => rtrim($this->graphBaseUrl, '/').'/.default',+ ])+ ->throw()+ ->json();++ return $this->token = (string) ($response['access_token'] ?? '');+ }++ /**+ * Push writable metadata to a managed device via Graph beta's+ * per-device endpoint. The v1.0 endpoint doesn't expose notes+ * as writable. Beta does (matches what community integrations+ * like Brady Widener's Snipe-IT-Azure-Integration use). Fields+ * the caller doesn't include stay untouched.+ *+ * @param array<string, scalar|null> $payload+ */+ public function updateManagedDevice(string $deviceId, array $payload): void+ {+ $url = rtrim($this->graphBaseUrl, '/').'/beta/deviceManagement/managedDevices/'.$deviceId;++ Http::withToken($this->bearer())+ ->asJson()+ ->acceptJson()+ ->timeout(30)+ ->patch($url, $payload)+ ->throw();+ }++ private function request(): PendingRequest+ {+ return Http::withToken($this->bearer())+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/Jamf/JamfAdapter.php b/app/SyncAdapters/Jamf/JamfAdapter.phpnew file mode 100644index 0000000000..7d2a7e5b6f--- /dev/null+++ b/app/SyncAdapters/Jamf/JamfAdapter.php@@ -0,0 +1,254 @@+<?php++namespace App\SyncAdapters\Jamf;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * Jamf Pro adapter. Pulls computer inventory via the Jamf Pro API and+ * normalizes it into HostInventoryRecord objects. Uses a Jamf-generated+ * Personal Access Token as a bearer credential. Also pushes+ * Snipe-IT-authoritative fields (asset_tag today) back to Jamf via+ * the /api/v1/computers-inventory-detail/{id} PATCH endpoint.+ */+class JamfAdapter extends ConfigurableAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'Jamf Pro';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://your-subdomain.jamfcloud.com';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => 'API Token',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_jamf_token_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'jamf_udid' => 'Jamf UDID',+ 'jamf_last_enrolled' => 'Jamf Last Enrolled',+ 'jamf_model_identifier' => 'Jamf Model Identifier',+ ];+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return 'Jamf Site';+ }++ public function fetchGroups(): array+ {+ $client = new JamfClient(baseUrl: $this->url(), token: $this->credential('token'));++ return array_map(+ fn (array $site) => [+ 'id' => (string) ($site['id'] ?? ''),+ 'label' => (string) ($site['name'] ?? $site['id'] ?? '?'),+ ],+ $client->sites(),+ );+ }++ public function pull(): iterable+ {+ $client = new JamfClient(baseUrl: $this->url(), token: $this->credential('token'));++ foreach ($client->computers() as $computer) {+ yield $this->normalize($computer);+ }+ }++ /**+ * Convert a Jamf computer payload into the normalized record shape.+ * Jamf's numeric `id` is stable per enrollment and is what we key+ * asset_external_sources on. Fields come from the GENERAL, HARDWARE, and+ * OPERATING_SYSTEM sections (the client only requests those).+ *+ * @param array<string, mixed> $computer+ */+ private function normalize(array $computer): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($computer, 'id'),+ hostname: Arr::get($computer, 'general.name'),+ hardwareSerial: Arr::get($computer, 'hardware.serialNumber'),+ hardwareModel: Arr::get($computer, 'hardware.model'),+ manufacturer: Arr::get($computer, 'hardware.make'),+ primaryMac: Arr::get($computer, 'hardware.macAddress'),+ primaryIp: null,+ os: Arr::get($computer, 'operatingSystem.name'),+ osVersion: Arr::get($computer, 'operatingSystem.version'),+ lastSeen: $this->parseTimestamp(Arr::get($computer, 'general.lastContactTime')),+ assetTag: Arr::get($computer, 'general.assetTag'),+ assignedUserEmail: Arr::get($computer, 'userAndLocation.email'),+ assignedUserName: Arr::get($computer, 'userAndLocation.username'),+ vendorGroupId: Arr::has($computer, 'general.site.id') ? (string) Arr::get($computer, 'general.site.id') : null,+ extra: [+ 'jamf_udid' => Arr::get($computer, 'udid'),+ 'jamf_last_enrolled' => Arr::get($computer, 'general.lastEnrolledDate'),+ 'jamf_model_identifier' => Arr::get($computer, 'hardware.modelIdentifier'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }++ /**+ * Jamf Pro writes are gated by the PAT's API role scopes. Both+ * pull + push work with the same token when the role grants the+ * "Update Computers" privilege. No tier / license gate, so canPush+ * is always true for a configured instance.+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * Jamf Pro's computer record has a freeform notes field at+ * general.notes on the inventory-detail JSON. Dotted path so+ * Arr::set can slot the composed value into the right nested+ * object.+ */+ public function notesFieldTarget(): ?string+ {+ return 'general.notes';+ }++ /**+ * Push Snipe-IT-authoritative fields to Jamf Pro via the newer+ * JSON detail endpoint. The payload uses Jamf's nested-object+ * shape (assetTag lives inside userAndLocation, not at the top+ * level), so sourceFieldToJamfPath() returns dotted paths that+ * get assembled via Arr::set before the PATCH.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): void+ {+ $pushFields = $this->pushDirectedFields();+ if ($pushFields === []) {+ return;+ }++ if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {+ return;+ }++ $externalSource = AssetExternalSource::query()+ ->where('asset_id', $asset->id)+ ->where('source', $this->name())+ ->first();++ if ($externalSource === null) {+ return;+ }++ $payload = [];+ $touched = [];+ foreach ($pushFields as $field) {+ $path = self::sourceFieldToJamfPath($field);+ if ($path === null) {+ continue;+ }++ $value = $this->assetValueForSourceField($asset, $field);+ if ($value === null) {+ continue;+ }++ Arr::set($payload, $path, $value);+ $touched[] = $path;+ }++ $template = $this->pushNotesTemplate();+ $notesTarget = $this->effectiveNotesTarget();+ if ($template !== '' && $notesTarget !== null) {+ $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);+ if ($composed !== '') {+ Arr::set($payload, $notesTarget, $composed);+ $touched[] = $notesTarget;+ }+ }++ if ($payload === []) {+ return;+ }++ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would PATCH Jamf computer %s with %s',+ $this->name(),+ $externalSource->external_id,+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ ));++ return;+ }++ $client = new JamfClient(baseUrl: $this->url(), token: $this->credential('token'));+ $client->updateComputerDetail($externalSource->external_id, $payload);++ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Jamf computer %s at paths [%s]',+ $this->name(),+ $externalSource->external_id,+ implode(', ', $touched),+ ));+ }++ /**+ * Map a source-field name to its dotted path in Jamf's+ * computers-inventory-detail JSON. Return null for fields Jamf+ * doesn't expose as writable (hostname is derived from the device+ * itself, not admin-settable).+ */+ private static function sourceFieldToJamfPath(string $field): ?string+ {+ return match ($field) {+ 'asset_tag' => 'userAndLocation.assetTag',+ default => null,+ };+ }++ private function assetValueForSourceField(Asset $asset, string $field): mixed+ {+ return match ($field) {+ 'asset_tag' => $asset->asset_tag,+ default => null,+ };+ }+}diff --git a/app/SyncAdapters/Jamf/JamfClient.php b/app/SyncAdapters/Jamf/JamfClient.phpnew file mode 100644index 0000000000..2c870416df--- /dev/null+++ b/app/SyncAdapters/Jamf/JamfClient.php@@ -0,0 +1,108 @@+<?php++namespace App\SyncAdapters\Jamf;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Jamf Pro API. Owns auth + pagination for the+ * endpoints the sync adapter uses. Yields raw decoded JSON, no+ * normalization (that's the adapter's job).+ *+ * Auth model: a Jamf-generated Personal Access Token (create one under+ * Settings -> System -> API Roles and Clients -> API Roles) passed as+ * a bearer token. This skips the /api/v1/auth/token exchange dance and+ * keeps the credential storage shape identical to the other bearer-+ * token adapters (Fleet, Kandji, JumpCloud).+ *+ * Jamf Pro API reference: https://developer.jamf.com/jamf-pro/reference+ */+class JamfClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $token,+ ) {}++ /**+ * Iterate every managed computer in the Jamf tenant, one page at a+ * time. Returns a generator so callers stream through large fleets+ * without holding the whole list in memory.+ *+ * @return iterable<array<string, mixed>>+ */+ public function computers(int $pageSize = 100): iterable+ {+ $page = 0;++ do {+ $response = $this->request()+ ->get('/api/v1/computers-inventory', [+ 'page' => $page,+ 'page-size' => $pageSize,+ // Only the sections we normalize. skipping the+ // heavier ones (applications, plugins, fonts,+ // certificates) keeps payloads small and stays+ // well under Jamf's per-tenant rate limit.+ 'section' => ['GENERAL', 'HARDWARE', 'OPERATING_SYSTEM', 'USER_AND_LOCATION'],+ ])+ ->throw()+ ->json();++ $results = $response['results'] ?? [];+ foreach ($results as $computer) {+ yield $computer;+ }++ // Jamf returns totalCount on this endpoint. Stop when we've+ // seen enough results or when a short page comes back.+ $total = $response['totalCount'] ?? null;+ $seenSoFar = ($page + 1) * $pageSize;+ $done = count($results) < $pageSize+ || ($total !== null && $seenSoFar >= $total);+ $page++;+ } while (! $done);+ }++ /**+ * List every Site in the Jamf Pro tenant. Used by the adapter's+ * fetchGroups() so admins can map Sites to Snipe-IT companies.+ * Response shape is a bare array of {id, name} objects.+ *+ * @return array<int, array<string, mixed>>+ */+ public function sites(): array+ {+ $response = $this->request()+ ->get('/api/v1/sites')+ ->throw()+ ->json();++ return is_array($response) ? $response : [];+ }++ /**+ * Update a computer's inventory detail via Jamf Pro's newer JSON+ * API. Accepts a partial payload with nested objects like+ * `userAndLocation` (assetTag lives at userAndLocation.assetTag).+ * Fields the caller doesn't include stay untouched.+ *+ * @param array<string, mixed> $payload+ */+ public function updateComputerDetail(string $computerId, array $payload): void+ {+ $this->request()+ ->asJson()+ ->patch('/api/v1/computers-inventory-detail/'.$computerId, $payload)+ ->throw();+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withToken($this->token)+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/JamfSchool/JamfSchoolAdapter.php b/app/SyncAdapters/JamfSchool/JamfSchoolAdapter.phpnew file mode 100644index 0000000000..060d82a2eb--- /dev/null+++ b/app/SyncAdapters/JamfSchool/JamfSchoolAdapter.php@@ -0,0 +1,134 @@+<?php++namespace App\SyncAdapters\JamfSchool;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * Jamf School adapter. Pulls managed-device inventory via the Jamf+ * School (formerly ZuluDesk) API and normalizes it into+ * HostInventoryRecord objects. Distinct product from Jamf Pro: separate+ * API, separate auth model (HTTP Basic with Network ID + API Key), so+ * separate adapter.+ */+class JamfSchoolAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'Jamf School';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://your-subdomain.jamfcloud.com/api';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'network_id',+ 'label' => 'Network ID',+ 'help' => trans('admin/settings/general.sync_adapter_jamf_school_network_id_help'),+ ],+ [+ 'key' => 'api_key',+ 'label' => 'API Key',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_jamf_school_api_key_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'jamf_school_model_identifier' => 'Jamf School Model Identifier',+ 'jamf_school_supervised' => ['label' => 'Jamf School Supervised', 'type' => 'boolean'],+ 'jamf_school_location_id' => 'Jamf School Location ID',+ ];+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return 'Jamf School Location';+ }++ public function fetchGroups(): array+ {+ $client = new JamfSchoolClient(+ baseUrl: $this->url(),+ networkId: $this->credential('network_id'),+ apiKey: $this->credential('api_key'),+ );++ return array_map(+ fn (array $location) => [+ 'id' => (string) ($location['id'] ?? ''),+ 'label' => (string) ($location['name'] ?? $location['id'] ?? '?'),+ ],+ $client->locations(),+ );+ }++ public function pull(): iterable+ {+ $client = new JamfSchoolClient(+ baseUrl: $this->url(),+ networkId: $this->credential('network_id'),+ apiKey: $this->credential('api_key'),+ );++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a Jamf School device payload into the normalized record+ * shape. Jamf School's UDID is stable per enrolled device and is+ * what we key asset_external_sources on.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'UDID'),+ hostname: Arr::get($device, 'name'),+ hardwareSerial: Arr::get($device, 'serialNumber'),+ hardwareModel: Arr::get($device, 'model.name'),+ manufacturer: 'Apple',+ primaryMac: Arr::get($device, 'wifiMacAddress'),+ primaryIp: null,+ os: Arr::get($device, 'os'),+ osVersion: Arr::get($device, 'osVersion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'lastCheckin')),+ assetTag: Arr::get($device, 'assetTag'),+ vendorGroupId: Arr::has($device, 'locationId') ? (string) Arr::get($device, 'locationId') : null,+ extra: [+ 'jamf_school_model_identifier' => Arr::get($device, 'model.identifier'),+ 'jamf_school_supervised' => Arr::get($device, 'isSupervised'),+ 'jamf_school_location_id' => Arr::get($device, 'locationId'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/JamfSchool/JamfSchoolClient.php b/app/SyncAdapters/JamfSchool/JamfSchoolClient.phpnew file mode 100644index 0000000000..d8815a75f0--- /dev/null+++ b/app/SyncAdapters/JamfSchool/JamfSchoolClient.php@@ -0,0 +1,89 @@+<?php++namespace App\SyncAdapters\JamfSchool;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Jamf School (formerly ZuluDesk) API. Owns+ * auth + pagination for the endpoints the sync adapter uses. Yields+ * raw decoded JSON, no normalization (that's the adapter's job).+ *+ * Auth model: HTTP Basic auth with the tenant's Network ID as the+ * username and API key as the password. Both come from the Jamf School+ * admin console under Organization -> Settings -> API. This is a+ * distinct product and API from Jamf Pro (which uses bearer tokens).+ *+ * Jamf School API reference: https://school.jamfcloud.com/api/docs/+ */+class JamfSchoolClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $networkId,+ private readonly string $apiKey,+ ) {}++ /**+ * Iterate every enrolled device in the Jamf School tenant, one+ * page at a time. Returns a generator so callers stream through+ * large fleets without holding the whole list in memory.+ *+ * @return iterable<array<string, mixed>>+ */+ public function devices(int $pageSize = 100): iterable+ {+ $page = 1;++ do {+ $response = $this->request()+ ->get('/devices', [+ 'page' => $page,+ 'pageSize' => $pageSize,+ ])+ ->throw()+ ->json();++ $devices = $response['devices'] ?? [];+ foreach ($devices as $device) {+ yield $device;+ }++ // Jamf School returns a total count on this endpoint. Stop+ // when seen-so-far reaches it, or on a short page as a+ // fallback if the count field is absent.+ $total = $response['count'] ?? null;+ $seenSoFar = ($page - 1) * $pageSize + count($devices);+ $done = count($devices) < $pageSize+ || ($total !== null && $seenSoFar >= $total);+ $page++;+ } while (! $done);+ }++ /**+ * List every Location in the Jamf School tenant. Locations are+ * typically schools within a district. Used by the adapter's+ * fetchGroups() so admins can map Locations to Snipe-IT+ * companies.+ *+ * @return array<int, array<string, mixed>>+ */+ public function locations(): array+ {+ $response = $this->request()+ ->get('/locations')+ ->throw()+ ->json();++ return $response['locations'] ?? (is_array($response) ? $response : []);+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withBasicAuth($this->networkId, $this->apiKey)+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/JumpCloud/JumpCloudAdapter.php b/app/SyncAdapters/JumpCloud/JumpCloudAdapter.phpnew file mode 100644index 0000000000..376bb31a79--- /dev/null+++ b/app/SyncAdapters/JumpCloud/JumpCloudAdapter.php@@ -0,0 +1,113 @@+<?php++namespace App\SyncAdapters\JumpCloud;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * JumpCloud adapter. Pulls managed-system inventory via the JumpCloud+ * Systems API and normalizes it into HostInventoryRecord objects.+ * Auth uses the tenant's static API key in the x-api-key header, not+ * a bearer token.+ */+class JumpCloudAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'JumpCloud';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://console.jumpcloud.com/api';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => 'API Key',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_jumpcloud_token_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'jumpcloud_arch' => 'JumpCloud Architecture',+ 'jumpcloud_os_family' => 'JumpCloud OS Family',+ 'jumpcloud_agent_version' => 'JumpCloud Agent Version',+ 'jumpcloud_active' => ['label' => 'JumpCloud Active', 'type' => 'boolean'],+ ];+ }++ public function pull(): iterable+ {+ $client = new JumpCloudClient(baseUrl: $this->url(), apiKey: $this->credential('token'));++ foreach ($client->systems() as $system) {+ yield $this->normalize($system);+ }+ }++ /**+ * Convert a JumpCloud system payload into the normalized record+ * shape. JumpCloud's `_id` is stable per enrolled system and is+ * what we key asset_external_sources on.+ *+ * The bulk /systems endpoint doesn't return network interfaces, so+ * primaryMac stays null. A future enrichment pass could hit+ * /systems/{id}/networkinterfaces per record to fill it in, at the+ * cost of N+1 requests per sync run.+ *+ * @param array<string, mixed> $system+ */+ private function normalize(array $system): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($system, '_id'),+ hostname: Arr::get($system, 'hostname') ?? Arr::get($system, 'displayName'),+ hardwareSerial: Arr::get($system, 'serialNumber'),+ hardwareModel: Arr::get($system, 'systemType'),+ manufacturer: $this->guessManufacturer(Arr::get($system, 'osFamily')),+ primaryMac: null,+ primaryIp: null,+ os: Arr::get($system, 'os'),+ osVersion: Arr::get($system, 'version'),+ lastSeen: $this->parseTimestamp(Arr::get($system, 'lastContact')),+ extra: [+ 'jumpcloud_arch' => Arr::get($system, 'arch'),+ 'jumpcloud_os_family' => Arr::get($system, 'osFamily'),+ 'jumpcloud_agent_version' => Arr::get($system, 'agentVersion'),+ 'jumpcloud_active' => Arr::get($system, 'active'),+ ],+ );+ }++ /**+ * JumpCloud doesn't return a manufacturer field. Infer from+ * osFamily so downstream mapping still gets a reasonable value.+ * darwin => Apple, windows / linux stay unknown because the vendor+ * varies per hardware.+ */+ private function guessManufacturer(?string $osFamily): ?string+ {+ return $osFamily === 'darwin' ? 'Apple' : null;+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/JumpCloud/JumpCloudClient.php b/app/SyncAdapters/JumpCloud/JumpCloudClient.phpnew file mode 100644index 0000000000..baac53050d--- /dev/null+++ b/app/SyncAdapters/JumpCloud/JumpCloudClient.php@@ -0,0 +1,68 @@+<?php++namespace App\SyncAdapters\JumpCloud;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the JumpCloud Systems API. Owns auth + pagination+ * for the endpoints the sync adapter uses. Yields raw decoded JSON, no+ * normalization (that's the adapter's job).+ *+ * Auth model: the tenant's static API key from the JumpCloud admin+ * console, passed via `x-api-key` header (JumpCloud's convention, not+ * a bearer token like the other adapters).+ *+ * JumpCloud API reference: https://docs.jumpcloud.com/api/1.0+ */+class JumpCloudClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $apiKey,+ ) {}++ /**+ * Iterate every managed system in the JumpCloud tenant, one page at+ * a time. Returns a generator so callers stream through large+ * fleets without holding the whole list in memory.+ *+ * @return iterable<array<string, mixed>>+ */+ public function systems(int $limit = 100): iterable+ {+ $skip = 0;++ do {+ $response = $this->request()+ ->get('/systems', [+ 'limit' => $limit,+ 'skip' => $skip,+ ])+ ->throw()+ ->json();++ $results = $response['results'] ?? [];+ foreach ($results as $system) {+ yield $system;+ }++ // JumpCloud returns totalCount on this endpoint. Stop when+ // seen-so-far reaches it or the vendor sends a short page.+ $total = $response['totalCount'] ?? null;+ $seenSoFar = $skip + count($results);+ $done = count($results) < $limit+ || ($total !== null && $seenSoFar >= $total);+ $skip += $limit;+ } while (! $done);+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withHeaders(['x-api-key' => $this->apiKey])+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/Kandji/KandjiAdapter.php b/app/SyncAdapters/Kandji/KandjiAdapter.phpnew file mode 100644index 0000000000..a802be6d15--- /dev/null+++ b/app/SyncAdapters/Kandji/KandjiAdapter.php@@ -0,0 +1,276 @@+<?php++namespace App\SyncAdapters\Kandji;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * Kandji adapter. Pulls device inventory from a Kandji tenant via the+ * Kandji Enterprise API and normalizes it into HostInventoryRecord+ * objects. Also pushes Snipe-IT-authoritative fields back to Kandji+ * (asset_tag today) when the admin marks the mapping row as 'push'.+ */+class KandjiAdapter extends ConfigurableAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'Kandji';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://your-subdomain.api.kandji.io';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => 'API Token',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_kandji_token_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'kandji_blueprint_id' => 'Kandji Blueprint ID',+ 'kandji_mdm_enabled' => ['label' => 'Kandji MDM Enabled', 'type' => 'boolean'],+ 'kandji_is_missing' => ['label' => 'Kandji Marked Missing', 'type' => 'boolean'],+ ];+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return 'Kandji Blueprint';+ }++ public function fetchGroups(): array+ {+ $client = new KandjiClient(baseUrl: $this->url(), token: $this->credential('token'));++ return array_map(+ fn (array $bp) => [+ 'id' => (string) ($bp['id'] ?? ''),+ 'label' => (string) ($bp['name'] ?? $bp['id'] ?? '?'),+ ],+ $client->blueprints(),+ );+ }++ public function pull(): iterable+ {+ $client = new KandjiClient(baseUrl: $this->url(), token: $this->credential('token'));++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a Kandji device payload into the normalized record shape.+ * Kandji's `device_id` is stable per enrolled device and is what we+ * key asset_external_sources on.+ *+ * The bulk /devices endpoint doesn't return network interfaces, so+ * primaryMac stays null here. A future enrichment pass could hit+ * /devices/{id}/details per record to fill it in, at the cost of+ * N+1 requests per sync run.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'device_id'),+ hostname: Arr::get($device, 'device_name'),+ hardwareSerial: Arr::get($device, 'serial_number'),+ hardwareModel: Arr::get($device, 'model'),+ manufacturer: Arr::get($device, 'platform') === 'Mac' ? 'Apple' : null,+ primaryMac: null,+ primaryIp: null,+ os: Arr::get($device, 'platform'),+ osVersion: Arr::get($device, 'os_version'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'last_check_in')),+ assetTag: Arr::get($device, 'asset_tag'),+ assignedUserEmail: Arr::get($device, 'user.email'),+ assignedUserName: Arr::get($device, 'user.name'),+ vendorGroupId: Arr::has($device, 'assigned_blueprint_id') ? (string) Arr::get($device, 'assigned_blueprint_id') : null,+ extra: [+ 'kandji_blueprint_id' => Arr::get($device, 'assigned_blueprint_id'),+ 'kandji_mdm_enabled' => Arr::get($device, 'mdm_enabled'),+ 'kandji_is_missing' => Arr::get($device, 'is_missing'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }++ /**+ * Kandji's device API accepts writes on any Admin API token so+ * push is always available for a configured instance (no tier+ * gate the way Fleet's manual labels have).+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * Kandji devices carry a single freeform `notes` field that+ * admins commonly repurpose for composed asset info from+ * Snipe-IT. When pushNotesTemplate() is set, we render it and+ * PATCH the notes field alongside any other push-directed+ * fields.+ */+ public function notesFieldTarget(): ?string+ {+ return 'notes';+ }++ /**+ * Push Snipe-IT-authoritative fields to the vendor. Filters the+ * asset's fields down to those marked 'push' in the mapping table+ * for this instance, serializes them into Kandji's field-name+ * shape, and PATCHes the device.+ *+ * Silently no-ops when the asset has never been synced from this+ * instance (no asset_external_sources row -> no vendor device id+ * to write against) or when nothing on the mapping is directed+ * 'push'.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): void+ {+ $pushFields = $this->pushDirectedFields();+ if ($pushFields === []) {+ return;+ }++ // Optional early-exit: if the caller told us which source+ // fields changed and none of them are push-directed, skip+ // the API call entirely. Empty $changedFields = "push all+ // push-directed fields regardless".+ if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {+ return;+ }++ $externalSource = AssetExternalSource::query()+ ->where('asset_id', $asset->id)+ ->where('source', $this->name())+ ->first();++ if ($externalSource === null) {+ return;+ }++ $payload = [];+ foreach ($pushFields as $field) {+ $mapped = self::sourceFieldToKandjiField($field);+ if ($mapped === null) {+ continue;+ }++ $value = $this->assetValueForSourceField($asset, $field);+ if ($value === null) {+ continue;+ }++ $payload[$mapped] = $value;+ }++ // Composed notes: template + effectiveNotesTarget (admin+ // override or adapter default) merge into the same payload+ // so admins can push both an asset_tag AND a composed notes+ // blob in a single API call.+ $template = $this->pushNotesTemplate();+ $notesTarget = $this->effectiveNotesTarget();+ if ($template !== '' && $notesTarget !== null) {+ $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);+ if ($composed !== '') {+ $payload[$notesTarget] = $composed;+ }+ }++ if ($payload === []) {+ return;+ }++ // Dry-run: log the payload we WOULD send and return without+ // hitting Kandji. Lets admins verify their config end-to-end+ // (mapping resolution, direction, credential wiring, external_id+ // lookup) without a real API call.+ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would PATCH Kandji device %s with %s',+ $this->name(),+ $externalSource->external_id,+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ ));++ return;+ }++ $client = new KandjiClient(baseUrl: $this->url(), token: $this->credential('token'));+ $client->updateDevice($externalSource->external_id, $payload);++ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Kandji device %s with fields [%s]',+ $this->name(),+ $externalSource->external_id,+ implode(', ', array_keys($payload)),+ ));+ }++ /**+ * Map a source-field name (from MappingTargets::FIELDS or the+ * adapter's extraFields) to Kandji's device-endpoint form field+ * name. Returns null when there's no writable equivalent, which+ * excludes read-only vendor state like hostname (Kandji derives+ * it from the device itself, not admin metadata).+ */+ private static function sourceFieldToKandjiField(string $field): ?string+ {+ return match ($field) {+ 'asset_tag' => 'asset_tag',+ default => null,+ };+ }++ /**+ * Resolve a Snipe-IT source of truth for a given source-field+ * name. Currently only asset_tag is push-supported for Kandji.+ * Additional fields (notes, assigned_to, etc.) add cases here.+ */+ private function assetValueForSourceField(Asset $asset, string $field): mixed+ {+ return match ($field) {+ 'asset_tag' => $asset->asset_tag,+ default => null,+ };+ }+}diff --git a/app/SyncAdapters/Kandji/KandjiClient.php b/app/SyncAdapters/Kandji/KandjiClient.phpnew file mode 100644index 0000000000..58d1d9173d--- /dev/null+++ b/app/SyncAdapters/Kandji/KandjiClient.php@@ -0,0 +1,116 @@+<?php++namespace App\SyncAdapters\Kandji;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Kandji Enterprise API. Owns auth + pagination+ * for the endpoints the sync adapter uses. Yields raw decoded JSON, no+ * normalization (that's the adapter's job).+ *+ * Kandji API reference: https://api-docs.kandji.io/+ */+class KandjiClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $token,+ ) {}++ /**+ * Iterate every device in the Kandji tenant, one page at a time.+ * Returns a generator so callers stream through large fleets without+ * holding the whole list in memory. Kandji caps limit at 300 and+ * uses offset-based pagination.+ *+ * @return iterable<array<string, mixed>>+ */+ public function devices(int $limit = 300): iterable+ {+ $offset = 0;++ do {+ $response = $this->request()+ ->get('/api/v1/devices', [+ 'limit' => $limit,+ 'offset' => $offset,+ ])+ ->throw()+ ->json();++ // Kandji returns a bare array of device objects on this+ // endpoint (no wrapper). Bail when the vendor returns an+ // unexpected shape rather than iterating over garbage.+ $devices = is_array($response) ? $response : [];++ foreach ($devices as $device) {+ yield $device;+ }++ // Terminate when a short page comes back. No totalCount in+ // Kandji's response for this endpoint so a short page is+ // the accepted end-of-stream signal.+ $done = count($devices) < $limit;+ $offset += $limit;+ } while (! $done);+ }++ /**+ * List every Blueprint in the Kandji tenant. Used by the+ * adapter's fetchGroups() so admins can map Blueprints to+ * Snipe-IT companies. Endpoint returns a paginated list. Walk+ * all pages up to the vendor cap.+ *+ * @return array<int, array<string, mixed>>+ */+ public function blueprints(int $limit = 300): array+ {+ $blueprints = [];+ $offset = 0;++ do {+ $response = $this->request()+ ->get('/api/v1/blueprints', ['limit' => $limit, 'offset' => $offset])+ ->throw()+ ->json();++ $batch = $response['results'] ?? (is_array($response) ? $response : []);+ $blueprints = array_merge($blueprints, $batch);++ $done = count($batch) < $limit;+ $offset += $limit;+ } while (! $done);++ return $blueprints;+ }++ /**+ * Update a device's writable metadata (asset_tag, blueprint,+ * user assignment, etc.). Sends a PATCH to the per-device+ * endpoint with a form-encoded body since Kandji's device API+ * uses form-urlencoded for writes rather than JSON. Fields the+ * caller doesn't include stay untouched.+ *+ * @param array<string, scalar|null> $fields+ */+ public function updateDevice(string $deviceId, array $fields): void+ {+ Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withToken($this->token)+ ->acceptJson()+ ->asForm()+ ->timeout(30)+ ->patch('/api/v1/devices/'.$deviceId, $fields)+ ->throw();+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withToken($this->token)+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/MerakiSystemsManager/MerakiClient.php b/app/SyncAdapters/MerakiSystemsManager/MerakiClient.phpnew file mode 100644index 0000000000..5ef589a303--- /dev/null+++ b/app/SyncAdapters/MerakiSystemsManager/MerakiClient.php@@ -0,0 +1,112 @@+<?php++namespace App\SyncAdapters\MerakiSystemsManager;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Http\Client\Response;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Cisco Meraki Dashboard API for the+ * Systems Manager (SM) module. Owns auth + pagination for the+ * SM devices endpoint.+ *+ * Auth model: Meraki API key from the admin user's profile, passed+ * via the vendor-specific `X-Cisco-Meraki-API-Key` header.+ *+ * Pagination: Meraki returns a `Link` HTTP response header containing+ * a rel=next URL when more pages exist. Follow it until the header+ * is absent. Batch size configurable via `perPage` up to Meraki's+ * cap of 1000.+ */+class MerakiClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $apiKey,+ private readonly string $organizationId,+ ) {}++ /**+ * Iterate every Systems Manager device across every SM-enabled+ * network in the configured organization.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function devices(int $perPage = 500): iterable+ {+ $networks = $this->smNetworks();++ foreach ($networks as $network) {+ $networkId = $network['id'] ?? null;+ if ($networkId === null) {+ continue;+ }++ $url = '/networks/'.$networkId.'/sm/devices?perPage='.$perPage;++ do {+ $response = $this->request()->get($url)->throw();+ $devices = $response->json();++ foreach ((is_array($devices) ? $devices : []) as $device) {+ yield $device + ['_networkId' => $networkId];+ }++ $url = $this->extractNextLink($response);+ } while ($url !== null);+ }+ }++ /**+ * SM-enabled networks in the configured organization. Filters the+ * full networks list down to those with the systemsManager product+ * type so we don't waste API calls on wireless-only or switch-only+ * networks.+ *+ * @return array<int, array<string, mixed>>+ */+ public function smNetworks(): array+ {+ $networks = $this->request()+ ->get('/organizations/'.$this->organizationId.'/networks')+ ->throw()+ ->json();++ return array_values(array_filter(+ is_array($networks) ? $networks : [],+ fn (array $n) => in_array('systemsManager', $n['productTypes'] ?? [], true),+ ));+ }++ /**+ * Follow Meraki's `Link` HTTP header to find the next cursor.+ * Returns null when the current page is the last.+ */+ private function extractNextLink(Response $response): ?string+ {+ $link = $response->header('Link');+ if ($link === '' || $link === null) {+ return null;+ }++ if (preg_match('/<([^>]+)>;\s*rel="?next"?/', $link, $m)) {+ // Meraki returns absolute URLs in the Link header. Strip+ // the base host so the PendingRequest's baseUrl still+ // applies uniformly.+ $parsed = parse_url($m[1]);++ return ($parsed['path'] ?? '/').(isset($parsed['query']) ? '?'.$parsed['query'] : '');+ }++ return null;+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withHeaders(['X-Cisco-Meraki-API-Key' => $this->apiKey])+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/MerakiSystemsManager/MerakiSystemsManagerAdapter.php b/app/SyncAdapters/MerakiSystemsManager/MerakiSystemsManagerAdapter.phpnew file mode 100644index 0000000000..e6f86081ba--- /dev/null+++ b/app/SyncAdapters/MerakiSystemsManager/MerakiSystemsManagerAdapter.php@@ -0,0 +1,101 @@+<?php++namespace App\SyncAdapters\MerakiSystemsManager;++use App\SyncAdapters\Support\ConfigurableAdapter;++/**+ * Cisco Meraki Systems Manager adapter. STUB, registration + settings-+ * page presence exist so the shared /admin/adapters page renders the+ * tab. The pull() against the Meraki Dashboard API+ * (https://api.meraki.com/api/v1/organizations/{orgId}/sm/devices)+ * with an X-Cisco-Meraki-API-Key header is a follow-up.+ *+ * Meraki's API is org-scoped, so a real pull() needs to walk from the+ * API key's accessible organizations down through each org's Systems+ * Manager networks to the device list. The organization ID lives as+ * schema config rather than being discovered per-sync so admins can+ * pin a specific org when the account owns several.+ */+class MerakiSystemsManagerAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'Meraki Systems Manager';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://api.meraki.com/api/v1';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'api_key',+ 'label' => 'API Key',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_meraki_sm_api_key_help'),+ ],+ [+ 'key' => 'organization_id',+ 'label' => 'Organization ID',+ 'help' => trans('admin/settings/general.sync_adapter_meraki_sm_organization_id_help'),+ ],+ ];+ }++ public function pull(): iterable+ {+ $client = new MerakiClient(+ baseUrl: $this->url(),+ apiKey: $this->credential('api_key'),+ organizationId: $this->credential('organization_id'),+ );++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a Meraki SM device payload into the normalized record+ * shape. Meraki's `id` is stable per enrolled device and is what+ * we key asset_external_sources on. Network id is stuffed on+ * every device by the client so we can carry it into extras.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): \App\SyncAdapters\HostInventoryRecord+ {+ return new \App\SyncAdapters\HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) \Illuminate\Support\Arr::get($device, 'id'),+ hostname: \Illuminate\Support\Arr::get($device, 'name')+ ?? \Illuminate\Support\Arr::get($device, 'systemModel'),+ hardwareSerial: \Illuminate\Support\Arr::get($device, 'serialNumber'),+ hardwareModel: \Illuminate\Support\Arr::get($device, 'systemModel'),+ manufacturer: \Illuminate\Support\Arr::get($device, 'manufacturer'),+ primaryMac: \Illuminate\Support\Arr::get($device, 'wifiMac'),+ primaryIp: \Illuminate\Support\Arr::get($device, 'ip'),+ os: \Illuminate\Support\Arr::get($device, 'osName'),+ osVersion: \Illuminate\Support\Arr::get($device, 'systemType'),+ lastSeen: $this->parseTimestamp(\Illuminate\Support\Arr::get($device, 'lastConnectAt')),+ extra: [+ 'meraki_network_id' => \Illuminate\Support\Arr::get($device, '_networkId'),+ 'meraki_tags' => \Illuminate\Support\Arr::get($device, 'tags'),+ 'meraki_user' => \Illuminate\Support\Arr::get($device, 'ownerUsername'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?\Carbon\Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return \Carbon\Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/Mosyle/MosyleAdapter.php b/app/SyncAdapters/Mosyle/MosyleAdapter.phpnew file mode 100644index 0000000000..1fa4c99f29--- /dev/null+++ b/app/SyncAdapters/Mosyle/MosyleAdapter.php@@ -0,0 +1,263 @@+<?php++namespace App\SyncAdapters\Mosyle;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * Mosyle adapter. Pulls device inventory from a Mosyle tenant (either+ * Manager or Business) via the Mosyle API and normalizes it into+ * HostInventoryRecord objects. The configured base URL determines+ * which product the adapter targets. Also pushes Snipe-IT-+ * authoritative asset_tag back via Mosyle's serial-number-scoped+ * set_asset_tag operation.+ */+class MosyleAdapter extends ConfigurableAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'Mosyle';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://managerapi.mosyle.com/v2';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => 'Access Token',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_mosyle_token_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'mosyle_user_id' => 'Mosyle User ID',+ 'mosyle_supervised' => ['label' => 'Mosyle Supervised', 'type' => 'boolean'],+ ];+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return 'Mosyle Location';+ }++ public function fetchGroups(): array+ {+ $client = new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));++ return array_map(+ fn (array $location) => [+ 'id' => (string) ($location['id'] ?? $location['locationid'] ?? ''),+ 'label' => (string) ($location['name'] ?? $location['location_name'] ?? $location['id'] ?? '?'),+ ],+ $client->locations(),+ );+ }++ public function pull(): iterable+ {+ $client = new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a Mosyle device payload into the normalized record shape.+ * Mosyle's `deviceudid` is stable per enrolled device and is what+ * we key asset_external_sources on.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'deviceudid'),+ hostname: Arr::get($device, 'device_name'),+ hardwareSerial: Arr::get($device, 'serial_number'),+ hardwareModel: Arr::get($device, 'device_model_name'),+ manufacturer: 'Apple',+ primaryMac: Arr::get($device, 'wifi_mac_address'),+ primaryIp: Arr::get($device, 'ip_address'),+ os: Arr::get($device, 'os'),+ osVersion: Arr::get($device, 'osversion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'date_info')),+ assetTag: Arr::get($device, 'asset_tag'),+ assignedUserEmail: Arr::get($device, 'useremail'),+ assignedUserName: Arr::get($device, 'usename'),+ vendorGroupId: Arr::has($device, 'locationid') ? (string) Arr::get($device, 'locationid') : null,+ extra: [+ 'mosyle_user_id' => Arr::get($device, 'userid'),+ 'mosyle_supervised' => Arr::get($device, 'is_supervised'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }++ /**+ * Mosyle writes are token-scoped. Same credential used for pull+ * works for push when the API token has the "Devices - Write"+ * permission. No tier / license gate, so canPush is always true+ * for a configured instance.+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * Mosyle exposes a freeform notes field per device via the+ * `set_notes_by_serial_number` operation. Returning the field+ * name here signals to the push framework that composed notes+ * can flow to this vendor.+ */+ public function notesFieldTarget(): ?string+ {+ return 'notes';+ }++ /**+ * Push Snipe-IT asset_tag back to Mosyle. Mosyle's write API is+ * a single POST endpoint dispatched by an `operation` field.+ * `set_asset_tag_by_serial_number` targets the device by serial+ * (Mosyle also accepts UDID, but serial is what we cached from+ * pull and is more stable across re-enrollment).+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): void+ {+ $pushFields = $this->pushDirectedFields();+ if ($pushFields === []) {+ return;+ }++ if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {+ return;+ }++ $externalSource = AssetExternalSource::query()+ ->where('asset_id', $asset->id)+ ->where('source', $this->name())+ ->first();++ if ($externalSource === null) {+ return;+ }++ // Mosyle keys writes by serial number, not the UDID we+ // stored as external_id. Fall back to the external_id if+ // the asset has no serial (Mosyle Business uses serial ==+ // external_id for some device types).+ $serial = $asset->serial;+ if ($serial === null || $serial === '') {+ $serial = $externalSource->external_id;+ }+ if ($serial === '' || $serial === null) {+ return;+ }++ $pushedFields = [];+ $client = null;++ foreach ($pushFields as $field) {+ if ($field !== 'asset_tag') {+ continue;+ }++ $value = $this->assetValueForSourceField($asset, $field);+ if ($value === null || $value === '') {+ continue;+ }++ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would set Mosyle device serial=%s asset_tag=%s',+ $this->name(),+ $serial,+ $value,+ ));+ $pushedFields[] = $field;++ continue;+ }++ $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));+ $client->updateDeviceAssetTagBySerial($serial, (string) $value);+ $pushedFields[] = $field;+ }++ // Composed notes push. Independent from the asset_tag push+ // because Mosyle's write API dispatches per-op, so notes get+ // a second POST to /devices with the notes operation.+ $template = $this->pushNotesTemplate();+ if ($template !== '') {+ $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);+ if ($composed !== '') {+ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would set Mosyle device serial=%s notes=%s',+ $this->name(),+ $serial,+ $composed,+ ));+ } else {+ $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));+ $client->updateDeviceNotesBySerial($serial, $composed);+ }+ $pushedFields[] = 'notes';+ }+ }++ if ($pushedFields === []) {+ return;+ }++ if (! $this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Mosyle device serial=%s fields [%s]',+ $this->name(),+ $serial,+ implode(', ', $pushedFields),+ ));+ }+ }++ private function assetValueForSourceField(Asset $asset, string $field): mixed+ {+ return match ($field) {+ 'asset_tag' => $asset->asset_tag,+ default => null,+ };+ }+}diff --git a/app/SyncAdapters/Mosyle/MosyleClient.php b/app/SyncAdapters/Mosyle/MosyleClient.phpnew file mode 100644index 0000000000..3f259540c6--- /dev/null+++ b/app/SyncAdapters/Mosyle/MosyleClient.php@@ -0,0 +1,134 @@+<?php++namespace App\SyncAdapters\Mosyle;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Mosyle API. Owns auth + pagination for the+ * endpoints the sync adapter uses. Yields raw decoded JSON, no+ * normalization (that's the adapter's job).+ *+ * Auth model: bearer access token generated in the Mosyle admin console+ * (Account -> API). The same token works for both Mosyle Manager v2+ * (https://managerapi.mosyle.com/v2) and Mosyle Business v1+ * (https://businessapi.mosyle.com/v1). the base URL configured on the+ * adapter determines which product this instance talks to.+ *+ * Mosyle's devices endpoint takes POST with a JSON body (not GET with+ * query params like the other vendors here), which is unusual but+ * documented and stable.+ *+ * Mosyle API reference: https://school.mosyle.com/api/docs+ */+class MosyleClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $token,+ ) {}++ /**+ * Iterate every managed device in the Mosyle tenant, one page at a+ * time. Returns a generator so callers stream through large fleets+ * without holding the whole list in memory.+ *+ * @return iterable<array<string, mixed>>+ */+ public function devices(int $perPage = 200): iterable+ {+ $page = 1;++ do {+ $response = $this->request()+ ->post('/devices', [+ 'options' => [+ 'page' => $page,+ 'per_page' => $perPage,+ ],+ ])+ ->throw()+ ->json();++ // Mosyle's response nests devices under+ // response[0].response.rows on Manager v2 and under+ // response.devices on Business v1. Try both shapes so this+ // client works against either product.+ $rows = $response['response'][0]['response']['rows']+ ?? $response['response']['devices']+ ?? [];++ foreach ($rows as $device) {+ yield $device;+ }++ $done = count($rows) < $perPage;+ $page++;+ } while (! $done);+ }++ /**+ * List every Location in the Mosyle tenant. Used by the+ * adapter's fetchGroups() so admins can map Locations to+ * Snipe-IT companies. Mosyle uses POST for reads (same shape+ * as devices()).+ *+ * @return array<int, array<string, mixed>>+ */+ public function locations(): array+ {+ $response = $this->request()+ ->post('/locations', [])+ ->throw()+ ->json();++ return $response['response'][0]['response']['rows']+ ?? $response['response']['locations']+ ?? [];+ }++ /**+ * Update writable per-device metadata by serial number. Mosyle's+ * write API is a single POST endpoint dispatched by the+ * `operation` field. `set_asset_tag_by_serial_number` sets the+ * device's asset_tag field per Mosyle's Manager v2 API. Fields+ * the caller doesn't include stay untouched.+ */+ public function updateDeviceAssetTagBySerial(string $serial, string $assetTag): void+ {+ $this->request()+ ->post('/devices', [+ 'operation' => 'set_asset_tag_by_serial_number',+ 'serial_number' => $serial,+ 'asset_tag' => $assetTag,+ ])+ ->throw();+ }++ /**+ * Set the device's notes field. Same operation-dispatch shape+ * as asset_tag. Mosyle Manager v2 exposes `set_notes_by_serial_number`+ * for admin freeform notes. On tenants where the operation+ * doesn't exist Mosyle returns a 4xx that surfaces in the log.+ */+ public function updateDeviceNotesBySerial(string $serial, string $notes): void+ {+ $this->request()+ ->post('/devices', [+ 'operation' => 'set_notes_by_serial_number',+ 'serial_number' => $serial,+ 'notes' => $notes,+ ])+ ->throw();+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withToken($this->token)+ ->acceptJson()+ ->asJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.phpnew file mode 100644index 0000000000..9816278e8a--- /dev/null+++ b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php@@ -0,0 +1,287 @@+<?php++namespace App\SyncAdapters\NinjaOne;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * NinjaOne (formerly NinjaRMM) adapter. Pulls managed devices from the+ * REST API v2 (/v2/devices-detailed) via an OAuth 2.0 client-credentials+ * application, keyed on NinjaOne's stable device id.+ *+ * NinjaOne is region-hosted: `app.ninjarmm.com` (US), `eu.ninjarmm.com`+ * (EU), `oc.ninjarmm.com` (AU/NZ), `ca.ninjarmm.com` (CA). Admins pick+ * the region-appropriate host in the Base URL field so the OAuth token+ * endpoint and the devices endpoint stay on the same host (NinjaOne+ * doesn't split the two the way Microsoft Graph does).+ *+ * client_id is non-secret per OAuth 2.0 convention and stored plain+ * text so admins can audit which OAuth application a Snipe-IT instance+ * is talking to. client_secret is encrypted at rest.+ *+ * Push story: NinjaOne has no first-class asset_tag field, but the+ * admin can create per-device Custom Fields under Administration ->+ * Devices -> Custom Fields. Push writes to whichever custom field name+ * the admin puts in the "Asset Tag Custom Field Name" schema slot. If+ * empty, push silently no-ops (nothing to write to).+ */+class NinjaOneAdapter extends ConfigurableAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'NinjaOne';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://app.ninjarmm.com';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'client_id',+ 'label' => 'Client ID',+ 'help' => trans('admin/settings/general.sync_adapter_ninjaone_client_id_help'),+ ],+ [+ 'key' => 'client_secret',+ 'label' => 'Client Secret',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_ninjaone_client_secret_help'),+ ],+ [+ 'key' => 'asset_tag_custom_field',+ 'label' => 'Asset Tag Custom Field Name',+ 'required' => false,+ 'help' => trans('admin/settings/general.sync_adapter_ninjaone_asset_tag_field_help'),+ ],+ ];+ }++ public function pull(): iterable+ {+ $client = new NinjaOneClient(+ baseUrl: $this->url(),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ );++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a NinjaOne device payload into the normalized record+ * shape. NinjaOne's `id` is a stable long integer per registered+ * agent. We key asset_external_sources on it as a string.+ *+ * Hostname preference walks systemName -> dnsName -> netbiosName+ * because Ninja fills them opportunistically depending on OS and+ * agent version. Serial preference walks the SMBIOS system serial+ * first, then falls back to the BIOS serial (VM hosts often only+ * populate one or the other).+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'id'),+ hostname: Arr::get($device, 'systemName')+ ?? Arr::get($device, 'dnsName')+ ?? Arr::get($device, 'netbiosName'),+ hardwareSerial: Arr::get($device, 'system.serialNumber')+ ?? Arr::get($device, 'system.biosSerialNumber')+ ?? Arr::get($device, 'serialNumber'),+ hardwareModel: Arr::get($device, 'system.model')+ ?? Arr::get($device, 'model'),+ manufacturer: Arr::get($device, 'system.manufacturer')+ ?? Arr::get($device, 'manufacturer'),+ primaryMac: null, // Ninja returns per-adapter MACs via a separate endpoint; not worth an extra call per device today+ primaryIp: Arr::get($device, 'publicIP'),+ os: Arr::get($device, 'os.name') ?? Arr::get($device, 'nodeClass'),+ osVersion: Arr::get($device, 'os.buildNumber')+ ?? Arr::get($device, 'os.releaseId'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'lastContact')),+ assignedUserEmail: null,+ assignedUserName: Arr::get($device, 'userTitle'),+ vendorGroupId: (string) (Arr::get($device, 'organizationId') ?? ''),+ extra: [+ 'ninjaone_node_class' => Arr::get($device, 'nodeClass'),+ 'ninjaone_organization_id' => Arr::get($device, 'organizationId'),+ 'ninjaone_location_id' => Arr::get($device, 'locationId'),+ 'ninjaone_offline' => Arr::get($device, 'offline'),+ 'ninjaone_chassis_type' => Arr::get($device, 'chassisType'),+ ],+ );+ }++ /**+ * NinjaOne emits lastContact as a Unix epoch (seconds, sometimes+ * fractional). Bail on absent / zero values so we don't record+ * "device last seen in 1970".+ */+ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '' || $value === 0) {+ return null;+ }++ return Carbon::createFromTimestamp((float) $value);+ }++ /**+ * NinjaOne push is always available in principle. Per-write+ * validity depends on the admin having created the custom field+ * whose name is in the schema slot. Not a canPush gate because+ * "field not configured" is different from "vendor doesn't+ * support push at all".+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * NinjaOne has no first-class freeform notes field. Composed+ * notes would require another admin-configured custom field+ * (same pattern as asset_tag) which we can add if there's demand.+ */+ public function notesFieldTarget(): ?string+ {+ return null;+ }++ /**+ * Push Snipe-IT asset_tag to a NinjaOne custom field. NinjaOne+ * doesn't expose a top-level asset_tag column, so the admin must+ * pre-create a custom field in the NinjaOne dashboard and put its+ * name in the "Asset Tag Custom Field Name" schema slot. If the+ * slot is blank, push silently no-ops (nothing to write to).+ * If the slot has a name but no such field exists in NinjaOne,+ * NinjaOne returns a 4xx and the error surfaces in the log.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): void+ {+ $pushFields = $this->pushDirectedFields();+ if ($pushFields === []) {+ return;+ }++ if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {+ return;+ }++ $externalSource = AssetExternalSource::query()+ ->where('asset_id', $asset->id)+ ->where('source', $this->name())+ ->first();++ if ($externalSource === null) {+ return;+ }++ $customFieldName = $this->credentialOrNull('asset_tag_custom_field');+ if ($customFieldName === null || $customFieldName === '') {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push: skipped asset %d (no Ninja custom field name configured)',+ $this->name(),+ $asset->id,+ ));++ return;+ }++ $payload = [];+ foreach ($pushFields as $field) {+ if ($field !== 'asset_tag') {+ continue;+ }+ $value = $this->assetValueForSourceField($asset, $field);+ if ($value === null || $value === '') {+ continue;+ }+ $payload[$customFieldName] = $value;+ }++ // Composed notes go into a separate admin-named Custom Field+ // via the same /custom-fields PATCH endpoint. Ninja accepts+ // multiple field name / value pairs in one request, so we+ // merge asset_tag + notes when both are configured. Admin+ // sets the notes-target field via the composed-notes fieldset+ // override. Nothing default because Ninja has no built-in+ // notes concept for us to guess.+ $template = $this->pushNotesTemplate();+ $notesTarget = $this->effectiveNotesTarget();+ if ($template !== '' && $notesTarget !== null) {+ $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);+ if ($composed !== '') {+ $payload[$notesTarget] = $composed;+ }+ }++ if ($payload === []) {+ return;+ }++ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would PATCH Ninja device %s custom-fields %s',+ $this->name(),+ $externalSource->external_id,+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ ));++ return;+ }++ $client = new NinjaOneClient(+ baseUrl: $this->url(),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ );+ $client->updateDeviceCustomFields($externalSource->external_id, $payload);++ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Ninja device %s custom field "%s"',+ $this->name(),+ $externalSource->external_id,+ $customFieldName,+ ));+ }++ private function assetValueForSourceField(Asset $asset, string $field): mixed+ {+ return match ($field) {+ 'asset_tag' => $asset->asset_tag,+ default => null,+ };+ }++ /**+ * credential() throws when the key is absent. For optional fields+ * (required=false in the schema) we want a nullable read, so wrap+ * with a catch and return null.+ */+ private function credentialOrNull(string $key): ?string+ {+ try {+ return $this->credential($key);+ } catch (\Throwable) {+ return null;+ }+ }+}diff --git a/app/SyncAdapters/NinjaOne/NinjaOneClient.php b/app/SyncAdapters/NinjaOne/NinjaOneClient.phpnew file mode 100644index 0000000000..04ac9a7119--- /dev/null+++ b/app/SyncAdapters/NinjaOne/NinjaOneClient.php@@ -0,0 +1,118 @@+<?php++namespace App\SyncAdapters\NinjaOne;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the NinjaOne (formerly NinjaRMM) REST API v2.+ * Handles OAuth 2.0 client-credentials token exchange against the+ * region-scoped token endpoint and cursor-based pagination through+ * the /v2/devices endpoint.+ *+ * Auth model: OAuth application (client_id + client_secret) issued+ * from Administration -> Apps -> API in the NinjaOne dashboard.+ * Token exchange POSTs to /ws/oauth/token with scope=monitoring.+ * The returned bearer is valid for ~60 minutes and is cached on+ * this instance for the life of the sync run.+ *+ * Pagination: /v2/devices returns a flat array. Cursor forward using+ * `?after=<lastId>&pageSize=N` until a short page comes back.+ */+class NinjaOneClient+{+ private ?string $token = null;++ public function __construct(+ private readonly string $baseUrl,+ private readonly string $clientId,+ private readonly string $clientSecret,+ ) {}++ /**+ * Iterate every device visible to the OAuth application. Uses+ * the detailed device shape (`?df=os,references`) so we get the+ * nested os object + org/location references in one call rather+ * than hydrating per-device on the client side.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function devices(int $pageSize = 500): iterable+ {+ $after = 0;++ do {+ $devices = $this->request()+ ->get('/v2/devices-detailed', [+ 'pageSize' => $pageSize,+ 'after' => $after,+ ])+ ->throw()+ ->json();++ $devices = is_array($devices) ? $devices : [];++ foreach ($devices as $device) {+ yield $device;+ }++ $count = count($devices);+ if ($count > 0) {+ $after = (int) ($devices[$count - 1]['id'] ?? 0);+ }+ } while ($count === $pageSize && $after > 0);+ }++ /**+ * Fetch (or reuse) a bearer token via OAuth 2.0 client-credentials.+ * The scope=monitoring value is the minimum needed for read access+ * to the devices endpoint. Broader scopes (management, control)+ * aren't required because sync is pull-only.+ */+ private function bearer(): string+ {+ if ($this->token !== null) {+ return $this->token;+ }++ $response = Http::asForm()+ ->timeout(30)+ ->post(rtrim($this->baseUrl, '/').'/ws/oauth/token', [+ 'grant_type' => 'client_credentials',+ 'client_id' => $this->clientId,+ 'client_secret' => $this->clientSecret,+ 'scope' => 'monitoring',+ ])+ ->throw()+ ->json();++ return $this->token = (string) ($response['access_token'] ?? '');+ }++ /**+ * Update a device's custom field values. NinjaOne exposes no+ * first-class asset_tag field, but admins can create their own+ * "custom fields" per-device and write to them via+ * PATCH /v2/device/{id}/custom-fields. Body is a flat map of+ * custom-field-name -> value. NinjaOne rejects names that don't+ * exist on the device role's custom-field schema.+ *+ * @param array<string, scalar|null> $fields+ */+ public function updateDeviceCustomFields(string $deviceId, array $fields): void+ {+ $this->request()+ ->asJson()+ ->patch('/v2/device/'.$deviceId.'/custom-fields', $fields)+ ->throw();+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withToken($this->bearer())+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/Osctrl/OsctrlAdapter.php b/app/SyncAdapters/Osctrl/OsctrlAdapter.phpnew file mode 100644index 0000000000..deb91da645--- /dev/null+++ b/app/SyncAdapters/Osctrl/OsctrlAdapter.php@@ -0,0 +1,98 @@+<?php++namespace App\SyncAdapters\Osctrl;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * osctrl adapter. Pulls osquery-enrolled node inventory from an osctrl+ * instance and normalizes it into HostInventoryRecord objects.+ *+ * osctrl installs can host multiple osquery environments (prod, dev,+ * staging, etc.). the Environment schema field pins this instance to+ * one of them. Set up a second sync-adapter instance per environment+ * when a single osctrl install serves multiple.+ */+class OsctrlAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'osctrl';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => 'API Token',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_osctrl_token_help'),+ ],+ [+ 'key' => 'environment',+ 'label' => 'Environment',+ 'help' => trans('admin/settings/general.sync_adapter_osctrl_environment_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'osctrl_environment' => 'osctrl Environment',+ 'osctrl_osquery_version' => 'osquery Version',+ 'osctrl_cpu_type' => 'CPU Type',+ ];+ }++ public function pull(): iterable+ {+ $client = new OsctrlClient(baseUrl: $this->url(), token: $this->credential('token'));++ foreach ($client->nodes($this->credential('environment')) as $node) {+ yield $this->normalize($node);+ }+ }++ /**+ * Convert an osctrl node payload into the normalized record shape.+ * osctrl's `uuid` is stable per enrolled node and is what we key+ * asset_external_sources on.+ *+ * @param array<string, mixed> $node+ */+ private function normalize(array $node): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($node, 'uuid'),+ hostname: Arr::get($node, 'hostname') ?? Arr::get($node, 'localname'),+ hardwareSerial: Arr::get($node, 'hardware_serial'),+ hardwareModel: Arr::get($node, 'hardware_model'),+ manufacturer: Arr::get($node, 'hardware_vendor'),+ primaryMac: null,+ primaryIp: Arr::get($node, 'ip_address'),+ os: Arr::get($node, 'platform'),+ osVersion: Arr::get($node, 'platform_version'),+ lastSeen: $this->parseTimestamp(Arr::get($node, 'last_seen')),+ extra: [+ 'osctrl_environment' => Arr::get($node, 'environment'),+ 'osctrl_osquery_version' => Arr::get($node, 'osquery_version'),+ 'osctrl_cpu_type' => Arr::get($node, 'cpu_type'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/Osctrl/OsctrlClient.php b/app/SyncAdapters/Osctrl/OsctrlClient.phpnew file mode 100644index 0000000000..08e4b3f4c2--- /dev/null+++ b/app/SyncAdapters/Osctrl/OsctrlClient.php@@ -0,0 +1,59 @@+<?php++namespace App\SyncAdapters\Osctrl;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the osctrl Admin API. Owns auth for the nodes+ * endpoint the sync adapter uses. Yields raw decoded JSON, no+ * normalization (that's the adapter's job).+ *+ * osctrl is environment-scoped: each install can host multiple osquery+ * enrollment environments (prod, dev, staging, etc.) and the API path+ * takes the environment name. Callers pass it into nodes().+ *+ * Auth model: JWT bearer token generated in the osctrl admin console+ * (Users -> API tokens).+ *+ * osctrl API reference: https://osctrl.net/usage/api/+ */+class OsctrlClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $token,+ ) {}++ /**+ * List every enrolled node in the given osctrl environment. The+ * nodes endpoint returns the whole list in a single response, so+ * no pagination is needed. the generator shape is kept for+ * consistency with the other adapters.+ *+ * @return iterable<array<string, mixed>>+ */+ public function nodes(string $environment): iterable+ {+ $response = $this->request()+ ->get('/api/v1/nodes/'.$environment.'/all')+ ->throw()+ ->json();++ // osctrl returns a bare array of node objects on this endpoint.+ $nodes = is_array($response) ? $response : [];++ foreach ($nodes as $node) {+ yield $node;+ }+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withToken($this->token)+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/PushableAdapter.php b/app/SyncAdapters/PushableAdapter.phpnew file mode 100644index 0000000000..c0561a4307--- /dev/null+++ b/app/SyncAdapters/PushableAdapter.php@@ -0,0 +1,68 @@+<?php++namespace App\SyncAdapters;++use App\Models\Asset;++/**+ * Marker + contract for adapters that support pushing Snipe-IT-owned+ * field values back to the vendor (Snipe-IT asset_tag -> vendor+ * asset_tag, Snipe-IT notes -> vendor notes, etc.). Kept separate+ * from HostInventoryAdapter so pull-only vendors (osctrl, Zentral,+ * UniFi) don't have to stub anything.+ *+ * Adapters that implement this ALSO implement HostInventoryAdapter+ * in practice — the two directions share credentials, base URL, and+ * asset identity (asset_external_sources.external_id). The interfaces+ * stay separate so an adapter can be pull-only, push-only, or both.+ */+interface PushableAdapter+{+ /**+ * Runtime check: is push actually available for this instance+ * right now? Adapters return false when a vendor-side gate is+ * in effect (Fleet manual labels are Premium-only, Jamf writes+ * need extra role scopes, etc.) so the settings-page UI hides+ * the push controls instead of letting admins configure a path+ * that will 403 at execution time.+ *+ * Default implementations may return true unconditionally. The+ * check is opt-in per adapter.+ */+ public function canPush(): bool;++ /**+ * Name (or dotted path) of the vendor's single freeform notes+ * field that admins can compose from a template. Return null+ * when the vendor has no such field (or when routing composed+ * notes would be a semantic stretch, e.g. hostname).+ *+ * Push implementations render pushNotesTemplate() through+ * NotesComposer and set the composed string on this field's+ * position in the outgoing payload.+ */+ public function notesFieldTarget(): ?string;++ /**+ * Push the currently-configured `push`-direction fields for one+ * asset to the vendor. Implementations are responsible for:+ * - Resolving the vendor-side external_id from the asset's+ * asset_external_sources row scoped to this adapter's instance+ * - Filtering the field set to those directed 'push' via+ * ConfigurableAdapter::directionFor()+ * - Serializing each field into the vendor's expected shape+ * - Sending the write call+ *+ * Silent no-op is acceptable when the asset has no external_source+ * row for this instance (never synced from here, so we have no+ * vendor-side id to write against).+ *+ * @param array<int, string> $changedFields+ * Optional list of source-field names (hostname, asset_tag,+ * etc.) that changed and prompted this push. Implementations+ * may use this to skip an API call when no push-direction field+ * is in the changed set. When empty, treat as "push everything+ * marked push-direction".+ */+ public function push(Asset $asset, array $changedFields = []): void;+}diff --git a/app/SyncAdapters/Support/ConfigurableAdapter.php b/app/SyncAdapters/Support/ConfigurableAdapter.phpnew file mode 100644index 0000000000..92849653fb--- /dev/null+++ b/app/SyncAdapters/Support/ConfigurableAdapter.php@@ -0,0 +1,763 @@+<?php++namespace App\SyncAdapters\Support;++use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Rules\ExternalUrl;+use App\SyncAdapters\HostInventoryAdapter;+use Illuminate\Http\Request;+use Illuminate\Support\Facades\Crypt;++/**+ * The single base class every host-inventory adapter extends. Owns+ * every piece of behavior that's the same across adapters regardless+ * of auth shape: URL storage with SSRF-guarded validation, encrypted+ * secret storage, blank-preserves-existing save semantics, active ++ * heartbeat toggles, per-field target mapping, isEnabled().+ *+ * The one thing subclasses declare is their credentialSchema(): a+ * list of the auth fields the vendor requires and whether each is a+ * secret (masked with a show/hide toggle) or plain text. That's+ * enough for the shared blade partial to render the form, for+ * saveConfig() to persist correctly, for isEnabled() to enforce+ * required-cred presence, and for the sync path to read decrypted+ * values via credential().+ *+ * Auth shapes currently modeled by schema alone:+ * - single API token (Fleet, Kandji, Jamf Pro, osctrl, Zentral, JumpCloud)+ * - dual key pair (Addigy, Datto RMM)+ * - OAuth 2.0 client credentials (Intune, Google Workspace, Azure AD)+ *+ * Auth shapes we can add later without touching the base. Schema+ * gains a `type` value beyond text/password (file upload for JSON+ * key files and certs, oauth_button for browser-redirect flows,+ * textarea for pasted private keys):+ * - Google service account (file upload)+ * - Apple ABM/ASM (certificate + private key)+ * - Slack / any browser-redirect OAuth (oauth_button + callback)+ * - AWS SigV4 (still three text/password fields plus a region)+ * - Basic auth (still two fields, no new type)+ */+abstract class ConfigurableAdapter implements HostInventoryAdapter+{+ public function __construct(protected readonly SyncAdapterInstance $instance) {}++ /** Display label for the adapter TYPE (not the instance). Shown in the "Add adapter" dropdown. */+ abstract public static function typeLabel(): string;++ /** Vendor-specific inventory fetch. Yield HostInventoryRecord objects. */+ abstract public function pull(): iterable;++ /**+ * Declare this adapter's authentication field schema. The base+ * class drives every settings-page, storage, validation, and+ * enable-check decision off this list. Adapters typically have+ * only this and pull() to think about.+ *+ * Field entry keys:+ * - key (required) storage key AND form-field-name suffix+ * - label (required) display label rendered next to the input+ * - secret (optional, default false) render as password with+ * show/hide toggle AND encrypt the value at rest+ * - required (optional, default true) treat as required for the+ * isEnabled() gate. UI hint is up to the label copy+ * - help (optional, default null) inline help text under the+ * field, passed straight to `<x-form.row help_text=...>`+ *+ * @return array<int, array{key: string, label: string, secret?: bool, required?: bool, help?: string|null}>+ */+ abstract public function credentialSchema(): array;++ /**+ * Adapter-specific extra fields the vendor emits, keyed by the+ * extra-array key from HostInventoryRecord. Values are either a+ * plain string label (defaults to text type) or an array shaped+ * ['label' => 'Human Label', 'type' => 'text' | 'boolean'].+ *+ * Type filters the target pool via MappingTargets::optionsForExtra:+ * 'text' offers text/textarea/markdown-textarea custom fields,+ * 'boolean' offers checkbox fields. Extras never route to native+ * or external targets by design.+ *+ * Adapters that don't emit extras leave this empty.+ *+ * @return array<string, string|array{label: string, type?: string}>+ */+ public function extraFields(): array+ {+ return [];+ }++ public function name(): string+ {+ return $this->instance->slug;+ }++ public function label(): string+ {+ return $this->instance->label;+ }++ public function isActive(): bool+ {+ return $this->instance->active;+ }++ public function isBuiltIn(): bool+ {+ return $this->instance->built_in;+ }++ public function isEnabled(): bool+ {+ if (! $this->instance->active) {+ return false;+ }++ if (empty(SyncAdapterConfig::get($this->instance->id, 'url'))) {+ return false;+ }++ foreach ($this->credentialSchema() as $field) {+ if (($field['required'] ?? true) && ! SyncAdapterConfig::has($this->instance->id, $field['key'])) {+ return false;+ }+ }++ return true;+ }++ /**+ * Three-state readiness for the settings-page tab indicator:+ *+ * - 'active' = will sync (Active toggle on AND URL + required credentials all present)+ * - 'partial' = Active toggle on but the config is incomplete (admin turned it on before finishing setup)+ * - 'inactive' = Active toggle off (regardless of whether config exists, this is the "off" state)+ *+ * Kept separate from isEnabled() so the tab indicator can distinguish+ * "not turned on yet" from "turned on but not working yet", which+ * needs different admin attention.+ */+ public function readinessStatus(): string+ {+ if ($this->isEnabled()) {+ return 'active';+ }++ return $this->instance->active ? 'partial' : 'inactive';+ }++ public function settingsView(): string+ {+ return 'settings.adapters.adapter_credentials';+ }++ /**+ * Rules the controller enforces before saveConfig() runs.+ * ExternalUrl blocks loopback / RFC-1918 / cloud-metadata targets+ * so an admin can't turn Snipe-IT into an SSRF primitive by+ * pointing at 127.0.0.1 or 169.254.169.254. Credential fields+ * stay nullable at rules-time so admins can save a URL-only+ * draft while they go fetch credentials from the vendor console.+ */+ public function validationRules(): array+ {+ $slug = $this->instance->slug;++ $rules = [+ $slug.'_url' => ['required', new ExternalUrl],+ $slug.'_asset_tag_pattern' => ['nullable', 'string', 'max:191'],+ $slug.'_default_category_id' => ['required', 'integer', 'exists:categories,id'],+ $slug.'_default_status_id' => ['required', 'integer', 'exists:status_labels,id'],+ $slug.'_user_match_strategy' => ['nullable', 'string', 'in:none,email,username,username_then_email'],+ ];++ foreach ($this->credentialSchema() as $field) {+ // Auth fields default to required so admins can't save a+ // half-configured adapter that then silently refuses to+ // sync because isEnabled() returns false. Secret fields+ // are pre-populated with the decrypted value on the+ // settings page, so submission always carries a value+ // unless the admin explicitly cleared it (which is an+ // error worth surfacing). Adapters declaring a truly+ // optional credential set `required => false`.+ $required = $field['required'] ?? true;++ $rules[$slug.'_'.$field['key']] = [+ $required ? 'required' : 'nullable',+ 'string',+ ];+ }++ return $rules;+ }++ public function saveConfig(Request $request): void+ {+ $slug = $this->instance->slug;++ SyncAdapterConfig::put($this->instance->id, 'url', $request->input($slug.'_url'));++ // Blank input preserves the existing value so admins can update+ // the URL without re-entering every credential every time.+ // Secrets get encrypted at rest. plain-text fields (like OAuth+ // tenant / client IDs) get stored as-is.+ foreach ($this->credentialSchema() as $field) {+ $fieldName = $slug.'_'.$field['key'];+ if (! $request->filled($fieldName)) {+ continue;+ }++ $value = $request->input($fieldName);+ if ($field['secret'] ?? false) {+ $value = Crypt::encrypt($value);+ }+ SyncAdapterConfig::put($this->instance->id, $field['key'], $value);+ }++ SyncAdapterConfig::put(+ $this->instance->id,+ 'log_heartbeats',+ $request->boolean($slug.'_log_heartbeats') ? '1' : '0',+ );++ // Asset-tag pattern for auto-created assets. Empty input clears+ // the setting so we fall back to Asset::autoincrement_asset().+ SyncAdapterConfig::put(+ $this->instance->id,+ 'asset_tag_pattern',+ (string) $request->input($slug.'_asset_tag_pattern', ''),+ );++ // Default category for auto-created AssetModels. Empty falls+ // back to the get-or-create "Discovered Hardware" category.+ SyncAdapterConfig::put(+ $this->instance->id,+ 'default_category_id',+ (string) $request->input($slug.'_default_category_id', ''),+ );++ // Default status label for auto-created assets. Empty falls+ // back to the first deployable label (or any label if none+ // are marked deployable).+ SyncAdapterConfig::put(+ $this->instance->id,+ 'default_status_id',+ (string) $request->input($slug.'_default_status_id', ''),+ );++ // User match strategy for sync-driven assignments. 'none'+ // disables the lookup entirely. Anything else the accessor+ // doesn't recognize also degrades to 'none'.+ SyncAdapterConfig::put(+ $this->instance->id,+ 'user_match_strategy',+ (string) $request->input($slug.'_user_match_strategy', 'none'),+ );++ // Suppress notifications checkbox. Stored as '0' when the+ // admin opted OUT of suppression (i.e., wants events to fire).+ // Any other value means suppress. Matches the accessor.+ SyncAdapterConfig::put(+ $this->instance->id,+ 'suppress_notifications',+ $request->boolean($slug.'_suppress_notifications') ? '1' : '0',+ );++ // Opt-in: check the asset in when the vendor stops reporting+ // an assigned user (a previously-assigned device that now+ // returns null / empty on the user field). Default off because+ // any single missing sync cycle would flap the assignment.+ // Admins turn it on when they trust their vendor's user+ // reporting to be consistent.+ SyncAdapterConfig::put(+ $this->instance->id,+ 'checkin_on_null_user',+ $request->boolean($slug.'_checkin_on_null_user') ? '1' : '0',+ );++ // Push dry-run flag. When on, adapters log the push payload+ // instead of sending it, so admins can verify mapping ++ // direction config against real assets without any vendor+ // side effect.+ SyncAdapterConfig::put(+ $this->instance->id,+ 'push_dry_run',+ $request->boolean($slug.'_push_dry_run') ? '1' : '0',+ );++ // Push notes template. Blade-ish {placeholder} string that+ // adapters with a notes-shape vendor field (Intune, Kandji,+ // Jamf, etc.) render + push to that field. Blank = don't push+ // a notes field. Empty-string save clears the template.+ SyncAdapterConfig::put(+ $this->instance->id,+ 'push_notes_template',+ (string) $request->input($slug.'_push_notes_template', ''),+ );++ // Optional override for which vendor field the composed+ // notes get pushed to. Blank = use the adapter's default+ // (Kandji: notes, Jamf: general.notes, Intune: notes, etc.).+ // Admin sets this when their vendor has multiple candidate+ // fields (Kandji's `notes` vs a specific custom field, WS1's+ // Custom Attribute name, Ninja's Custom Field name).+ SyncAdapterConfig::put(+ $this->instance->id,+ 'push_notes_target',+ (string) $request->input($slug.'_push_notes_target', ''),+ );++ // Per-vendor-group Snipe-IT company mappings. Form emits one+ // input per group (name = {slug}_group_mapping[{vendor_group_id}]).+ // Blank / "unassigned" values clear that group's mapping so+ // it falls back to the instance company_id at sync time.+ if ($this->supportsGroupScoping()) {+ foreach ((array) $request->input($slug.'_group_mapping', []) as $vendorGroupId => $companyId) {+ $key = 'group_mapping.'.$vendorGroupId;+ if ($companyId === null || $companyId === '') {+ SyncAdapterConfig::forget($this->instance->id, $key);+ } else {+ SyncAdapterConfig::put($this->instance->id, $key, (string) (int) $companyId);+ }+ }+ }++ // Standard fields have shipped defaults from MappingTargets.+ // Extras default to skip. Both share the same mapping.{key}+ // storage prefix because the two key namespaces don't collide+ // (standard = hostname/serial/etc, extras = adapter-prefixed).+ $validFields = array_merge(+ MappingTargets::FIELDS,+ array_keys($this->extraFields()),+ );++ foreach ((array) $request->input($slug.'_mapping', []) as $field => $target) {+ if (! in_array($field, $validFields, true)) {+ continue;+ }+ SyncAdapterConfig::put($this->instance->id, 'mapping.'.$field, (string) $target);+ }++ // Per-field direction (pull / push / skip). Orthogonal to the+ // target column stored above so admins can flip direction+ // without re-picking the target. Only meaningful for adapters+ // that implement PushableAdapter. For pull-only adapters the+ // form doesn't render the direction column and this loop is+ // a no-op. Value 'pull' is the default and doesn't need+ // storing, but writing it explicitly keeps the round-trip+ // behavior predictable for admins reading raw config.+ foreach ((array) $request->input($slug.'_direction', []) as $field => $direction) {+ if (! in_array($field, $validFields, true)) {+ continue;+ }+ if (! in_array($direction, ['pull', 'push', 'skip', 'both'], true)) {+ continue;+ }+ SyncAdapterConfig::put($this->instance->id, 'direction.'.$field, (string) $direction);+ }++ $this->afterSaveConfig();+ }++ /**+ * Hook that runs after saveConfig() finishes persisting the form.+ * Empty on the base class. Adapters override to do things like+ * probe the vendor for tier / feature-flag info now that credentials+ * are in place (FleetAdapter caches its license tier here so the+ * group-mapping UI can be hidden on Fleet Free).+ */+ protected function afterSaveConfig(): void+ {+ // no-op by default+ }++ /**+ * Per-field direction for the sync mapping. Returns one of:+ * - 'pull' (vendor -> Snipe-IT, default)+ * - 'push' (Snipe-IT -> vendor)+ * - 'skip' (no sync in either direction)+ *+ * Only meaningful for adapters implementing PushableAdapter. For+ * pure pull adapters callers should always get 'pull' back.+ */+ /**+ * Dry-run mode for push: when true, PushableAdapter::push()+ * implementations should build the payload and log it via the+ * sync-adapters channel but skip the actual vendor API call.+ * Lets admins verify their mapping + direction configuration+ * end-to-end without touching the vendor. Off by default.+ */+ public function isPushDryRun(): bool+ {+ return SyncAdapterConfig::get($this->instance->id, 'push_dry_run') === '1';+ }++ /**+ * Template string admins configure to compose a single-field+ * notes blob from many Snipe-IT fields (asset_tag + status ++ * assigned_to + custom fields, etc.). PushableAdapter+ * implementations render this via NotesComposer and push the+ * result to their vendor's notes-shape field. Empty string+ * means "don't push notes."+ */+ public function pushNotesTemplate(): string+ {+ return (string) SyncAdapterConfig::get($this->instance->id, 'push_notes_template');+ }++ /**+ * Admin-configured vendor field name (or dotted path) for the+ * composed notes push. Blank = fall back to the adapter's+ * suggested default via PushableAdapter::notesFieldTarget().+ * Set this when the vendor exposes multiple candidate targets+ * (Custom Attribute name for WS1, Custom Field name for+ * NinjaOne, alternative path for Jamf, etc.).+ */+ public function pushNotesTargetOverride(): ?string+ {+ $stored = (string) SyncAdapterConfig::get($this->instance->id, 'push_notes_target');++ return $stored === '' ? null : $stored;+ }++ /**+ * Effective vendor field for composed notes: the admin's+ * override if set, else the adapter's suggested default via+ * PushableAdapter::notesFieldTarget(). Returns null when+ * neither is set (adapter doesn't expose a notes concept AND+ * admin didn't name a target field).+ */+ public function effectiveNotesTarget(): ?string+ {+ $override = $this->pushNotesTargetOverride();+ if ($override !== null) {+ return $override;+ }++ return $this instanceof \App\SyncAdapters\PushableAdapter+ ? $this->notesFieldTarget()+ : null;+ }++ public function directionFor(string $field): string+ {+ $stored = SyncAdapterConfig::get($this->instance->id, 'direction.'.$field);++ return in_array($stored, ['pull', 'push', 'skip', 'both'], true) ? $stored : 'pull';+ }++ /**+ * Enumeration of source-field names currently directed 'push' or+ * 'both' on this instance. Used by push() implementations to+ * build the PATCH payload without scanning every possible field.+ *+ * @return array<int, string>+ */+ public function pushDirectedFields(): array+ {+ $out = [];+ $candidates = array_merge(MappingTargets::FIELDS, array_keys($this->extraFields()));+ foreach ($candidates as $field) {+ if (in_array($this->directionFor($field), ['push', 'both'], true)) {+ $out[] = $field;+ }+ }++ return $out;+ }++ /**+ * Currently-selected target for a field, or the shipped default+ * when no per-instance override exists. Standard fields fall back+ * to MappingTargets::defaultTarget(). extras fall back to skip.+ */+ public function mappingFor(string $field): string+ {+ $default = in_array($field, MappingTargets::FIELDS, true)+ ? MappingTargets::defaultTarget($field)+ : 'skip';++ return SyncAdapterConfig::get(+ $this->instance->id,+ 'mapping.'.$field,+ $default,+ );+ }++ public function getUrl(): ?string+ {+ return SyncAdapterConfig::get($this->instance->id, 'url');+ }++ public function logsHeartbeats(): bool+ {+ return SyncAdapterConfig::get($this->instance->id, 'log_heartbeats') === '1';+ }++ /**+ * Custom asset-tag pattern the admin configured for auto-created+ * assets. Null when unset (SyncHostFromAdapter falls back to+ * Asset::autoincrement_asset() in that case). Placeholders like+ * `{serial}` / `{external_id}` / `{hostname}` get substituted at+ * create time from HostInventoryRecord fields.+ */+ public function assetTagPattern(): ?string+ {+ $stored = SyncAdapterConfig::get($this->instance->id, 'asset_tag_pattern');++ return $stored === null || $stored === '' ? null : $stored;+ }++ /**+ * Default category id for auto-created AssetModels from this+ * adapter. Vendors don't send Snipe-IT's category concept, but+ * every AssetModel needs one. When null, SyncHostFromAdapter+ * falls back to a get-or-create "Discovered Hardware" category.+ */+ public function defaultCategoryId(): ?int+ {+ $stored = SyncAdapterConfig::get($this->instance->id, 'default_category_id');++ return $stored === null || $stored === '' ? null : (int) $stored;+ }++ /**+ * Default status label id for auto-created assets from this+ * adapter. When null, SyncHostFromAdapter falls back to the+ * first deployable status label (or, absent that, any status+ * label). Admins pick a specific status to route synced devices+ * into a curated workflow bucket ("Awaiting Assignment", "In+ * Production", etc.) rather than lumping them into whatever+ * happens to be the first deployable row.+ */+ public function defaultStatusId(): ?int+ {+ $stored = SyncAdapterConfig::get($this->instance->id, 'default_status_id');++ return $stored === null || $stored === '' ? null : (int) $stored;+ }++ /**+ * How the sync path resolves a Snipe-IT user from the vendor's+ * assigned-user data. Returns one of:+ * - 'none' no assignment attempted (default)+ * - 'username' match against users.username only+ * - 'email' match against users.email only+ * - 'username_then_email' try username first, fall back to email+ *+ * Anything unrecognized (or absent) degrades to 'none' so a+ * corrupt row or a future rename can't leak into an unexpected+ * match strategy.+ */+ public function userMatchStrategy(): string+ {+ $stored = SyncAdapterConfig::get($this->instance->id, 'user_match_strategy');++ return in_array($stored, ['email', 'username', 'username_then_email'], true) ? $stored : 'none';+ }++ /**+ * Whether sync-driven user assignments skip the checkout+ * notification path entirely. When true, the sync goes through+ * silentAssignToUser() which bypasses the CheckoutableCheckedOut+ * event and every listener on it (email, Slack, webhook, etc.).+ * Default true so scheduled syncs don't blast users every time+ * their device phones home.+ */+ public function suppressesNotifications(): bool+ {+ $stored = SyncAdapterConfig::get($this->instance->id, 'suppress_notifications');++ // Absent = suppress (safe default). Only an explicit '0'+ // opts back into the standard checkout-event flow.+ return $stored !== '0';+ }++ /**+ * Whether sync should check the asset in when the vendor stops+ * reporting an assigned user. Default false. Turning it on means+ * a device that reported alice@ yesterday and reports null today+ * gets checked in from Alice. Admins opt in when their vendor's+ * user reporting is consistent enough that a null value truly+ * means "unassigned" rather than "field wasn't populated this+ * sync cycle".+ */+ public function checksInOnNullUser(): bool+ {+ return SyncAdapterConfig::get($this->instance->id, 'checkin_on_null_user') === '1';+ }++ /**+ * Whether this adapter's vendor exposes a groups concept+ * (Fleet Teams, Jamf Sites, Kandji Blueprints, etc.) that+ * admins can map to Snipe-IT companies. Default false so+ * adapters without group support don't render the mapping+ * section on the settings page. Adapters override to true and+ * implement fetchGroups() + populate vendorGroupId in normalize.+ */+ public function supportsGroupScoping(): bool+ {+ return false;+ }++ /**+ * Vendor's own terminology for their groups concept. Used in the+ * mapping section header (e.g. "Fleet Team", "Kandji Blueprint",+ * "Jamf Site") so admins see wording they recognize.+ */+ public function vendorGroupLabel(): string+ {+ return 'Group';+ }++ /**+ * Placeholder shown in the base-URL input on the settings page.+ * Overridden by adapters whose vendor uses a well-known URL+ * (SaaS APIs with fixed hostnames or a well-defined subdomain+ * pattern). Adapters targeting self-hosted vendors return null.+ */+ public function baseUrlPlaceholder(): ?string+ {+ return null;+ }++ /**+ * Live-fetch the current list of groups from the vendor.+ * Returns an array of ['id' => '...', 'label' => '...']. Called+ * when the admin clicks the "refresh groups" button on the+ * settings page. Default throws so adapters that opt into+ * supportsGroupScoping have to implement it. Adapters without+ * group support never have this called.+ *+ * @return array<int, array{id: string, label: string}>+ */+ public function fetchGroups(): array+ {+ throw new \RuntimeException(static::class.' declared group scoping support but did not implement fetchGroups().');+ }++ /**+ * Per-instance vendor-group to Snipe-IT-company mappings, keyed+ * by vendor group id. Empty when the admin has not configured any+ * mappings.+ *+ * @return array<string, int>+ */+ public function groupMappings(): array+ {+ $mappings = [];+ foreach (SyncAdapterConfig::listForInstance($this->instance->id) as $key => $value) {+ if (! str_starts_with($key, 'group_mapping.')) {+ continue;+ }+ $vendorGroupId = substr($key, strlen('group_mapping.'));+ if ($value !== null && $value !== '') {+ $mappings[$vendorGroupId] = (int) $value;+ }+ }++ return $mappings;+ }++ /**+ * Snipe-IT company id for a vendor group id, or null when the+ * group has no mapping. Callers (SyncHostFromAdapter) fall back+ * to the instance's own company_id in that case.+ */+ public function companyForVendorGroup(string $vendorGroupId): ?int+ {+ $mappings = $this->groupMappings();++ return $mappings[$vendorGroupId] ?? null;+ }++ /**+ * Cached copy of the last fetchGroups() result, so the settings+ * page renders the mapping table without hitting the vendor on+ * every page load. Refreshed when the admin clicks the button.+ *+ * @return array<int, array{id: string, label: string}>+ */+ public function cachedGroups(): array+ {+ $stored = SyncAdapterConfig::get($this->instance->id, 'cached_groups');+ if ($stored === null || $stored === '') {+ return [];+ }+ $decoded = json_decode($stored, true);++ return is_array($decoded) ? $decoded : [];+ }++ public function lastSyncedAt(): ?\Carbon\CarbonInterface+ {+ return $this->instance->last_synced_at;+ }++ public function lastSyncResult(): ?string+ {+ return $this->instance->last_sync_result;+ }++ /**+ * Value of a credential for form pre-fill. Returns '' on any+ * failure (missing row, rotated app key, corrupt ciphertext) so+ * blade always has a string to drop into `value=""`. Failed+ * decryption becomes an empty field the admin can re-enter.+ * Loud failures during sync go through credential() instead.+ */+ public function credentialForDisplay(string $key): string+ {+ try {+ return $this->credential($key);+ } catch (\Throwable) {+ return '';+ }+ }++ /**+ * Decrypted (or plain, per schema) value of a credential, for+ * pull() implementations building their vendor API client.+ * Throws loudly on any failure so admins see a real error message+ * instead of a silent auth failure on the vendor's side.+ */+ public function credential(string $key): string+ {+ $stored = SyncAdapterConfig::get($this->instance->id, $key);+ if ($stored === null) {+ throw new \RuntimeException(+ 'No '.$key.' stored for '.$this->instance->label.'. Save one on the adapters settings page.',+ );+ }++ foreach ($this->credentialSchema() as $field) {+ if ($field['key'] !== $key) {+ continue;+ }++ if (! ($field['secret'] ?? false)) {+ return $stored;+ }++ try {+ return Crypt::decrypt($stored);+ } catch (\Throwable $e) {+ throw new \RuntimeException(+ 'Unable to decrypt '.$key.' for '.$this->instance->label.'. Re-enter it on the adapters settings page.',+ previous: $e,+ );+ }+ }++ throw new \RuntimeException(+ $key.' is not a declared credential for '.$this->instance->label,+ );+ }++ protected function url(): string+ {+ return SyncAdapterConfig::get($this->instance->id, 'url') ?? '';+ }+}diff --git a/app/SyncAdapters/Support/MappingTargets.php b/app/SyncAdapters/Support/MappingTargets.phpnew file mode 100644index 0000000000..3ee121707b--- /dev/null+++ b/app/SyncAdapters/Support/MappingTargets.php@@ -0,0 +1,195 @@+<?php++namespace App\SyncAdapters\Support;++use App\Models\CustomField;++/**+ * Enumerates the target options each normalized host-inventory field can+ * be mapped to. Every adapter reads the same normalized shape (hostname,+ * serial, model, mac, ip, os, os_version, last_seen) and hands it to+ * SyncHostFromAdapter. per-instance overrides let admins redirect each+ * field to a different Snipe-IT destination (native column, side table,+ * custom field, or skip).+ *+ * Target encoding is `<type>:<id>` so the value stays compact and+ * self-describing when stored in sync_adapter_settings:+ * - skip -> don't write this field+ * - native:name -> asset.name+ * - native:serial -> asset.serial+ * - native:model -> AssetModel (auto-created if missing)+ * - external:mac -> asset_external_sources.primary_mac+ * - external:ip -> asset_external_sources.primary_ip+ * - external:os -> asset_external_sources.os+ * - external:os_version -> asset_external_sources.os_version+ * - external:last_seen -> asset_external_sources.last_seen+ * - custom:{id} -> assets._snipeit_<db_column>_<id>+ */+class MappingTargets+{+ /** Every normalized field the sync pipeline knows about. */+ public const FIELDS = ['hostname', 'serial', 'asset_tag', 'model', 'mac', 'ip', 'os', 'os_version', 'last_seen'];++ /**+ * The shipped default target for a field (before any per-instance+ * override). Used by SyncHostFromAdapter as the fallback.+ */+ public static function defaultTarget(string $field): string+ {+ return match ($field) {+ 'hostname' => 'native:name',+ 'serial' => 'native:serial',+ 'model' => 'native:model',+ 'mac' => 'external:mac',+ 'ip' => 'external:ip',+ 'os' => 'external:os',+ 'os_version' => 'external:os_version',+ 'last_seen' => 'external:last_seen',+ // Vendor-side asset tag mapping to Snipe-IT's asset_tag+ // column is the useful default. writeNative()'s+ // "only overwrite when vendor sent a non-empty tag" guard+ // means admin-curated tags survive vendor payloads that+ // happen to omit the field.+ 'asset_tag' => 'native:asset_tag',+ default => 'skip',+ };+ }++ /**+ * Dropdown options for a given normalized field, keyed by target+ * encoding and valued by human-readable label. Custom fields whose+ * element type doesn't fit the normalized field's value shape are+ * filtered out.+ *+ * @return array<string, string>+ */+ public static function options(string $field): array+ {+ $options = ['skip' => trans('admin/settings/general.sync_adapter_target_skip')];++ $default = self::defaultTarget($field);+ if ($default !== 'skip') {+ $options[$default] = self::labelFor($default).' '.trans('admin/settings/general.sync_adapter_target_default_suffix');+ }++ foreach (self::compatibleCustomFields($field) as $customField) {+ $options['custom:'.$customField->id] = trans('admin/settings/general.sync_adapter_target_custom_prefix').': '.$customField->name;+ }++ return $options;+ }++ /**+ * Human-readable label for a stored target value, used when+ * rendering the current selection outside a dropdown context.+ */+ public static function labelFor(string $target): string+ {+ if ($target === 'skip') {+ return trans('admin/settings/general.sync_adapter_target_skip');+ }++ [$type, $id] = array_pad(explode(':', $target, 2), 2, '');++ return match ($type) {+ 'native' => trans('admin/settings/general.sync_adapter_target_native_'.$id),+ 'external' => trans('admin/settings/general.sync_adapter_target_external_'.$id),+ 'custom' => trans('admin/settings/general.sync_adapter_target_custom_prefix').': '+ .(CustomField::find((int) $id)?->name ?? '?'),+ default => $target,+ };+ }++ /**+ * Dropdown options for an adapter-specific extra field. Extras+ * can only be routed to a custom field or skipped. `type` filters+ * the custom-field target pool: 'text' offers text/textarea/+ * markdown-textarea fields, 'boolean' offers checkbox fields.+ *+ * @return array<string, string>+ */+ public static function optionsForExtra(string $type = 'text'): array+ {+ $options = ['skip' => trans('admin/settings/general.sync_adapter_target_skip')];++ // Text-type extras can also route into native asset columns+ // that hold arbitrary strings. Admins whose vendor stores+ // per-device metadata in a labels / blueprint / team field+ // may want that landing in asset_tag or notes rather than a+ // custom field. asset_tag is uniqueness-constrained so the+ // sync path relies on the vendor value being unique per host+ // when this target is picked. Not appropriate for list-typed+ // extras like fleet_labels which stringify to comma-joined+ // sets. Boolean-typed extras stay custom-fields-only because+ // no native asset column carries a boolean semantic.+ if ($type !== 'boolean') {+ foreach (['asset_tag', 'notes'] as $nativeColumn) {+ $options['native:'.$nativeColumn] = trans('admin/settings/general.sync_adapter_target_native_'.$nativeColumn);+ }+ }++ $customFields = match ($type) {+ 'boolean' => self::checkboxCustomFields(),+ default => self::textLikeCustomFields(),+ };++ foreach ($customFields as $customField) {+ $options['custom:'.$customField->id] = trans('admin/settings/general.sync_adapter_target_custom_prefix').': '.$customField->name;+ }++ return $options;+ }++ /**+ * Custom fields whose element type can plausibly hold this+ * normalized field's value. For MVP: text/textarea for any string,+ * date_picker/datetime_picker for last_seen. Extend as we hit+ * real-world requests.+ *+ * @return \Illuminate\Support\Collection<int, CustomField>+ */+ private static function compatibleCustomFields(string $field): \Illuminate\Support\Collection+ {+ $textLike = ['text', 'textarea', 'markdown-textarea'];+ $dateLike = ['date_picker', 'datetime_picker'];++ $accepted = match ($field) {+ 'last_seen' => $dateLike,+ default => $textLike,+ };++ return CustomField::query()+ ->whereIn('element', $accepted)+ ->orderBy('name')+ ->get();+ }++ /**+ * Text-like custom fields, used as the target pool for extras.+ * Extras are stringified before write so any text-like field can+ * hold whatever the vendor emits.+ *+ * @return \Illuminate\Support\Collection<int, CustomField>+ */+ private static function textLikeCustomFields(): \Illuminate\Support\Collection+ {+ return CustomField::query()+ ->whereIn('element', ['text', 'textarea', 'markdown-textarea'])+ ->orderBy('name')+ ->get();+ }++ /**+ * Checkbox-style custom fields, used as the target pool for+ * boolean-typed extras (mdm_enabled, supervised, adopted, etc).+ *+ * @return \Illuminate\Support\Collection<int, CustomField>+ */+ private static function checkboxCustomFields(): \Illuminate\Support\Collection+ {+ return CustomField::query()+ ->where('element', 'checkbox')+ ->orderBy('name')+ ->get();+ }+}diff --git a/app/SyncAdapters/Support/NotesComposer.php b/app/SyncAdapters/Support/NotesComposer.phpnew file mode 100644index 0000000000..4792784241--- /dev/null+++ b/app/SyncAdapters/Support/NotesComposer.php@@ -0,0 +1,103 @@+<?php++namespace App\SyncAdapters\Support;++use App\Models\Asset;+use App\Models\CustomField;++/**+ * Renders a multi-field notes blob from an Asset using a+ * placeholder template. Used by PushableAdapter implementations+ * whose vendor has a single freeform "notes" field per device and+ * admins want to push a composed summary (asset_tag + status ++ * assigned user + custom fields, etc.) rather than one Snipe-IT+ * field to one vendor field.+ *+ * Placeholders use `{key}` syntax with a fixed vocabulary. Custom+ * fields are addressed via `{custom.field_name}` where `field_name`+ * is the exact CustomField name (case-sensitive). Unknown keys and+ * null values render as empty strings so a template with references+ * to missing custom fields degrades gracefully.+ */+class NotesComposer+{+ /**+ * Compose the notes value for an asset from the template.+ * Returns the empty string when the template is blank so+ * callers can gate on `''` for "nothing to push".+ */+ public static function compose(Asset $asset, string $template): string+ {+ if (trim($template) === '') {+ return '';+ }++ // Match anything between braces that isn't itself a brace.+ // Permissive so custom field names with spaces / punctuation+ // ({custom.Cost Center}, {custom.Warranty (extended)}) match+ // cleanly. The resolver decides validity.+ return preg_replace_callback(+ '/\{([^{}]+)\}/',+ fn (array $m) => (string) self::resolve($asset, $m[1]),+ $template,+ ) ?? '';+ }++ /**+ * Resolve a single placeholder key against the asset. Native+ * columns and relationship-derived values are hardcoded. Custom+ * fields go through the `custom.field_name` path.+ */+ private static function resolve(Asset $asset, string $key): string+ {+ if (str_starts_with($key, 'custom.')) {+ return self::resolveCustomField($asset, substr($key, 7));+ }++ return match ($key) {+ 'asset_tag' => (string) ($asset->asset_tag ?? ''),+ 'name' => (string) ($asset->name ?? ''),+ 'serial' => (string) ($asset->serial ?? ''),+ 'model' => (string) ($asset->model?->name ?? ''),+ 'model_number' => (string) ($asset->model?->model_number ?? ''),+ 'manufacturer' => (string) ($asset->model?->manufacturer?->name ?? ''),+ 'category' => (string) ($asset->model?->category?->name ?? ''),+ 'status' => (string) ($asset->status?->name ?? ''),+ 'status_type' => (string) ($asset->status?->getStatuslabelType() ?? ''),+ 'assigned_to' => (string) ($asset->assignedTo?->present()?->name() ?? ''),+ 'assigned_to_email' => (string) ($asset->assignedTo?->email ?? ''),+ 'assigned_to_username' => (string) ($asset->assignedTo?->username ?? ''),+ 'location' => (string) ($asset->location?->name ?? ''),+ 'company' => (string) ($asset->company?->name ?? ''),+ 'supplier' => (string) ($asset->supplier?->name ?? ''),+ 'last_checkout' => (string) ($asset->last_checkout ?? ''),+ 'last_checkin' => (string) ($asset->last_checkin ?? ''),+ 'expected_checkin' => (string) ($asset->expected_checkin ?? ''),+ 'notes' => (string) ($asset->notes ?? ''),+ 'order_number' => (string) ($asset->order_number ?? ''),+ 'purchase_date' => (string) ($asset->purchase_date ?? ''),+ 'purchase_cost' => (string) ($asset->purchase_cost ?? ''),+ 'warranty_months' => (string) ($asset->warranty_months ?? ''),+ 'warranty_expires' => (string) ($asset->warranty_expires ?? ''),+ default => '',+ };+ }++ /**+ * Look up a custom field value by name. Snipe-IT custom fields+ * store per-asset values on the asset row via a `_snipeit_...`+ * db_column, so we resolve the CustomField -> db_column ->+ * $asset->$dbColumn.+ */+ private static function resolveCustomField(Asset $asset, string $fieldName): string+ {+ $field = CustomField::query()->where('name', $fieldName)->first();+ if ($field === null || $field->db_column === null) {+ return '';+ }++ $value = $asset->getAttribute($field->db_column);++ return $value === null ? '' : (string) $value;+ }+}diff --git a/app/SyncAdapters/SyncHostFromAdapter.php b/app/SyncAdapters/SyncHostFromAdapter.phpnew file mode 100644index 0000000000..d55ceab91c--- /dev/null+++ b/app/SyncAdapters/SyncHostFromAdapter.php@@ -0,0 +1,881 @@+<?php++namespace App\SyncAdapters;++use App\Models\Actionlog;+use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\Category;+use App\Models\CustomField;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Models\User;+use App\SyncAdapters\Support\ConfigurableAdapter;+use App\SyncAdapters\Support\MappingTargets;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Log;+use RuntimeException;++/**+ * Shared asset-side upsert path for every host-inventory adapter.+ * Accepts a normalized HostInventoryRecord and either creates a new+ * asset or updates an existing one keyed on (source, external_id) in+ * asset_external_sources.+ *+ * The write path is deliberately dumb about vendors: no adapter-specific+ * logic lives here. Adapters do their own normalization and hand a+ * clean record over. Per-instance target mappings (configured via+ * MappingTargets on the settings page) let admins redirect each+ * normalized field to a custom field or skip it entirely.+ * SyncHostFromAdapter reads those overrides and dispatches values+ * accordingly.+ */+class SyncHostFromAdapter+{+ public static function run(HostInventoryRecord $record): Asset+ {+ return DB::transaction(function () use ($record) {+ $instance = SyncAdapterInstance::query()->where('slug', $record->sourceKey)->first();+ $mapping = self::loadMapping($instance);++ $existingSource = DB::table('asset_external_sources')+ ->where('source', $record->sourceKey)+ ->where('external_id', $record->sourceId)+ ->first();++ $asset = $existingSource ? Asset::find($existingSource->asset_id) : null;+ $isNew = $asset === null;++ if ($isNew) {+ $asset = self::createShellAsset($record, $instance);++ // Identity row created empty of inventory columns. the+ // mapping loop below fills them and the write goes out+ // through upsertExternalSource().+ DB::table('asset_external_sources')->insert([+ 'asset_id' => $asset->id,+ 'company_id' => $instance?->company_id,+ 'source' => $record->sourceKey,+ 'external_id' => $record->sourceId,+ // NULL for CLI / scheduled runs, admin id for+ // interactive Sync Now clicks.+ 'created_by' => auth()->id(),+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);+ } else {+ // Update-sync path: if the vendor moved this device+ // to a different group and the new group maps to a+ // different Snipe-IT company, reassign. Same+ // "vendor is authoritative" model as native:asset_tag+ // for tags. Admins who want to preserve manual+ // company assignments turn off group scoping for+ // this adapter or delete the specific mapping.+ $resolvedCompanyId = self::resolveCompanyId($record, $instance);+ if ($resolvedCompanyId !== null && $resolvedCompanyId !== (int) $asset->company_id) {+ $asset->company_id = $resolvedCompanyId;+ }+ }++ // Apply per-field mappings. Routes each normalized field to+ // native asset columns, external-source columns, custom+ // fields, or skips it, based on per-instance config. Fields+ // directed 'push' or 'skip' on this instance are excluded+ // from the pull path so the vendor's value can't overwrite+ // a Snipe-IT-authoritative field (asset_tag pushed to the+ // vendor shouldn't get pulled back from what the vendor+ // reports). 'both' direction still pulls (naive last-write-+ // wins) so both sides converge on whichever side ran most+ // recently.+ $adapterForDirection = $instance?->adapter();+ $externalUpdates = [];+ foreach (MappingTargets::FIELDS as $field) {+ $target = $mapping[$field] ?? MappingTargets::defaultTarget($field);+ if ($target === 'skip') {+ continue;+ }+ if ($adapterForDirection instanceof ConfigurableAdapter+ && ! in_array($adapterForDirection->directionFor($field), ['pull', 'both'], true)) {+ continue;+ }++ $value = self::recordValueFor($record, $field);+ self::writeToTarget($asset, $externalUpdates, $target, $value, $instance);+ }++ // Apply extra-field mappings. Extras are vendor-specific+ // keys the adapter emits into HostInventoryRecord::$extra.+ // Valid targets for extras are custom fields OR a small+ // set of native asset columns (asset_tag, notes) for+ // admins who store per-device metadata in the vendor's+ // labels / blueprint / team field. Values get stringified+ // so array or object payloads (Fleet's labels list, etc.)+ // land as readable text regardless of the underlying+ // native / custom write path.+ if ($instance !== null) {+ $adapter = $instance->adapter();+ if ($adapter instanceof ConfigurableAdapter) {+ $extraFields = $adapter->extraFields();+ foreach (array_keys($extraFields) as $extraKey) {+ $target = $mapping[$extraKey] ?? 'skip';+ if ($target === 'skip') {+ continue;+ }+ $isCustom = str_starts_with($target, 'custom:');+ $isNative = str_starts_with($target, 'native:');+ if (! $isCustom && ! $isNative) {+ continue;+ }++ $raw = $record->extra[$extraKey] ?? null;+ $type = self::extraFieldType($extraFields, $extraKey);++ // Booleans render '0' when raw is false. other+ // types treat blank strings as null. Guard on+ // raw-is-null so we don't blank existing data+ // for partially populated payloads.+ if ($raw === null && $type !== 'boolean') {+ continue;+ }++ $value = self::stringifyExtra($raw, $type);+ if ($value === null) {+ continue;+ }++ if ($isCustom) {+ self::writeCustom($asset, (int) substr($target, 7), $value);+ } else {+ self::writeNative($asset, substr($target, 7), $value, $instance);+ }+ }+ }+ }++ // Snapshot the current external-source inventory columns+ // before the write so we can diff and log any real changes+ // to non-heartbeat fields (MAC / IP / OS / os_version) via+ // a manual Actionlog. AssetObserver only sees native-column+ // diffs via getDirty(), so external-source column changes+ // would otherwise go untracked in the asset history.+ $previousExternal = $isNew ? [] : self::loadExternalSourceInventory($asset->id);++ // Push native and custom-field writes. Laravel skips the+ // UPDATE when $asset->isDirty() is false, so a sync that+ // only changed external-source columns is a no-op on the+ // asset row: no AssetObserver::updating fires (we handle+ // external-source logging separately below).+ $wasDirty = $asset->isDirty();+ $asset->saveOrFail();++ // External-source column writes gather during the mapping+ // loop and go out together so we make one row-write per+ // sync instead of N updates.+ if ($externalUpdates !== []) {+ self::upsertExternalSource($asset, $externalUpdates);+ }++ // Sync-driven user assignment. Runs after saveOrFail so+ // the asset is committed before we try to check it out.+ // Only touches assets whose adapter has a user-match+ // strategy configured. missing or unresolved users skip+ // silently after logging a warning.+ self::assignUserIfMatched($asset, $record, $instance);++ // Diff external-source column changes and decide whether+ // to log + touch. Meaningful diff (MAC / IP / OS /+ // os_version) always logs. last_seen-only diff logs only+ // when the admin opted into heartbeat logging.+ if (! $isNew) {+ $externalDiff = self::diffExternal($previousExternal, $externalUpdates);+ $meaningfulExternalChange = count(array_diff(array_keys($externalDiff), ['last_seen'])) > 0;+ $heartbeatOnly = $externalDiff !== [] && ! $meaningfulExternalChange;++ $logsHeartbeats = false;+ if ($instance !== null) {+ $adapter = $instance->adapter();+ if ($adapter instanceof ConfigurableAdapter) {+ $logsHeartbeats = $adapter->logsHeartbeats();+ }+ }++ if ($meaningfulExternalChange || ($heartbeatOnly && $logsHeartbeats)) {+ self::writeExternalSourceActionlog($asset, $externalDiff);+ // Bump updated_at so "recently updated" sorts+ // reflect the sync activity. Use saveQuietly so+ // AssetObserver::updating doesn't fire and log a+ // redundant `update` Actionlog on top of the+ // external-source row we just wrote. Skipped when+ // the asset was already dirty (native columns+ // changed) because the save above handles it.+ if (! $wasDirty) {+ $asset->updated_at = now();+ $asset->saveQuietly();+ }+ }+ }++ return $asset->refresh();+ });+ }++ /**+ * Snapshot the current inventory columns from the+ * asset_external_sources row for diffing. Returns an empty array+ * when no row exists yet (first sync on this asset from any+ * adapter). Identity columns (source, external_id, company_id,+ * asset_id, id, timestamps) are stripped so the diff only covers+ * the columns the mapping loop writes.+ *+ * @return array<string, mixed>+ */+ private static function loadExternalSourceInventory(int $assetId): array+ {+ $row = DB::table('asset_external_sources')->where('asset_id', $assetId)->first();+ if ($row === null) {+ return [];+ }++ $arr = (array) $row;+ unset(+ $arr['id'],+ $arr['asset_id'],+ $arr['company_id'],+ $arr['source'],+ $arr['external_id'],+ $arr['created_at'],+ $arr['updated_at'],+ );++ return $arr;+ }++ /**+ * Which inventory columns differ between the pre-sync snapshot+ * and the just-written updates. Only diffs the columns the sync+ * actually touched. untouched columns stay stable.+ *+ * @param array<string, mixed> $previous+ * @param array<string, mixed> $updates+ * @return array<string, array{old: mixed, new: mixed}>+ */+ private static function diffExternal(array $previous, array $updates): array+ {+ $diff = [];+ foreach ($updates as $column => $newValue) {+ $oldValue = $previous[$column] ?? null;+ if ((string) $oldValue !== (string) $newValue) {+ $diff[$column] = ['old' => $oldValue, 'new' => $newValue];+ }+ }++ return $diff;+ }++ /**+ * Write an Actionlog entry describing an external-source column+ * change. Uses log_meta with the same shape AssetObserver uses on+ * native-column updates so the asset-history renderer can display+ * it uniformly. log_meta is a plain TEXT column carrying JSON-+ * encoded strings (per feedback_log_meta_column memory).+ *+ * @param array<string, array{old: mixed, new: mixed}> $diff+ */+ private static function writeExternalSourceActionlog(Asset $asset, array $diff): void+ {+ $log = new Actionlog;+ $log->item_id = $asset->id;+ $log->item_type = Asset::class;+ $log->created_at = now();+ $log->created_by = null; // system-driven, not a user action+ $log->log_meta = json_encode($diff);+ $log->logaction('update');+ }++ /**+ * Read all mapping.* config keys for this instance and index them+ * by normalized field name. Empty array when the instance is null+ * (asset carries a legacy source with no corresponding instance).+ *+ * @return array<string, string>+ */+ private static function loadMapping(?SyncAdapterInstance $instance): array+ {+ if ($instance === null) {+ return [];+ }++ $mapping = [];++ // Standard normalized fields.+ foreach (MappingTargets::FIELDS as $field) {+ $stored = SyncAdapterConfig::get($instance->id, 'mapping.'.$field);+ if ($stored !== null) {+ $mapping[$field] = $stored;+ }+ }++ // Adapter-specific extra fields, if the adapter declares any.+ $adapter = $instance->adapter();+ if ($adapter instanceof ConfigurableAdapter) {+ foreach (array_keys($adapter->extraFields()) as $extraKey) {+ $stored = SyncAdapterConfig::get($instance->id, 'mapping.'.$extraKey);+ if ($stored !== null) {+ $mapping[$extraKey] = $stored;+ }+ }+ }++ return $mapping;+ }++ /**+ * Convert an extra-field value from the vendor's payload into a+ * string suitable for a custom field. Boolean-typed extras render+ * to '1' or '0' so a checkbox custom field's stored value matches+ * what its UI expects. Scalars pass through. Arrays of scalars+ * get comma-joined so a list like Fleet's labels lands as+ * "server, prod, us-east". Everything else falls back to JSON so+ * admins at least see the raw shape.+ */+ private static function stringifyExtra(mixed $value, string $type = 'text'): ?string+ {+ if ($value === null) {+ return null;+ }++ if ($type === 'boolean') {+ return ((bool) $value) ? '1' : '0';+ }++ if (is_scalar($value)) {+ return (string) $value;+ }++ if (is_array($value)) {+ $allScalar = array_reduce(+ $value,+ fn ($carry, $v) => $carry && is_scalar($v),+ true,+ );++ return $allScalar+ ? implode(', ', array_map(fn ($v) => (string) $v, $value))+ : json_encode($value);+ }++ return json_encode($value);+ }++ /**+ * Extract the type of an extra field from an adapter's+ * extraFields() declaration. Entries can be either plain strings+ * (defaults to text) or arrays with an explicit `type` value+ * ('text', 'boolean').+ *+ * @param array<string, string|array{label: string, type?: string}> $extraFields+ */+ private static function extraFieldType(array $extraFields, string $key): string+ {+ $entry = $extraFields[$key] ?? null;+ if (is_array($entry) && isset($entry['type'])) {+ return $entry['type'];+ }++ return 'text';+ }++ /**+ * Create the minimum viable Asset row so we have an id to hang+ * downstream mapping writes off. Uses a synthetic name (source+ * slug + external id) since the hostname mapping may point at a+ * custom field or be skipped entirely. The mapping loop overwrites+ * asset.name if the hostname mapping is native:name.+ *+ * When the instance is scoped to a company, new assets inherit its+ * company_id so FMCS-scoped views only see their own company's+ * synced hosts.+ */+ private static function createShellAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance): Asset+ {+ $asset = new Asset;+ $asset->name = $record->sourceKey.'-'.$record->sourceId;+ $asset->model_id = self::resolveModelId($record, $instance);+ $asset->status_id = self::resolveStatusId($instance);+ $asset->asset_tag = self::resolveAssetTag($record, $instance);+ $asset->company_id = self::resolveCompanyId($record, $instance);+ $asset->save();++ return $asset;+ }++ /**+ * Status label id for newly-created assets. Precedence:+ * 1. Adapter's configured default_status_id (when set and the+ * referenced label still exists).+ * 2. First deployable status label.+ * 3. First status label of any kind.+ * Throws if the tenant has no status labels at all, since Asset+ * requires status_id to be set.+ */+ private static function resolveStatusId(?SyncAdapterInstance $instance): int+ {+ if ($instance !== null) {+ $adapter = $instance->adapter();+ if ($adapter instanceof ConfigurableAdapter) {+ $configuredId = $adapter->defaultStatusId();+ if ($configuredId !== null && Statuslabel::whereKey($configuredId)->exists()) {+ return $configuredId;+ }+ }+ }++ $status = Statuslabel::deployable()->first() ?? Statuslabel::first();+ if ($status === null) {+ throw new RuntimeException('No status label available for auto-created host inventory assets.');+ }++ return $status->id;+ }++ /**+ * Pick the Snipe-IT company id for a newly-created asset.+ * Precedence:+ * 1. Adapter's per-group company mapping (when adapter supports+ * group scoping AND record has a vendorGroupId AND the group+ * is mapped).+ * 2. Instance's own company_id (existing behavior).+ * 3. Null (asset lands in the shared/no-company bucket).+ *+ * Group mappings let one adapter instance sync devices from a+ * multi-tenant vendor (Kandji, Fleet, Jamf) into per-customer+ * Snipe-IT companies without needing one adapter instance per+ * company. See ConfigurableAdapter::groupMappings().+ */+ private static function resolveCompanyId(HostInventoryRecord $record, ?SyncAdapterInstance $instance): ?int+ {+ if ($instance !== null && $record->vendorGroupId !== null && $record->vendorGroupId !== '') {+ $adapter = $instance->adapter();+ if ($adapter instanceof ConfigurableAdapter && $adapter->supportsGroupScoping()) {+ $mapped = $adapter->companyForVendorGroup($record->vendorGroupId);+ if ($mapped !== null) {+ return $mapped;+ }+ }+ }++ return $instance?->company_id;+ }++ /**+ * Pick the asset tag for a newly-created asset. Precedence:+ * 1. Adapter's configured pattern (with placeholders substituted).+ * 2. Snipe-IT's global autoincrement setting.+ * 3. Fallback synthetic tag (source-external_id) so save never+ * lands with a null tag even when the other two miss.+ *+ * The pattern lets admins force a stable per-vendor tag scheme+ * (KANDJI-{serial}, FLEET-{external_id}, etc.) so re-imported+ * assets keep their tag across reinstalls. See ConfigurableAdapter+ * -> assetTagPattern() for the storage side.+ */+ private static function resolveAssetTag(HostInventoryRecord $record, ?SyncAdapterInstance $instance): string+ {+ $adapter = $instance?->adapter();+ if ($adapter instanceof ConfigurableAdapter) {+ $pattern = $adapter->assetTagPattern();+ if ($pattern !== null) {+ $rendered = self::renderAssetTagPattern($pattern, $record);+ if ($rendered !== null && $rendered !== '') {+ return $rendered;+ }+ }+ }++ return Asset::autoincrement_asset()+ ?: $record->sourceKey.'-'.$record->sourceId;+ }++ /**+ * Substitute the known placeholders in an asset-tag pattern with+ * values from the record. Unknown / unpopulated placeholders+ * render as empty. Returns the trimmed result, or null when the+ * pattern rendered to an empty string entirely (which triggers+ * the caller's autoincrement fallback).+ *+ * Placeholders supported today: {serial} {external_id} {hostname}+ * {model} {source}. Extras (e.g. {extra.kandji_asset_tag}) can be+ * added later without touching callers.+ */+ private static function renderAssetTagPattern(string $pattern, HostInventoryRecord $record): ?string+ {+ $substitutions = [+ '{serial}' => (string) ($record->hardwareSerial ?? ''),+ '{external_id}' => $record->sourceId,+ '{hostname}' => (string) ($record->hostname ?? ''),+ '{model}' => (string) ($record->hardwareModel ?? ''),+ '{source}' => $record->sourceKey,+ ];++ $rendered = trim(strtr($pattern, $substitutions));++ return $rendered === '' ? null : $rendered;+ }++ /**+ * Extract the normalized value for a given field from the record.+ */+ private static function recordValueFor(HostInventoryRecord $record, string $field): mixed+ {+ return match ($field) {+ 'hostname' => $record->hostname,+ 'serial' => $record->hardwareSerial,+ 'asset_tag' => $record->assetTag,+ 'model' => $record->hardwareModel,+ 'mac' => $record->primaryMac,+ 'ip' => $record->primaryIp,+ 'os' => $record->os,+ 'os_version' => $record->osVersion,+ 'last_seen' => $record->lastSeen?->toDateTimeString(),+ default => null,+ };+ }++ /**+ * Route a single (field, target, value) triple. Native writes go+ * on the Asset instance (saved together at the end of the run).+ * External-source column writes gather into a batch. Custom+ * field writes hit the asset's dynamic column via the model's+ * standard attribute magic.+ *+ * @param array<string, mixed> $externalUpdates passed by reference+ */+ private static function writeToTarget(Asset $asset, array &$externalUpdates, string $target, mixed $value, ?SyncAdapterInstance $instance = null): void+ {+ if ($value === null && $target !== 'native:model') {+ // Nothing to write. Skip so we don't blank existing data on+ // partial syncs.+ return;+ }++ [$type, $id] = array_pad(explode(':', $target, 2), 2, '');++ switch ($type) {+ case 'native':+ self::writeNative($asset, $id, $value, $instance);+ break;+ case 'external':+ // Normalized field names get translated to actual+ // side-table column names here. Keeps the target+ // encoding symmetric with MappingTargets::FIELDS+ // rather than leaking `primary_` schema naming into+ // the target strings and translation keys.+ $column = match ($id) {+ 'mac' => 'primary_mac',+ 'ip' => 'primary_ip',+ default => $id,+ };+ $externalUpdates[$column] = $value;+ break;+ case 'custom':+ self::writeCustom($asset, (int) $id, $value);+ break;+ }+ }++ private static function writeNative(Asset $asset, string $column, mixed $value, ?SyncAdapterInstance $instance = null): void+ {+ switch ($column) {+ case 'name':+ if ($value !== null && $value !== '') {+ $asset->name = $value;+ }+ break;+ case 'serial':+ $asset->serial = $value;+ break;+ case 'asset_tag':+ // Only overwrite when the vendor sent a non-empty tag,+ // so a sync run that happens to omit the tag doesn't+ // blank whatever the admin already curated.+ if ($value !== null && $value !== '') {+ $asset->asset_tag = $value;+ }+ break;+ case 'notes':+ // Same non-empty guard as asset_tag. Reachable when+ // an admin routes a text-like extra (fleet_labels,+ // kandji_blueprint_id, etc.) to native:notes.+ if ($value !== null && $value !== '') {+ $asset->notes = $value;+ }+ break;+ case 'model':+ // Model comes as a string name. Resolve or auto-create+ // using the instance's configured default category+ // (or fall back to "Discovered Hardware" when unset).+ if ($value !== null && $value !== '') {+ $asset->model_id = self::resolveModelIdByName((string) $value, $instance);+ }+ break;+ }+ }++ private static function writeCustom(Asset $asset, int $customFieldId, mixed $value): void+ {+ $field = CustomField::find($customFieldId);+ if ($field === null || $field->db_column === null) {+ return;+ }++ $asset->{$field->db_column} = $value;+ }++ /**+ * Write the inventory columns onto the asset's external-source+ * row. The identity columns (source, external_id, company_id)+ * are already written at create time and never change here.+ * updateOrInsert covers the edge case where the identity row was+ * somehow deleted between the create step and this write.+ */+ private static function upsertExternalSource(Asset $asset, array $updates): void+ {+ DB::table('asset_external_sources')->updateOrInsert(+ ['asset_id' => $asset->id],+ $updates + ['updated_at' => now()],+ );+ }++ /**+ * Look up an AssetModel by the record's hardware_model string,+ * auto-create if missing. When the vendor sends no hardware_model+ * (osquery sometimes omits it, some MDMs return null for VMs),+ * return null so the caller / Asset validation ("model_id" is+ * required in Asset::$rules) refuses the save. That leaves the+ * host out of Snipe-IT rather than piling nameless assets into+ * an "Unknown" bucket admins can't clean up later.+ *+ * Auto-created models get hung off a "Discovered Hardware"+ * category which is itself get-or-created.+ */+ private static function resolveModelId(HostInventoryRecord $record, ?SyncAdapterInstance $instance = null): ?int+ {+ if ($record->hardwareModel === null || $record->hardwareModel === '') {+ return null;+ }++ return self::resolveModelIdByName($record->hardwareModel, $instance);+ }++ private static function resolveModelIdByName(string $modelName, ?SyncAdapterInstance $instance = null): int+ {+ $model = AssetModel::where('name', $modelName)->first();+ if ($model !== null) {+ return $model->id;+ }++ $model = new AssetModel;+ $model->name = $modelName;+ $model->category_id = self::categoryIdFor($instance);+ $model->save();++ return $model->id;+ }++ /**+ * Category id auto-created models get hung off. Uses the+ * adapter's configured default_category_id when set (and the+ * category still exists), else falls back to a get-or-create+ * "Discovered Hardware" category so we always produce a valid+ * category_id (AssetModel requires one).+ */+ private static function categoryIdFor(?SyncAdapterInstance $instance): int+ {+ if ($instance !== null) {+ $adapter = $instance->adapter();+ if ($adapter instanceof ConfigurableAdapter) {+ $configuredId = $adapter->defaultCategoryId();+ if ($configuredId !== null && Category::whereKey($configuredId)->exists()) {+ return $configuredId;+ }+ }+ }++ return Category::firstOrCreate(+ ['name' => 'Discovered Hardware', 'category_type' => 'asset'],+ )->id;+ }++ /**+ * Look up the vendor-reported user on the record against Snipe-IT+ * users per the adapter's configured match strategy, and assign+ * the asset when the lookup succeeds. Never un-assigns: a payload+ * missing the user field leaves the existing assignment intact.+ */+ private static function assignUserIfMatched(Asset $asset, HostInventoryRecord $record, ?SyncAdapterInstance $instance): void+ {+ if ($instance === null) {+ return;+ }++ $adapter = $instance->adapter();+ if (! $adapter instanceof ConfigurableAdapter) {+ return;+ }++ $strategy = $adapter->userMatchStrategy();+ if ($strategy === 'none') {+ return;+ }++ // Build the ordered list of (field, value) attempts. Cascade+ // strategy tries username first (guaranteed unique in+ // Snipe-IT) then email as fallback. Explicit single-field+ // strategies produce one attempt.+ $attempts = match ($strategy) {+ 'email' => [['email', $record->assignedUserEmail]],+ 'username' => [['username', $record->assignedUserName]],+ 'username_then_email' => [+ ['username', $record->assignedUserName],+ ['email', $record->assignedUserEmail],+ ],+ default => [],+ };++ // Filter out attempts where the vendor gave us nothing to+ // match on so we can distinguish "vendor reported no user at+ // all" from "vendor gave us a user we couldn't find". The+ // first case may trigger the opt-in checkin-on-null path.+ // The second gets a warning log.+ $attempts = array_values(array_filter(+ $attempts,+ fn (array $a) => is_string($a[1]) && $a[1] !== '',+ ));++ if ($attempts === []) {+ if ($adapter->checksInOnNullUser()+ && $asset->assigned_to !== null+ && $asset->assigned_type === User::class) {+ self::silentCheckinAsset($asset, $instance);+ }++ return;+ }++ $user = null;+ $matchedVia = null;+ foreach ($attempts as [$field, $value]) {+ $candidate = User::query()->where($field, $value)->first();+ if ($candidate !== null) {+ $user = $candidate;+ $matchedVia = sprintf('%s=%s', $field, $value);+ break;+ }+ }++ if ($user === null) {+ $tried = implode(', ', array_map(+ fn (array $a) => sprintf('%s=%s', $a[0], $a[1]),+ $attempts,+ ));+ Log::channel('sync-adapters')->warning(sprintf(+ '%s sync: no Snipe-IT user matched (strategy=%s, tried [%s]) for host %s',+ $instance->slug,+ $strategy,+ $tried,+ $record->sourceId,+ ));++ return;+ }++ Log::channel('sync-adapters')->info(sprintf(+ '%s sync: matched user via %s for host %s',+ $instance->slug,+ $matchedVia,+ $record->sourceId,+ ));++ // Already assigned to the resolved user: no-op.+ if ((int) $asset->assigned_to === (int) $user->id+ && $asset->assigned_type === User::class) {+ return;+ }++ // Suppress mode: always silent (direct assignment). Otherwise+ // fall through to Asset::checkOut() which fires the+ // CheckoutableCheckedOut event and its notification listener.+ // The event constructor requires a non-null admin User. auth()+ // is null for CLI-triggered sync runs, so silently fall back+ // to direct assignment when there's no auth context to attach+ // the event to.+ $admin = auth()->user();+ if ($adapter->suppressesNotifications() || $admin === null) {+ self::silentAssignToUser($asset, $user);+ } else {+ $asset->checkOut(+ target: $user,+ admin: $admin,+ checkout_at: now()->toDateTimeString(),+ note: 'Assigned via sync from '.$instance->slug,+ name: $asset->name,+ );+ }+ }++ /**+ * Direct assignment that skips the CheckoutableCheckedOut event+ * (and therefore the checkout-email listener). Used when the+ * adapter has suppress_notifications on. Still writes an+ * Actionlog entry so the asset's history reflects the assignment.+ */+ private static function silentAssignToUser(Asset $asset, User $user): void+ {+ $asset->assigned_to = $user->id;+ $asset->assigned_type = User::class;+ $asset->last_checkout = now();+ if ($user->location_id !== null) {+ $asset->location_id = $user->location_id;+ }+ $asset->saveOrFail();++ $log = new Actionlog;+ $log->item_id = $asset->id;+ $log->item_type = Asset::class;+ $log->target_id = $user->id;+ $log->target_type = User::class;+ $log->created_at = now();+ $log->created_by = null; // system-driven+ $log->note = 'Assigned via sync';+ $log->logaction('checkout');+ }++ /**+ * Silent counterpart to silentAssignToUser: clears the assignment+ * on the asset and writes a checkin Actionlog so the asset's+ * history shows the sync-driven un-assign. Skips the standard+ * CheckoutableCheckedIn event to keep scheduled syncs from+ * blasting checkin notifications every cycle.+ */+ private static function silentCheckinAsset(Asset $asset, SyncAdapterInstance $instance): void+ {+ $previousUserId = $asset->assigned_to;+ $previousUserType = $asset->assigned_type;++ $asset->assigned_to = null;+ $asset->assigned_type = null;+ $asset->last_checkin = now();+ $asset->saveOrFail();++ $log = new Actionlog;+ $log->item_id = $asset->id;+ $log->item_type = Asset::class;+ $log->target_id = $previousUserId;+ $log->target_type = $previousUserType;+ $log->created_at = now();+ $log->created_by = null;+ $log->note = 'Checked in via sync from '.$instance->slug.' (vendor reported no assigned user)';+ $log->logaction('checkin from');+ }+}diff --git a/app/SyncAdapters/Unifi/UnifiAdapter.php b/app/SyncAdapters/Unifi/UnifiAdapter.phpnew file mode 100644index 0000000000..d06647024c--- /dev/null+++ b/app/SyncAdapters/Unifi/UnifiAdapter.php@@ -0,0 +1,119 @@+<?php++namespace App\SyncAdapters\Unifi;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * UniFi adapter. Pulls network-hardware inventory (APs, switches,+ * gateways, cameras) from a UniFi controller and normalizes it into+ * HostInventoryRecord objects.+ *+ * Uses UniFi's modern Network Integration API with X-API-KEY bearer+ * auth (UniFi OS 4.0.6+ / Network Application 9.0.108+ / Site Manager+ * cloud). Older controllers on session-cookie auth are not supported.+ * Admins should upgrade UniFi rather than us carrying the legacy+ * cookie flow.+ *+ * Site scoping: the UniFi API is site-scoped. The Site ID field pins+ * this instance to one site. Multi-site controllers create one+ * sync-adapter instance per site (each with its own tab under+ * Settings -> Sync Adapters).+ */+class UnifiAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'UniFi';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://your-controller:8443';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'api_key',+ 'label' => 'API Key',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_unifi_api_key_help'),+ ],+ [+ 'key' => 'site_id',+ 'label' => 'Site ID',+ 'help' => trans('admin/settings/general.sync_adapter_unifi_site_id_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'unifi_model_key' => 'UniFi Model Code',+ 'unifi_state' => 'UniFi Device State',+ 'unifi_uplink_mac' => 'UniFi Uplink MAC',+ 'unifi_adopted' => ['label' => 'UniFi Adopted', 'type' => 'boolean'],+ ];+ }++ public function pull(): iterable+ {+ $client = new UnifiClient(+ baseUrl: $this->url(),+ apiKey: $this->credential('api_key'),+ siteId: $this->credential('site_id'),+ );++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a UniFi device payload into the normalized record shape.+ * UniFi's `id` (UUID) is stable per adopted device and is what we+ * key asset_external_sources on. Serial is populated on most+ * device types but occasionally null on virtual or legacy devices.+ * SyncHostFromAdapter treats null serials as acceptable so the+ * asset still lands even when the controller doesn't report one.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'id'),+ hostname: Arr::get($device, 'name'),+ hardwareSerial: Arr::get($device, 'serialNumber'),+ hardwareModel: Arr::get($device, 'model'),+ manufacturer: 'Ubiquiti',+ primaryMac: Arr::get($device, 'macAddress'),+ primaryIp: Arr::get($device, 'ipAddress'),+ os: 'UniFi',+ osVersion: Arr::get($device, 'firmwareVersion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'lastSeen')),+ extra: [+ 'unifi_model_key' => Arr::get($device, 'modelKey'),+ 'unifi_state' => Arr::get($device, 'state'),+ 'unifi_uplink_mac' => Arr::get($device, 'uplink.mac'),+ 'unifi_adopted' => Arr::get($device, 'adopted'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/Unifi/UnifiClient.php b/app/SyncAdapters/Unifi/UnifiClient.phpnew file mode 100644index 0000000000..c530267454--- /dev/null+++ b/app/SyncAdapters/Unifi/UnifiClient.php@@ -0,0 +1,79 @@+<?php++namespace App\SyncAdapters\Unifi;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the UniFi Network Integration API. Owns auth ++ * pagination for the endpoints the sync adapter uses. Yields raw+ * decoded JSON, no normalization (that's the adapter's job).+ *+ * Auth model: API key generated in the UniFi admin console under+ * Settings -> Admins & Users -> API Keys, passed via `X-API-KEY`+ * header. Available on UniFi OS 4.0.6+, UniFi Network Application+ * 9.0.108+, and Site Manager cloud. Older controllers only support+ * session-cookie auth which this client does not implement.+ *+ * Endpoint path is under /proxy/network/integration/v1/ on local+ * controllers, or at api.ui.com/v1/ on Site Manager cloud. The+ * adapter's Base URL setting controls which. the paths this client+ * hits are relative and identical on both.+ *+ * UniFi Network Integration API reference:+ * https://developer.ui.com/unifi-api/+ */+class UnifiClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $apiKey,+ private readonly string $siteId,+ ) {}++ /**+ * List every managed device in the configured UniFi site (APs,+ * switches, gateways, cameras, etc). Returns a generator so+ * callers stream through large deployments without buffering the+ * whole list in memory.+ *+ * @return iterable<array<string, mixed>>+ */+ public function devices(int $limit = 100): iterable+ {+ $offset = 0;++ do {+ $response = $this->request()+ ->get('/proxy/network/integration/v1/sites/'.$this->siteId.'/devices', [+ 'offset' => $offset,+ 'limit' => $limit,+ ])+ ->throw()+ ->json();++ $devices = $response['data'] ?? [];+ foreach ($devices as $device) {+ yield $device;+ }++ // Stop when seen-so-far reaches totalCount or a short+ // page comes back. Belt-and-suspenders: either signal+ // alone would work.+ $total = $response['totalCount'] ?? null;+ $seenSoFar = $offset + count($devices);+ $done = count($devices) < $limit+ || ($total !== null && $seenSoFar >= $total);+ $offset += $limit;+ } while (! $done);+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withHeaders(['X-API-KEY' => $this->apiKey])+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.phpnew file mode 100644index 0000000000..506c482cd8--- /dev/null+++ b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php@@ -0,0 +1,313 @@+<?php++namespace App\SyncAdapters\WorkspaceOne;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * Omnissa Workspace ONE adapter (formerly VMware Workspace ONE UEM,+ * originally AirWatch). Pulls managed devices from the REST device+ * search endpoint via OAuth 2.0 client credentials. Also pushes+ * Snipe-IT asset_tag back via WS1's AssetNumber field on the+ * device-update endpoint.+ *+ * Modern Workspace ONE tenants use OAuth 2.0 client credentials+ * against a per-region auth endpoint (na.uemauth.vmwservices.com,+ * emea.uemauth.vmwservices.com, apac.uemauth.vmwservices.com, etc.).+ * The access token is carried as `Authorization: Bearer` on Dashboard+ * API calls plus an `aw-tenant-code` header identifying which tenant+ * to scope the call to. tenant_code and client_id are non-secret.+ * Only client_secret encrypts at rest.+ *+ * The Base URL field on the settings page controls the Dashboard API+ * host (e.g. asXXX.awmdm.com). The region-appropriate auth endpoint+ * is derived from the same host convention below.+ *+ * Legacy tenants on Basic-auth + admin credentials aren't covered by+ * this schema. If someone needs it, a WorkspaceOneBasicAuthAdapter+ * sibling with a different schema is the right shape rather than+ * making this schema conditional on auth mode.+ */+class WorkspaceOneAdapter extends ConfigurableAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'Omnissa Workspace ONE';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://as###.awmdm.com';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'tenant_code',+ 'label' => 'Tenant Code',+ 'help' => trans('admin/settings/general.sync_adapter_workspace_one_tenant_code_help'),+ ],+ [+ 'key' => 'client_id',+ 'label' => 'Client ID',+ 'help' => trans('admin/settings/general.sync_adapter_workspace_one_client_id_help'),+ ],+ [+ 'key' => 'client_secret',+ 'label' => 'Client Secret',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_workspace_one_client_secret_help'),+ ],+ ];+ }++ public function pull(): iterable+ {+ $apiBaseUrl = $this->url();++ $client = new WorkspaceOneClient(+ apiBaseUrl: $apiBaseUrl,+ authBaseUrl: $this->deriveAuthBaseUrl($apiBaseUrl),+ tenantCode: $this->credential('tenant_code'),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ );++ foreach ($client->devices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Derive the region-scoped OAuth token host from the API host.+ * Workspace ONE uses a per-region auth endpoint. asXXX.awmdm.com+ * → na.uemauth.vmwservices.com etc. The mapping is inferred from+ * the first two chars of the API host (as-, ds-, uat-).+ * Falls back to the NA endpoint when the base URL doesn't parse.+ */+ private function deriveAuthBaseUrl(string $apiBaseUrl): string+ {+ $host = parse_url($apiBaseUrl, PHP_URL_HOST);+ if (! is_string($host)) {+ return 'https://na.uemauth.vmwservices.com';+ }++ $prefix = strtolower(substr($host, 0, 3));++ return match ($prefix) {+ 'apa' => 'https://apac.uemauth.vmwservices.com',+ 'eme' => 'https://emea.uemauth.vmwservices.com',+ 'uat' => 'https://uat.uemauth.vmwservices.com',+ default => 'https://na.uemauth.vmwservices.com',+ };+ }++ /**+ * Convert a Workspace ONE device payload into the normalized record+ * shape. Uuid is the stable identifier across renames + re-enrollments+ * so we key asset_external_sources on it. UserEmailAddress is the+ * OS-level assignment. UserName is the enrollment account and can+ * differ.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) (Arr::get($device, 'Uuid') ?? Arr::get($device, 'Id.Value')),+ hostname: Arr::get($device, 'DeviceFriendlyName')+ ?? Arr::get($device, 'HostName'),+ hardwareSerial: Arr::get($device, 'SerialNumber'),+ hardwareModel: Arr::get($device, 'Model'),+ manufacturer: Arr::get($device, 'DeviceManufacturer'),+ primaryMac: Arr::get($device, 'MacAddress'),+ primaryIp: Arr::get($device, 'DeviceNetworkInfo.0.IPAddress')+ ?? Arr::get($device, 'IpAddress'),+ os: Arr::get($device, 'Platform') ?? Arr::get($device, 'OperatingSystem'),+ osVersion: Arr::get($device, 'OperatingSystem'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'LastSeen')),+ assignedUserEmail: Arr::get($device, 'UserEmailAddress'),+ assignedUserName: Arr::get($device, 'UserName'),+ extra: [+ 'workspace_one_enrollment_status' => Arr::get($device, 'EnrollmentStatus'),+ 'workspace_one_compliance_status' => Arr::get($device, 'ComplianceStatus'),+ 'workspace_one_ownership' => Arr::get($device, 'Ownership'),+ 'workspace_one_organization_group' => Arr::get($device, 'LocationGroupName'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }++ /**+ * WS1 writes need the OAuth application's role to include+ * device-write scope. Same credential used for pull works when+ * scoped correctly. No tier gate.+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * Workspace ONE's device record has no first-class freeform+ * notes field admins can rely on. Custom Attributes exist but+ * need per-tenant admin setup, same shape as NinjaOne's custom+ * fields. Return null for now. A future extension could accept+ * a Custom Attribute name in the credential schema.+ */+ public function notesFieldTarget(): ?string+ {+ return null;+ }++ /**+ * Push Snipe-IT asset_tag to WS1's AssetNumber field via the+ * device-update endpoint. Keys the device by UUID (WS1's stable+ * identifier across enrollment renames), which we cached as+ * external_id during pull.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): void+ {+ // Don't early-exit on empty pushFields. Composed notes may+ // still be configured without any per-field direction=push.+ // Only skip when we have push fields AND the caller told us+ // none of them are in the changed set.+ $pushFields = $this->pushDirectedFields();+ if ($pushFields !== [] && $changedFields !== []+ && array_intersect($changedFields, $pushFields) === []) {+ return;+ }++ $externalSource = AssetExternalSource::query()+ ->where('asset_id', $asset->id)+ ->where('source', $this->name())+ ->first();++ if ($externalSource === null) {+ return;+ }++ $payload = [];+ foreach ($pushFields as $field) {+ $mapped = self::sourceFieldToWs1Field($field);+ if ($mapped === null) {+ continue;+ }++ $value = $this->assetValueForSourceField($asset, $field);+ if ($value === null) {+ continue;+ }++ $payload[$mapped] = $value;+ }++ // Composed notes go to a WS1 Custom Attribute via a separate+ // endpoint from the top-level device fields (AssetNumber uses+ // PUT /devices/{uuid}, Custom Attributes use POST+ // /devices/{uuid}/customattributes). Two API calls when both+ // are configured. Admin sets the Custom Attribute name via+ // the composed-notes fieldset override. Nothing default+ // because WS1 has no built-in notes concept for us to guess.+ $notesTemplate = $this->pushNotesTemplate();+ $notesTarget = $this->effectiveNotesTarget();+ $composed = ($notesTemplate !== '' && $notesTarget !== null)+ ? \App\SyncAdapters\Support\NotesComposer::compose($asset, $notesTemplate)+ : '';++ if ($payload === [] && $composed === '') {+ return;+ }++ if ($this->isPushDryRun()) {+ if ($payload !== []) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would PUT Workspace ONE device %s with %s',+ $this->name(),+ $externalSource->external_id,+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ ));+ }+ if ($composed !== '') {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would set Workspace ONE Custom Attribute %s=%s on device %s',+ $this->name(),+ $notesTarget,+ $composed,+ $externalSource->external_id,+ ));+ }++ return;+ }++ $apiBaseUrl = $this->url();+ $client = new WorkspaceOneClient(+ apiBaseUrl: $apiBaseUrl,+ authBaseUrl: $this->deriveAuthBaseUrl($apiBaseUrl),+ tenantCode: $this->credential('tenant_code'),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ );++ if ($payload !== []) {+ $client->updateDevice($externalSource->external_id, $payload);+ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Workspace ONE device %s with fields [%s]',+ $this->name(),+ $externalSource->external_id,+ implode(', ', array_keys($payload)),+ ));+ }++ if ($composed !== '') {+ $client->updateDeviceCustomAttribute($externalSource->external_id, $notesTarget, $composed);+ Log::channel('sync-adapters')->info(sprintf(+ '%s push: set Workspace ONE Custom Attribute "%s" on device %s',+ $this->name(),+ $notesTarget,+ $externalSource->external_id,+ ));+ }+ }++ /**+ * Map a source-field name to Workspace ONE's device-record field+ * name. AssetNumber is WS1's native asset_tag equivalent (a+ * top-level string field on the device object).+ */+ private static function sourceFieldToWs1Field(string $field): ?string+ {+ return match ($field) {+ 'asset_tag' => 'AssetNumber',+ default => null,+ };+ }++ private function assetValueForSourceField(Asset $asset, string $field): mixed+ {+ return match ($field) {+ 'asset_tag' => $asset->asset_tag,+ default => null,+ };+ }+}diff --git a/app/SyncAdapters/WorkspaceOne/WorkspaceOneClient.php b/app/SyncAdapters/WorkspaceOne/WorkspaceOneClient.phpnew file mode 100644index 0000000000..747a82d71f--- /dev/null+++ b/app/SyncAdapters/WorkspaceOne/WorkspaceOneClient.php@@ -0,0 +1,138 @@+<?php++namespace App\SyncAdapters\WorkspaceOne;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Omnissa Workspace ONE UEM REST API.+ * Handles OAuth 2.0 client-credentials token exchange against the+ * region-scoped auth host and page-based iteration through the+ * device search endpoint.+ *+ * Auth model: client_id + client_secret from a Workspace ONE OAuth+ * application, exchanged at the region-appropriate token endpoint.+ * The `aw-tenant-code` header identifies which Workspace ONE tenant+ * the call is scoped to. The same value can be used across every+ * request in a sync run.+ *+ * Pagination: /api/mdm/devices/search returns { Total, PageSize,+ * Page, Devices[] }. Page is zero-indexed. Walk pages until the+ * running count reaches Total (or the page comes back empty).+ */+class WorkspaceOneClient+{+ private ?string $token = null;++ public function __construct(+ private readonly string $apiBaseUrl,+ private readonly string $authBaseUrl,+ private readonly string $tenantCode,+ private readonly string $clientId,+ private readonly string $clientSecret,+ ) {}++ /**+ * Iterate every device visible to the OAuth application.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function devices(int $pageSize = 500): iterable+ {+ $page = 0;+ $seen = 0;++ do {+ $response = $this->request()+ ->get('/api/mdm/devices/search', [+ 'pagesize' => $pageSize,+ 'page' => $page,+ ])+ ->throw()+ ->json();++ $devices = $response['Devices'] ?? [];+ foreach ($devices as $device) {+ yield $device;+ }++ $seen += count($devices);+ $total = $response['Total'] ?? null;+ $done = count($devices) === 0+ || ($total !== null && $seen >= $total);+ $page++;+ } while (! $done);+ }++ /**+ * Fetch (or reuse) a bearer token via OAuth 2.0 client-credentials+ * against the region-scoped auth host.+ */+ private function bearer(): string+ {+ if ($this->token !== null) {+ return $this->token;+ }++ $response = Http::asForm()+ ->timeout(30)+ ->post(rtrim($this->authBaseUrl, '/').'/connect/token', [+ 'grant_type' => 'client_credentials',+ 'client_id' => $this->clientId,+ 'client_secret' => $this->clientSecret,+ ])+ ->throw()+ ->json();++ return $this->token = (string) ($response['access_token'] ?? '');+ }++ /**+ * Update a device's writable metadata via Workspace ONE's device+ * update endpoint. AssetNumber is WS1's asset_tag equivalent, a+ * top-level string field on the device record.+ *+ * @param array<string, scalar|null> $payload+ */+ public function updateDevice(string $deviceUuid, array $payload): void+ {+ $this->request()+ ->asJson()+ ->put('/api/mdm/devices/'.$deviceUuid, $payload)+ ->throw();+ }++ /**+ * Set a Custom Attribute value on a device. WS1 Custom Attributes+ * are separately-defined key-value pairs the admin creates under+ * Devices -> Profiles & Resources -> Custom Attributes. Writing+ * uses a different endpoint from device-level fields (`AssetNumber`+ * uses updateDevice above). The `Application` / `AttributeName` /+ * `Value` shape is what WS1's REST API expects for CA writes.+ */+ public function updateDeviceCustomAttribute(string $deviceUuid, string $attributeName, string $value): void+ {+ $this->request()+ ->asJson()+ ->post('/api/mdm/devices/'.$deviceUuid.'/customattributes', [+ 'CustomAttributes' => [+ [+ 'Name' => $attributeName,+ 'Value' => $value,+ 'Application' => 'com.snipeit.sync',+ ],+ ],+ ])+ ->throw();+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->apiBaseUrl, '/'))+ ->withToken($this->bearer())+ ->withHeaders(['aw-tenant-code' => $this->tenantCode])+ ->acceptJson()+ ->timeout(30);+ }+}diff --git a/app/SyncAdapters/Zentral/ZentralAdapter.php b/app/SyncAdapters/Zentral/ZentralAdapter.phpnew file mode 100644index 0000000000..f32ceee97c--- /dev/null+++ b/app/SyncAdapters/Zentral/ZentralAdapter.php@@ -0,0 +1,86 @@+<?php++namespace App\SyncAdapters\Zentral;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * Zentral adapter. Pulls the aggregated inventory snapshot (merged+ * from every Zentral source module: Munki, Santa, MDM, Osquery, etc.)+ * and normalizes it into HostInventoryRecord objects.+ */+class ZentralAdapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'Zentral';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => 'API Token',+ 'secret' => true,+ 'help' => trans('admin/settings/general.sync_adapter_zentral_token_help'),+ ],+ ];+ }++ public function pull(): iterable+ {+ $client = new ZentralClient(baseUrl: $this->url(), token: $this->credential('token'));++ foreach ($client->machines() as $machine) {+ yield $this->normalize($machine);+ }+ }++ /**+ * Convert a Zentral machine snapshot into the normalized record+ * shape. Zentral keys machines on serial number (its primary+ * identifier across every source module), so that doubles as+ * external_id here.+ *+ * @param array<string, mixed> $machine+ */+ private function normalize(array $machine): HostInventoryRecord+ {+ $serial = Arr::get($machine, 'serial_number');++ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) $serial,+ hostname: Arr::get($machine, 'computer_name') ?? Arr::get($machine, 'hostname'),+ hardwareSerial: $serial,+ hardwareModel: Arr::get($machine, 'system_info.hardware_model')+ ?? Arr::get($machine, 'hardware_model'),+ manufacturer: Arr::get($machine, 'system_info.hardware_vendor')+ ?? Arr::get($machine, 'hardware_vendor'),+ primaryMac: Arr::get($machine, 'network_interfaces.0.mac'),+ primaryIp: Arr::get($machine, 'network_interfaces.0.address'),+ os: Arr::get($machine, 'os_version.name') ?? Arr::get($machine, 'platform'),+ osVersion: Arr::get($machine, 'os_version.version')+ ?? Arr::get($machine, 'os_version'),+ lastSeen: $this->parseTimestamp(Arr::get($machine, 'last_seen')),+ extra: [+ 'zentral_pk' => Arr::get($machine, 'id'),+ 'zentral_source' => Arr::get($machine, 'source.name'),+ 'zentral_cpu_type' => Arr::get($machine, 'system_info.cpu_type'),+ ],+ );+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/Zentral/ZentralClient.php b/app/SyncAdapters/Zentral/ZentralClient.phpnew file mode 100644index 0000000000..63fd2a9e19--- /dev/null+++ b/app/SyncAdapters/Zentral/ZentralClient.php@@ -0,0 +1,65 @@+<?php++namespace App\SyncAdapters\Zentral;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Zentral inventory API. Owns auth ++ * pagination for the endpoints the sync adapter uses.+ *+ * Auth model: service account API token from the Zentral admin+ * console, passed via the `Authorization: Token <token>` header+ * (Django REST Framework's TokenAuthentication shape).+ *+ * Zentral aggregates inventory from many sources (Munki, Santa,+ * MDM, Osquery, etc.). The /api/inventory/machines/ endpoint returns+ * the merged view: one row per physical machine keyed on serial.+ */+class ZentralClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $token,+ ) {}++ /**+ * Iterate every machine snapshot in the Zentral inventory.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function machines(int $limit = 100): iterable+ {+ $offset = 0;++ do {+ $response = $this->request()+ ->get('/api/inventory/machines/', [+ 'limit' => $limit,+ 'offset' => $offset,+ ])+ ->throw()+ ->json();++ $results = $response['results'] ?? (is_array($response) ? $response : []);+ foreach ($results as $machine) {+ yield $machine;+ }++ $total = $response['count'] ?? null;+ $seenSoFar = $offset + count($results);+ $done = count($results) < $limit+ || ($total !== null && $seenSoFar >= $total);+ $offset += $limit;+ } while (! $done);+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withHeaders(['Authorization' => 'Token '.$this->token])+ ->acceptJson()+ ->timeout(30);+ }+}