-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathsocialMeta.ts
More file actions
226 lines (203 loc) · 8.67 KB
/
Copy pathsocialMeta.ts
File metadata and controls
226 lines (203 loc) · 8.67 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
'use strict';
import type {Request} from 'express';
/**
* Builds the Open Graph + Twitter Card <meta> tag block for the pad page,
* timeslider and homepage. Output values are HTML-escaped — pad names are
* user-controlled, so this is the security boundary that prevents reflected
* XSS via crafted pad IDs.
*
* The description text is sourced from Etherpad's i18n catalog under the key
* `pad.social.description`. Operators have two ways to override it:
* - `settings.socialMeta.description` — flat string used regardless of
* negotiated language. Useful because most link-preview crawlers don't
* send Accept-Language and would otherwise always hit the English fallback.
* - `customLocaleStrings` — per-language override that participates in
* normal Accept-Language negotiation.
* The flat setting wins over the i18n catalog when set.
*/
const SOCIAL_DESCRIPTION_KEY = 'pad.social.description';
const ESCAPE_MAP: {[ch: string]: string} = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
const escapeHtml = (s: string): string => s.replace(/[&<>"']/g, (c) => ESCAPE_MAP[c]);
const resolveDescription = (
locales: {[lang: string]: {[key: string]: string}} | undefined,
renderLang: string,
): string => {
if (!locales) return '';
// Exact match.
if (locales[renderLang] && locales[renderLang][SOCIAL_DESCRIPTION_KEY]) {
return locales[renderLang][SOCIAL_DESCRIPTION_KEY];
}
// Primary subtag fallback (e.g. de-AT → de).
const primary = renderLang.split('-')[0];
if (locales[primary] && locales[primary][SOCIAL_DESCRIPTION_KEY]) {
return locales[primary][SOCIAL_DESCRIPTION_KEY];
}
// English fallback.
if (locales.en && locales.en[SOCIAL_DESCRIPTION_KEY]) {
return locales.en[SOCIAL_DESCRIPTION_KEY];
}
return '';
};
const toOgLocale = (renderLang: string): string => {
// Open Graph wants `xx_XX`. We already negotiate render language from
// request headers; if it has a region we keep it (lowercased primary,
// uppercased region), otherwise we just emit the primary subtag.
const parts = renderLang.split('-');
if (parts.length >= 2) return `${parts[0].toLowerCase()}_${parts[1].toUpperCase()}`;
return parts[0].toLowerCase();
};
export type SocialMetaOpts = {
url: string,
siteName: string,
title: string,
description: string,
imageUrl: string,
imageAlt: string,
renderLang: string,
};
export const buildSocialMetaHtml = (opts: SocialMetaOpts): string => {
const tag = (prop: string, value: string, attr: 'property' | 'name' = 'property') =>
` <meta ${attr}="${prop}" content="${escapeHtml(value)}">`;
return [
tag('og:type', 'website'),
tag('og:site_name', opts.siteName),
tag('og:title', opts.title),
tag('og:description', opts.description),
tag('og:url', opts.url),
tag('og:image', opts.imageUrl),
tag('og:image:alt', opts.imageAlt),
tag('og:locale', toOgLocale(opts.renderLang)),
tag('twitter:card', 'summary', 'name'),
tag('twitter:title', opts.title, 'name'),
tag('twitter:description', opts.description, 'name'),
tag('twitter:image', opts.imageUrl, 'name'),
tag('twitter:image:alt', opts.imageAlt, 'name'),
].join('\n');
};
// Only the keys are read; values are intentionally unconstrained because the
// i18n module hands us a record whose value shape varies by language.
type AvailableLangs = {[lang: string]: unknown};
// Narrow shape of the global Settings module that this file actually touches.
// Defined locally to avoid coupling socialMeta to the full Settings surface.
type SocialMetaSettings = {
title?: string,
favicon?: string | null,
publicURL?: string | null,
socialMeta?: {
// Wider than the operator-facing type: env-var-driven settings get
// pre-coerced by Settings.coerceValue(), so we may receive number/boolean
// even though "the value an operator types" is a string. Stringified at
// resolve time.
description?: string | number | boolean | null,
},
};
const negotiateRenderLang = (req: Request, availableLangs: AvailableLangs): string => {
if (req && typeof req.acceptsLanguages === 'function') {
const negotiated = req.acceptsLanguages(Object.keys(availableLangs));
if (negotiated) return negotiated;
}
return 'en';
};
// Strict hostname[:port] pattern. Rejects header injection (\r\n), userinfo
// (user@host), wildcards, and any non-DNS-character garbage. Length-capped so
// a giant Host header can't blow up the response.
const HOST_RE = /^[a-z0-9]([a-z0-9.-]{0,253}[a-z0-9])?(:\d{1,5})?$/i;
const sanitizeHost = (host: string | undefined): string | null => {
if (!host || host.length > 255) return null;
return HOST_RE.test(host) ? host : null;
};
const sanitizePublicURL = (raw: string | null | undefined): string | null => {
if (!raw || typeof raw !== 'string') return null;
// Must be http(s)://host[:port], no path. Strip trailing slash if present.
const m = raw.replace(/\/+$/, '').match(/^(https?):\/\/([^\/?#]+)$/i);
if (!m) return null;
return sanitizeHost(m[2]) ? `${m[1].toLowerCase()}://${m[2]}` : null;
};
// Builds an absolute URL. Prefers settings.publicURL when configured (operator-
// trusted); otherwise falls back to the request's protocol+Host with strict
// host validation so a crafted Host header can't appear in og:url / og:image.
// proxyPath is prepended to pathname in the fallback path — it recovers the
// public URL prefix that the reverse proxy stripped before forwarding the
// request. Ignored when publicURL is set (publicURL encodes the canonical
// origin and any path component the operator wants).
const buildAbsoluteUrl = (
req: Request, pathname: string, publicURL: string | null | undefined,
proxyPath: string,
): string => {
const trusted = sanitizePublicURL(publicURL);
if (trusted) return `${trusted}${pathname}`;
const proto = req.protocol === 'https' ? 'https' : 'http';
const host = sanitizeHost(req.get && req.get('host')) || 'localhost';
return `${proto}://${host}${proxyPath}${pathname}`;
};
const resolveImageUrl = (
req: Request, faviconSetting: string | null | undefined, publicURL: string | null | undefined,
proxyPath: string,
): string => {
if (faviconSetting && /^https?:\/\//i.test(faviconSetting)) return faviconSetting;
return buildAbsoluteUrl(req, '/favicon.ico', publicURL, proxyPath);
};
export type RenderOpts = {
req: Request,
settings: SocialMetaSettings,
availableLangs: AvailableLangs,
locales: {[lang: string]: {[key: string]: string}},
kind: 'pad' | 'timeslider' | 'home',
padName?: string,
// URL-path prefix Etherpad is being served under (`''` when running at root).
// When set, used as a path prefix for from-request fallback URLs. Ignored
// when settings.publicURL is configured (publicURL encodes the canonical
// origin and any path component the operator wants).
proxyPath?: string,
};
// Operator override wins when set. Settings.ts coerces env-var strings to
// their typed form (e.g. SOCIAL_META_DESCRIPTION="123" arrives as the number
// 123 and ="true" as the boolean true), so we accept string | number | boolean
// and stringify before comparing. Empty / whitespace-only values are treated
// as unset — an accidental "" in settings would otherwise silently blank out
// og:description and break previews entirely.
const resolveDescriptionWithOverride = (
override: string | number | boolean | null | undefined,
locales: {[lang: string]: {[key: string]: string}} | undefined,
renderLang: string,
): string => {
if (override !== null && override !== undefined) {
const s = String(override);
if (s.trim() !== '') return s;
}
return resolveDescription(locales, renderLang);
};
export const renderSocialMeta = (o: RenderOpts): string => {
const renderLang = negotiateRenderLang(o.req, o.availableLangs);
const siteName = o.settings.title || 'Etherpad';
const description = resolveDescriptionWithOverride(
o.settings.socialMeta && o.settings.socialMeta.description,
o.locales, renderLang);
const proxyPath = o.proxyPath || '';
const imageUrl = resolveImageUrl(o.req, o.settings.favicon, o.settings.publicURL, proxyPath);
const imageAlt = `${siteName} logo`;
let title = siteName;
let pathname = (o.req && o.req.originalUrl) || '/';
if (o.padName) {
// Express has already URL-decoded :pad route params; do not decode again.
if (o.kind === 'pad') title = `${o.padName} | ${siteName}`;
else if (o.kind === 'timeslider') title = `${o.padName} (history) | ${siteName}`;
}
const qIdx = pathname.indexOf('?');
if (qIdx >= 0) pathname = pathname.slice(0, qIdx);
return buildSocialMetaHtml({
url: buildAbsoluteUrl(o.req, pathname, o.settings.publicURL, proxyPath),
siteName,
title,
description,
imageUrl,
imageAlt,
renderLang,
});
};