-
Notifications
You must be signed in to change notification settings - Fork 320
Expand file tree
/
Copy pathhooks.server.ts
More file actions
263 lines (223 loc) · 8 KB
/
hooks.server.ts
File metadata and controls
263 lines (223 loc) · 8 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import * as Sentry from '@sentry/sveltekit';
import type { Handle } from '@sveltejs/kit';
import redirects from './redirects.json';
import { sequence } from '@sveltejs/kit/hooks';
import { getMarkdownContent } from '$lib/server/markdown';
import { type GithubUser } from '$routes/(init)/init/(utils)/auth';
import { createInitSessionClient } from '$routes/(init)/init/(utils)/appwrite';
import type { AppwriteUser } from '$lib/utils/console';
const redirectMap = new Map(redirects.map(({ link, redirect }) => [link, redirect]));
const markdownHandler: Handle = async ({ event, resolve }) => {
const pathname = event.url.pathname;
if (!pathname.endsWith('.md')) {
return resolve(event);
}
// strip trailing ".md" from the pathname to get the underlying route id
const withoutExt = pathname.replace(/\.md$/, '');
const routeId = withoutExt;
const content = await getMarkdownContent(routeId);
if (content == null) {
return new Response('Not found', { status: 404 });
}
return new Response(content, {
status: 200,
headers: {
'Content-Type': 'text/markdown; charset=utf-8'
}
});
};
const redirecter: Handle = async ({ event, resolve }) => {
const currentPath = event.url.pathname;
if (redirectMap.has(currentPath)) {
return new Response(null, {
status: 308,
headers: {
location: redirectMap.get(currentPath) ?? ''
}
});
}
return resolve(event);
};
const wwwRedirecter: Handle = async ({ event, resolve }) => {
if (event.url.host.startsWith('www.')) {
const location = new URL(event.url);
location.host = location.host.replace(/^www\./, '');
return new Response(null, {
status: 308,
headers: {
location: location.href
}
});
}
return resolve(event);
};
const securityheaders: Handle = async ({ event, resolve }) => {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
event.locals.nonce = nonce;
const response = await resolve(event, {
transformPageChunk: ({ html }) => {
return html.replace(/%sveltekit.nonce%/g, nonce);
}
});
// `true` if deployed via Coolify.
const isPreview = !!process.env.COOLIFY_FQDN || process.env.NODE_ENV === 'development';
// COOLIFY_FQDN already includes `http`.
const previewDomain = isPreview ? `${process.env.COOLIFY_FQDN}` : null;
const join = (arr: string[]) => arr.join(' ');
const cspDirectives: Record<string, string> = {
'default-src': "'self'",
'script-src': join([
"'self'",
'blob:',
"'unsafe-inline'",
"'unsafe-eval'",
'https://*.posthog.com',
'https://*.plausible.io',
'https://*.reo.dev',
'https://plausible.io',
'https://js.zi-scripts.com',
'https://ws.zoominfo.com',
'https://*.cookieyes.com',
'https://cdn-cookieyes.com'
]),
'style-src': "'self' 'unsafe-inline'",
'img-src': "'self' data: https:",
'font-src': "'self'",
'object-src': "'none'",
'base-uri': "'self'",
'form-action': "'self'",
'frame-ancestors': join(["'self'", 'https://www.youtube.com', 'https://*.vimeo.com']),
'block-all-mixed-content': '',
'upgrade-insecure-requests': '',
'connect-src': join([
"'self'",
'https://*.appwrite.io',
'https://*.appwrite.org',
'https://*.posthog.com',
'https://*.sentry.io',
'https://*.plausible.io',
'https://plausible.io',
'https://*.reo.dev',
'https://js.zi-scripts.com',
'https://aorta.clickagy.com',
'https://hemsync.clickagy.com',
'https://ws.zoominfo.com ',
'https://*.cookieyes.com',
'https://cdn-cookieyes.com'
]),
'frame-src': join([
"'self'",
'https://www.youtube.com',
'https://status.appwrite.online',
'https://www.youtube-nocookie.com',
'https://player.vimeo.com',
'https://hemsync.clickagy.com',
'https://cdn-cookieyes.com'
])
};
if (isPreview) {
delete cspDirectives['block-all-mixed-content'];
delete cspDirectives['upgrade-insecure-requests'];
['default-src', 'script-src', 'style-src', 'img-src', 'font-src', 'connect-src'].forEach(
(key) => {
cspDirectives[key] += ` ${previewDomain}`;
}
);
}
const cspDirectivesString = Object.entries(cspDirectives)
.map(([key, value]) => `${key} ${value}`.trim())
.join('; ');
// Set security headers
response.headers.set('Content-Security-Policy', cspDirectivesString);
// HTTP Strict Transport Security
// max-age is set to 1 year in seconds
response.headers.set(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload'
);
// X-Content-Type-Options
response.headers.set('X-Content-Type-Options', 'nosniff');
// X-Frame-Options
response.headers.set('X-Frame-Options', 'DENY');
return response;
};
const initSession: Handle = async ({ event, resolve }) => {
const session = await createInitSessionClient(event.cookies);
const getGithubUser = async () => {
try {
const identitiesList = await session?.account.listIdentities();
if (!identitiesList?.total) return null;
const identity = identitiesList.identities[0];
const { providerAccessToken, provider, providerEmail } = identity;
if (provider !== 'github') return null;
const res = await fetch('https://api.github.com/user', {
method: 'GET',
headers: {
Authorization: `Bearer ${providerAccessToken}`
}
})
.then((res) => {
return res.json() as Promise<GithubUser>;
})
.then((user) => ({
login: user.login,
name: user.name,
email: providerEmail,
avatar_url: user.avatar_url
}));
if (!res.login) {
await session?.account.deleteSession('current');
return null;
}
return res;
} catch (e) {
console.error(e);
return null;
}
};
const getAppwriteUser = async (): Promise<AppwriteUser | null> => {
const appwriteUser = await session?.account
.get()
.then((res) => res)
.catch(() => null);
return appwriteUser || null;
};
const getInitUser = async () => {
const [github, appwrite] = await Promise.all([getGithubUser(), getAppwriteUser()]);
return { github, appwrite };
};
event.locals.initUser = await getInitUser();
return resolve(event);
};
/**
* SEO optimization: noindex internal/auth pages and staging subdomains
*/
const NOINDEX_PATHS = [
/^\/console\/login\/?$/,
/^\/console\/register\/?$/,
/^\/v1\/storage\//,
/^\/v1\//
];
const NOINDEX_HOSTS = [/^stage\./i, /^fra\./i, /^internal\./i];
const seoOptimization: Handle = async ({ event, resolve }) => {
const { url } = event;
// Check if this is a path or host that should not be indexed
const shouldNoindex =
NOINDEX_PATHS.some((re) => re.test(url.pathname)) ||
NOINDEX_HOSTS.some((re) => re.test(url.hostname));
const response = await resolve(event);
if (shouldNoindex) {
response.headers.set('x-robots-tag', 'noindex, nofollow');
}
return response;
};
export const handle = sequence(
Sentry.sentryHandle(),
markdownHandler,
redirecter,
wwwRedirecter,
securityheaders,
initSession,
seoOptimization
);
export const handleError = Sentry.handleErrorWithSentry();