@digitalcanopy/links 1.0.0 → 1.0.1

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.
@@ -1,229 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from 'vitest';
2
- import {
3
- LinksClient,
4
- SunshadeLinksClient,
5
- resolveTrustScore,
6
- shortenUrl,
7
- } from '../client';
8
-
9
- describe('LinksClient SDK', () => {
10
- let mockFetch: ReturnType<typeof vi.fn>;
11
-
12
- beforeEach(() => {
13
- mockFetch = vi.fn();
14
- });
15
-
16
- it('shortens a destination URL and sanitizes trackers before sending payload', async () => {
17
- mockFetch.mockResolvedValueOnce({
18
- ok: true,
19
- json: async () => ({
20
- id: 'lnk_123',
21
- slug: 'test-slug',
22
- short_url: 'https://links.sunshade.icu/test-slug/bsky',
23
- destination_url: 'https://sunshade.icu/blog/hello',
24
- channel: 'bsky',
25
- campaign: 'fall2026',
26
- trust_score: 95,
27
- created_at: '2026-10-31T20:00:00.000Z',
28
- }),
29
- });
30
-
31
- const client = new LinksClient({
32
- fetch: mockFetch as unknown as typeof fetch,
33
- apiKey: 'test-api-key',
34
- tenantId: 'pym-energy',
35
- });
36
-
37
- const result = await client.shortenUrl({
38
- destination: 'https://sunshade.icu/blog/hello?fbclid=bad_param&utm_source=bsky',
39
- channel: 'bsky',
40
- campaign: 'fall2026',
41
- });
42
-
43
- expect(mockFetch).toHaveBeenCalledTimes(1);
44
- const [calledUrl, calledInit] = mockFetch.mock.calls[0];
45
-
46
- expect(calledUrl).toBe('https://links.sunshade.icu/api/v1/links');
47
- expect(calledInit.method).toBe('POST');
48
- expect(calledInit.headers['Authorization']).toBe('Bearer test-api-key');
49
- expect(calledInit.headers['x-tenant-id']).toBe('pym-energy');
50
-
51
- const body = JSON.parse(calledInit.body as string);
52
- // Verified sanitized destination before request body sent
53
- expect(body.destination).toBe('https://sunshade.icu/blog/hello?utm_source=bsky');
54
- expect(body.channel).toBe('bsky');
55
- expect(body.campaign).toBe('fall2026');
56
-
57
- expect(result.id).toBe('lnk_123');
58
- expect(result.slug).toBe('test-slug');
59
- expect(result.shortUrl).toBe('https://links.sunshade.icu/test-slug/bsky');
60
- expect(result.trustScore).toBe(95);
61
- });
62
-
63
- it('rejects transmitting apiKey over plaintext HTTP transport', () => {
64
- expect(() => {
65
- new LinksClient({
66
- baseUrl: 'http://insecure-api.sunshade.icu',
67
- apiKey: 'secret_token_123',
68
- });
69
- }).toThrow(/Insecure transport: apiKey cannot be transmitted over plaintext HTTP/);
70
-
71
- // Allows http on localhost
72
- expect(() => {
73
- new LinksClient({
74
- baseUrl: 'http://localhost:3000',
75
- apiKey: 'secret_token_123',
76
- });
77
- }).not.toThrow();
78
- });
79
-
80
- it('gracefully falls back to sanitized destination URL on network failure', async () => {
81
- mockFetch.mockRejectedValueOnce(new Error('Network offline'));
82
-
83
- const client = new LinksClient({
84
- fetch: mockFetch as unknown as typeof fetch,
85
- enableFallback: true,
86
- });
87
-
88
- const dirtyUrl = 'https://sunshade.icu/docs?gclid=tracker123&doc=1';
89
- const result = await client.shortenUrl({
90
- destination: dirtyUrl,
91
- channel: 'direct',
92
- });
93
-
94
- expect(result.id).toMatch(/^fallback-/);
95
- expect(result.destinationUrl).toBe('https://sunshade.icu/docs?doc=1');
96
- expect(result.shortUrl).toBe('https://sunshade.icu/docs?doc=1');
97
- expect(result.channel).toBe('direct');
98
- });
99
-
100
- it('throws an error if enableFallback is false and network fails', async () => {
101
- mockFetch.mockRejectedValueOnce(new Error('Network offline'));
102
-
103
- const client = new LinksClient({
104
- fetch: mockFetch as unknown as typeof fetch,
105
- enableFallback: false,
106
- });
107
-
108
- await expect(
109
- client.shortenUrl({ destination: 'https://example.com' })
110
- ).rejects.toThrow('Network offline');
111
- });
112
-
113
- it('resolves remote Link Trust Score from auditor API', async () => {
114
- mockFetch.mockResolvedValueOnce({
115
- ok: true,
116
- json: async () => ({
117
- url: 'https://sunshade.icu/manifesto',
118
- score: 96,
119
- tier: 'trusted',
120
- flags: {
121
- verified_did: true,
122
- sanitized_trackers: true,
123
- redirect_count: 0,
124
- reputation_tier: 'trusted',
125
- is_flagged: false,
126
- ssl_valid: true,
127
- },
128
- pillars: {
129
- provenance: 35,
130
- hygiene: 25,
131
- privacy: 20,
132
- networkDecay: 16,
133
- },
134
- did: 'did:key:z6MkhaXgBZDvotDkL5257faiz4898XnpGnxC65482357',
135
- last_hygiene_check: '2026-10-31T12:00:00Z',
136
- }),
137
- });
138
-
139
- const client = new LinksClient({
140
- fetch: mockFetch as unknown as typeof fetch,
141
- });
142
-
143
- const report = await client.resolveTrustScore('https://sunshade.icu/manifesto');
144
-
145
- expect(report.score).toBe(96);
146
- expect(report.status).toBe('trusted');
147
- expect(report.flags.verified_did).toBe(true);
148
- expect(report.pillars.provenance).toBe(35);
149
- expect(report.pillars.hygiene).toBe(25);
150
- expect(report.pillars.privacy).toBe(20);
151
- });
152
-
153
- it('falls back when audit response omits valid score data', async () => {
154
- mockFetch.mockResolvedValueOnce({
155
- ok: true,
156
- json: async () => ({}), // Missing score
157
- });
158
-
159
- const client = new LinksClient({
160
- fetch: mockFetch as unknown as typeof fetch,
161
- enableFallback: true,
162
- });
163
-
164
- const report = await client.resolveTrustScore('https://clean-site.org/page');
165
- expect(report.score).toBe(75);
166
- expect(report.status).toBe('warning');
167
- });
168
-
169
- it('computes deterministic local fallback when trust auditor is unreachable', async () => {
170
- mockFetch.mockRejectedValueOnce(new Error('Auditor offline'));
171
-
172
- const client = new LinksClient({
173
- fetch: mockFetch as unknown as typeof fetch,
174
- enableFallback: true,
175
- });
176
-
177
- // Test a clean HTTPS URL
178
- const reportClean = await client.resolveTrustScore('https://clean-site.org/page');
179
- expect(reportClean.score).toBe(75); // 10 provenance + 25 hygiene + 20 privacy + 20 decay
180
- expect(reportClean.status).toBe('warning'); // Baseline unverified is neutral/warning
181
- expect(reportClean.flags.ssl_valid).toBe(true);
182
- expect(reportClean.flags.sanitized_trackers).toBe(true);
183
-
184
- // Test an insecure HTTP URL with trackers
185
- mockFetch.mockRejectedValueOnce(new Error('Auditor offline'));
186
- const reportDirty = await client.resolveTrustScore('http://insecure-site.org/page?fbclid=bad');
187
- expect(reportDirty.score).toBe(45); // 10 provenance + 10 hygiene + 5 privacy + 20 decay
188
- expect(reportDirty.status).toBe('danger');
189
- expect(reportDirty.flags.ssl_valid).toBe(false);
190
- expect(reportDirty.flags.sanitized_trackers).toBe(false);
191
- expect(reportDirty.flags.is_flagged).toBe(true);
192
- });
193
-
194
- it('exports SunshadeLinksClient as alias of LinksClient', () => {
195
- expect(SunshadeLinksClient).toBe(LinksClient);
196
- });
197
-
198
- it('supports functional shortenUrl and resolveTrustScore helpers', async () => {
199
- mockFetch.mockResolvedValueOnce({
200
- ok: true,
201
- json: async () => ({
202
- id: 'func_1',
203
- short_url: 'https://links.sunshade.icu/fn/bsky',
204
- destination_url: 'https://sunshade.icu',
205
- channel: 'bsky',
206
- }),
207
- });
208
-
209
- const result = await shortenUrl(
210
- { destination: 'https://sunshade.icu', channel: 'bsky' },
211
- { fetch: mockFetch as unknown as typeof fetch }
212
- );
213
-
214
- expect(result.shortUrl).toBe('https://links.sunshade.icu/fn/bsky');
215
-
216
- mockFetch.mockResolvedValueOnce({
217
- ok: true,
218
- json: async () => ({
219
- url: 'https://sunshade.icu',
220
- score: 92,
221
- }),
222
- });
223
-
224
- const report = await resolveTrustScore('https://sunshade.icu', {
225
- fetch: mockFetch as unknown as typeof fetch,
226
- });
227
- expect(report.score).toBe(92);
228
- });
229
- });
@@ -1,253 +0,0 @@
1
- // @vitest-environment jsdom
2
- import { cleanup, render, renderHook, screen, waitFor } from '@testing-library/react';
3
- import React from 'react';
4
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
- import { LinksClient } from '../client';
6
- import { SafeAnchor, TrustBadge, useTrackedLink } from '../react';
7
-
8
- describe('React Integration (useTrackedLink, SafeAnchor, TrustBadge)', () => {
9
- let mockFetch: ReturnType<typeof vi.fn>;
10
- let client: LinksClient;
11
-
12
- beforeEach(() => {
13
- mockFetch = vi.fn();
14
- client = new LinksClient({
15
- fetch: mockFetch as unknown as typeof fetch,
16
- enableFallback: true,
17
- });
18
- });
19
-
20
- afterEach(() => {
21
- cleanup();
22
- });
23
-
24
- describe('useTrackedLink Hook', () => {
25
- it('shortens outbound links when telemetry is enabled', async () => {
26
- mockFetch.mockResolvedValueOnce({
27
- ok: true,
28
- json: async () => ({
29
- id: 'test_lnk',
30
- short_url: 'https://links.sunshade.icu/xyz/bsky',
31
- destination_url: 'https://sunshade.icu/announcement',
32
- channel: 'bsky',
33
- trust_score: 95,
34
- }),
35
- });
36
-
37
- const { result } = renderHook(() =>
38
- useTrackedLink('https://sunshade.icu/announcement?fbclid=bad', {
39
- client,
40
- channel: 'bsky',
41
- enabled: true,
42
- })
43
- );
44
-
45
- // Loading initially
46
- expect(result.current.isLoading).toBe(true);
47
-
48
- await waitFor(() => {
49
- expect(result.current.isLoading).toBe(false);
50
- });
51
-
52
- expect(result.current.href).toBe('https://links.sunshade.icu/xyz/bsky');
53
- expect(result.current.isShortened).toBe(true);
54
- expect(result.current.trustScore).toBe(95);
55
- expect(result.current.error).toBeNull();
56
- });
57
-
58
- it('returns sanitized raw destination immediately when enabled is false and no trust lookup', () => {
59
- const { result } = renderHook(() =>
60
- useTrackedLink('https://sunshade.icu/page?fbclid=strip_me&doc=2', {
61
- client,
62
- enabled: false,
63
- })
64
- );
65
-
66
- expect(result.current.isLoading).toBe(false);
67
- expect(result.current.isShortened).toBe(false);
68
- expect(result.current.href).toBe('https://sunshade.icu/page?doc=2');
69
- expect(mockFetch).not.toHaveBeenCalled();
70
- });
71
-
72
- it('resolves trust score when autoResolveTrust is true even if shortening enabled is false', async () => {
73
- mockFetch.mockResolvedValueOnce({
74
- ok: true,
75
- json: async () => ({
76
- url: 'https://sunshade.icu/post',
77
- score: 88,
78
- }),
79
- });
80
-
81
- const { result } = renderHook(() =>
82
- useTrackedLink('https://sunshade.icu/post', {
83
- client,
84
- enabled: false,
85
- autoResolveTrust: true,
86
- })
87
- );
88
-
89
- await waitFor(() => {
90
- expect(result.current.isLoading).toBe(false);
91
- });
92
-
93
- expect(result.current.isShortened).toBe(false);
94
- expect(result.current.href).toBe('https://sunshade.icu/post');
95
- expect(result.current.trustScore).toBe(88);
96
- expect(result.current.trustReport?.score).toBe(88);
97
- });
98
-
99
- it('retains successful short link even if independent trust resolution rejects', async () => {
100
- // Shortener succeeds
101
- mockFetch.mockImplementation(async (url: string) => {
102
- if (url.includes('/api/v1/links')) {
103
- return {
104
- ok: true,
105
- json: async () => ({
106
- short_url: 'https://links.sunshade.icu/success/direct',
107
- trust_score: 90,
108
- }),
109
- };
110
- }
111
- // Trust API fails
112
- throw new Error('Audit engine 503');
113
- });
114
-
115
- const clientNoFallback = new LinksClient({
116
- fetch: mockFetch as unknown as typeof fetch,
117
- enableFallback: false,
118
- });
119
-
120
- const { result } = renderHook(() =>
121
- useTrackedLink('https://sunshade.icu/article', {
122
- client: clientNoFallback,
123
- enabled: true,
124
- autoResolveTrust: true,
125
- })
126
- );
127
-
128
- await waitFor(() => {
129
- expect(result.current.isLoading).toBe(false);
130
- });
131
-
132
- // Retained short link!
133
- expect(result.current.href).toBe('https://links.sunshade.icu/success/direct');
134
- expect(result.current.isShortened).toBe(true);
135
- });
136
-
137
- it('falls back gracefully on network failure without breaking the link', async () => {
138
- mockFetch.mockRejectedValueOnce(new Error('Network offline'));
139
-
140
- const { result } = renderHook(() =>
141
- useTrackedLink('https://sunshade.icu/docs?fbclid=bad', {
142
- client,
143
- enabled: true,
144
- })
145
- );
146
-
147
- await waitFor(() => {
148
- expect(result.current.isLoading).toBe(false);
149
- });
150
-
151
- expect(result.current.href).toBe('https://sunshade.icu/docs');
152
- expect(result.current.isShortened).toBe(false);
153
- });
154
- });
155
-
156
- describe('SafeAnchor Component', () => {
157
- it('renders external link with target="_blank" and rel="noopener noreferrer"', () => {
158
- render(
159
- <SafeAnchor href="https://external-domain.com/post" trustScore={90}>
160
- External Post
161
- </SafeAnchor>
162
- );
163
-
164
- const anchor = screen.getByRole('link', { name: /External Post/i });
165
- expect(anchor).toBeDefined();
166
- expect(anchor.getAttribute('target')).toBe('_blank');
167
- expect(anchor.getAttribute('rel')).toBe('noopener noreferrer');
168
- expect(anchor.getAttribute('href')).toBe('https://external-domain.com/post');
169
- });
170
-
171
- it('handles protocol-relative URLs as external links', () => {
172
- render(
173
- <SafeAnchor href="//cdn.external.com/asset" trustScore={85}>
174
- CDN Asset
175
- </SafeAnchor>
176
- );
177
-
178
- const anchor = screen.getByRole('link', { name: /CDN Asset/i });
179
- expect(anchor.getAttribute('target')).toBe('_blank');
180
- expect(anchor.getAttribute('rel')).toBe('noopener noreferrer');
181
- expect(screen.getByTestId('trust-badge')).toBeDefined();
182
- });
183
-
184
- it('displays miniature TrustBadge alongside external links when showBadge is true', () => {
185
- render(
186
- <SafeAnchor
187
- href="https://sunshade.icu"
188
- showBadge={true}
189
- trustScore={95}
190
- >
191
- SunShade Ecosystem
192
- </SafeAnchor>
193
- );
194
-
195
- const badge = screen.getByTestId('trust-badge');
196
- expect(badge).toBeDefined();
197
- expect(badge.getAttribute('data-status')).toBe('trusted');
198
- expect(badge.textContent).toContain('95');
199
- });
200
-
201
- it('hides TrustBadge for internal relative links', () => {
202
- render(
203
- <SafeAnchor href="/dashboard/settings" showBadge={true}>
204
- Internal Settings
205
- </SafeAnchor>
206
- );
207
-
208
- expect(screen.queryByTestId('trust-badge')).toBeNull();
209
- const anchor = screen.getByRole('link', { name: /Internal Settings/i });
210
- expect(anchor.getAttribute('target')).toBeNull();
211
- });
212
-
213
- it('sanitizes tracking parameters in the href attribute', () => {
214
- render(
215
- <SafeAnchor href="https://sunshade.icu/article?fbclid=strip_me&tab=1">
216
- Article Link
217
- </SafeAnchor>
218
- );
219
-
220
- const anchor = screen.getByRole('link', { name: /Article Link/i });
221
- expect(anchor.getAttribute('href')).toBe('https://sunshade.icu/article?tab=1');
222
- });
223
- });
224
-
225
- describe('TrustBadge Component', () => {
226
- it('renders emerald theme for trusted tier (>= 85)', () => {
227
- render(<TrustBadge score={92} />);
228
- const badge = screen.getByTestId('trust-badge');
229
- expect(badge.getAttribute('data-status')).toBe('trusted');
230
- expect(badge.textContent).toBe('92');
231
- });
232
-
233
- it('renders amber theme for warning tier (60–84)', () => {
234
- render(<TrustBadge score={72} />);
235
- const badge = screen.getByTestId('trust-badge');
236
- expect(badge.getAttribute('data-status')).toBe('warning');
237
- expect(badge.textContent).toBe('72');
238
- });
239
-
240
- it('renders crimson theme for danger tier (< 60)', () => {
241
- render(<TrustBadge score={42} />);
242
- const badge = screen.getByTestId('trust-badge');
243
- expect(badge.getAttribute('data-status')).toBe('danger');
244
- expect(badge.textContent).toBe('42');
245
- });
246
-
247
- it('renders unverified badge when score is not provided', () => {
248
- render(<TrustBadge />);
249
- const badge = screen.getByTestId('trust-badge');
250
- expect(badge.getAttribute('data-status')).toBe('unknown');
251
- });
252
- });
253
- });
@@ -1,101 +0,0 @@
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
- });