@openpeepshq/common 0.2.0 → 0.3.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.
@@ -1,3 +1,10 @@
1
+ export interface MarkdownRenderProps {
2
+ source?: string;
3
+ mentions?: MentionProfileRef[];
4
+ linkPreviewMode?: 'prepend' | 'append' | 'inline' | 'none';
5
+ /** When true, all links open in a new tab (web) / system browser (RN). */
6
+ newTab?: boolean | ((link: string) => boolean);
7
+ }
1
8
  export type MentionProfileRef = {
2
9
  profile: {
3
10
  handle?: string | null;
@@ -11,6 +18,13 @@ export type MentionProfileRef = {
11
18
  * Bare `@handle` tokens use the allowed handle charset (letters, digits, `_`, `-`).
12
19
  */
13
20
  export declare const linkProfileMentions: (source: string, mentions?: MentionProfileRef[]) => string;
21
+ /**
22
+ * Pre-process markdown source: convert `@handle` mentions into markdown
23
+ * profile links. Hashtag conversion is handled per-platform (web regex vs.
24
+ * markdown-it plugin) because the resulting URL schemes differ.
25
+ * Shared by web and RN renderers so both start from the same text.
26
+ */
27
+ export declare const preprocessMarkdownSource: (source: string, mentions?: MentionProfileRef[]) => string;
14
28
  export declare const matchMentionHandles: (text?: string | null) => string[];
15
29
  /** Readable text for a shortened preview. Drops markdown marks, keeps words. */
16
30
  export declare const markdownPlainText: (markdown?: string | null) => string;
@@ -21,3 +35,26 @@ export declare const firstNWords: (markdown: string | undefined, n: number) => s
21
35
  * Always returns at least 1 for non-empty content.
22
36
  */
23
37
  export declare const minutesToRead: (markdown: string | undefined, wordsPerMinute?: number) => number;
38
+ /**
39
+ * True when `href` points to a different origin than `origin`.
40
+ * Same logic as the web `linkTargets.isExternalLink`.
41
+ */
42
+ export declare const isExternalLink: (href: string, origin?: string) => boolean;
43
+ /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
44
+ export declare const toGotoUrl: (url: string, origin: string) => string;
45
+ /**
46
+ * Tags, attrs and forbits shared by both the web (DOMPurify config) and
47
+ * RN (custom HTML token renderers) so both platforms apply the same policy.
48
+ */
49
+ export declare const MARKDOWN_HTML_ALLOWED_TAGS: readonly ["b", "i", "em", "strong", "a", "p", "br", "ul", "ol", "li", "blockquote", "code", "pre", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "img", "iframe", "video", "source", "picture", "figcaption"];
50
+ export declare const MARKDOWN_HTML_ALLOWED_ATTRS: readonly ["href", "src", "title", "alt", "target", "rel", "width", "height", "loading", "sandbox", "frameborder", "allowfullscreen", "referrerpolicy", "style"];
51
+ export declare const MARKDOWN_HTML_FORBIDDEN_TAGS: readonly ["script", "style", "form", "object", "embed"];
52
+ export declare const MARKDOWN_HTML_FORBIDDEN_ATTRS: readonly ["onload", "onerror", "onclick", "onmouseover"];
53
+ /** Extract all iframe `src` URLs found in an HTML string. */
54
+ export declare const extractIframeSrcs: (html: string) => string[];
55
+ /**
56
+ * Inject safety attributes onto `<iframe>` tags so they can't break out of
57
+ * their container or execute script navigation. Runs after sanitization
58
+ * (so attackers can't smuggle attributes through), before DOM injection.
59
+ */
60
+ export declare const injectIframeSafetyAttrs: (html: string) => string;
@@ -27,6 +27,13 @@ export const linkProfileMentions = (source, mentions = []) => {
27
27
  }
28
28
  return text.replace(new RegExp(mentionHandleRegexBase, 'g'), (_full, prefix, handle) => `${prefix}[@${handle}](/@${handle})`);
29
29
  };
30
+ /**
31
+ * Pre-process markdown source: convert `@handle` mentions into markdown
32
+ * profile links. Hashtag conversion is handled per-platform (web regex vs.
33
+ * markdown-it plugin) because the resulting URL schemes differ.
34
+ * Shared by web and RN renderers so both start from the same text.
35
+ */
36
+ export const preprocessMarkdownSource = linkProfileMentions;
30
37
  export const matchMentionHandles = (text) => {
31
38
  if (!text)
32
39
  return [];
@@ -91,3 +98,145 @@ export const minutesToRead = (markdown, wordsPerMinute = DEFAULT_WORDS_PER_MINUT
91
98
  ? 0
92
99
  : Math.max(1, Math.ceil(wordCount / wordsPerMinute));
93
100
  };
101
+ /* ------------------------------------------------------------------ */
102
+ /* Shared link utilities */
103
+ /* ------------------------------------------------------------------ */
104
+ /**
105
+ * True when `href` points to a different origin than `origin`.
106
+ * Same logic as the web `linkTargets.isExternalLink`.
107
+ */
108
+ export const isExternalLink = (href, origin) => {
109
+ if (!href || /^(mailto:|tel:|#)/.test(href)) {
110
+ return false;
111
+ }
112
+ if (href.startsWith('/') && !href.startsWith('//')) {
113
+ return false;
114
+ }
115
+ if (!origin) {
116
+ return !href.startsWith('/');
117
+ }
118
+ try {
119
+ return new URL(href, origin).origin !== origin;
120
+ }
121
+ catch {
122
+ return !href.startsWith('/');
123
+ }
124
+ };
125
+ /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
126
+ export const toGotoUrl = (url, origin) => {
127
+ if (url.includes('goto:/')) {
128
+ return url;
129
+ }
130
+ if (url.startsWith('/') && !url.startsWith('//')) {
131
+ return `goto:${url}`;
132
+ }
133
+ try {
134
+ const urlObj = new URL(url);
135
+ if (urlObj.origin === origin) {
136
+ return `goto:${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
137
+ }
138
+ }
139
+ catch {
140
+ // fall through
141
+ }
142
+ return url;
143
+ };
144
+ /* ------------------------------------------------------------------ */
145
+ /* HTML sanitization helpers (shared allowlist + iframe safety) */
146
+ /* ------------------------------------------------------------------ */
147
+ /**
148
+ * Tags, attrs and forbits shared by both the web (DOMPurify config) and
149
+ * RN (custom HTML token renderers) so both platforms apply the same policy.
150
+ */
151
+ export const MARKDOWN_HTML_ALLOWED_TAGS = [
152
+ 'b',
153
+ 'i',
154
+ 'em',
155
+ 'strong',
156
+ 'a',
157
+ 'p',
158
+ 'br',
159
+ 'ul',
160
+ 'ol',
161
+ 'li',
162
+ 'blockquote',
163
+ 'code',
164
+ 'pre',
165
+ 'h1',
166
+ 'h2',
167
+ 'h3',
168
+ 'h4',
169
+ 'h5',
170
+ 'h6',
171
+ 'hr',
172
+ 'img',
173
+ 'iframe',
174
+ 'video',
175
+ 'source',
176
+ 'picture',
177
+ 'figcaption',
178
+ ];
179
+ export const MARKDOWN_HTML_ALLOWED_ATTRS = [
180
+ 'href',
181
+ 'src',
182
+ 'title',
183
+ 'alt',
184
+ 'target',
185
+ 'rel',
186
+ 'width',
187
+ 'height',
188
+ 'loading',
189
+ 'sandbox',
190
+ 'frameborder',
191
+ 'allowfullscreen',
192
+ 'referrerpolicy',
193
+ 'style',
194
+ ];
195
+ export const MARKDOWN_HTML_FORBIDDEN_TAGS = [
196
+ 'script',
197
+ 'style',
198
+ 'form',
199
+ 'object',
200
+ 'embed',
201
+ ];
202
+ export const MARKDOWN_HTML_FORBIDDEN_ATTRS = [
203
+ 'onload',
204
+ 'onerror',
205
+ 'onclick',
206
+ 'onmouseover',
207
+ ];
208
+ /** Simple `<iframe>` tag detector for extracting embed URLs from raw HTML. */
209
+ const IFRAME_SRC_RE = /<iframe\b[^>]*?\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)')[^>]*>/gi;
210
+ /** Extract all iframe `src` URLs found in an HTML string. */
211
+ export const extractIframeSrcs = (html) => {
212
+ const srcs = [];
213
+ let match;
214
+ while ((match = IFRAME_SRC_RE.exec(html)) !== null) {
215
+ srcs.push(match[1] ?? match[2] ?? '');
216
+ }
217
+ return srcs;
218
+ };
219
+ /**
220
+ * Inject safety attributes onto `<iframe>` tags so they can't break out of
221
+ * their container or execute script navigation. Runs after sanitization
222
+ * (so attackers can't smuggle attributes through), before DOM injection.
223
+ */
224
+ export const injectIframeSafetyAttrs = (html) => {
225
+ return html.replace(/<iframe([^>]*?)>/gi, (match, attrs) => {
226
+ let safeAttrs = attrs;
227
+ if (!/loading\s*=/.test(safeAttrs)) {
228
+ safeAttrs += ' loading="lazy"';
229
+ }
230
+ if (!/sandbox\s*=/.test(safeAttrs)) {
231
+ safeAttrs +=
232
+ ' sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"';
233
+ }
234
+ if (!/referrerpolicy\s*=/.test(safeAttrs)) {
235
+ safeAttrs += ' referrerpolicy="no-referrer"';
236
+ }
237
+ if (!/style\s*=/.test(safeAttrs)) {
238
+ safeAttrs += ' style="max-width:100%;width:100%;border:0;display:block;"';
239
+ }
240
+ return `<iframe${safeAttrs}>`;
241
+ });
242
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/common",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1,5 +1,13 @@
1
1
  import { mentionHandleRegexBase } from '../types';
2
2
 
3
+ export interface MarkdownRenderProps {
4
+ source?: string;
5
+ mentions?: MentionProfileRef[];
6
+ linkPreviewMode?: 'prepend' | 'append' | 'inline' | 'none';
7
+ /** When true, all links open in a new tab (web) / system browser (RN). */
8
+ newTab?: boolean | ((link: string) => boolean);
9
+ }
10
+
3
11
  const escapeRegExp = (value: string) =>
4
12
  value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5
13
 
@@ -51,6 +59,14 @@ export const linkProfileMentions = (
51
59
  );
52
60
  };
53
61
 
62
+ /**
63
+ * Pre-process markdown source: convert `@handle` mentions into markdown
64
+ * profile links. Hashtag conversion is handled per-platform (web regex vs.
65
+ * markdown-it plugin) because the resulting URL schemes differ.
66
+ * Shared by web and RN renderers so both start from the same text.
67
+ */
68
+ export const preprocessMarkdownSource = linkProfileMentions;
69
+
54
70
  export const matchMentionHandles = (text?: string | null): string[] => {
55
71
  if (!text) return [];
56
72
  const handles = new Set<string>();
@@ -120,3 +136,155 @@ export const minutesToRead = (
120
136
  ? 0
121
137
  : Math.max(1, Math.ceil(wordCount / wordsPerMinute));
122
138
  };
139
+
140
+ /* ------------------------------------------------------------------ */
141
+ /* Shared link utilities */
142
+ /* ------------------------------------------------------------------ */
143
+
144
+ /**
145
+ * True when `href` points to a different origin than `origin`.
146
+ * Same logic as the web `linkTargets.isExternalLink`.
147
+ */
148
+ export const isExternalLink = (href: string, origin?: string): boolean => {
149
+ if (!href || /^(mailto:|tel:|#)/.test(href)) {
150
+ return false;
151
+ }
152
+ if (href.startsWith('/') && !href.startsWith('//')) {
153
+ return false;
154
+ }
155
+ if (!origin) {
156
+ return !href.startsWith('/');
157
+ }
158
+ try {
159
+ return new URL(href, origin).origin !== origin;
160
+ } catch {
161
+ return !href.startsWith('/');
162
+ }
163
+ };
164
+
165
+ /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
166
+ export const toGotoUrl = (url: string, origin: string): string => {
167
+ if (url.includes('goto:/')) {
168
+ return url;
169
+ }
170
+ if (url.startsWith('/') && !url.startsWith('//')) {
171
+ return `goto:${url}`;
172
+ }
173
+ try {
174
+ const urlObj = new URL(url);
175
+ if (urlObj.origin === origin) {
176
+ return `goto:${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
177
+ }
178
+ } catch {
179
+ // fall through
180
+ }
181
+ return url;
182
+ };
183
+
184
+ /* ------------------------------------------------------------------ */
185
+ /* HTML sanitization helpers (shared allowlist + iframe safety) */
186
+ /* ------------------------------------------------------------------ */
187
+
188
+ /**
189
+ * Tags, attrs and forbits shared by both the web (DOMPurify config) and
190
+ * RN (custom HTML token renderers) so both platforms apply the same policy.
191
+ */
192
+ export const MARKDOWN_HTML_ALLOWED_TAGS = [
193
+ 'b',
194
+ 'i',
195
+ 'em',
196
+ 'strong',
197
+ 'a',
198
+ 'p',
199
+ 'br',
200
+ 'ul',
201
+ 'ol',
202
+ 'li',
203
+ 'blockquote',
204
+ 'code',
205
+ 'pre',
206
+ 'h1',
207
+ 'h2',
208
+ 'h3',
209
+ 'h4',
210
+ 'h5',
211
+ 'h6',
212
+ 'hr',
213
+ 'img',
214
+ 'iframe',
215
+ 'video',
216
+ 'source',
217
+ 'picture',
218
+ 'figcaption',
219
+ ] as const;
220
+
221
+ export const MARKDOWN_HTML_ALLOWED_ATTRS = [
222
+ 'href',
223
+ 'src',
224
+ 'title',
225
+ 'alt',
226
+ 'target',
227
+ 'rel',
228
+ 'width',
229
+ 'height',
230
+ 'loading',
231
+ 'sandbox',
232
+ 'frameborder',
233
+ 'allowfullscreen',
234
+ 'referrerpolicy',
235
+ 'style',
236
+ ] as const;
237
+
238
+ export const MARKDOWN_HTML_FORBIDDEN_TAGS = [
239
+ 'script',
240
+ 'style',
241
+ 'form',
242
+ 'object',
243
+ 'embed',
244
+ ] as const;
245
+
246
+ export const MARKDOWN_HTML_FORBIDDEN_ATTRS = [
247
+ 'onload',
248
+ 'onerror',
249
+ 'onclick',
250
+ 'onmouseover',
251
+ ] as const;
252
+
253
+ /** Simple `<iframe>` tag detector for extracting embed URLs from raw HTML. */
254
+ const IFRAME_SRC_RE =
255
+ /<iframe\b[^>]*?\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)')[^>]*>/gi;
256
+
257
+ /** Extract all iframe `src` URLs found in an HTML string. */
258
+ export const extractIframeSrcs = (html: string): string[] => {
259
+ const srcs: string[] = [];
260
+ let match: RegExpExecArray | null;
261
+ while ((match = IFRAME_SRC_RE.exec(html)) !== null) {
262
+ srcs.push(match[1] ?? match[2] ?? '');
263
+ }
264
+ return srcs;
265
+ };
266
+
267
+ /**
268
+ * Inject safety attributes onto `<iframe>` tags so they can't break out of
269
+ * their container or execute script navigation. Runs after sanitization
270
+ * (so attackers can't smuggle attributes through), before DOM injection.
271
+ */
272
+ export const injectIframeSafetyAttrs = (html: string): string => {
273
+ return html.replace(/<iframe([^>]*?)>/gi, (match, attrs: string) => {
274
+ let safeAttrs = attrs;
275
+ if (!/loading\s*=/.test(safeAttrs)) {
276
+ safeAttrs += ' loading="lazy"';
277
+ }
278
+ if (!/sandbox\s*=/.test(safeAttrs)) {
279
+ safeAttrs +=
280
+ ' sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"';
281
+ }
282
+ if (!/referrerpolicy\s*=/.test(safeAttrs)) {
283
+ safeAttrs += ' referrerpolicy="no-referrer"';
284
+ }
285
+ if (!/style\s*=/.test(safeAttrs)) {
286
+ safeAttrs += ' style="max-width:100%;width:100%;border:0;display:block;"';
287
+ }
288
+ return `<iframe${safeAttrs}>`;
289
+ });
290
+ };