-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcc-domain-security-monitor.js
More file actions
854 lines (726 loc) · 26.3 KB
/
mcc-domain-security-monitor.js
File metadata and controls
854 lines (726 loc) · 26.3 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
/**
* MCC Domain Security Monitor v2.0.4
*
* Google Ads Script (MCC Level) to detect unauthorized URLs and domains across all managed accounts.
*
* Features:
* - Checks final URLs in ads (all campaign types: Search, Display, Video, App, Performance Max, Demand Gen)
* - Validates sitelink extensions
* - Monitors tracking templates at campaign and ad group levels
* - Supports global and per-account allowlists
* - Parallel execution for performance
* - Email alerts with anti-spam deduplication
* - Handles URL macros like {lpurl}, {ignore}, etc.
*
* VERSION: 2.0.4 (PRODUCTION READY - COMPLETE)
* DATE: 2026-02-28
* AUTHOR: Myriam Navas with Rosalind (Claude Code Brain)
* LICENSE: MIT
*/
// ============================================================================
// CONFIGURATION
// ============================================================================
var CONFIG = {
/**
* Email address to receive security alerts
* REQUIRED: Change this to your email
*/
ALERT_EMAIL: 'security-alerts@example.com',
/**
* Time window for checking active ads (in days)
* Only ads with impressions in this period will be checked
*/
DAYS_WINDOW: 7,
/**
* Global allowlist - domains allowed across ALL accounts
* Add domains that are common/trusted across all your clients
* Format: ['domain.com', 'subdomain.example.com']
*/
GLOBAL_ALLOWLIST: [
'google.com',
'youtube.com',
'googleadservices.com'
],
/**
* Account-specific allowlists
* Map customer IDs (without hyphens) to allowed domains
*
* IMPORTANT: Customer IDs must NOT have hyphens
* Example: '1234567890' NOT '123-456-7890'
*
* Format:
* 'CUSTOMER_ID': ['domain1.com', 'domain2.com']
*/
ACCOUNT_SPECIFIC_ALLOWLIST: {
'1234567890': ['example-client1.com', 'shop.example-client1.com'],
'0987654321': ['example-client2.com'],
'1111222233': ['example-client3.com', 'checkout.example-client3.com'],
'4444555566': ['example-client4.com']
},
/**
* Allowed URL macros that should be ignored during domain extraction
* These are standard Google Ads URL parameters and tracking codes
*/
ALLOWED_MACROS: [
'{lpurl}',
'{ignore}',
'{unescapedlpurl}',
'{escapedlpurl}',
'{lpurl+2}',
'{lpurl+3}',
'{campaignid}',
'{adgroupid}',
'{creative}',
'{keyword}',
'{matchtype}',
'{placement}',
'{network}',
'{device}',
'{ifmobile}',
'{ifnotmobile}',
'{ifsearch}',
'{ifcontent}',
'{param1}',
'{param2}',
'{gclid}',
'{wbraid}',
'{gbraid}'
]
};
// ============================================================================
// MAIN EXECUTION
// ============================================================================
/**
* Main function - Entry point for MCC script
* Executes processAccount() in parallel across all managed accounts
*/
function main() {
Logger.log('=== MCC Domain Security Monitor v2.0.4 ===');
Logger.log('Starting at: ' + new Date().toString());
Logger.log('Checking last ' + CONFIG.DAYS_WINDOW + ' days of data');
var accountSelector = AdsManagerApp.accounts();
// Execute in parallel across all accounts
accountSelector.executeInParallel(
'processAccount',
'processResults'
);
// Note: Code here executes BEFORE parallel processing completes
// Do not add logic here - use processResults() callback
}
// ============================================================================
// ACCOUNT PROCESSING
// ============================================================================
/**
* Process a single account - executed in parallel
* This function runs independently for each managed account
*
* @returns {string} JSON string with issues found and execution metadata
*/
function processAccount() {
var startTime = new Date().getTime();
var customerId = AdsApp.currentAccount().getCustomerId().replace(/-/g, '');
var accountName = AdsApp.currentAccount().getName();
Logger.log('[' + customerId + ' - ' + accountName + '] Starting account processing');
try {
var issues = [];
// Check 1: Ad URLs (traditional campaigns: Search, Display, Video, App)
Logger.log('[' + customerId + '] Checking ad URLs...');
var adIssues = checkAdUrls(customerId);
Logger.log('[' + customerId + '] Found ' + adIssues.length + ' ad URL issues');
issues = issues.concat(adIssues);
// Check 2: Asset Group URLs (Performance Max and Demand Gen campaigns)
Logger.log('[' + customerId + '] Checking asset group URLs...');
var assetIssues = checkAssetGroupUrls(customerId);
Logger.log('[' + customerId + '] Found ' + assetIssues.length + ' asset group issues');
issues = issues.concat(assetIssues);
// Check 3: Sitelink extensions
Logger.log('[' + customerId + '] Checking sitelinks...');
var sitelinkIssues = checkSitelinks(customerId);
Logger.log('[' + customerId + '] Found ' + sitelinkIssues.length + ' sitelink issues');
issues = issues.concat(sitelinkIssues);
// Check 4: Tracking templates (campaign and ad group level)
Logger.log('[' + customerId + '] Checking tracking templates...');
var trackingIssues = checkTrackingTemplates(customerId);
Logger.log('[' + customerId + '] Found ' + trackingIssues.length + ' tracking template issues');
issues = issues.concat(trackingIssues);
var elapsed = (new Date().getTime() - startTime) / 1000;
Logger.log('[' + customerId + '] COMPLETED in ' + elapsed + 's with ' + issues.length + ' total issues');
// Return JSON string (required by executeInParallel)
return JSON.stringify({
customerId: customerId,
accountName: accountName,
issues: issues,
executionTime: elapsed
});
} catch (e) {
Logger.log('[' + customerId + '] ERROR: ' + e.message);
Logger.log('[' + customerId + '] Stack: ' + e.stack);
// Return error info (must still return a string)
return JSON.stringify({
customerId: customerId,
accountName: accountName,
error: e.message,
issues: []
});
}
}
// ============================================================================
// CHECK FUNCTIONS
// ============================================================================
/**
* Check ad URLs in traditional campaigns using GAQL
* Covers: Search, Display, Video, App campaigns
*
* @param {string} customerId - Account customer ID (without hyphens)
* @returns {Array} Array of issue objects
*/
function checkAdUrls(customerId) {
var issues = [];
var daysWindow = 'LAST_' + CONFIG.DAYS_WINDOW + '_DAYS';
var query =
'SELECT campaign.name, ad_group.name, ad_group_ad.ad.final_urls ' +
'FROM ad_group_ad ' +
'WHERE campaign.status = \'ENABLED\' ' +
' AND ad_group.status = \'ENABLED\' ' +
' AND ad_group_ad.status = \'ENABLED\' ' +
' AND segments.date DURING ' + daysWindow + ' ' +
' AND metrics.impressions > 0 ' +
'LIMIT 10000';
try {
var report = AdsApp.report(query);
var rows = report.rows();
var rowCount = 0;
while (rows.hasNext()) {
var row = rows.next();
rowCount++;
if (rowCount % 1000 === 0) {
Logger.log('[' + customerId + '] Processed ' + rowCount + ' ad rows');
}
var campaignName = row['campaign.name'];
var adGroupName = row['ad_group.name'];
var finalUrls = row['ad_group_ad.ad.final_urls'];
if (finalUrls) {
var urls = finalUrls.split(';');
for (var i = 0; i < urls.length; i++) {
var url = urls[i].trim();
if (url) {
var domains = extractDomains(url);
for (var j = 0; j < domains.length; j++) {
if (!isAllowedDomain(domains[j], customerId)) {
issues.push({
type: 'Ad Final URL',
campaign: campaignName,
adGroup: adGroupName,
url: url,
domain: domains[j]
});
}
}
}
}
}
}
Logger.log('[' + customerId + '] Total ad rows processed: ' + rowCount);
} catch (e) {
Logger.log('[' + customerId + '] Error in checkAdUrls: ' + e.message);
}
return issues;
}
/**
* Check asset group URLs in Performance Max and Demand Gen campaigns using GAQL
*
* @param {string} customerId - Account customer ID (without hyphens)
* @returns {Array} Array of issue objects
*/
function checkAssetGroupUrls(customerId) {
var issues = [];
var daysWindow = 'LAST_' + CONFIG.DAYS_WINDOW + '_DAYS';
var query =
'SELECT campaign.name, campaign.advertising_channel_type, ' +
'asset_group.name, asset_group.final_urls ' +
'FROM asset_group ' +
'WHERE campaign.status = \'ENABLED\' ' +
' AND asset_group.status = \'ENABLED\' ' +
' AND segments.date DURING ' + daysWindow + ' ' +
' AND metrics.impressions > 0 ' +
'LIMIT 10000';
try {
var report = AdsApp.report(query);
var rows = report.rows();
var rowCount = 0;
while (rows.hasNext()) {
var row = rows.next();
rowCount++;
if (rowCount % 500 === 0) {
Logger.log('[' + customerId + '] Processed ' + rowCount + ' asset group rows');
}
var campaignName = row['campaign.name'];
var channelType = row['campaign.advertising_channel_type'];
var assetGroupName = row['asset_group.name'];
var finalUrls = row['asset_group.final_urls'];
if (finalUrls) {
var urls = finalUrls.split(';');
for (var i = 0; i < urls.length; i++) {
var url = urls[i].trim();
if (url) {
var domains = extractDomains(url);
for (var j = 0; j < domains.length; j++) {
if (!isAllowedDomain(domains[j], customerId)) {
issues.push({
type: 'Asset Group URL (' + channelType + ')',
campaign: campaignName,
adGroup: assetGroupName,
url: url,
domain: domains[j]
});
}
}
}
}
}
}
Logger.log('[' + customerId + '] Total asset group rows processed: ' + rowCount);
} catch (e) {
Logger.log('[' + customerId + '] Error in checkAssetGroupUrls: ' + e.message);
}
return issues;
}
/**
* Check sitelink extension URLs using GAQL
*
* @param {string} customerId - Account customer ID (without hyphens)
* @returns {Array} Array of issue objects
*/
function checkSitelinks(customerId) {
var issues = [];
var daysWindow = 'LAST_' + CONFIG.DAYS_WINDOW + '_DAYS';
var query =
'SELECT campaign.name, ad_group.name, ' +
'extensions.sitelink_feed_item.sitelink_final_urls, ' +
'extensions.sitelink_feed_item.sitelink_text ' +
'FROM campaign ' +
'WHERE campaign.status = \'ENABLED\' ' +
' AND segments.date DURING ' + daysWindow + ' ' +
' AND metrics.impressions > 0 ' +
'LIMIT 5000';
try {
var report = AdsApp.report(query);
var rows = report.rows();
var rowCount = 0;
while (rows.hasNext()) {
var row = rows.next();
rowCount++;
var campaignName = row['campaign.name'];
var sitelinkText = row['extensions.sitelink_feed_item.sitelink_text'] || 'Unknown';
var finalUrls = row['extensions.sitelink_feed_item.sitelink_final_urls'];
if (finalUrls) {
var urls = finalUrls.split(';');
for (var i = 0; i < urls.length; i++) {
var url = urls[i].trim();
if (url) {
var domains = extractDomains(url);
for (var j = 0; j < domains.length; j++) {
if (!isAllowedDomain(domains[j], customerId)) {
issues.push({
type: 'Sitelink',
campaign: campaignName,
adGroup: 'Sitelink: ' + sitelinkText,
url: url,
domain: domains[j]
});
}
}
}
}
}
}
Logger.log('[' + customerId + '] Total sitelink rows processed: ' + rowCount);
} catch (e) {
Logger.log('[' + customerId + '] Error in checkSitelinks: ' + e.message);
}
return issues;
}
/**
* Check tracking templates at campaign and ad group levels using GAQL
* Note: Account-level tracking templates are not checked (field not available in API)
*
* @param {string} customerId - Account customer ID (without hyphens)
* @returns {Array} Array of issue objects
*/
function checkTrackingTemplates(customerId) {
var issues = [];
var daysWindow = 'LAST_' + CONFIG.DAYS_WINDOW + '_DAYS';
// Check campaign-level tracking templates
var campaignQuery =
'SELECT campaign.name, campaign.tracking_url_template ' +
'FROM campaign ' +
'WHERE campaign.status = \'ENABLED\' ' +
' AND segments.date DURING ' + daysWindow + ' ' +
' AND metrics.impressions > 0 ' +
'LIMIT 5000';
try {
var report = AdsApp.report(campaignQuery);
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var campaignName = row['campaign.name'];
var template = row['campaign.tracking_url_template'];
if (template) {
var domains = extractDomains(template);
for (var i = 0; i < domains.length; i++) {
if (!isAllowedDomain(domains[i], customerId)) {
issues.push({
type: 'Campaign Tracking Template',
campaign: campaignName,
adGroup: 'N/A',
url: template,
domain: domains[i]
});
}
}
}
}
} catch (e) {
Logger.log('[' + customerId + '] Error checking campaign tracking templates: ' + e.message);
}
// Check ad group-level tracking templates
var adGroupQuery =
'SELECT campaign.name, ad_group.name, ad_group.tracking_url_template ' +
'FROM ad_group ' +
'WHERE campaign.status = \'ENABLED\' ' +
' AND ad_group.status = \'ENABLED\' ' +
' AND segments.date DURING ' + daysWindow + ' ' +
' AND metrics.impressions > 0 ' +
'LIMIT 5000';
try {
var report = AdsApp.report(adGroupQuery);
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var campaignName = row['campaign.name'];
var adGroupName = row['ad_group.name'];
var template = row['ad_group.tracking_url_template'];
if (template) {
var domains = extractDomains(template);
for (var i = 0; i < domains.length; i++) {
if (!isAllowedDomain(domains[i], customerId)) {
issues.push({
type: 'Ad Group Tracking Template',
campaign: campaignName,
adGroup: adGroupName,
url: template,
domain: domains[i]
});
}
}
}
}
} catch (e) {
Logger.log('[' + customerId + '] Error checking ad group tracking templates: ' + e.message);
}
return issues;
}
// ============================================================================
// DOMAIN EXTRACTION AND VALIDATION
// ============================================================================
/**
* Extract all domains from a URL or template string
* Handles URLs with macros, multiple domains, and edge cases
*
* Security: Searches for ALL https?:// patterns in string, even within macros
*
* @param {string} url - URL or template string to extract domains from
* @returns {Array} Array of domain strings (e.g., ['example.com', 'tracking.com'])
*/
function extractDomains(url) {
if (!url) return [];
var domains = [];
var cleanedUrl = url;
// Step 1: Remove allowed macros from string
for (var i = 0; i < CONFIG.ALLOWED_MACROS.length; i++) {
var macro = CONFIG.ALLOWED_MACROS[i];
cleanedUrl = cleanedUrl.split(macro).join('');
}
// Step 2: Find ALL https?:// patterns in the cleaned string
// This catches domains even if they were embedded in macro values
var httpPattern = /https?:\/\/([^\/\s\?&#]+)/gi;
var matches = cleanedUrl.match(httpPattern);
if (matches) {
for (var j = 0; j < matches.length; j++) {
var domain = parseDomain(matches[j]);
if (domain && domains.indexOf(domain) === -1) {
domains.push(domain);
}
}
}
// Step 3: Fallback for URLs without protocol (e.g., "example.com/page")
if (domains.length === 0) {
var fallbackDomain = extractDomainFallback(cleanedUrl);
if (fallbackDomain) {
domains.push(fallbackDomain);
}
}
return domains;
}
/**
* Parse domain from a URL string with protocol
* Removes protocol, path, query, fragment, and port
*
* @param {string} url - Full URL string (e.g., "https://example.com:443/path?q=1#anchor")
* @returns {string} Clean domain (e.g., "example.com")
*/
function parseDomain(url) {
if (!url) return null;
// Remove protocol
var withoutProtocol = url.replace(/^https?:\/\//i, '');
// Remove port, path, query, and fragment
var domain = withoutProtocol.split(':')[0]; // Remove port
domain = domain.split('/')[0]; // Remove path
domain = domain.split('?')[0]; // Remove query
domain = domain.split('#')[0]; // Remove fragment
return domain.toLowerCase().trim();
}
/**
* Fallback domain extraction for URLs without protocol
* Used when no https?:// pattern is found
*
* @param {string} str - String that might contain a domain
* @returns {string|null} Extracted domain or null
*/
function extractDomainFallback(str) {
if (!str) return null;
// Look for domain-like patterns: word.word
var domainPattern = /([a-z0-9-]+\.[a-z0-9-\.]+)/i;
var match = str.match(domainPattern);
if (match && match[1]) {
return parseDomain(match[1]);
}
return null;
}
/**
* Check if a domain is allowed for a specific account
* Checks both global allowlist and account-specific allowlist
* Supports subdomain matching (e.g., "shop.example.com" matches allowlist "example.com")
*
* @param {string} domain - Domain to check (e.g., "shop.example.com")
* @param {string} customerId - Account customer ID (without hyphens)
* @returns {boolean} True if domain is allowed, false otherwise
*/
function isAllowedDomain(domain, customerId) {
if (!domain) return true;
var lowerDomain = domain.toLowerCase();
// Check global allowlist
for (var i = 0; i < CONFIG.GLOBAL_ALLOWLIST.length; i++) {
var allowed = CONFIG.GLOBAL_ALLOWLIST[i].toLowerCase();
// Exact match or subdomain match
if (lowerDomain === allowed || lowerDomain.endsWith('.' + allowed)) {
return true;
}
}
// Check account-specific allowlist
var accountAllowlist = CONFIG.ACCOUNT_SPECIFIC_ALLOWLIST[customerId];
if (accountAllowlist) {
for (var j = 0; j < accountAllowlist.length; j++) {
var allowed = accountAllowlist[j].toLowerCase();
// Exact match or subdomain match
if (lowerDomain === allowed || lowerDomain.endsWith('.' + allowed)) {
return true;
}
}
}
return false;
}
// ============================================================================
// RESULTS PROCESSING
// ============================================================================
/**
* Process results from all accounts after parallel execution
* Deduplicates issues, checks anti-spam, and sends email alert if needed
*
* @param {Array} results - Results from executeInParallel (each result is a JSON string)
*/
function processResults(results) {
Logger.log('=== Processing Results from All Accounts ===');
var allIssues = [];
var errors = [];
var accountsProcessed = 0;
while (results.hasNext()) {
var result = results.next();
accountsProcessed++;
try {
var accountResult = JSON.parse(result.getReturnValue());
// Collect errors
if (accountResult.error) {
errors.push({
customerId: accountResult.customerId,
accountName: accountResult.accountName,
error: accountResult.error
});
}
// Collect issues
if (accountResult.issues && accountResult.issues.length > 0) {
allIssues = allIssues.concat(accountResult.issues);
}
} catch (e) {
Logger.log('Error parsing result: ' + e.message);
errors.push({
customerId: 'Unknown',
accountName: 'Unknown',
error: 'JSON parse error: ' + e.message
});
}
}
Logger.log('Accounts processed: ' + accountsProcessed);
Logger.log('Total issues found: ' + allIssues.length);
Logger.log('Total errors: ' + errors.length);
// Deduplicate issues
var deduped = deduplicateIssues(allIssues);
Logger.log('After deduplication: ' + deduped.length + ' unique issues');
// Check if should send email (anti-spam check)
if (deduped.length > 0 || errors.length > 0) {
var hash = calculateHash(deduped, errors);
var lastHash = PropertiesService.getScriptProperties().getProperty('lastAlertHash');
if (hash !== lastHash) {
sendAlert(deduped, errors);
PropertiesService.getScriptProperties().setProperty('lastAlertHash', hash);
Logger.log('Alert sent with hash: ' + hash);
} else {
Logger.log('Alert suppressed - identical to last alert (hash: ' + hash + ')');
}
} else {
Logger.log('No issues or errors found - no alert sent');
}
Logger.log('=== Script Execution Complete ===');
return;
}
/**
* Deduplicate issues by type|campaign|domain
* This prevents hundreds of alerts for the same domain in different URLs
*
* @param {Array} issues - Array of issue objects
* @returns {Array} Deduplicated array of issue objects
*/
function deduplicateIssues(issues) {
var seen = {};
var deduped = [];
for (var i = 0; i < issues.length; i++) {
var issue = issues[i];
// Deduplication key: type|campaign|domain (NOT including URL or adGroup)
var key = issue.type + '|' + issue.campaign + '|' + issue.domain;
if (!seen[key]) {
seen[key] = true;
deduped.push(issue);
}
}
return deduped;
}
/**
* Calculate hash for issues and errors to implement anti-spam
* Same issues = same hash = email suppressed
*
* @param {Array} issues - Deduplicated issues array
* @param {Array} errors - Errors array
* @returns {string} Hash string
*/
function calculateHash(issues, errors) {
var hashInput = '';
// Hash issues
for (var i = 0; i < issues.length; i++) {
hashInput += issues[i].type + '|' + issues[i].campaign + '|' + issues[i].domain + '\n';
}
// Hash errors
for (var j = 0; j < errors.length; j++) {
hashInput += errors[j].customerId + '|' + errors[j].error + '\n';
}
return simpleHash(hashInput);
}
/**
* Simple hash function (FNV-1a variant)
* Note: Not cryptographically secure, but sufficient for anti-spam
*
* @param {string} str - String to hash
* @returns {string} Hash as hex string
*/
function simpleHash(str) {
var hash = 2166136261; // FNV offset basis
for (var i = 0; i < str.length; i++) {
hash ^= str.charCodeAt(i);
hash *= 16777619; // FNV prime
hash = hash >>> 0; // Convert to unsigned 32-bit
}
return hash.toString(16);
}
// ============================================================================
// EMAIL ALERT
// ============================================================================
/**
* Send email alert with security issues and errors
*
* @param {Array} issues - Deduplicated issues array
* @param {Array} errors - Errors array
*/
function sendAlert(issues, errors) {
var subject = '[SECURITY ALERT] Unauthorized Domains Detected - ' + issues.length + ' issues';
var body = '';
body += 'MCC Domain Security Monitor has detected unauthorized domains in your Google Ads accounts.\n\n';
body += '='.repeat(80) + '\n';
body += 'SUMMARY\n';
body += '='.repeat(80) + '\n\n';
body += 'Total Issues: ' + issues.length + '\n';
body += 'Execution Errors: ' + errors.length + '\n';
body += 'Alert Time: ' + new Date().toString() + '\n\n';
// Group issues by domain
if (issues.length > 0) {
body += '='.repeat(80) + '\n';
body += 'UNAUTHORIZED DOMAINS DETECTED\n';
body += '='.repeat(80) + '\n\n';
var byDomain = {};
for (var i = 0; i < issues.length; i++) {
var domain = issues[i].domain;
if (!byDomain[domain]) {
byDomain[domain] = [];
}
byDomain[domain].push(issues[i]);
}
for (var domain in byDomain) {
var domainIssues = byDomain[domain];
body += 'Domain: ' + domain + ' (' + domainIssues.length + ' occurrences)\n';
body += '-'.repeat(80) + '\n';
for (var j = 0; j < domainIssues.length; j++) {
var issue = domainIssues[j];
body += ' Type: ' + issue.type + '\n';
body += ' Campaign: ' + issue.campaign + '\n';
if (issue.adGroup && issue.adGroup !== 'N/A') {
body += ' Ad Group: ' + issue.adGroup + '\n';
}
body += ' URL: ' + issue.url + '\n';
body += '\n';
}
body += '\n';
}
}
// List errors
if (errors.length > 0) {
body += '='.repeat(80) + '\n';
body += 'EXECUTION ERRORS\n';
body += '='.repeat(80) + '\n\n';
for (var k = 0; k < errors.length; k++) {
body += 'Account: ' + errors[k].customerId;
if (errors[k].accountName) {
body += ' (' + errors[k].accountName + ')';
}
body += '\n';
body += 'Error: ' + errors[k].error + '\n\n';
}
}
body += '='.repeat(80) + '\n';
body += 'NEXT STEPS\n';
body += '='.repeat(80) + '\n\n';
body += '1. Review unauthorized domains above\n';
body += '2. If domains are legitimate, add them to CONFIG.ACCOUNT_SPECIFIC_ALLOWLIST\n';
body += '3. If domains are malicious, pause affected campaigns and investigate\n';
body += '4. Check for account compromise if many unknown domains appear\n\n';
body += 'This is an automated alert from MCC Domain Security Monitor v2.0.4\n';
MailApp.sendEmail(CONFIG.ALERT_EMAIL, subject, body);
Logger.log('Email alert sent to: ' + CONFIG.ALERT_EMAIL);
}