@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,171 +0,0 @@
1
- import { useCallback, useEffect, useRef, useState } from 'react';
2
- import { getDefaultClient, LinksClient } from '../client';
3
- import { sanitizeUrl } from '../sanitizer';
4
- import type { TrustScoreReport } from '../types';
5
-
6
- export interface UseTrackedLinkOptions {
7
- channel?: string;
8
- campaign?: string;
9
- tenantId?: string;
10
- enabled?: boolean;
11
- client?: LinksClient;
12
- autoResolveTrust?: boolean;
13
- }
14
-
15
- export interface UseTrackedLinkResult {
16
- href: string;
17
- isLoading: boolean;
18
- isShortened: boolean;
19
- trustScore?: number;
20
- trustReport?: TrustScoreReport;
21
- error: Error | null;
22
- refetch: () => Promise<void>;
23
- }
24
-
25
- export function useTrackedLink(
26
- destinationUrl: string,
27
- options: UseTrackedLinkOptions = {}
28
- ): UseTrackedLinkResult {
29
- const {
30
- channel,
31
- campaign,
32
- tenantId,
33
- enabled = true,
34
- client: customClient,
35
- autoResolveTrust = false,
36
- } = options;
37
-
38
- const client = customClient || getDefaultClient();
39
- const sanitizedDestination = sanitizeUrl(destinationUrl);
40
-
41
- const [href, setHref] = useState<string>(sanitizedDestination);
42
- const [isLoading, setIsLoading] = useState<boolean>(
43
- Boolean((enabled || autoResolveTrust) && destinationUrl)
44
- );
45
- const [isShortened, setIsShortened] = useState<boolean>(false);
46
- const [trustScore, setTrustScore] = useState<number | undefined>(undefined);
47
- const [trustReport, setTrustReport] = useState<TrustScoreReport | undefined>(undefined);
48
- const [error, setError] = useState<Error | null>(null);
49
-
50
- const isMountedRef = useRef<boolean>(true);
51
- const activeRequestIdRef = useRef<number>(0);
52
-
53
- const executeTrackedLink = useCallback(async () => {
54
- if (!destinationUrl) {
55
- setHref('');
56
- setIsLoading(false);
57
- setIsShortened(false);
58
- setError(null);
59
- return;
60
- }
61
-
62
- if (!enabled && !autoResolveTrust) {
63
- setHref(sanitizeUrl(destinationUrl));
64
- setIsLoading(false);
65
- setIsShortened(false);
66
- setError(null);
67
- return;
68
- }
69
-
70
- const currentRequestId = ++activeRequestIdRef.current;
71
- setIsLoading(true);
72
- setError(null);
73
-
74
- // 1. Run shortening if enabled
75
- const shortPromise = enabled
76
- ? client.shortenUrl({
77
- destination: destinationUrl,
78
- channel,
79
- campaign,
80
- tenantId,
81
- })
82
- : Promise.resolve(null);
83
-
84
- // 2. Run trust resolution if requested
85
- const trustPromise = autoResolveTrust
86
- ? client.resolveTrustScore(destinationUrl)
87
- : Promise.resolve(null);
88
-
89
- const [shortResultSettled, trustResultSettled] = await Promise.allSettled([
90
- shortPromise,
91
- trustPromise,
92
- ]);
93
-
94
- if (!isMountedRef.current || currentRequestId !== activeRequestIdRef.current) {
95
- return;
96
- }
97
-
98
- let finalHref = sanitizedDestination;
99
- let finalIsShortened = false;
100
- let finalTrustScore: number | undefined = undefined;
101
- let finalTrustReport: TrustScoreReport | undefined = undefined;
102
- let caughtError: Error | null = null;
103
-
104
- // Handle shortener outcome
105
- if (shortResultSettled.status === 'fulfilled' && shortResultSettled.value) {
106
- finalHref = shortResultSettled.value.shortUrl;
107
- finalIsShortened = shortResultSettled.value.shortUrl !== sanitizedDestination;
108
- if (typeof shortResultSettled.value.trustScore === 'number') {
109
- finalTrustScore = shortResultSettled.value.trustScore;
110
- }
111
- } else if (shortResultSettled.status === 'rejected') {
112
- finalHref = sanitizedDestination;
113
- finalIsShortened = false;
114
- caughtError =
115
- shortResultSettled.reason instanceof Error
116
- ? shortResultSettled.reason
117
- : new Error(String(shortResultSettled.reason));
118
- }
119
-
120
- // Handle trust resolution outcome independently
121
- if (trustResultSettled.status === 'fulfilled' && trustResultSettled.value) {
122
- finalTrustReport = trustResultSettled.value;
123
- if (finalTrustScore === undefined) {
124
- finalTrustScore = trustResultSettled.value.score;
125
- }
126
- } else if (trustResultSettled.status === 'rejected' && !caughtError) {
127
- caughtError =
128
- trustResultSettled.reason instanceof Error
129
- ? trustResultSettled.reason
130
- : new Error(String(trustResultSettled.reason));
131
- }
132
-
133
- setHref(finalHref);
134
- setIsShortened(finalIsShortened);
135
- setTrustScore(finalTrustScore);
136
- if (finalTrustReport) {
137
- setTrustReport(finalTrustReport);
138
- }
139
- setError(caughtError);
140
- setIsLoading(false);
141
- }, [
142
- destinationUrl,
143
- enabled,
144
- channel,
145
- campaign,
146
- tenantId,
147
- autoResolveTrust,
148
- client,
149
- sanitizedDestination,
150
- ]);
151
-
152
- useEffect(() => {
153
- isMountedRef.current = true;
154
- executeTrackedLink();
155
-
156
- return () => {
157
- isMountedRef.current = false;
158
- activeRequestIdRef.current++;
159
- };
160
- }, [executeTrackedLink]);
161
-
162
- return {
163
- href,
164
- isLoading,
165
- isShortened,
166
- trustScore,
167
- trustReport,
168
- error,
169
- refetch: executeTrackedLink,
170
- };
171
- }
package/src/sanitizer.ts DELETED
@@ -1,103 +0,0 @@
1
- /**
2
- * Privacy Sanitizer for SunShade Links
3
- * Strips invasive surveillance and ad-tech tracking parameters while
4
- * preserving clean attribution parameters (UTM, ch, ref) and query payload.
5
- */
6
-
7
- export const INVASIVE_TRACKING_PARAMS = new Set([
8
- 'fbclid',
9
- 'gclid',
10
- 'msclkid',
11
- 'ttclid',
12
- 'twclid',
13
- '_hsenc',
14
- 'mc_eid',
15
- 'sc_campaign',
16
- 'igshid',
17
- 'dclid',
18
- 'gad_source',
19
- 'gbraid',
20
- 'wbraid',
21
- 'yclid',
22
- '_openstat',
23
- 's_kwcid',
24
- ]);
25
-
26
- const DANGEROUS_PROTOCOLS = /^(javascript|vbscript|data):/i;
27
-
28
- /**
29
- * Checks whether a URL contains invasive surveillance tokens.
30
- */
31
- export function hasSurveillanceTokens(rawUrl: string): boolean {
32
- if (!rawUrl || typeof rawUrl !== 'string') return false;
33
- const queryIdx = rawUrl.indexOf('?');
34
- if (queryIdx === -1) return false;
35
-
36
- const hashIdx = rawUrl.indexOf('#', queryIdx);
37
- const queryString =
38
- hashIdx !== -1
39
- ? rawUrl.slice(queryIdx + 1, hashIdx)
40
- : rawUrl.slice(queryIdx + 1);
41
-
42
- const searchParams = new URLSearchParams(queryString);
43
- for (const key of searchParams.keys()) {
44
- if (INVASIVE_TRACKING_PARAMS.has(key.toLowerCase())) {
45
- return true;
46
- }
47
- }
48
- return false;
49
- }
50
-
51
- /**
52
- * Strips known surveillance tokens and returns a sanitized clean URL.
53
- * Neutralizes dangerous executable URL schemes (e.g. javascript:).
54
- */
55
- export function sanitizeUrl(rawUrl: string): string {
56
- if (!rawUrl || typeof rawUrl !== 'string') {
57
- return '';
58
- }
59
-
60
- const trimmed = rawUrl.trim();
61
- if (!trimmed) return '';
62
-
63
- // Neutralize executable / script injection schemes
64
- if (DANGEROUS_PROTOCOLS.test(trimmed)) {
65
- return 'about:blank';
66
- }
67
-
68
- // Handle hash fragment
69
- const hashIdx = trimmed.indexOf('#');
70
- const hash = hashIdx !== -1 ? trimmed.slice(hashIdx) : '';
71
- const withoutHash = hashIdx !== -1 ? trimmed.slice(0, hashIdx) : trimmed;
72
-
73
- const queryIdx = withoutHash.indexOf('?');
74
- const pathPart = queryIdx !== -1 ? withoutHash.slice(0, queryIdx) : withoutHash;
75
- const queryPart = queryIdx !== -1 ? withoutHash.slice(queryIdx + 1) : '';
76
-
77
- // If there are no query parameters, return path + hash directly
78
- if (!queryPart) {
79
- return `${pathPart}${hash}`;
80
- }
81
-
82
- try {
83
- const searchParams = new URLSearchParams(queryPart);
84
- const keysToRemove: string[] = [];
85
-
86
- for (const key of searchParams.keys()) {
87
- if (INVASIVE_TRACKING_PARAMS.has(key.toLowerCase())) {
88
- keysToRemove.push(key);
89
- }
90
- }
91
-
92
- for (const key of keysToRemove) {
93
- searchParams.delete(key);
94
- }
95
-
96
- const cleanQuery = searchParams.toString();
97
- const cleanSearch = cleanQuery ? `?${cleanQuery}` : '';
98
-
99
- return `${pathPart}${cleanSearch}${hash}`;
100
- } catch {
101
- return trimmed;
102
- }
103
- }
package/src/types.ts DELETED
@@ -1,76 +0,0 @@
1
- /**
2
- * @digitalcanopy/links Types & Interfaces
3
- */
4
-
5
- export type ReputationTier =
6
- | 'canonical'
7
- | 'trusted'
8
- | 'neutral'
9
- | 'warning'
10
- | 'danger'
11
- | 'unverified';
12
-
13
- export type TrustTier = 'trusted' | 'warning' | 'danger';
14
-
15
- export interface TrustFlags {
16
- verified_did: boolean;
17
- sanitized_trackers: boolean;
18
- redirect_count: number;
19
- reputation_tier: ReputationTier;
20
- is_flagged?: boolean;
21
- ssl_valid?: boolean;
22
- }
23
-
24
- export interface TrustPillars {
25
- /** Cryptographic provenance and DID verification score (0–35) */
26
- provenance: number;
27
- /** Destination hygiene, SSL validity, and redirect hop score (0–25) */
28
- hygiene: number;
29
- /** Privacy footprint and surveillance tracker stripping score (0–20) */
30
- privacy: number;
31
- /** Network corroboration and temporal decay score (0–20) */
32
- networkDecay: number;
33
- }
34
-
35
- export interface TrustScoreReport {
36
- url: string;
37
- slug?: string;
38
- score: number;
39
- tier: ReputationTier;
40
- status: TrustTier;
41
- flags: TrustFlags;
42
- pillars: TrustPillars;
43
- lastHygieneCheck?: string;
44
- did?: string;
45
- recommendation?: string;
46
- }
47
-
48
- export interface ShortenUrlOptions {
49
- destination: string;
50
- channel?: string;
51
- campaign?: string;
52
- tenantId?: string;
53
- slug?: string;
54
- metadata?: Record<string, unknown>;
55
- }
56
-
57
- export interface ShortLinkResult {
58
- id: string;
59
- slug: string;
60
- shortUrl: string;
61
- destinationUrl: string;
62
- channel: string;
63
- campaign?: string;
64
- tenantId?: string;
65
- trustScore?: number;
66
- createdAt: string;
67
- }
68
-
69
- export interface ClientConfig {
70
- baseUrl?: string;
71
- apiKey?: string;
72
- tenantId?: string;
73
- fetch?: typeof fetch;
74
- enableFallback?: boolean;
75
- timeoutMs?: number;
76
- }
@@ -1,12 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "noEmit": false,
5
- "emitDeclarationOnly": true,
6
- "declaration": true,
7
- "declarationMap": true,
8
- "outDir": "./dist"
9
- },
10
- "include": ["src/**/*"],
11
- "exclude": ["node_modules", "dist", "src/__tests__"]
12
- }
package/tsconfig.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es2020",
4
- "lib": ["esnext", "dom"],
5
- "allowJs": true,
6
- "skipLibCheck": true,
7
- "strict": true,
8
- "forceConsistentCasingInFileNames": true,
9
- "noEmit": true,
10
- "esModuleInterop": true,
11
- "module": "esnext",
12
- "moduleResolution": "bundler",
13
- "resolveJsonModule": true,
14
- "isolatedModules": true,
15
- "jsx": "react-jsx",
16
- "declaration": true,
17
- "declarationMap": true
18
- },
19
- "include": ["src/**/*"],
20
- "exclude": ["node_modules", "dist"]
21
- }
package/vitest.config.ts DELETED
@@ -1,11 +0,0 @@
1
- import { defineConfig } from 'vitest/config';
2
- import react from '@vitejs/plugin-react';
3
-
4
- export default defineConfig({
5
- plugins: [react()],
6
- test: {
7
- globals: true,
8
- environment: 'jsdom',
9
- css: false,
10
- },
11
- });