@digitalcanopy/links 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +108 -2
- package/package.json +52 -4
- package/src/__tests__/client.test.ts +229 -0
- package/src/__tests__/react.test.tsx +253 -0
- package/src/__tests__/sanitizer.test.ts +101 -0
- package/src/client.ts +332 -0
- package/src/index.ts +41 -0
- package/src/react/SafeAnchor.tsx +89 -0
- package/src/react/TrustBadge.tsx +122 -0
- package/src/react/index.ts +6 -0
- package/src/react/useTrackedLink.ts +171 -0
- package/src/sanitizer.ts +103 -0
- package/src/types.ts +76 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.json +21 -0
- package/vitest.config.ts +11 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
hasSurveillanceTokens,
|
|
4
|
+
INVASIVE_TRACKING_PARAMS,
|
|
5
|
+
sanitizeUrl,
|
|
6
|
+
} from '../sanitizer';
|
|
7
|
+
|
|
8
|
+
describe('Privacy Sanitizer (sanitizeUrl & hasSurveillanceTokens)', () => {
|
|
9
|
+
it('strips all major ad-tech and surveillance query parameters', () => {
|
|
10
|
+
const dirtyUrl =
|
|
11
|
+
'https://sunshade.icu/post?fbclid=12345&gclid=67890&msclkid=abc&ttclid=xyz&twclid=tw123&_hsenc=hs123&mc_eid=mc123&sc_campaign=sc123&igshid=ig123&dclid=dc123&gad_source=gad1&gbraid=gb1&wbraid=wb1&yclid=yc1';
|
|
12
|
+
|
|
13
|
+
const cleaned = sanitizeUrl(dirtyUrl);
|
|
14
|
+
expect(cleaned).toBe('https://sunshade.icu/post');
|
|
15
|
+
expect(hasSurveillanceTokens(dirtyUrl)).toBe(true);
|
|
16
|
+
expect(hasSurveillanceTokens(cleaned)).toBe(false);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('preserves clean attribution and application query parameters', () => {
|
|
20
|
+
const mixedUrl =
|
|
21
|
+
'https://links.sunshade.icu/article?utm_source=bsky&utm_medium=social&utm_campaign=launch&utm_term=crypto&utm_content=v1&ch=direct&ref=hub&fbclid=strip_me&doc_id=987';
|
|
22
|
+
|
|
23
|
+
const cleaned = sanitizeUrl(mixedUrl);
|
|
24
|
+
const parsed = new URL(cleaned);
|
|
25
|
+
|
|
26
|
+
expect(parsed.searchParams.get('fbclid')).toBeNull();
|
|
27
|
+
expect(parsed.searchParams.get('utm_source')).toBe('bsky');
|
|
28
|
+
expect(parsed.searchParams.get('utm_medium')).toBe('social');
|
|
29
|
+
expect(parsed.searchParams.get('utm_campaign')).toBe('launch');
|
|
30
|
+
expect(parsed.searchParams.get('utm_term')).toBe('crypto');
|
|
31
|
+
expect(parsed.searchParams.get('utm_content')).toBe('v1');
|
|
32
|
+
expect(parsed.searchParams.get('ch')).toBe('direct');
|
|
33
|
+
expect(parsed.searchParams.get('ref')).toBe('hub');
|
|
34
|
+
expect(parsed.searchParams.get('doc_id')).toBe('987');
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('preserves URL hash fragments', () => {
|
|
38
|
+
const urlWithHash = 'https://sunshade.icu/docs?fbclid=bad#installation-guide';
|
|
39
|
+
const cleaned = sanitizeUrl(urlWithHash);
|
|
40
|
+
|
|
41
|
+
expect(cleaned).toBe('https://sunshade.icu/docs#installation-guide');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('sanitizes relative URLs safely while preserving path traversals', () => {
|
|
45
|
+
const relative = '/dashboard/overview?fbclid=strip_me&tab=analytics#summary';
|
|
46
|
+
const cleaned = sanitizeUrl(relative);
|
|
47
|
+
|
|
48
|
+
expect(cleaned).toBe('/dashboard/overview?tab=analytics#summary');
|
|
49
|
+
expect(hasSurveillanceTokens(relative)).toBe(true);
|
|
50
|
+
expect(hasSurveillanceTokens(cleaned)).toBe(false);
|
|
51
|
+
|
|
52
|
+
// Parent-relative traversals
|
|
53
|
+
expect(sanitizeUrl('../invite?gclid=bad&ref=sidebar')).toBe('../invite?ref=sidebar');
|
|
54
|
+
expect(sanitizeUrl('../../settings?fbclid=123')).toBe('../../settings');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('neutralizes dangerous executable URL schemes', () => {
|
|
58
|
+
expect(sanitizeUrl('javascript:alert(1)')).toBe('about:blank');
|
|
59
|
+
expect(sanitizeUrl('JAVASCRIPT:void(0)')).toBe('about:blank');
|
|
60
|
+
expect(sanitizeUrl('vbscript:msgbox(1)')).toBe('about:blank');
|
|
61
|
+
expect(sanitizeUrl('data:text/html,<script>alert(1)</script>')).toBe('about:blank');
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('preserves protocol-relative external URLs', () => {
|
|
65
|
+
const protoRelative = '//other.example/page?fbclid=bad&ref=shared#section';
|
|
66
|
+
expect(sanitizeUrl(protoRelative)).toBe('//other.example/page?ref=shared#section');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('handles relative paths without leading slash', () => {
|
|
70
|
+
const relative = 'invite?gclid=bad&ref=friend';
|
|
71
|
+
const cleaned = sanitizeUrl(relative);
|
|
72
|
+
|
|
73
|
+
expect(cleaned).toBe('invite?ref=friend');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('handles root domain URLs cleanly without lingering trailing questions', () => {
|
|
77
|
+
const rootUrl = 'https://sunshade.icu?fbclid=bad_param';
|
|
78
|
+
const cleaned = sanitizeUrl(rootUrl);
|
|
79
|
+
|
|
80
|
+
expect(cleaned).toBe('https://sunshade.icu');
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('returns empty string for empty, null, or invalid non-string input', () => {
|
|
84
|
+
expect(sanitizeUrl('')).toBe('');
|
|
85
|
+
// @ts-expect-error test invalid inputs
|
|
86
|
+
expect(sanitizeUrl(null)).toBe('');
|
|
87
|
+
// @ts-expect-error test invalid inputs
|
|
88
|
+
expect(sanitizeUrl(undefined)).toBe('');
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('verifies INVASIVE_TRACKING_PARAMS set contains key ad platforms', () => {
|
|
92
|
+
expect(INVASIVE_TRACKING_PARAMS.has('fbclid')).toBe(true);
|
|
93
|
+
expect(INVASIVE_TRACKING_PARAMS.has('gclid')).toBe(true);
|
|
94
|
+
expect(INVASIVE_TRACKING_PARAMS.has('msclkid')).toBe(true);
|
|
95
|
+
expect(INVASIVE_TRACKING_PARAMS.has('ttclid')).toBe(true);
|
|
96
|
+
expect(INVASIVE_TRACKING_PARAMS.has('twclid')).toBe(true);
|
|
97
|
+
expect(INVASIVE_TRACKING_PARAMS.has('_hsenc')).toBe(true);
|
|
98
|
+
expect(INVASIVE_TRACKING_PARAMS.has('mc_eid')).toBe(true);
|
|
99
|
+
expect(INVASIVE_TRACKING_PARAMS.has('sc_campaign')).toBe(true);
|
|
100
|
+
});
|
|
101
|
+
});
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SunShade Universal Links Client SDK
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { hasSurveillanceTokens, sanitizeUrl } from './sanitizer';
|
|
6
|
+
import type {
|
|
7
|
+
ClientConfig,
|
|
8
|
+
ReputationTier,
|
|
9
|
+
ShortLinkResult,
|
|
10
|
+
ShortenUrlOptions,
|
|
11
|
+
TrustFlags,
|
|
12
|
+
TrustPillars,
|
|
13
|
+
TrustScoreReport,
|
|
14
|
+
TrustTier,
|
|
15
|
+
} from './types';
|
|
16
|
+
|
|
17
|
+
const DEFAULT_BASE_URL = 'https://links.sunshade.icu';
|
|
18
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
19
|
+
|
|
20
|
+
export class LinksClient {
|
|
21
|
+
private baseUrl: string;
|
|
22
|
+
private apiKey?: string;
|
|
23
|
+
private tenantId?: string;
|
|
24
|
+
private customFetch: typeof fetch;
|
|
25
|
+
private enableFallback: boolean;
|
|
26
|
+
private timeoutMs: number;
|
|
27
|
+
|
|
28
|
+
constructor(config: ClientConfig = {}) {
|
|
29
|
+
const rawBase = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
30
|
+
this.apiKey = config.apiKey;
|
|
31
|
+
|
|
32
|
+
// Security check: Never send credentials over plaintext HTTP in production
|
|
33
|
+
if (
|
|
34
|
+
this.apiKey &&
|
|
35
|
+
rawBase.startsWith('http://') &&
|
|
36
|
+
!rawBase.includes('localhost') &&
|
|
37
|
+
!rawBase.includes('127.0.0.1')
|
|
38
|
+
) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
'Insecure transport: apiKey cannot be transmitted over plaintext HTTP (use HTTPS or localhost).'
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
this.baseUrl = rawBase;
|
|
45
|
+
this.tenantId = config.tenantId;
|
|
46
|
+
this.customFetch = config.fetch || globalThis.fetch.bind(globalThis);
|
|
47
|
+
this.enableFallback = config.enableFallback ?? true;
|
|
48
|
+
this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Shorten a destination URL with channel routing and privacy sanitization.
|
|
53
|
+
*/
|
|
54
|
+
async shortenUrl(options: ShortenUrlOptions): Promise<ShortLinkResult> {
|
|
55
|
+
if (!options?.destination) {
|
|
56
|
+
throw new Error('Destination URL is required');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const sanitizedDestination = this.sanitizeUrl(options.destination);
|
|
60
|
+
const channel = options.channel || 'direct';
|
|
61
|
+
const tenantId = options.tenantId || this.tenantId;
|
|
62
|
+
|
|
63
|
+
const payload = {
|
|
64
|
+
destination: sanitizedDestination,
|
|
65
|
+
channel,
|
|
66
|
+
campaign: options.campaign,
|
|
67
|
+
tenant_id: tenantId,
|
|
68
|
+
slug: options.slug,
|
|
69
|
+
metadata: options.metadata,
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const headers: Record<string, string> = {
|
|
73
|
+
'Content-Type': 'application/json',
|
|
74
|
+
Accept: 'application/json',
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
if (this.apiKey) {
|
|
78
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
79
|
+
}
|
|
80
|
+
if (tenantId) {
|
|
81
|
+
headers['x-tenant-id'] = tenantId;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
const response = await this.customFetch(`${this.baseUrl}/api/v1/links`, {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
headers,
|
|
91
|
+
body: JSON.stringify(payload),
|
|
92
|
+
signal: controller.signal,
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
if (!response.ok) {
|
|
96
|
+
throw new Error(`Links API error: ${response.status} ${response.statusText}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const data = await response.json();
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
id: data.id || `lnk_${Math.random().toString(36).substring(2, 9)}`,
|
|
103
|
+
slug: data.slug || options.slug || '',
|
|
104
|
+
shortUrl:
|
|
105
|
+
data.short_url ||
|
|
106
|
+
data.shortUrl ||
|
|
107
|
+
`${this.baseUrl}/${data.slug || options.slug || ''}/${channel}`,
|
|
108
|
+
destinationUrl: data.destination_url || data.destinationUrl || sanitizedDestination,
|
|
109
|
+
channel: data.channel || channel,
|
|
110
|
+
campaign: data.campaign || options.campaign,
|
|
111
|
+
tenantId: data.tenant_id || data.tenantId || tenantId,
|
|
112
|
+
trustScore: data.trust_score ?? data.trustScore,
|
|
113
|
+
createdAt: data.created_at || data.createdAt || new Date().toISOString(),
|
|
114
|
+
};
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (!this.enableFallback) {
|
|
117
|
+
throw err;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Fallback: return sanitized URL directly without shortening
|
|
121
|
+
return {
|
|
122
|
+
id: `fallback-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
|
|
123
|
+
slug: options.slug || '',
|
|
124
|
+
shortUrl: sanitizedDestination,
|
|
125
|
+
destinationUrl: sanitizedDestination,
|
|
126
|
+
channel,
|
|
127
|
+
campaign: options.campaign,
|
|
128
|
+
tenantId,
|
|
129
|
+
trustScore: undefined,
|
|
130
|
+
createdAt: new Date().toISOString(),
|
|
131
|
+
};
|
|
132
|
+
} finally {
|
|
133
|
+
clearTimeout(timeout);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Resolve the Link Trust Score and 4-pillar audit report.
|
|
139
|
+
*/
|
|
140
|
+
async resolveTrustScore(urlOrSlug: string): Promise<TrustScoreReport> {
|
|
141
|
+
if (!urlOrSlug) {
|
|
142
|
+
throw new Error('URL or slug is required');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const isUrl =
|
|
146
|
+
urlOrSlug.startsWith('http://') ||
|
|
147
|
+
urlOrSlug.startsWith('https://') ||
|
|
148
|
+
urlOrSlug.startsWith('//');
|
|
149
|
+
|
|
150
|
+
const endpoint = isUrl
|
|
151
|
+
? `${this.baseUrl}/api/v1/trust?url=${encodeURIComponent(urlOrSlug)}`
|
|
152
|
+
: `${this.baseUrl}/api/v1/trust/${encodeURIComponent(urlOrSlug)}`;
|
|
153
|
+
|
|
154
|
+
const headers: Record<string, string> = {
|
|
155
|
+
Accept: 'application/json',
|
|
156
|
+
};
|
|
157
|
+
if (this.apiKey) {
|
|
158
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
159
|
+
}
|
|
160
|
+
if (this.tenantId) {
|
|
161
|
+
headers['x-tenant-id'] = this.tenantId;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const controller = new AbortController();
|
|
165
|
+
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
const response = await this.customFetch(endpoint, {
|
|
169
|
+
method: 'GET',
|
|
170
|
+
headers,
|
|
171
|
+
signal: controller.signal,
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
if (!response.ok) {
|
|
175
|
+
throw new Error(`Trust API error: ${response.status} ${response.statusText}`);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const data = await response.json();
|
|
179
|
+
const rawScore = data.score ?? data.trust_score;
|
|
180
|
+
|
|
181
|
+
// Validate that the remote response actually provided a score
|
|
182
|
+
if (typeof rawScore !== 'number' || isNaN(rawScore)) {
|
|
183
|
+
throw new Error('Invalid audit response: missing or unparseable trust score');
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const score: number = Math.max(0, Math.min(100, rawScore));
|
|
187
|
+
|
|
188
|
+
const status: TrustTier =
|
|
189
|
+
score >= 85 ? 'trusted' : score >= 60 ? 'warning' : 'danger';
|
|
190
|
+
const tier: ReputationTier =
|
|
191
|
+
data.tier ||
|
|
192
|
+
(score >= 85 ? 'trusted' : score >= 60 ? 'neutral' : 'danger');
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
url: data.url || urlOrSlug,
|
|
196
|
+
slug: data.slug,
|
|
197
|
+
score,
|
|
198
|
+
tier,
|
|
199
|
+
status,
|
|
200
|
+
flags: data.flags || {
|
|
201
|
+
verified_did: !!data.verified_did,
|
|
202
|
+
sanitized_trackers: !hasSurveillanceTokens(urlOrSlug),
|
|
203
|
+
redirect_count: data.redirect_count ?? 0,
|
|
204
|
+
reputation_tier: tier,
|
|
205
|
+
is_flagged: score < 60,
|
|
206
|
+
ssl_valid: urlOrSlug.startsWith('https://') || urlOrSlug.startsWith('//'),
|
|
207
|
+
},
|
|
208
|
+
pillars: data.pillars || {
|
|
209
|
+
provenance: Math.round(score * 0.35),
|
|
210
|
+
hygiene: Math.round(score * 0.25),
|
|
211
|
+
privacy: Math.round(score * 0.2),
|
|
212
|
+
networkDecay: Math.round(score * 0.2),
|
|
213
|
+
},
|
|
214
|
+
lastHygieneCheck:
|
|
215
|
+
data.last_hygiene_check || data.lastHygieneCheck || new Date().toISOString(),
|
|
216
|
+
did: data.did,
|
|
217
|
+
recommendation: data.recommendation,
|
|
218
|
+
};
|
|
219
|
+
} catch (err) {
|
|
220
|
+
if (!this.enableFallback) {
|
|
221
|
+
throw err;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Offline / Local Deterministic Trust Evaluation Fallback
|
|
225
|
+
return this.computeLocalTrustScore(urlOrSlug);
|
|
226
|
+
} finally {
|
|
227
|
+
clearTimeout(timeout);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Sanitizes a URL by stripping surveillance and ad-tech tracking parameters.
|
|
233
|
+
*/
|
|
234
|
+
sanitizeUrl(rawUrl: string): string {
|
|
235
|
+
return sanitizeUrl(rawUrl);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Deterministic client-side evaluation fallback when the remote trust auditor is unreachable.
|
|
240
|
+
*/
|
|
241
|
+
private computeLocalTrustScore(urlOrSlug: string): TrustScoreReport {
|
|
242
|
+
const isHttps = urlOrSlug.startsWith('https://') || urlOrSlug.startsWith('//');
|
|
243
|
+
const hasTrackers = hasSurveillanceTokens(urlOrSlug);
|
|
244
|
+
|
|
245
|
+
// Provenance (Pillar 1: 0-35)
|
|
246
|
+
const provenance = 10; // Unverified author baseline
|
|
247
|
+
|
|
248
|
+
// Target Hygiene (Pillar 2: 0-25)
|
|
249
|
+
const hygiene = isHttps ? 25 : 10;
|
|
250
|
+
|
|
251
|
+
// Privacy (Pillar 3: 0-20)
|
|
252
|
+
const privacy = hasTrackers ? 5 : 20;
|
|
253
|
+
|
|
254
|
+
// Network / Temporal Decay (Pillar 4: 0-20)
|
|
255
|
+
const networkDecay = 20;
|
|
256
|
+
|
|
257
|
+
const score = provenance + hygiene + privacy + networkDecay;
|
|
258
|
+
const status: TrustTier = score >= 85 ? 'trusted' : score >= 60 ? 'warning' : 'danger';
|
|
259
|
+
const tier: ReputationTier = score >= 85 ? 'trusted' : score >= 60 ? 'neutral' : 'danger';
|
|
260
|
+
|
|
261
|
+
const flags: TrustFlags = {
|
|
262
|
+
verified_did: false,
|
|
263
|
+
sanitized_trackers: !hasTrackers,
|
|
264
|
+
redirect_count: 0,
|
|
265
|
+
reputation_tier: tier,
|
|
266
|
+
is_flagged: score < 60,
|
|
267
|
+
ssl_valid: isHttps,
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
const pillars: TrustPillars = {
|
|
271
|
+
provenance,
|
|
272
|
+
hygiene,
|
|
273
|
+
privacy,
|
|
274
|
+
networkDecay,
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
return {
|
|
278
|
+
url: urlOrSlug,
|
|
279
|
+
score,
|
|
280
|
+
tier,
|
|
281
|
+
status,
|
|
282
|
+
flags,
|
|
283
|
+
pillars,
|
|
284
|
+
lastHygieneCheck: new Date().toISOString(),
|
|
285
|
+
recommendation:
|
|
286
|
+
score < 60
|
|
287
|
+
? 'Destination has potential security or tracking concerns.'
|
|
288
|
+
: 'Destination is reachable and verified against standard security baselines.',
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Singleton and default client management
|
|
294
|
+
let defaultClientInstance: LinksClient | null = null;
|
|
295
|
+
|
|
296
|
+
export function getDefaultClient(): LinksClient {
|
|
297
|
+
if (!defaultClientInstance) {
|
|
298
|
+
defaultClientInstance = new LinksClient();
|
|
299
|
+
}
|
|
300
|
+
return defaultClientInstance;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function setDefaultClient(client: LinksClient): void {
|
|
304
|
+
defaultClientInstance = client;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Universal functional export to shorten a URL.
|
|
309
|
+
*/
|
|
310
|
+
export async function shortenUrl(
|
|
311
|
+
options: ShortenUrlOptions,
|
|
312
|
+
config?: ClientConfig
|
|
313
|
+
): Promise<ShortLinkResult> {
|
|
314
|
+
const client = config ? new LinksClient(config) : getDefaultClient();
|
|
315
|
+
return client.shortenUrl(options);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Universal functional export to resolve a Link Trust Score.
|
|
320
|
+
*/
|
|
321
|
+
export async function resolveTrustScore(
|
|
322
|
+
urlOrSlug: string,
|
|
323
|
+
config?: ClientConfig
|
|
324
|
+
): Promise<TrustScoreReport> {
|
|
325
|
+
const client = config ? new LinksClient(config) : getDefaultClient();
|
|
326
|
+
return client.resolveTrustScore(urlOrSlug);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Alias for ecosystem naming consistency.
|
|
331
|
+
*/
|
|
332
|
+
export const SunshadeLinksClient = LinksClient;
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @digitalcanopy/links
|
|
3
|
+
* Universal Linking Client Library for SunShade Systems
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// Core types
|
|
7
|
+
export type {
|
|
8
|
+
ClientConfig,
|
|
9
|
+
ReputationTier,
|
|
10
|
+
ShortLinkResult,
|
|
11
|
+
ShortenUrlOptions,
|
|
12
|
+
TrustFlags,
|
|
13
|
+
TrustPillars,
|
|
14
|
+
TrustScoreReport,
|
|
15
|
+
TrustTier,
|
|
16
|
+
} from './types';
|
|
17
|
+
|
|
18
|
+
// URL & Privacy Sanitizer
|
|
19
|
+
export {
|
|
20
|
+
INVASIVE_TRACKING_PARAMS,
|
|
21
|
+
hasSurveillanceTokens,
|
|
22
|
+
sanitizeUrl,
|
|
23
|
+
} from './sanitizer';
|
|
24
|
+
|
|
25
|
+
// Links Client SDK
|
|
26
|
+
export {
|
|
27
|
+
LinksClient,
|
|
28
|
+
SunshadeLinksClient,
|
|
29
|
+
getDefaultClient,
|
|
30
|
+
resolveTrustScore,
|
|
31
|
+
setDefaultClient,
|
|
32
|
+
shortenUrl,
|
|
33
|
+
} from './client';
|
|
34
|
+
|
|
35
|
+
// React Type Exports (Runtime components exported via '@digitalcanopy/links/react')
|
|
36
|
+
export type {
|
|
37
|
+
SafeAnchorProps,
|
|
38
|
+
TrustBadgeProps,
|
|
39
|
+
UseTrackedLinkOptions,
|
|
40
|
+
UseTrackedLinkResult,
|
|
41
|
+
} from './react';
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { LinksClient } from '../client';
|
|
3
|
+
import { sanitizeUrl } from '../sanitizer';
|
|
4
|
+
import { TrustBadge } from './TrustBadge';
|
|
5
|
+
import { useTrackedLink } from './useTrackedLink';
|
|
6
|
+
|
|
7
|
+
export interface SafeAnchorProps
|
|
8
|
+
extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
|
|
9
|
+
href: string;
|
|
10
|
+
children?: React.ReactNode;
|
|
11
|
+
showBadge?: boolean;
|
|
12
|
+
telemetry?: boolean;
|
|
13
|
+
trustScore?: number;
|
|
14
|
+
resolveTrust?: boolean;
|
|
15
|
+
badgeSize?: 'sm' | 'md' | 'lg';
|
|
16
|
+
channel?: string;
|
|
17
|
+
campaign?: string;
|
|
18
|
+
tenantId?: string;
|
|
19
|
+
client?: LinksClient;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const SafeAnchor: React.FC<SafeAnchorProps> = ({
|
|
23
|
+
href,
|
|
24
|
+
children,
|
|
25
|
+
showBadge = true,
|
|
26
|
+
telemetry = false,
|
|
27
|
+
trustScore: explicitTrustScore,
|
|
28
|
+
resolveTrust = false,
|
|
29
|
+
badgeSize = 'sm',
|
|
30
|
+
channel,
|
|
31
|
+
campaign,
|
|
32
|
+
tenantId,
|
|
33
|
+
client,
|
|
34
|
+
target,
|
|
35
|
+
rel,
|
|
36
|
+
className = '',
|
|
37
|
+
style,
|
|
38
|
+
...rest
|
|
39
|
+
}) => {
|
|
40
|
+
const isExternal =
|
|
41
|
+
typeof href === 'string' &&
|
|
42
|
+
(href.startsWith('http://') ||
|
|
43
|
+
href.startsWith('https://') ||
|
|
44
|
+
href.startsWith('//'));
|
|
45
|
+
|
|
46
|
+
// Tracked link hook handles shortening (when telemetry is true)
|
|
47
|
+
// AND handles trust resolution (when resolveTrust is true)
|
|
48
|
+
const tracked = useTrackedLink(href, {
|
|
49
|
+
enabled: telemetry && isExternal,
|
|
50
|
+
autoResolveTrust: resolveTrust && isExternal && explicitTrustScore === undefined,
|
|
51
|
+
channel,
|
|
52
|
+
campaign,
|
|
53
|
+
tenantId,
|
|
54
|
+
client,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const finalHref = telemetry ? tracked.href : sanitizeUrl(href);
|
|
58
|
+
const effectiveScore = explicitTrustScore ?? tracked.trustScore;
|
|
59
|
+
|
|
60
|
+
const finalTarget = target ?? (isExternal ? '_blank' : undefined);
|
|
61
|
+
const finalRel =
|
|
62
|
+
rel ?? (isExternal && finalTarget === '_blank' ? 'noopener noreferrer' : undefined);
|
|
63
|
+
|
|
64
|
+
return (
|
|
65
|
+
<a
|
|
66
|
+
href={finalHref}
|
|
67
|
+
target={finalTarget}
|
|
68
|
+
rel={finalRel}
|
|
69
|
+
className={className}
|
|
70
|
+
style={{
|
|
71
|
+
display: 'inline-flex',
|
|
72
|
+
alignItems: 'center',
|
|
73
|
+
gap: '6px',
|
|
74
|
+
textDecoration: 'none',
|
|
75
|
+
...style,
|
|
76
|
+
}}
|
|
77
|
+
{...rest}
|
|
78
|
+
>
|
|
79
|
+
<span>{children}</span>
|
|
80
|
+
{showBadge && isExternal && (
|
|
81
|
+
<TrustBadge
|
|
82
|
+
score={effectiveScore}
|
|
83
|
+
size={badgeSize}
|
|
84
|
+
showLabel={false}
|
|
85
|
+
/>
|
|
86
|
+
)}
|
|
87
|
+
</a>
|
|
88
|
+
);
|
|
89
|
+
};
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import type { ReputationTier, TrustTier } from '../types';
|
|
3
|
+
|
|
4
|
+
export interface TrustBadgeProps {
|
|
5
|
+
score?: number;
|
|
6
|
+
tier?: ReputationTier;
|
|
7
|
+
status?: TrustTier;
|
|
8
|
+
showLabel?: boolean;
|
|
9
|
+
size?: 'sm' | 'md' | 'lg';
|
|
10
|
+
className?: string;
|
|
11
|
+
onClick?: (e: React.MouseEvent) => void;
|
|
12
|
+
'data-testid'?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const TrustBadge: React.FC<TrustBadgeProps> = ({
|
|
16
|
+
score,
|
|
17
|
+
tier,
|
|
18
|
+
status,
|
|
19
|
+
showLabel = false,
|
|
20
|
+
size = 'sm',
|
|
21
|
+
className = '',
|
|
22
|
+
onClick,
|
|
23
|
+
'data-testid': testId = 'trust-badge',
|
|
24
|
+
}) => {
|
|
25
|
+
const hasScore = typeof score === 'number' && !isNaN(score);
|
|
26
|
+
|
|
27
|
+
// Determine status and tier from score if not provided
|
|
28
|
+
const effectiveStatus: TrustTier | 'unknown' = status
|
|
29
|
+
? status
|
|
30
|
+
: hasScore
|
|
31
|
+
? score! >= 85
|
|
32
|
+
? 'trusted'
|
|
33
|
+
: score! >= 60
|
|
34
|
+
? 'warning'
|
|
35
|
+
: 'danger'
|
|
36
|
+
: 'unknown';
|
|
37
|
+
|
|
38
|
+
// Visual Tokens
|
|
39
|
+
const colorMap = {
|
|
40
|
+
trusted: {
|
|
41
|
+
bg: 'rgba(16, 185, 129, 0.1)',
|
|
42
|
+
border: 'rgba(16, 185, 129, 0.3)',
|
|
43
|
+
text: '#10B981', // Emerald
|
|
44
|
+
},
|
|
45
|
+
warning: {
|
|
46
|
+
bg: 'rgba(245, 158, 11, 0.1)',
|
|
47
|
+
border: 'rgba(245, 158, 11, 0.3)',
|
|
48
|
+
text: '#F59E0B', // Amber
|
|
49
|
+
},
|
|
50
|
+
danger: {
|
|
51
|
+
bg: 'rgba(239, 68, 68, 0.1)',
|
|
52
|
+
border: 'rgba(239, 68, 68, 0.3)',
|
|
53
|
+
text: '#EF4444', // Crimson
|
|
54
|
+
},
|
|
55
|
+
unknown: {
|
|
56
|
+
bg: 'rgba(100, 116, 139, 0.1)',
|
|
57
|
+
border: 'rgba(100, 116, 139, 0.3)',
|
|
58
|
+
text: '#64748B', // Muted Slate
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const currentTheme = colorMap[effectiveStatus];
|
|
63
|
+
|
|
64
|
+
const sizeDimensions = {
|
|
65
|
+
sm: { icon: 12, fontSize: '0.7rem', padding: '1px 5px', gap: '3px' },
|
|
66
|
+
md: { icon: 14, fontSize: '0.8rem', padding: '2px 8px', gap: '4px' },
|
|
67
|
+
lg: { icon: 18, fontSize: '0.9rem', padding: '4px 10px', gap: '6px' },
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const dim = sizeDimensions[size];
|
|
71
|
+
|
|
72
|
+
const labelText = hasScore
|
|
73
|
+
? `${score}/100`
|
|
74
|
+
: tier || 'Unverified';
|
|
75
|
+
|
|
76
|
+
return (
|
|
77
|
+
<span
|
|
78
|
+
data-testid={testId}
|
|
79
|
+
data-status={effectiveStatus}
|
|
80
|
+
role="img"
|
|
81
|
+
aria-label={`Trust Score: ${hasScore ? `${score} out of 100` : 'Unverified'}`}
|
|
82
|
+
onClick={onClick}
|
|
83
|
+
style={{
|
|
84
|
+
display: 'inline-flex',
|
|
85
|
+
alignItems: 'center',
|
|
86
|
+
gap: dim.gap,
|
|
87
|
+
padding: dim.padding,
|
|
88
|
+
fontSize: dim.fontSize,
|
|
89
|
+
lineHeight: 1,
|
|
90
|
+
borderRadius: '9999px',
|
|
91
|
+
backgroundColor: currentTheme.bg,
|
|
92
|
+
border: `1px solid ${currentTheme.border}`,
|
|
93
|
+
color: currentTheme.text,
|
|
94
|
+
fontWeight: 600,
|
|
95
|
+
verticalAlign: 'middle',
|
|
96
|
+
cursor: onClick ? 'pointer' : 'default',
|
|
97
|
+
userSelect: 'none',
|
|
98
|
+
}}
|
|
99
|
+
className={className}
|
|
100
|
+
>
|
|
101
|
+
{/* Inline SVG Shield Icon */}
|
|
102
|
+
<svg
|
|
103
|
+
width={dim.icon}
|
|
104
|
+
height={dim.icon}
|
|
105
|
+
viewBox="0 0 24 24"
|
|
106
|
+
fill="none"
|
|
107
|
+
stroke={currentTheme.text}
|
|
108
|
+
strokeWidth="2.2"
|
|
109
|
+
strokeLinecap="round"
|
|
110
|
+
strokeLinejoin="round"
|
|
111
|
+
aria-hidden="true"
|
|
112
|
+
>
|
|
113
|
+
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
|
|
114
|
+
{effectiveStatus === 'trusted' && <path d="m9 12 2 2 4-4" />}
|
|
115
|
+
{effectiveStatus === 'warning' && <path d="M12 8v4M12 16h.01" />}
|
|
116
|
+
{effectiveStatus === 'danger' && <path d="m15 9-6 6M9 9l6 6" />}
|
|
117
|
+
</svg>
|
|
118
|
+
{showLabel && <span>{labelText}</span>}
|
|
119
|
+
{!showLabel && hasScore && <span>{score}</span>}
|
|
120
|
+
</span>
|
|
121
|
+
);
|
|
122
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { TrustBadge } from './TrustBadge';
|
|
2
|
+
export type { TrustBadgeProps } from './TrustBadge';
|
|
3
|
+
export { SafeAnchor } from './SafeAnchor';
|
|
4
|
+
export type { SafeAnchorProps } from './SafeAnchor';
|
|
5
|
+
export { useTrackedLink } from './useTrackedLink';
|
|
6
|
+
export type { UseTrackedLinkOptions, UseTrackedLinkResult } from './useTrackedLink';
|