File size: 4,693 Bytes
097eaf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { configDotenv } from "dotenv";
import { v7 as uuidv7 } from "uuid";
import { config } from "../../../config";
import { parse } from "tldts";
import { TeamFlags } from "../../../controllers/v1/types";
import {
  supabase_rr_service,
  supabase_service,
} from "../../../services/supabase";

configDotenv();

type BlocklistBlob = {
  blocklist: string[];
  allowedKeywords: string[];
};

type BlockContext = {
  team_id?: string | null;
  origin?: string | null;
};

type BlockHit = {
  id: string;
  domain: string;
  url: string;
  team_id: string | null;
  origin: string | null;
};

const HIT_BUFFER_FLUSH_MS = 5000;
const HIT_BUFFER_MAX_SIZE = 200;
let hitBuffer: BlockHit[] = [];
let hitFlushTimer: NodeJS.Timeout | null = null;

async function flushHits(): Promise<void> {
  if (hitBuffer.length === 0) return;
  const batch = hitBuffer;
  hitBuffer = [];
  if (config.USE_DB_AUTHENTICATION !== true) return;
  try {
    await supabase_service.from("blocklist_hits").insert(batch);
  } catch {}
}

function scheduleHitFlush(): void {
  if (hitFlushTimer !== null) return;
  hitFlushTimer = setTimeout(() => {
    hitFlushTimer = null;
    void flushHits();
  }, HIT_BUFFER_FLUSH_MS);
  if (typeof hitFlushTimer.unref === "function") hitFlushTimer.unref();
}

function recordHit(
  url: string,
  domain: string,
  context: BlockContext | undefined,
): void {
  if (context === undefined) return;
  if (config.USE_DB_AUTHENTICATION !== true) return;
  hitBuffer.push({
    id: uuidv7(),
    domain,
    url: url.length > 2048 ? url.slice(0, 2048) : url,
    team_id: context.team_id ?? null,
    origin: context.origin ?? null,
  });
  if (hitBuffer.length >= HIT_BUFFER_MAX_SIZE) {
    if (hitFlushTimer !== null) {
      clearTimeout(hitFlushTimer);
      hitFlushTimer = null;
    }
    void flushHits();
  } else {
    scheduleHitFlush();
  }
}

function allowedKeywordMatches(url: string, allowedKeyword: string): boolean {
  const keyword = allowedKeyword.trim();
  if (!keyword) {
    return false;
  }

  if (keyword.startsWith("regex:")) {
    try {
      return new RegExp(keyword.slice("regex:".length), "i").test(url);
    } catch {
      return false;
    }
  }

  const regexMatch = keyword.match(/^\/(.+)\/([dgimsuvy]*)$/);
  if (regexMatch) {
    try {
      return new RegExp(regexMatch[1], regexMatch[2]).test(url);
    } catch {
      return false;
    }
  }

  return url.toLowerCase().includes(keyword.toLowerCase());
}

let blob: BlocklistBlob | null = null;

export async function initializeBlocklist() {
  if (config.USE_DB_AUTHENTICATION !== true || config.DISABLE_BLOCKLIST) {
    blob = {
      blocklist: [],
      allowedKeywords: [],
    };
    return;
  }

  const { data, error } = await supabase_rr_service
    .from("blocklist")
    .select("*")
    .single();

  if (error) {
    throw new Error(`Error getting blocklist: ${error.message}`);
  }

  if (!data) {
    throw new Error("Error getting blocklist: No data returned from database");
  }
  blob = data.data;
}

export function isUrlBlocked(
  url: string,
  flags: TeamFlags,
  context?: BlockContext,
): boolean {
  if (blob === null) {
    throw new Error("Blocklist not initialized");
  }

  const lowerCaseUrl = url.trim().toLowerCase();

  let blockedlist = [...blob.blocklist];

  if (flags?.unblockedDomains) {
    blockedlist = blockedlist.filter(
      blocked => !flags.unblockedDomains!.includes(blocked),
    );
  }

  const decryptedUrl =
    blockedlist.find(decrypted => lowerCaseUrl === decrypted) || lowerCaseUrl;

  // If the URL is empty or invalid, return false
  let parsedUrl: any;
  try {
    parsedUrl = parse(decryptedUrl);
  } catch {
    console.log("Error parsing URL:", url);
    return false;
  }

  const domain = parsedUrl.domain;
  const publicSuffix = parsedUrl.publicSuffix;

  if (!domain) {
    return false;
  }

  // Check if URL contains any allowed keyword
  if (
    blob.allowedKeywords.some(keyword => allowedKeywordMatches(url, keyword))
  ) {
    return false;
  }

  // Block exact matches
  if (blockedlist.includes(domain)) {
    recordHit(url, domain, context);
    return true;
  }

  // Block subdomains
  if (blockedlist.some(blocked => domain.endsWith(`.${blocked}`))) {
    recordHit(url, domain, context);
    return true;
  }

  // Block different TLDs of the same base domain
  const baseDomain = domain.split(".")[0]; // Extract the base domain (e.g., "facebook" from "facebook.com")

  if (
    publicSuffix &&
    baseDomain.length > 2 &&
    blockedlist.some(
      blocked => blocked.startsWith(baseDomain + ".") && blocked !== domain,
    )
  ) {
    recordHit(url, domain, context);
    return true;
  }

  return false;
}