-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstallation_tracker.py
More file actions
executable file
·2746 lines (2433 loc) · 118 KB
/
installation_tracker.py
File metadata and controls
executable file
·2746 lines (2433 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Installation Tracker for clawbot/moltbot/openclaw
Detects installations, active status, and connection resources.
"""
import json
import os
import re
import socket
import subprocess
import glob
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, List, Any
# Try to import yaml, fallback to basic parsing if not available
try:
import yaml
YAML_AVAILABLE = True
except ImportError:
YAML_AVAILABLE = False
# Configuration - Add your API key here
API_KEY = "YOUR_API_KEY_HERE"
# Known services/apps for categorization
KNOWN_SERVICES = {
# AI/ML Services
"anthropic": {"name": "Anthropic Claude", "category": "AI/ML"},
"openai": {"name": "OpenAI", "category": "AI/ML"},
"api.openai.com": {"name": "OpenAI API", "category": "AI/ML"},
"api.anthropic.com": {"name": "Anthropic API", "category": "AI/ML"},
"huggingface": {"name": "Hugging Face", "category": "AI/ML"},
"cohere": {"name": "Cohere", "category": "AI/ML"},
"replicate": {"name": "Replicate", "category": "AI/ML"},
"palm": {"name": "Google PaLM", "category": "AI/ML"},
"gemini": {"name": "Google Gemini", "category": "AI/ML"},
"vertex": {"name": "Google Vertex AI", "category": "AI/ML"},
"bedrock": {"name": "AWS Bedrock", "category": "AI/ML"},
"azure.openai": {"name": "Azure OpenAI", "category": "AI/ML"},
# Cloud Providers
"amazonaws.com": {"name": "AWS", "category": "Cloud"},
"aws": {"name": "AWS", "category": "Cloud"},
"s3.": {"name": "AWS S3", "category": "Cloud Storage"},
"ec2.": {"name": "AWS EC2", "category": "Cloud Compute"},
"lambda.": {"name": "AWS Lambda", "category": "Cloud Compute"},
"azure": {"name": "Microsoft Azure", "category": "Cloud"},
"blob.core.windows": {"name": "Azure Blob Storage", "category": "Cloud Storage"},
"googleapis.com": {"name": "Google Cloud", "category": "Cloud"},
"storage.googleapis": {"name": "Google Cloud Storage", "category": "Cloud Storage"},
"digitalocean": {"name": "DigitalOcean", "category": "Cloud"},
# Version Control
"github.com": {"name": "GitHub", "category": "Version Control"},
"api.github.com": {"name": "GitHub API", "category": "Version Control"},
"gitlab": {"name": "GitLab", "category": "Version Control"},
"bitbucket": {"name": "Bitbucket", "category": "Version Control"},
# Databases
"mongodb": {"name": "MongoDB", "category": "Database"},
"postgres": {"name": "PostgreSQL", "category": "Database"},
"mysql": {"name": "MySQL", "category": "Database"},
"redis": {"name": "Redis", "category": "Database"},
"elasticsearch": {"name": "Elasticsearch", "category": "Database"},
"dynamodb": {"name": "AWS DynamoDB", "category": "Database"},
"firestore": {"name": "Google Firestore", "category": "Database"},
"supabase": {"name": "Supabase", "category": "Database"},
# Calendar Services
"calendar": {"name": "Calendar Service", "category": "Calendar"},
"google.com/calendar": {"name": "Google Calendar", "category": "Calendar"},
"calendar.google.com": {"name": "Google Calendar", "category": "Calendar"},
"googleapis.com/calendar": {"name": "Google Calendar API", "category": "Calendar"},
"www.googleapis.com/calendar": {"name": "Google Calendar API", "category": "Calendar"},
"outlook.office.com/calendar": {"name": "Outlook Calendar", "category": "Calendar"},
"outlook.office365.com": {"name": "Microsoft 365 Calendar", "category": "Calendar"},
"graph.microsoft.com": {"name": "Microsoft Graph API", "category": "Calendar"},
"calendly": {"name": "Calendly", "category": "Calendar"},
"calendly.com": {"name": "Calendly", "category": "Calendar"},
"api.calendly.com": {"name": "Calendly API", "category": "Calendar"},
"cal.com": {"name": "Cal.com", "category": "Calendar"},
"ical": {"name": "iCalendar", "category": "Calendar"},
"caldav": {"name": "CalDAV", "category": "Calendar"},
"webcal": {"name": "Web Calendar", "category": "Calendar"},
"nylas": {"name": "Nylas Calendar", "category": "Calendar"},
"cronofy": {"name": "Cronofy", "category": "Calendar"},
"timekit": {"name": "Timekit", "category": "Calendar"},
"acuityscheduling": {"name": "Acuity Scheduling", "category": "Calendar"},
"doodle": {"name": "Doodle", "category": "Calendar"},
"eventbrite": {"name": "Eventbrite", "category": "Calendar"},
"meetup": {"name": "Meetup", "category": "Calendar"},
"zoom": {"name": "Zoom", "category": "Calendar"},
"teams.microsoft": {"name": "Microsoft Teams", "category": "Calendar"},
"meet.google": {"name": "Google Meet", "category": "Calendar"},
# Note-taking / Knowledge Management
"obsidian": {"name": "Obsidian", "category": "Notes"},
"obsidian.md": {"name": "Obsidian", "category": "Notes"},
"sync.obsidian.md": {"name": "Obsidian Sync", "category": "Notes"},
"publish.obsidian.md": {"name": "Obsidian Publish", "category": "Notes"},
"api.obsidian.md": {"name": "Obsidian API", "category": "Notes"},
"roam": {"name": "Roam Research", "category": "Notes"},
"roamresearch": {"name": "Roam Research", "category": "Notes"},
"logseq": {"name": "Logseq", "category": "Notes"},
"evernote": {"name": "Evernote", "category": "Notes"},
"onenote": {"name": "OneNote", "category": "Notes"},
"bear": {"name": "Bear Notes", "category": "Notes"},
"craft": {"name": "Craft", "category": "Notes"},
"apple.notes": {"name": "Apple Notes", "category": "Notes"},
"standardnotes": {"name": "Standard Notes", "category": "Notes"},
"simplenote": {"name": "Simplenote", "category": "Notes"},
"joplin": {"name": "Joplin", "category": "Notes"},
"dendron": {"name": "Dendron", "category": "Notes"},
"remnote": {"name": "RemNote", "category": "Notes"},
"mem.ai": {"name": "Mem", "category": "Notes"},
"capacities": {"name": "Capacities", "category": "Notes"},
"anytype": {"name": "Anytype", "category": "Notes"},
"tana": {"name": "Tana", "category": "Notes"},
"coda": {"name": "Coda", "category": "Notes"},
# Communication
"slack": {"name": "Slack", "category": "Communication"},
"slack.com": {"name": "Slack", "category": "Communication"},
"hooks.slack.com": {"name": "Slack Webhook", "category": "Communication"},
"discord": {"name": "Discord", "category": "Communication"},
"discord.com": {"name": "Discord", "category": "Communication"},
"discordapp.com": {"name": "Discord", "category": "Communication"},
"telegram": {"name": "Telegram", "category": "Communication"},
"telegram.org": {"name": "Telegram", "category": "Communication"},
"api.telegram.org": {"name": "Telegram Bot API", "category": "Communication"},
"t.me": {"name": "Telegram Link", "category": "Communication"},
"core.telegram.org": {"name": "Telegram Core", "category": "Communication"},
"twilio": {"name": "Twilio", "category": "Communication"},
"sendgrid": {"name": "SendGrid", "category": "Communication"},
"mailgun": {"name": "Mailgun", "category": "Communication"},
"whatsapp": {"name": "WhatsApp", "category": "Communication"},
"signal": {"name": "Signal", "category": "Communication"},
# Authentication
"auth0": {"name": "Auth0", "category": "Authentication"},
"okta": {"name": "Okta", "category": "Authentication"},
"oauth": {"name": "OAuth Provider", "category": "Authentication"},
"cognito": {"name": "AWS Cognito", "category": "Authentication"},
# Monitoring/Logging
"datadog": {"name": "Datadog", "category": "Monitoring"},
"sentry": {"name": "Sentry", "category": "Monitoring"},
"newrelic": {"name": "New Relic", "category": "Monitoring"},
"splunk": {"name": "Splunk", "category": "Monitoring"},
"grafana": {"name": "Grafana", "category": "Monitoring"},
"prometheus": {"name": "Prometheus", "category": "Monitoring"},
# CI/CD
"jenkins": {"name": "Jenkins", "category": "CI/CD"},
"circleci": {"name": "CircleCI", "category": "CI/CD"},
"travis": {"name": "Travis CI", "category": "CI/CD"},
"actions.github": {"name": "GitHub Actions", "category": "CI/CD"},
# Container/Orchestration
"docker": {"name": "Docker", "category": "Container"},
"kubernetes": {"name": "Kubernetes", "category": "Orchestration"},
"k8s": {"name": "Kubernetes", "category": "Orchestration"},
# Project Management / Productivity
"jira": {"name": "Jira", "category": "Project Management"},
"atlassian": {"name": "Atlassian", "category": "Project Management"},
"trello": {"name": "Trello", "category": "Project Management"},
"asana": {"name": "Asana", "category": "Project Management"},
"notion": {"name": "Notion", "category": "Productivity"},
"airtable": {"name": "Airtable", "category": "Productivity"},
"monday": {"name": "Monday.com", "category": "Project Management"},
"clickup": {"name": "ClickUp", "category": "Project Management"},
"linear": {"name": "Linear", "category": "Project Management"},
# Payment / E-commerce
"stripe": {"name": "Stripe", "category": "Payment"},
"paypal": {"name": "PayPal", "category": "Payment"},
"shopify": {"name": "Shopify", "category": "E-commerce"},
# CRM / Marketing
"salesforce": {"name": "Salesforce", "category": "CRM"},
"hubspot": {"name": "HubSpot", "category": "CRM"},
"zendesk": {"name": "Zendesk", "category": "Support"},
"intercom": {"name": "Intercom", "category": "Support"},
"mailchimp": {"name": "Mailchimp", "category": "Marketing"},
# Analytics
"segment": {"name": "Segment", "category": "Analytics"},
"mixpanel": {"name": "Mixpanel", "category": "Analytics"},
"amplitude": {"name": "Amplitude", "category": "Analytics"},
"google-analytics": {"name": "Google Analytics", "category": "Analytics"},
"analytics.google": {"name": "Google Analytics", "category": "Analytics"},
# Automation / Integration Platforms
"zapier": {"name": "Zapier", "category": "Automation"},
"hooks.zapier": {"name": "Zapier Webhook", "category": "Automation"},
"ifttt": {"name": "IFTTT", "category": "Automation"},
"make.com": {"name": "Make (Integromat)", "category": "Automation"},
"n8n": {"name": "n8n", "category": "Automation"},
"pipedream": {"name": "Pipedream", "category": "Automation"},
# Local Services
"localhost": {"name": "Localhost", "category": "Local"},
"127.0.0.1": {"name": "Localhost", "category": "Local"},
"0.0.0.0": {"name": "All Interfaces", "category": "Local"},
}
# Known installation paths and configurations
# Based on actual moltbot/clawdbot source code from paths.ts:
# - State dir: ~/.moltbot (new) or ~/.clawdbot (legacy)
# - Config files: moltbot.json or clawdbot.json in state dir
# - Logs: macOS unified log (subsystem: bot.molt) + /tmp/moltbot-gateway.log
# - Default port: 18789
TOOL_CONFIGS = {
"openclaw": {
# openclaw is the same as moltbot (different branding)
"config_paths": [
"~/.moltbot/moltbot.json",
"~/.moltbot/clawdbot.json",
"~/.clawdbot/moltbot.json",
"~/.clawdbot/clawdbot.json",
"~/.openclaw/openclaw.json",
"~/.openclaw/config.json",
"~/.config/openclaw/config.json",
],
"log_paths": [
"/tmp/moltbot-gateway.log",
"/tmp/clawdbot-gateway.log",
"~/.moltbot/logs/*.log",
"~/.clawdbot/logs/*.log",
"~/.openclaw/logs/*.log",
],
"workspace_path": "~/.moltbot",
# Specific process patterns - avoid generic 'node'
"process_names": ["moltbot gateway", "moltbot-gateway", "clawdbot gateway", "clawdbot-gateway", "openclaw gateway", "openclaw-gateway"],
"default_port": 18789,
"binary_names": ["moltbot", "clawdbot", "openclaw"],
"macos_log_subsystem": "bot.molt", # macOS unified logging subsystem
},
"moltbot": {
"config_paths": [
"~/.moltbot/moltbot.json",
"~/.moltbot/clawdbot.json",
"~/.clawdbot/moltbot.json",
"~/.clawdbot/clawdbot.json",
"~/.config/moltbot/config.json",
],
"log_paths": [
"/tmp/moltbot-gateway.log",
"/tmp/clawdbot-gateway.log",
"~/.moltbot/logs/*.log",
"~/.clawdbot/logs/*.log",
],
"workspace_path": "~/.moltbot",
# Specific process patterns - avoid generic 'node'
"process_names": ["moltbot gateway", "moltbot-gateway", "clawdbot gateway", "clawdbot-gateway"],
"default_port": 18789,
"binary_names": ["moltbot"],
"macos_log_subsystem": "bot.molt",
},
"clawbot": {
# clawbot/clawdbot is the legacy name for moltbot
"config_paths": [
"~/.clawdbot/clawdbot.json",
"~/.clawdbot/moltbot.json",
"~/.moltbot/clawdbot.json",
"~/.moltbot/moltbot.json",
"~/.clawbot/config.json",
"~/.config/clawbot/config.json",
],
"log_paths": [
"/tmp/moltbot-gateway.log",
"/tmp/clawdbot-gateway.log",
"~/.clawdbot/logs/*.log",
"~/.moltbot/logs/*.log",
"~/.clawbot/logs/*.log",
],
"workspace_path": "~/.clawdbot",
# Specific process patterns - avoid generic 'node'
"process_names": ["clawdbot gateway", "clawdbot-gateway", "moltbot gateway", "moltbot-gateway"],
"default_port": 18789,
"binary_names": ["clawdbot", "clawbot", "moltbot"],
"macos_log_subsystem": "bot.molt",
},
}
class InstallationTracker:
def __init__(self, api_key: str = API_KEY):
self.api_key = api_key
self.username = self._get_current_username()
self.hostname = socket.gethostname()
self.results: Dict[str, Any] = {}
def _get_current_username(self) -> str:
"""Get the current system username."""
return os.environ.get("USER") or os.environ.get("USERNAME") or "unknown"
def _get_machine_user_info(self) -> Dict[str, Any]:
"""Get detailed user information from local machine settings."""
user_info = {
"username": self.username,
"home_directory": os.path.expanduser("~"),
"user_id": None,
"group_id": None,
"full_name": None,
"shell": os.environ.get("SHELL", "unknown"),
"groups": [],
}
# Get user ID
try:
result = subprocess.run(["id", "-u"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
user_info["user_id"] = result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Get group ID
try:
result = subprocess.run(["id", "-g"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
user_info["group_id"] = result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Get full name (macOS specific with id -F)
try:
result = subprocess.run(["id", "-F"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
user_info["full_name"] = result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Fallback: Try dscl for macOS to get real name
if not user_info["full_name"]:
try:
result = subprocess.run(
["dscl", ".", "-read", f"/Users/{self.username}", "RealName"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
lines = result.stdout.strip().split("\n")
if len(lines) > 1:
user_info["full_name"] = lines[1].strip()
elif lines:
user_info["full_name"] = lines[0].replace("RealName:", "").strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Fallback for Linux: Try getent
if not user_info["full_name"]:
try:
result = subprocess.run(
["getent", "passwd", self.username],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
parts = result.stdout.strip().split(":")
if len(parts) >= 5:
user_info["full_name"] = parts[4].split(",")[0]
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Get user groups
try:
result = subprocess.run(["groups"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
user_info["groups"] = result.stdout.strip().split()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Get additional system info
try:
result = subprocess.run(["uname", "-a"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
user_info["system_info"] = result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Get computer name (macOS)
try:
result = subprocess.run(
["scutil", "--get", "ComputerName"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
user_info["computer_name"] = result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Get local hostname (macOS)
try:
result = subprocess.run(
["scutil", "--get", "LocalHostName"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
user_info["local_hostname"] = result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
return user_info
def _expand_path(self, path: str) -> str:
"""Expand ~ and environment variables in path."""
return os.path.expanduser(os.path.expandvars(path))
def _check_binary_installed(self, binary_name: str) -> Optional[str]:
"""Check if a binary is installed and return its path."""
try:
result = subprocess.run(
["which", binary_name],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
return result.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
return None
def _check_npm_package(self, package_name: str) -> Optional[Dict[str, str]]:
"""Check if an npm package is installed globally."""
try:
result = subprocess.run(
["npm", "list", "-g", package_name, "--json"],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
data = json.loads(result.stdout)
if "dependencies" in data and package_name in data["dependencies"]:
return {
"version": data["dependencies"][package_name].get("version", "unknown"),
"path": data.get("path", "unknown")
}
except (subprocess.TimeoutExpired, FileNotFoundError, json.JSONDecodeError):
pass
return None
def _check_process_running(self, process_names: List[str]) -> List[Dict[str, Any]]:
"""Check if any of the specified processes are running."""
running_processes = []
# Patterns to exclude (our own script, grep, etc.)
exclude_patterns = ["installation_tracker", "grep", "ps aux"]
try:
result = subprocess.run(
["ps", "aux"],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
for line in result.stdout.split("\n"):
line_lower = line.lower()
# Skip excluded patterns
if any(excl in line_lower for excl in exclude_patterns):
continue
for proc_name in process_names:
if proc_name.lower() in line_lower:
parts = line.split()
if len(parts) >= 11:
running_processes.append({
"user": parts[0],
"pid": parts[1],
"cpu": parts[2],
"mem": parts[3],
"command": " ".join(parts[10:]),
"process_name": proc_name
})
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
return running_processes
def _check_port_listening(self, port: int) -> bool:
"""Check if a port is listening."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(1)
result = s.connect_ex(("127.0.0.1", port))
return result == 0
except socket.error:
return False
def _read_config_file(self, config_path: str) -> Optional[Dict[str, Any]]:
"""Read and parse a JSON or YAML configuration file."""
expanded_path = self._expand_path(config_path)
if os.path.exists(expanded_path):
try:
with open(expanded_path, "r") as f:
content = f.read()
# Determine file type by extension
is_yaml = expanded_path.lower().endswith(('.yaml', '.yml'))
if is_yaml:
return self._parse_yaml(content, expanded_path)
else:
# Handle JSON with comments or trailing commas
content = re.sub(r'//.*?\n', '\n', content)
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
content = re.sub(r',(\s*[}\]])', r'\1', content)
return json.loads(content)
except (json.JSONDecodeError, IOError) as e:
return {"_error": str(e), "_path": expanded_path}
return None
def _parse_yaml(self, content: str, filepath: str) -> Optional[Dict[str, Any]]:
"""Parse YAML content, with fallback if PyYAML not installed."""
if YAML_AVAILABLE:
try:
# Use safe_load to prevent arbitrary code execution
data = yaml.safe_load(content)
if isinstance(data, dict):
return data
return {"_data": data, "_type": type(data).__name__}
except yaml.YAMLError as e:
return {"_error": str(e), "_path": filepath}
else:
# Basic YAML parsing fallback (handles simple key: value pairs)
return self._basic_yaml_parse(content, filepath)
def _basic_yaml_parse(self, content: str, filepath: str) -> Dict[str, Any]:
"""Basic YAML parser for simple configs when PyYAML is not available."""
result = {"_warning": "PyYAML not installed, using basic parser", "_path": filepath}
current_dict = result
indent_stack = [(0, result)]
for line in content.split('\n'):
# Skip comments and empty lines
stripped = line.strip()
if not stripped or stripped.startswith('#'):
continue
# Calculate indent level
indent = len(line) - len(line.lstrip())
# Find the key-value pair
if ':' in stripped:
key, _, value = stripped.partition(':')
key = key.strip()
value = value.strip()
# Remove quotes from value
if value and value[0] in '"\'':
value = value[1:-1] if len(value) > 1 and value[-1] == value[0] else value[1:]
# Handle nested structures
while indent_stack and indent <= indent_stack[-1][0]:
if len(indent_stack) > 1:
indent_stack.pop()
else:
break
current_dict = indent_stack[-1][1]
if value:
# Convert common types
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
elif value.lower() in ('null', 'none', '~'):
value = None
elif value.isdigit():
value = int(value)
elif re.match(r'^-?\d+\.\d+$', value):
value = float(value)
current_dict[key] = value
else:
# Nested dict
new_dict = {}
current_dict[key] = new_dict
indent_stack.append((indent + 1, new_dict))
return result
def _find_log_files(self, log_patterns: List[str]) -> List[str]:
"""Find all log files matching the patterns."""
log_files = []
for pattern in log_patterns:
expanded_pattern = self._expand_path(pattern)
log_files.extend(glob.glob(expanded_pattern))
return sorted(log_files, key=os.path.getmtime, reverse=True) if log_files else []
def _parse_log_connections(self, log_file: str, max_lines: int = 1000) -> List[Dict[str, Any]]:
"""Parse log file for connection information."""
connections = []
connection_patterns = [
r'connect(?:ed|ing)?\s+(?:to\s+)?["\']?([a-zA-Z0-9\-._]+(?::\d+)?)["\']?',
r'(?:api|server|host|endpoint|url)["\s:=]+["\']?(https?://[^\s"\']+)["\']?',
r'(?:websocket|ws|wss)://([^\s"\']+)',
r'(?:authenticated|login|auth)\s+(?:to|with|as)\s+["\']?([^\s"\']+)["\']?',
r'model["\s:=]+["\']?([^\s"\']+)["\']?',
]
try:
with open(log_file, "r", errors="ignore") as f:
lines = f.readlines()[-max_lines:]
for line in lines:
for pattern in connection_patterns:
matches = re.findall(pattern, line, re.IGNORECASE)
for match in matches:
connections.append({
"resource": match,
"log_file": log_file,
"pattern": pattern[:30] + "...",
"line_sample": line.strip()[:100]
})
except IOError:
pass
# Deduplicate by resource
seen = set()
unique_connections = []
for conn in connections:
if conn["resource"] not in seen:
seen.add(conn["resource"])
unique_connections.append(conn)
return unique_connections
def _parse_log_for_accessed_apps(self, log_file: str, max_lines: int = 2000) -> List[Dict[str, Any]]:
"""Parse log file to identify apps/services accessed or attempted to access."""
accessed_apps = []
# Patterns for identifying access attempts and their status
access_patterns = [
# HTTP/API requests
(r'(?:GET|POST|PUT|DELETE|PATCH)\s+["\']?(https?://[^\s"\']+)["\']?', "http_request"),
(r'(?:request|fetch|call)(?:ing|ed)?\s+(?:to\s+)?["\']?(https?://[^\s"\']+)["\']?', "api_call"),
(r'(?:api|endpoint)["\s:=]+["\']?(https?://[^\s"\'<>]+)["\']?', "api_endpoint"),
# URLs and hosts
(r'(?:url|host|server|endpoint)["\s:=]+["\']?([a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z0-9][-a-zA-Z0-9]*)+(?::\d+)?)["\']?', "host"),
(r'https?://([a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z0-9][-a-zA-Z0-9]*)+)(?:[:/]|$)', "url_host"),
# Connection events
(r'connect(?:ed|ing|ion)?\s+(?:to\s+)?["\']?([a-zA-Z0-9][-a-zA-Z0-9.]+(?::\d+)?)["\']?', "connection"),
(r'(?:establish|open)(?:ed|ing)?\s+(?:connection\s+)?(?:to\s+)?["\']?([^\s"\']+)["\']?', "connection"),
# Authentication
(r'(?:auth|login|signin|authenticate)(?:ed|ing|ation)?\s+(?:to|with|for|at)\s+["\']?([^\s"\']+)["\']?', "auth"),
(r'(?:oauth|sso|saml)\s+(?:to|with|for)\s+["\']?([^\s"\']+)["\']?', "oauth"),
(r'(?:token|credential|key)\s+(?:for|from)\s+["\']?([^\s"\']+)["\']?', "credential"),
# WebSocket
(r'(?:websocket|ws|wss)://([^\s"\']+)', "websocket"),
# Database connections
(r'(?:mongodb|postgres|mysql|redis|elasticsearch)(?:://)?([^\s"\']+)', "database"),
(r'(?:database|db)\s+(?:connection|host)["\s:=]+["\']?([^\s"\']+)["\']?', "database"),
# Service-specific
(r'(?:github|gitlab|bitbucket)\.com[/:]?([^\s"\']*)', "vcs"),
# Messaging services - improved patterns
(r'(api\.telegram\.org[^\s"\']*)', "telegram"),
(r'(telegram\.org[^\s"\']*)', "telegram"),
(r'(t\.me[/][^\s"\']*)', "telegram"),
(r'telegram["\s:=]+["\']?([^\s"\']+)["\']?', "telegram"),
(r'(slack\.com[^\s"\']*)', "slack"),
(r'(hooks\.slack\.com[^\s"\']*)', "slack"),
(r'(discord\.com[^\s"\']*)', "discord"),
(r'(discordapp\.com[^\s"\']*)', "discord"),
(r'(?:slack|discord|telegram)(?:_|-)(?:bot|api|webhook|token|key)["\s:=]+["\']?([^\s"\']+)["\']?', "messaging_config"),
(r'(?:send|post|message)(?:ing|ed)?\s+(?:to\s+)?(?:telegram|slack|discord)[^\s]*["\']?([^\s"\']*)["\']?', "messaging"),
# Bot tokens
(r'bot[_-]?token["\s:=]+["\']?([^\s"\']+)["\']?', "bot_token"),
(r'(\d+:[\w-]{35,})', "telegram_bot_token"), # Telegram bot token format
# Calendar services
(r'(calendar\.google\.com[^\s"\']*)', "google_calendar"),
(r'(www\.googleapis\.com/calendar[^\s"\']*)', "google_calendar_api"),
(r'(googleapis\.com/calendar[^\s"\']*)', "google_calendar_api"),
(r'(outlook\.office\.com/calendar[^\s"\']*)', "outlook_calendar"),
(r'(outlook\.office365\.com[^\s"\']*)', "outlook_calendar"),
(r'(graph\.microsoft\.com[^\s"\']*)', "microsoft_graph"),
(r'(calendly\.com[^\s"\']*)', "calendly"),
(r'(api\.calendly\.com[^\s"\']*)', "calendly_api"),
(r'(cal\.com[^\s"\']*)', "cal_com"),
(r'(?:calendar|event|meeting|schedule|appointment)["\s:=]+["\']?([^\s"\']+)["\']?', "calendar_config"),
(r'(?:ical|ics|caldav|webcal)(?:://|["\s:=]+)["\']?([^\s"\']+)["\']?', "calendar_protocol"),
(r'(cronofy\.com[^\s"\']*)', "cronofy"),
(r'(nylas\.com[^\s"\']*)', "nylas"),
(r'(api\.nylas\.com[^\s"\']*)', "nylas_api"),
(r'(zoom\.us[^\s"\']*)', "zoom"),
(r'(api\.zoom\.us[^\s"\']*)', "zoom_api"),
(r'(teams\.microsoft\.com[^\s"\']*)', "ms_teams"),
(r'(meet\.google\.com[^\s"\']*)', "google_meet"),
(r'(?:create|add|sync|fetch)(?:ing|ed)?\s+(?:calendar|event|meeting|appointment)[^\s]*', "calendar_action"),
(r'calendar[_-]?(?:id|api|key|token|secret)["\s:=]+["\']?([^\s"\']+)["\']?', "calendar_credential"),
(r'google[_-]?calendar["\s:=]+["\']?([^\s"\']+)["\']?', "google_calendar"),
(r'outlook[_-]?calendar["\s:=]+["\']?([^\s"\']+)["\']?', "outlook_calendar"),
# Obsidian and note-taking apps
(r'(obsidian\.md[^\s"\']*)', "obsidian"),
(r'(sync\.obsidian\.md[^\s"\']*)', "obsidian_sync"),
(r'(publish\.obsidian\.md[^\s"\']*)', "obsidian_publish"),
(r'(api\.obsidian\.md[^\s"\']*)', "obsidian_api"),
(r'obsidian["\s:=]+["\']?([^\s"\']+)["\']?', "obsidian_config"),
(r'obsidian[_-]?(?:vault|sync|api|token|key)["\s:=]+["\']?([^\s"\']+)["\']?', "obsidian_config"),
(r'(?:vault|workspace)["\s:=]+["\']?([^\s"\']*obsidian[^\s"\']*)["\']?', "obsidian_vault"),
(r'(roamresearch\.com[^\s"\']*)', "roam"),
(r'(logseq\.com[^\s"\']*)', "logseq"),
(r'(evernote\.com[^\s"\']*)', "evernote"),
(r'(notion\.so[^\s"\']*)', "notion"),
(r'(api\.notion\.com[^\s"\']*)', "notion_api"),
(r's3://([^\s"\']+)', "s3"),
(r'(?:bucket|container)["\s:=]+["\']?([^\s"\']+)["\']?', "storage"),
# File system access
(r'(?:read|write|access|open)(?:ing|ed)?\s+(?:file\s+)?["\']?(/[^\s"\']+)["\']?', "file"),
(r'(?:path|file|directory)["\s:=]+["\']?(/[^\s"\']+)["\']?', "file"),
# Model/AI service
(r'(?:model|llm)["\s:=]+["\']?([^\s"\']+)["\']?', "model"),
(r'(?:claude|gpt|gemini|llama|mistral)[-\s]?[\d.]*', "ai_model"),
# Generic integration detection
(r'(?:integration|plugin|addon|extension|connector)["\s:=]+["\']?([^\s"\']+)["\']?', "integration"),
(r'(?:integrat|connect|link|sync)(?:ing|ed|ion)?\s+(?:to|with)\s+["\']?([^\s"\']+)["\']?', "integration_action"),
(r'(?:webhook|hook|callback)["\s_-]?(?:url|endpoint)?["\s:=]+["\']?(https?://[^\s"\']+)["\']?', "webhook"),
(r'(?:api|service)[_-]?(?:key|token|secret|credential)["\s:=]+["\']?([^\s"\']+)["\']?', "api_credential"),
(r'(?:oauth|access)[_-]?token["\s:=]+["\']?([^\s"\']+)["\']?', "oauth_token"),
(r'(?:client)[_-]?(?:id|secret)["\s:=]+["\']?([^\s"\']+)["\']?', "oauth_client"),
(r'(?:enabled|active|configured)\s+(?:integration|service|plugin)["\s:]*["\']?([^\s"\']+)["\']?', "enabled_integration"),
# Third-party services
(r'(jira\.atlassian\.com[^\s"\']*)', "jira"),
(r'(api\.atlassian\.com[^\s"\']*)', "atlassian"),
(r'(trello\.com[^\s"\']*)', "trello"),
(r'(api\.trello\.com[^\s"\']*)', "trello_api"),
(r'(asana\.com[^\s"\']*)', "asana"),
(r'(api\.asana\.com[^\s"\']*)', "asana_api"),
(r'(notion\.so[^\s"\']*)', "notion"),
(r'(api\.notion\.com[^\s"\']*)', "notion_api"),
(r'(airtable\.com[^\s"\']*)', "airtable"),
(r'(api\.airtable\.com[^\s"\']*)', "airtable_api"),
(r'(monday\.com[^\s"\']*)', "monday"),
(r'(clickup\.com[^\s"\']*)', "clickup"),
(r'(linear\.app[^\s"\']*)', "linear"),
(r'(stripe\.com[^\s"\']*)', "stripe"),
(r'(api\.stripe\.com[^\s"\']*)', "stripe_api"),
(r'(paypal\.com[^\s"\']*)', "paypal"),
(r'(shopify\.com[^\s"\']*)', "shopify"),
(r'(salesforce\.com[^\s"\']*)', "salesforce"),
(r'(hubspot\.com[^\s"\']*)', "hubspot"),
(r'(zendesk\.com[^\s"\']*)', "zendesk"),
(r'(intercom\.com[^\s"\']*)', "intercom"),
(r'(mailchimp\.com[^\s"\']*)', "mailchimp"),
(r'(twilio\.com[^\s"\']*)', "twilio"),
(r'(segment\.com[^\s"\']*)', "segment"),
(r'(mixpanel\.com[^\s"\']*)', "mixpanel"),
(r'(amplitude\.com[^\s"\']*)', "amplitude"),
(r'(zapier\.com[^\s"\']*)', "zapier"),
(r'(hooks\.zapier\.com[^\s"\']*)', "zapier_webhook"),
(r'(ifttt\.com[^\s"\']*)', "ifttt"),
(r'(make\.com[^\s"\']*)', "make"),
(r'(n8n\.io[^\s"\']*)', "n8n"),
(r'(pipedream\.com[^\s"\']*)', "pipedream"),
]
# Status indicators
success_indicators = ['success', 'ok', '200', '201', '204', 'connected', 'authenticated', 'completed', 'done']
failure_indicators = ['fail', 'error', 'denied', 'refused', 'timeout', '401', '403', '404', '500', '502', '503', 'rejected', 'unauthorized']
attempt_indicators = ['attempt', 'trying', 'connecting', 'requesting', 'fetching']
try:
with open(log_file, "r", errors="ignore") as f:
lines = f.readlines()[-max_lines:]
for line_num, line in enumerate(lines):
line_lower = line.lower()
# Determine access status from line context
status = "unknown"
if any(ind in line_lower for ind in success_indicators):
status = "success"
elif any(ind in line_lower for ind in failure_indicators):
status = "failed"
elif any(ind in line_lower for ind in attempt_indicators):
status = "attempted"
# Try to extract timestamp
timestamp = None
timestamp_patterns = [
r'(\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2})',
r'(\d{2}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2})',
r'\[(\d+)\]', # Unix timestamp
]
for ts_pattern in timestamp_patterns:
ts_match = re.search(ts_pattern, line)
if ts_match:
timestamp = ts_match.group(1)
break
# Find all access patterns
for pattern, access_type in access_patterns:
matches = re.findall(pattern, line, re.IGNORECASE)
for match in matches:
if isinstance(match, tuple):
match = match[0]
# Skip empty or too short matches
if not match or len(match) < 3:
continue
# Categorize the service
service_info = self._categorize_service(match)
accessed_apps.append({
"resource": match,
"access_type": access_type,
"status": status,
"timestamp": timestamp,
"service_name": service_info.get("name"),
"service_category": service_info.get("category"),
"log_file": log_file,
"line_number": line_num + 1,
"line_sample": line.strip()[:150]
})
except IOError:
pass
return accessed_apps
def _categorize_service(self, resource: str) -> Dict[str, str]:
"""Categorize a resource/service based on known patterns."""
resource_lower = resource.lower()
for pattern, info in KNOWN_SERVICES.items():
if pattern.lower() in resource_lower:
return info
# Try to identify by domain patterns
if re.search(r'\.gov$', resource_lower):
return {"name": "Government Service", "category": "Government"}
if re.search(r'\.edu$', resource_lower):
return {"name": "Educational Institution", "category": "Education"}
if re.search(r'\.internal$|\.local$|\.corp$', resource_lower):
return {"name": "Internal Service", "category": "Internal"}
if re.search(r'api\.', resource_lower):
return {"name": "API Service", "category": "API"}
return {"name": "Unknown", "category": "Unknown"}
def _read_macos_unified_log(self, subsystem: str, max_lines: int = 500, time_range: str = "1h") -> List[str]:
"""Read logs from macOS unified logging system.
Args:
subsystem: The log subsystem (e.g., 'bot.molt' for moltbot)
max_lines: Maximum lines to return
time_range: Time range like '1h', '30m', '1d'
Returns:
List of log lines
"""
import platform
if platform.system() != "Darwin":
return []
try:
# Try without sudo first (may have limited data)
cmd = [
"log", "show",
"--predicate", f'subsystem == "{subsystem}"',
"--last", time_range,
"--info"
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
lines = result.stdout.strip().split('\n')
# Filter out header lines and empty lines
log_lines = [l for l in lines if l.strip() and not l.startswith('Filtering')]
return log_lines[-max_lines:] if len(log_lines) > max_lines else log_lines
except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
pass
return []
def _parse_macos_log_for_integrations(self, tool_name: str) -> Dict[str, Any]:
"""Parse macOS unified log for integration/connection info.
Returns dictionary with connections, integrations, accessed services.
"""
result = {
"log_source": "macos_unified_log",
"connections": [],
"accessed_apps": [],
"integrations": []
}
config = TOOL_CONFIGS.get(tool_name, {})
subsystem = config.get("macos_log_subsystem")
if not subsystem:
return result
log_lines = self._read_macos_unified_log(subsystem, max_lines=1000, time_range="24h")
if not log_lines:
return result
# Write to temp file and parse using existing methods
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.log', delete=False) as f:
f.write('\n'.join(log_lines))
temp_log_path = f.name
try:
result["connections"] = self._parse_log_connections(temp_log_path)
result["accessed_apps"] = self._parse_log_for_accessed_apps(temp_log_path)
finally:
os.unlink(temp_log_path)
return result
def _aggregate_accessed_apps(self, apps: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Aggregate accessed apps into a summary with statistics."""
summary = {
"total_access_events": len(apps),
"by_category": {},
"by_status": {"success": 0, "failed": 0, "attempted": 0, "unknown": 0},
"unique_services": [],
"access_timeline": [],
}
seen_services = {}
for app in apps:
# Count by status
status = app.get("status", "unknown")
if status in summary["by_status"]:
summary["by_status"][status] += 1
# Group by category
category = app.get("service_category", "Unknown")
if category not in summary["by_category"]:
summary["by_category"][category] = []
# Track unique services per category
resource = app.get("resource", "")
service_key = f"{category}:{resource}"
if service_key not in seen_services:
seen_services[service_key] = {
"resource": resource,
"service_name": app.get("service_name"),
"category": category,
"access_count": 0,
"success_count": 0,
"failure_count": 0,
"first_seen": app.get("timestamp"),
"last_seen": app.get("timestamp"),
"access_types": set(),
}
summary["by_category"][category].append(seen_services[service_key])
# Update service stats
seen_services[service_key]["access_count"] += 1
seen_services[service_key]["access_types"].add(app.get("access_type", "unknown"))
if status == "success":
seen_services[service_key]["success_count"] += 1
elif status == "failed":
seen_services[service_key]["failure_count"] += 1
if app.get("timestamp"):
seen_services[service_key]["last_seen"] = app.get("timestamp")
# Convert sets to lists for JSON serialization
for service in seen_services.values():
service["access_types"] = list(service["access_types"])
summary["unique_services"].append(service)
# Sort unique services by access count
summary["unique_services"].sort(key=lambda x: x["access_count"], reverse=True)
return summary
def _extract_integrations_from_config(self, config: Dict[str, Any], tool_name: str) -> List[Dict[str, Any]]:
"""Extract integrations/channels from tool configuration."""
integrations = []
if not isinstance(config, dict):
return integrations
# OpenClaw specific: channels.* configuration