Commit 0c6cf335b1

0c6cf335b1542d0e8efa53314ce4d08f4a46700b

parent: 3201ebd829

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-06-07 11:54 UTC

Updates website to use new API

Layout: unified · split

web/.env.sample +9 −1
@@ -14,8 +14,16 @@ OUTPUT=''
1414# Used to generate sitemap.xml and for canonical URLs
1515SITE_URL=''
1616
17# Base URL of the Awesome Privacy API (powers search and enrichment data).
18# Defaults to the hosted instance; override to point at a self-hosted API.
19PUBLIC_API_URL='https://api.awesome-privacy.xyz'
20
21# Bearer token for the API's enrichment routes (/v1/enrich/*).
22# Only needed at build-time, and only if the target API has auth enabled.
23API_TOKEN=''
24
1725# GitHub API key (with pub repo read perms).
18# This is used to fetch reposity stats for open source apps which are listed
26# Used for repo metrics and contributor lists fetched directly from GitHub.
1927GITHUB_API_KEY=''
2028
2129# A Font Awesome Pro package token
web/src/components/things/GitHubDetailedInfo.astro +1 −1
@@ -166,7 +166,7 @@ const languageChart = `https://quickchart.io/chart?c=${generateChartData(gitHubD
166166 <h4>Size</h4>
167167 <p>{formatBigNumber(gitHubData.info.size)} KB</p>
168168 <h4>Stars</h4>
169 <p>{formatBigNumber(gitHubData.info.scarCount)}</p>
169 <p>{formatBigNumber(gitHubData.info.starCount)}</p>
170170 <h4>Forks</h4>
171171 <p>{formatBigNumber(gitHubData.info.forksCount)}</p>
172172 <h4>Watchers</h4>
web/src/components/things/ItemGitHubMetrics.astro +69 −87
@@ -1,120 +1,102 @@
11---
2import FontAwesome from "@components/form/FontAwesome.svelte";
3import { error } from "@utils/logger";
2import FontAwesome from '@components/form/FontAwesome.svelte';
3import { error } from '@utils/logger';
4import { safeFetch } from '@utils/safe-fetch';
5import { fetchGitHubStats } from '@utils/fetch-repo-info';
6
47const { github } = Astro.props;
58
6interface GitHubRepoData {
7 stargazers_count?: number;
8 forks_count?: number;
9 open_issues_count?: number;
10 language?: string;
11 license?: { spdx_id?: string; name?: string };
9interface RepoMetrics {
10 stars: number;
11 forks: number;
12 openIssues: number;
13 language: string;
14 licenseSpdx: string;
15 licenseName: string;
1216}
1317
14/**
15 * For a given `user/repo` fetch repository stats from the GitHub API data
16 * If API key is available through env var, use it to increase rate limit
17 * Returns the response data and status code (200 == success)
18 * @param repo
19 */
20const fetchGitHubData = async (repo: string) => {
21 const apiKey = import.meta.env.GITHUB_API_KEY;
22 const headers = new Headers();
23 if (apiKey) {
24 headers.append("Authorization", `token ${apiKey}`);
25 }
18const normalizeRepo = (repo: string) =>
19 repo.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, '');
2620
27 let data: GitHubRepoData = {};
28 let statusCode;
29
30 const response = await fetch(`https://api.github.com/repos/${repo}`, {
31 headers: headers,
32 }).catch((e) => {
33 error('GitHub API', `Network error for ${repo}: ${e.message}`);
34 // Return a placeholder response to handle this gracefully
21// Fallback straight to the GitHub API when our API is unavailable.
22const fromGitHub = async (repo: string): Promise<RepoMetrics | null> => {
23 const headers: Record<string, string> = { 'User-Agent': 'awesome-privacy' };
24 const apiKey = import.meta.env.GITHUB_API_KEY;
25 if (apiKey) headers['Authorization'] = `token ${apiKey}`;
26 try {
27 const res = await safeFetch(`https://api.github.com/repos/${repo}`, { headers });
28 if (!res.ok) {
29 error('GitHub API', `HTTP ${res.status} for ${repo}`);
30 return null;
31 }
32 const data = await res.json();
33 return {
34 stars: data.stargazers_count ?? 0,
35 forks: data.forks_count ?? 0,
36 openIssues: data.open_issues_count ?? 0,
37 language: data.language ?? '',
38 licenseSpdx: data.license?.spdx_id ?? '',
39 licenseName: data.license?.name ?? '',
40 };
41 } catch (e) {
42 error('GitHub API', `Network error for ${repo}: ${e}`);
3543 return null;
36 });
37
38 // Check if fetch was successful but caught by the catch block
39 if (!response) {
40 return { data, statusCode: 503 }; // Use an appropriate error status code
4144 }
45};
4246
43 statusCode = response.status;
44
45 // Only attempt to parse JSON if the response was OK
46 if (response.ok) {
47 data = await response.json();
48 } else {
49 error('GitHub API', `HTTP ${response.status} for ${repo}`);
47// Prefer our unified API, then fall back to the GitHub API directly.
48const getMetrics = async (repo: string): Promise<RepoMetrics | null> => {
49 const stats = await fetchGitHubStats(repo);
50 if (stats) {
51 const { info } = stats;
52 return {
53 stars: info.starCount,
54 forks: info.forksCount,
55 openIssues: info.openIssues,
56 language: info.language,
57 licenseSpdx: info.license,
58 licenseName: info.licenseName,
59 };
5060 }
51
52 return { data, statusCode };
61 return fromGitHub(normalizeRepo(repo));
5362};
5463
64const formatLicense = (spdx: string) => {
65 if (!spdx) return 'Unknown';
66 if (spdx === 'NOASSERTION') return 'No License';
67 return spdx;
68};
5569
56/**
57 * Given a license object, return SPDX ID, or a formatted name
58 * @param license
59 */
60const formatLicense = (license?: { spdx_id?: string, name?: string }) => {
61 if (!license) {
62 return "Unknown";
63 }
64 if (license.spdx_id === "NOASSERTION") {
65 return "No License";
66 }
67 return license.spdx_id;
68}
69
70/**
71 * Given a (possibly large) number, return a formatted string
72 * E.g. If greater than thousand, then return in k format
73 * @param num
74 */
7570const formatBigNumber = (num: number | undefined) => {
7671 if (num == null) return 0;
7772 if (num > 1000) {
7873 return `${(num / 1000).toFixed(1)}k`;
7974 }
8075 return num;
81}
82
83// Initiate GitHub fetch, and make available to the component
84const stats = await fetchGitHubData(github);
85
86const {
87 stargazers_count, forks_count, open_issues_count, language, license,
88} = stats.data;
89
76};
9077
78const metrics = await getMetrics(github);
9179---
9280
9381<div class="github-metrics">
94 <!-- <span title={`Built / owned by @${user}`}>
95 <img src={`https://github.com/${user}.png`} alt={user || owner?.login} width="20" height="20" />
96 </span> -->
97 <!-- <span title={`${repo} is open source, with code published on GitHub`}>
98 <FontAwesome iconName="openSource" /> Open Source
99 </span> -->
10082 <span title={`GitHub repository: ${github}`}>
10183 <a href={`https://github.com/${github}`} target="_blank"><FontAwesome iconName="github" /> {github}</a>
10284 </span>
103 { stats.statusCode === 200 && stats.data && (
104 <span title={`GitHub Star Count: ${stargazers_count}`}>
105 <FontAwesome iconName="stars" /> {formatBigNumber(stargazers_count)}
85 { metrics && (
86 <span title={`GitHub Star Count: ${metrics.stars}`}>
87 <FontAwesome iconName="stars" /> {formatBigNumber(metrics.stars)}
10688 </span>
107 <span title={`GitHub Fork Count: ${forks_count}`}>
108 <FontAwesome iconName="forks" /> {formatBigNumber(forks_count)}
89 <span title={`GitHub Fork Count: ${metrics.forks}`}>
90 <FontAwesome iconName="forks" /> {formatBigNumber(metrics.forks)}
10991 </span>
110 <span title={`Open Issues / Bugs: ${open_issues_count}`}>
111 <FontAwesome iconName="issues" /> {formatBigNumber(open_issues_count)}
92 <span title={`Open Issues / Bugs: ${metrics.openIssues}`}>
93 <FontAwesome iconName="issues" /> {formatBigNumber(metrics.openIssues)}
11294 </span>
113 <span title={`Code licensed under ${license?.name}`}>
114 <FontAwesome iconName="license" /> {formatLicense(license)}
95 <span title={`Code licensed under ${metrics.licenseName}`}>
96 <FontAwesome iconName="license" /> {formatLicense(metrics.licenseSpdx)}
11597 </span>
116 <span title={`Primary programming language ${language}`}>
117 <FontAwesome iconName="language" /> {language}
98 <span title={`Primary programming language ${metrics.language}`}>
99 <FontAwesome iconName="language" /> {metrics.language}
118100 </span>
119101 )}
120102</div>
web/src/components/things/SmartSuggestions.svelte +4 −3
@@ -3,6 +3,7 @@
33 import type { Category, Service } from '../../types/Service';
44 import { formatLink } from '@utils/parse-markdown';
55 import { slugify } from '@utils/fetch-data';
6 import { apiBase } from '@utils/api-config';
67
78 interface ServiceResult extends Service {
89 path: string;
@@ -20,11 +21,11 @@
2021 str.toLowerCase().replace(/[^a-z0-9]/g, '');
2122
2223 onMount(async () => {
23 const apiEndpoint = `https://awesome-privacy.as93.workers.dev/${searchTerm}`;
24 const apiEndpoint = `${apiBase}/v1/search?q=${encodeURIComponent(searchTerm)}`;
2425 const fetchedServices = await fetch(apiEndpoint)
2526 .then((response) => response.json())
26 .then((data) =>
27 (JSON.parse(data) || []).map((servName: string) => normalize(servName)),
27 .then((res) =>
28 (res.data || []).map((hit: { name: string }) => normalize(hit.name)),
2829 );
2930
3031 const tmpResults: ServiceResult[] = [];
web/src/utils/api-config.ts added +12
@@ -0,0 +1,12 @@
1// Base URL and auth for the unified Awesome Privacy API.
2const strip = (value: string): string => value.replace(/['";]+/g, '').trim();
3
4export const apiBase =
5 strip(import.meta.env.PUBLIC_API_URL || '').replace(/\/+$/, '') ||
6 'https://api.awesome-privacy.xyz';
7
8// Bearer header for enrichment routes; omitted when no token is set.
9export const enrichHeaders = (): Record<string, string> => {
10 const token = strip(import.meta.env.API_TOKEN || '');
11 return token ? { Authorization: `Bearer ${token}` } : {};
12};
web/src/utils/fetch-android-info.ts +4 −2
@@ -1,5 +1,6 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
34
45const extractPackage = (str: string): string =>
56 str.includes('id=') ? str.split('id=')[1] : str;
@@ -7,9 +8,10 @@ const extractPackage = (str: string): string =>
78export const fetchAndroidInfo = async (
89 androidPackage: string,
910): Promise<AndroidInfo | null> => {
10 const endpoint = `https://android-app-privacy.as93.net/${extractPackage(androidPackage)}`;
11 const pkg = extractPackage(androidPackage);
12 const endpoint = `${apiBase}/v1/enrich/android/${pkg}`;
1113 try {
12 const res = await safeFetch(endpoint);
14 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
1315 if (!res.ok) {
1416 error(
1517 'Android',
web/src/utils/fetch-discord-info.ts +3 −2
@@ -1,12 +1,13 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
34
45export const fetchDiscordInfo = async (
56 discordInvite: string,
67): Promise<DiscordInfo | null> => {
7 const endpoint = `https://discord-invite-info.as93.net/${discordInvite}`;
8 const endpoint = `${apiBase}/v1/enrich/discord/${discordInvite}`;
89 try {
9 const res = await safeFetch(endpoint);
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
1011 if (!res.ok) {
1112 error('Discord', `HTTP ${res.status} for ${discordInvite} (${endpoint})`);
1213 return null;
web/src/utils/fetch-ios-info.ts +9 −2
@@ -1,12 +1,19 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4
5// Pull the id from an App Store URL's `/id123` segment, else pass it through.
6const extractId = (iosUrl: string): string => {
7 const match = iosUrl.match(/\/id(\d+)/);
8 return match ? match[1] : iosUrl;
9};
310
411export const fetchIosInfo = async (
512 iosUrl: string,
613): Promise<IoSApiResponse | null> => {
7 const endpoint = `https://ios-app-info.as93.net?appStoreUrl=${iosUrl}`;
14 const endpoint = `${apiBase}/v1/enrich/ios/${extractId(iosUrl)}`;
815 try {
9 const res = await safeFetch(endpoint);
16 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
1017 if (!res.ok) {
1118 error('iOS', `HTTP ${res.status} for ${iosUrl} (${endpoint})`);
1219 return null;
web/src/utils/fetch-privacy-policy.ts +5 −3
@@ -1,12 +1,14 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
34
5// Wrap the flat ToS;DR v3 record in the shape the app already consumes.
46export const fetchTosdrPrivacy = async (
57 serviceId: string,
68): Promise<PrivacyPolicyResponse | null> => {
7 const endpoint = `https://privacy-policies.as93.workers.dev/${serviceId}`;
9 const endpoint = `${apiBase}/v1/enrich/privacy/${serviceId}`;
810 try {
9 const res = await safeFetch(endpoint);
11 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
1012 if (!res.ok) {
1113 error(
1214 'ToS;DR',
@@ -14,7 +16,7 @@ export const fetchTosdrPrivacy = async (
1416 );
1517 return null;
1618 }
17 return await res.json();
19 return { error: 0, message: '', parameters: await res.json() };
1820 } catch (err) {
1921 error('ToS;DR', `Network error for service ${serviceId}: ${err}`);
2022 return null;
web/src/utils/fetch-reddit-info.ts +3 −2
@@ -1,12 +1,13 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
34
45export const fetchRedditInfo = async (
56 subreddit: string,
67): Promise<RedditData | null> => {
7 const endpoint = `https://subreddit-info.as93.net/${subreddit}`;
8 const endpoint = `${apiBase}/v1/enrich/reddit/${subreddit}`;
89 try {
9 const res = await safeFetch(endpoint);
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
1011 if (!res.ok) {
1112 error('Reddit', `HTTP ${res.status} for r/${subreddit} (${endpoint})`);
1213 return null;
web/src/utils/fetch-repo-info.ts +17 −122
@@ -1,135 +1,25 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3
4const githubHeaders = (): Record<string, string> => {
5 const headers: Record<string, string> = {
6 'User-Agent': 'awesome-privacy',
7 Accept: 'application/vnd.github.v3+json',
8 };
9 const token = import.meta.env.GITHUB_API_KEY;
10 if (token) headers['Authorization'] = `token ${token}`;
11 return headers;
12};
13
14const fetchFromGitHub = async (
15 github: string,
16): Promise<GitHubStatsResponse | null> => {
17 const base = `https://api.github.com/repos/${github}`;
18 const headers = githubHeaders();
19
20 const [infoRes, langsRes, tagsRes, contribRes, commitsRes] =
21 await Promise.all([
22 safeFetch(base, { headers }),
23 safeFetch(`${base}/languages`, { headers }),
24 safeFetch(`${base}/tags`, { headers }),
25 safeFetch(`${base}/contributors`, { headers }),
26 safeFetch(`${base}/commits`, { headers }),
27 ]);
28
29 if (!infoRes.ok) {
30 error(
31 'GitHub Stats',
32 `GitHub API returned ${infoRes.status} for ${github}`,
33 );
34 return null;
35 }
36
37 const parseJson = (r: Response) =>
38 r.ok && r.status !== 204 ? r.json() : null;
39
40 const [info, languages, tags, contributors, commits] = await Promise.all(
41 [infoRes, langsRes, tagsRes, contribRes, commitsRes].map(parseJson),
42 );
43
44 return {
45 info: {
46 ownerUsername: info.owner?.login ?? '',
47 ownerAvatar: info.owner?.avatar_url ?? '',
48 description: info.description ?? '',
49 url: info.html_url ?? '',
50 homepage: info.homepage ?? '',
51 language: info.language ?? '',
52 topics: info.topics ?? [],
53 license: info.license?.spdx_id ?? '',
54 isFork: info.fork ?? false,
55 isArchived: info.archived ?? false,
56 createdAt: info.created_at ?? '',
57 updatedAt: info.updated_at ?? '',
58 size: info.size ?? 0,
59 scarCount: info.stargazers_count ?? 0,
60 forksCount: info.forks_count ?? 0,
61 watchersCount: info.watchers_count ?? 0,
62 },
63 languages: languages ?? {},
64 versions: (tags ?? []).map(
65 (tag: {
66 name: string;
67 commit?: { sha?: string };
68 zipball_url?: string;
69 tarball_url?: string;
70 }) => ({
71 name: tag.name,
72 commit: tag.commit?.sha ?? '',
73 zipball: tag.zipball_url ?? '',
74 tarball: tag.tarball_url ?? '',
75 }),
76 ),
77 contributors: (contributors ?? []).map(
78 (c: { login?: string; avatar_url?: string; contributions?: number }) => ({
79 username: c.login ?? '',
80 avatar: c.avatar_url ?? '',
81 contributions: c.contributions ?? 0,
82 }),
83 ),
84 commits: (commits ?? []).map(
85 (c: {
86 sha?: string;
87 commit?: {
88 author?: { name?: string; date?: string };
89 message?: string;
90 };
91 author?: { login?: string; avatar_url?: string };
92 }) => ({
93 sha: c.sha ?? '',
94 authorName: c.commit?.author?.name ?? '',
95 authorDate: c.commit?.author?.date ?? '',
96 message: c.commit?.message ?? '',
97 authorUsername: c.author?.login ?? '',
98 authorAvatar: c.author?.avatar_url ?? '',
99 }),
100 ),
101 };
102};
103
104const fetchFromWorker = async (
105 github: string,
106): Promise<GitHubStatsResponse | null> => {
107 const res = await safeFetch(`https://repo-info.as93.workers.dev/${github}`);
108 if (!res.ok) return null;
109 return res.json();
110};
3import { apiBase, enrichHeaders } from './api-config';
1114
1125const normalizeRepo = (github: string): string =>
113 github.replace(/^https?:\/\/github\.com\//, '');
6 github.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, '');
1147
1158export const fetchGitHubStats = async (
1169 github: string,
11710): Promise<GitHubStatsResponse | null> => {
118 github = normalizeRepo(github);
11 const repo = normalizeRepo(github);
12 const endpoint = `${apiBase}/v1/enrich/github/${repo}`;
11913 try {
120 const result = await fetchFromGitHub(github);
121 if (result) return result;
122 const fallback = await fetchFromWorker(github);
123 if (fallback) return fallback;
124 error('GitHub Stats', `Both direct API and worker failed for ${github}`);
125 return null;
126 } catch (err) {
127 try {
128 return await fetchFromWorker(github);
129 } catch {
130 error('GitHub Stats', `All fetches failed for ${github}: ${err}`);
14 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
15 if (!res.ok) {
16 error('GitHub Stats', `HTTP ${res.status} for ${repo} (${endpoint})`);
13117 return null;
13218 }
19 return await res.json();
20 } catch (err) {
21 error('GitHub Stats', `Network error for ${repo}: ${err}`);
22 return null;
13323 }
13424};
13525
@@ -143,14 +33,18 @@ export interface GitHubStatsResponse {
14333 language: string;
14434 topics: string[];
14535 license: string;
36 licenseName: string;
14637 isFork: boolean;
14738 isArchived: boolean;
39 forkParent: string;
14840 createdAt: string;
14941 updatedAt: string;
42 pushedAt: string;
15043 size: number;
151 scarCount: number;
44 starCount: number;
15245 forksCount: number;
15346 watchersCount: number;
47 openIssues: number;
15448 };
15549 languages: {
15650 [key: string]: number;
@@ -164,6 +58,7 @@ export interface GitHubStatsResponse {
16458 contributors: Array<{
16559 username: string;
16660 avatar: string;
61 url: string;
16762 contributions: number;
16863 }>;
16964 commits: Array<{
web/src/utils/fetch-website-info.ts +3 −2
@@ -1,12 +1,13 @@
11import { error } from './logger';
22import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
34
45export const fetchWebsiteInfo = async (
56 url: string,
67): Promise<WebsiteData | null> => {
7 const endpoint = `https://site-info-fetch.as93.workers.dev/?url=${url}`;
8 const endpoint = `${apiBase}/v1/enrich/website?url=${encodeURIComponent(url)}`;
89 try {
9 const res = await safeFetch(endpoint);
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
1011 if (!res.ok) {
1112 error('Website', `HTTP ${res.status} for ${url} (${endpoint})`);
1213 return null;