@openpeepshq/common 0.1.46 → 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.
Files changed (83) hide show
  1. package/dist/lib/adminSections.js +1 -1
  2. package/dist/lib/capabilitiesHelpers.js +30 -40
  3. package/dist/lib/csvHelpers.js +1 -1
  4. package/dist/lib/eventIcs.js +26 -32
  5. package/dist/lib/eventRecurrence.d.ts +17 -0
  6. package/dist/lib/eventRecurrence.js +75 -18
  7. package/dist/lib/eventTime.js +9 -11
  8. package/dist/lib/groupHelpers.js +13 -34
  9. package/dist/lib/groupTemplateHelpers.js +6 -10
  10. package/dist/lib/jamHelpers.js +6 -9
  11. package/dist/lib/markdownHelpers.d.ts +37 -0
  12. package/dist/lib/markdownHelpers.js +151 -3
  13. package/dist/lib/postHelpers.js +70 -97
  14. package/dist/lib/profileHelpers.js +17 -24
  15. package/dist/lib/pushHelpers.js +3 -4
  16. package/dist/lib/scopeHelpers.js +6 -9
  17. package/dist/lib/ssoLoginUrl.js +4 -6
  18. package/dist/lib/ssoProviders.js +35 -39
  19. package/dist/lib/tokenHelpers.js +5 -5
  20. package/dist/lib/utils.js +6 -7
  21. package/dist/types/admin-db.js +1 -1
  22. package/dist/types/api.d.ts +1 -0
  23. package/dist/types/api.js +1 -1
  24. package/dist/types/config.d.ts +3 -0
  25. package/dist/types/config.js +3 -0
  26. package/dist/types/models.js +1 -1
  27. package/dist/types/plugins.js +2 -2
  28. package/dist/zod.d.ts +1 -0
  29. package/dist/zod.js +1 -0
  30. package/package.json +36 -6
  31. package/src/index.ts +4 -0
  32. package/src/lib/adminSections.ts +84 -0
  33. package/src/lib/attachmentHelpers.ts +14 -0
  34. package/src/lib/capabilitiesHelpers.ts +532 -0
  35. package/src/lib/colors.ts +20 -0
  36. package/src/lib/csvHelpers.ts +31 -0
  37. package/src/lib/eventIcs.ts +265 -0
  38. package/src/lib/eventRecurrence.ts +495 -0
  39. package/src/lib/eventTime.ts +206 -0
  40. package/src/lib/federationHosts.ts +22 -0
  41. package/src/lib/feedCursor.ts +27 -0
  42. package/src/lib/feedFormat.ts +24 -0
  43. package/src/lib/groupHelpers.ts +421 -0
  44. package/src/lib/groupTemplateHelpers.ts +83 -0
  45. package/src/lib/index.ts +29 -0
  46. package/src/lib/jamHelpers.ts +164 -0
  47. package/src/lib/legacyThemeRoot.ts +14 -0
  48. package/src/lib/markdownHelpers.ts +290 -0
  49. package/src/lib/mediaDimensions.ts +21 -0
  50. package/src/lib/postHelpers.ts +783 -0
  51. package/src/lib/profileHelpers.ts +220 -0
  52. package/src/lib/pushHelpers.ts +34 -0
  53. package/src/lib/reactions.ts +52 -0
  54. package/src/lib/reportHelpers.ts +7 -0
  55. package/src/lib/scopeHelpers.ts +176 -0
  56. package/src/lib/ssoLoginUrl.ts +93 -0
  57. package/src/lib/ssoProviders.ts +472 -0
  58. package/src/lib/text.ts +26 -0
  59. package/src/lib/timeZone.ts +52 -0
  60. package/src/lib/tokenHelpers.ts +119 -0
  61. package/src/lib/utils.ts +322 -0
  62. package/src/types/admin-db.ts +74 -0
  63. package/src/types/admin-email.ts +55 -0
  64. package/src/types/admin-jobs.ts +17 -0
  65. package/src/types/admin-performance.ts +20 -0
  66. package/src/types/analytics.ts +318 -0
  67. package/src/types/api.ts +871 -0
  68. package/src/types/apple-app-site-association.ts +54 -0
  69. package/src/types/auth.ts +22 -0
  70. package/src/types/capabilities.ts +280 -0
  71. package/src/types/config.ts +546 -0
  72. package/src/types/db.ts +138 -0
  73. package/src/types/export.ts +10 -0
  74. package/src/types/index.ts +20 -0
  75. package/src/types/internal.ts +338 -0
  76. package/src/types/models.ts +939 -0
  77. package/src/types/notifications.ts +92 -0
  78. package/src/types/plugins.ts +150 -0
  79. package/src/types/roleDefaults.ts +132 -0
  80. package/src/types/stats.ts +195 -0
  81. package/src/types/stripe.ts +45 -0
  82. package/src/types/utils.ts +100 -0
  83. package/src/zod.ts +1 -0
@@ -1,13 +1,10 @@
1
1
  import { defaultGroupAdminCapabilityAdds, defaultGroupOwnerCapabilityAdds, defaultGroupRoles, } from '../types/capabilities.js';
2
2
  import { checkCapabilities, getGroupCapabilitiesByRoles, } from './capabilitiesHelpers.js';
3
3
  import { profileName } from './profileHelpers.js';
4
- const withModerator = (member) => {
5
- var _a, _b;
6
- return ({
7
- add: [...((_a = member.add) !== null && _a !== void 0 ? _a : []), 'core-posts-delete'],
8
- ...(((_b = member.remove) === null || _b === void 0 ? void 0 : _b.length) ? { remove: member.remove } : {}),
9
- });
10
- };
4
+ const withModerator = (member) => ({
5
+ add: [...(member.add ?? []), 'core-posts-delete'],
6
+ ...(member.remove?.length ? { remove: member.remove } : {}),
7
+ });
11
8
  const ownerCapabilities = {
12
9
  add: [...defaultGroupOwnerCapabilityAdds],
13
10
  };
@@ -15,7 +12,7 @@ const adminCapabilities = {
15
12
  add: [...defaultGroupAdminCapabilityAdds],
16
13
  };
17
14
  const containsIgnoreCase = (candidate, query) => candidate.toLowerCase().indexOf(query.toLowerCase()) > -1;
18
- export const groupName = (group) => (group === null || group === void 0 ? void 0 : group.displayName) || (group === null || group === void 0 ? void 0 : group.handle) || '';
15
+ export const groupName = (group) => group?.displayName || group?.handle || '';
19
16
  export const matchesGroupQuery = (group, query, queryOptions = { handle: true, displayName: true, description: false }) => (queryOptions.handle && containsIgnoreCase(group.handle, query)) ||
20
17
  (queryOptions.displayName &&
21
18
  group.displayName &&
@@ -23,15 +20,9 @@ export const matchesGroupQuery = (group, query, queryOptions = { handle: true, d
23
20
  (queryOptions.description &&
24
21
  group.description &&
25
22
  containsIgnoreCase(group.description, query));
26
- export const sortGroupMembers = (members) => {
27
- var _a;
28
- return (_a = members === null || members === void 0 ? void 0 : members.sort((a, b) => profileName(a.profile).localeCompare(profileName(b.profile)))) !== null && _a !== void 0 ? _a : [];
29
- };
30
- export const groupMembershipHasRole = (roles, role) => (roles !== null && roles !== void 0 ? roles : []).includes(role);
31
- export const actorIsGroupOwner = (profile, groupId) => {
32
- var _a, _b;
33
- return groupMembershipHasRole((_b = (_a = profile.memberships) === null || _a === void 0 ? void 0 : _a.find((m) => m.group.id === groupId)) === null || _b === void 0 ? void 0 : _b.roles, 'owner');
34
- };
23
+ export const sortGroupMembers = (members) => members?.sort((a, b) => profileName(a.profile).localeCompare(profileName(b.profile))) ?? [];
24
+ export const groupMembershipHasRole = (roles, role) => (roles ?? []).includes(role);
25
+ export const actorIsGroupOwner = (profile, groupId) => groupMembershipHasRole(profile.memberships?.find((m) => m.group.id === groupId)?.roles, 'owner');
35
26
  export const countGroupOwners = (members) => members.filter((m) => groupMembershipHasRole(m.roles, 'owner')).length;
36
27
  export const groupRoleChangeBlocked = ({ actorIsOwner, currentRoles, nextRoles, ownerCount, }) => {
37
28
  const wasOwner = groupMembershipHasRole(currentRoles, 'owner');
@@ -49,25 +40,13 @@ export const assignableGroupRoles = (actorIsOwner) => actorIsOwner
49
40
  ? [...defaultGroupRoles]
50
41
  : defaultGroupRoles.filter((role) => role !== 'owner');
51
42
  export const groupRolesForAssignment = (role) => (role === 'member' ? ['member'] : ['member', role]);
52
- export const canChangeMemberRole = (profile, group) => {
53
- var _a, _b, _c;
54
- return checkCapabilities(['core-groups-changeMemberRole'], getGroupCapabilitiesByRoles((_c = (_b = (_a = profile.memberships) === null || _a === void 0 ? void 0 : _a.find((m) => m.group.id === group.id)) === null || _b === void 0 ? void 0 : _b.roles) !== null && _c !== void 0 ? _c : [], group)).success;
55
- };
56
- export const canAddMember = (profile, group) => {
57
- var _a, _b, _c;
58
- return checkCapabilities(['core-groups-addMember'], getGroupCapabilitiesByRoles((_c = (_b = (_a = profile.memberships) === null || _a === void 0 ? void 0 : _a.find((m) => m.group.id === group.id)) === null || _b === void 0 ? void 0 : _b.roles) !== null && _c !== void 0 ? _c : [], group)).success;
59
- };
60
- export const canRemoveMember = (profile, group) => {
61
- var _a, _b, _c;
62
- return checkCapabilities(['core-groups-removeMember'], getGroupCapabilitiesByRoles((_c = (_b = (_a = profile.memberships) === null || _a === void 0 ? void 0 : _a.find((m) => m.group.id === group.id)) === null || _b === void 0 ? void 0 : _b.roles) !== null && _c !== void 0 ? _c : [], group)).success;
63
- };
43
+ export const canChangeMemberRole = (profile, group) => checkCapabilities(['core-groups-changeMemberRole'], getGroupCapabilitiesByRoles(profile.memberships?.find((m) => m.group.id === group.id)?.roles ?? [], group)).success;
44
+ export const canAddMember = (profile, group) => checkCapabilities(['core-groups-addMember'], getGroupCapabilitiesByRoles(profile.memberships?.find((m) => m.group.id === group.id)?.roles ?? [], group)).success;
45
+ export const canRemoveMember = (profile, group) => checkCapabilities(['core-groups-removeMember'], getGroupCapabilitiesByRoles(profile.memberships?.find((m) => m.group.id === group.id)?.roles ?? [], group)).success;
64
46
  export const isGroupDiscoverable = (group) => checkCapabilities(['core-groups-read'], getGroupCapabilitiesByRoles(['none'], group)).success;
65
47
  /** Posts are only readable by explicit group members (not public/local). */
66
- export const hasMemberOnlyPostsVisibility = (capabilities) => {
67
- var _a, _b, _c, _d;
68
- return !((_b = (_a = capabilities === null || capabilities === void 0 ? void 0 : capabilities.none) === null || _a === void 0 ? void 0 : _a.add) === null || _b === void 0 ? void 0 : _b.includes('core-posts-read')) &&
69
- !((_d = (_c = capabilities === null || capabilities === void 0 ? void 0 : capabilities.local) === null || _c === void 0 ? void 0 : _c.add) === null || _d === void 0 ? void 0 : _d.includes('core-posts-read'));
70
- };
48
+ export const hasMemberOnlyPostsVisibility = (capabilities) => !capabilities?.none?.add?.includes('core-posts-read') &&
49
+ !capabilities?.local?.add?.includes('core-posts-read');
71
50
  export const groupCapabilityTemplates = {
72
51
  defaultGroup: {
73
52
  name: 'defaultGroup',
@@ -14,19 +14,15 @@ const TEMPLATE_RELATIONSHIPS = [
14
14
  'admin',
15
15
  'owner',
16
16
  ];
17
- const normalizeBucket = (bucket) => {
18
- var _a, _b;
19
- return ({
20
- add: [...((_a = bucket === null || bucket === void 0 ? void 0 : bucket.add) !== null && _a !== void 0 ? _a : [])].sort(),
21
- remove: [...((_b = bucket === null || bucket === void 0 ? void 0 : bucket.remove) !== null && _b !== void 0 ? _b : [])].sort(),
22
- });
23
- };
17
+ const normalizeBucket = (bucket) => ({
18
+ add: [...(bucket?.add ?? [])].sort(),
19
+ remove: [...(bucket?.remove ?? [])].sort(),
20
+ });
24
21
  export const normalizeGroupCapabilitiesForMatch = (capabilities) => {
25
- var _a, _b;
26
22
  const normalized = {};
27
23
  for (const relationship of TEMPLATE_RELATIONSHIPS) {
28
- const bucket = capabilities === null || capabilities === void 0 ? void 0 : capabilities[relationship];
29
- if (!((_a = bucket === null || bucket === void 0 ? void 0 : bucket.add) === null || _a === void 0 ? void 0 : _a.length) && !((_b = bucket === null || bucket === void 0 ? void 0 : bucket.remove) === null || _b === void 0 ? void 0 : _b.length))
24
+ const bucket = capabilities?.[relationship];
25
+ if (!bucket?.add?.length && !bucket?.remove?.length)
30
26
  continue;
31
27
  normalized[relationship] = normalizeBucket(bucket);
32
28
  }
@@ -2,9 +2,8 @@ import { normalizeRecurrenceId } from './eventRecurrence.js';
2
2
  export const jamRoomName = (postId, _recurrenceId) => postId;
3
3
  const UUID_PREFIX = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_.*)?$/i;
4
4
  export const postIdFromJamRoomName = (roomName) => {
5
- var _a;
6
5
  const match = roomName.match(UUID_PREFIX);
7
- return (_a = match === null || match === void 0 ? void 0 : match[1]) !== null && _a !== void 0 ? _a : roomName;
6
+ return match?.[1] ?? roomName;
8
7
  };
9
8
  /** Recurring jams use one LiveKit room per event; leftover occurrence rooms still collapse. */
10
9
  export const uniquePostsById = (posts) => {
@@ -30,32 +29,30 @@ export const getJamUrl = (id, origin, occurrence) => {
30
29
  return `${origin}/events/${id}/jam${query}`;
31
30
  };
32
31
  export const jamFromEvent = (event) => {
33
- var _a, _b;
34
- if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === 'event' && ((_b = event.data) === null || _b === void 0 ? void 0 : _b.jam)) {
32
+ if (event.data?.type === 'event' && event.data?.jam) {
35
33
  return event.data.jam;
36
34
  }
37
35
  return undefined;
38
36
  };
39
- export const canModerateJam = (profile, post) => { var _a, _b; return !!(profile && ((_b = (_a = jamFromEvent(post)) === null || _a === void 0 ? void 0 : _a.moderators) === null || _b === void 0 ? void 0 : _b.includes(profile.id))); };
37
+ export const canModerateJam = (profile, post) => !!(profile && jamFromEvent(post)?.moderators?.includes(profile.id));
40
38
  /** Host or jam moderator — same gate as the event Attendees tab. */
41
39
  export const canViewJamAttendees = (profile, post) => !!(profile &&
42
40
  (post.profile.id === profile.id || canModerateJam(profile, post)));
43
41
  export const canAccessJamRecordings = (profile, post) => {
44
- var _a, _b, _c, _d;
45
42
  if (!profile) {
46
43
  return false;
47
44
  }
48
45
  if (post.profile.id === profile.id) {
49
46
  return true;
50
47
  }
51
- if (((_a = post.data) === null || _a === void 0 ? void 0 : _a.type) !== 'event') {
48
+ if (post.data?.type !== 'event') {
52
49
  return false;
53
50
  }
54
51
  const event = post.data;
55
- if ((_b = event.moderators) === null || _b === void 0 ? void 0 : _b.includes(profile.id)) {
52
+ if (event.moderators?.includes(profile.id)) {
56
53
  return true;
57
54
  }
58
- return !!((_d = (_c = event.jam) === null || _c === void 0 ? void 0 : _c.moderators) === null || _d === void 0 ? void 0 : _d.includes(profile.id));
55
+ return !!event.jam?.moderators?.includes(profile.id);
59
56
  };
60
57
  export const jamRecordingAcceptsUpload = (status) => status === 'requested' || status === 'active' || status === 'finalizing';
61
58
  export const isRtmpJamRecording = (recording) => recording.kind === 'rtmp';
@@ -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;
@@ -10,12 +10,11 @@ const mentionSuffix = '(?=\\s|$|[.,!?;:])';
10
10
  */
11
11
  export const linkProfileMentions = (source, mentions = []) => {
12
12
  const aliases = mentions.flatMap(({ profile }) => {
13
- var _a, _b;
14
- const handle = (_a = profile.handle) === null || _a === void 0 ? void 0 : _a.trim();
13
+ const handle = profile.handle?.trim();
15
14
  if (!handle)
16
15
  return [];
17
16
  const names = new Set([handle]);
18
- const displayName = (_b = profile.displayName) === null || _b === void 0 ? void 0 : _b.trim();
17
+ const displayName = profile.displayName?.trim();
19
18
  if (displayName)
20
19
  names.add(displayName);
21
20
  return [...names].map((name) => ({ name, handle }));
@@ -28,6 +27,13 @@ export const linkProfileMentions = (source, mentions = []) => {
28
27
  }
29
28
  return text.replace(new RegExp(mentionHandleRegexBase, 'g'), (_full, prefix, handle) => `${prefix}[@${handle}](/@${handle})`);
30
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;
31
37
  export const matchMentionHandles = (text) => {
32
38
  if (!text)
33
39
  return [];
@@ -92,3 +98,145 @@ export const minutesToRead = (markdown, wordsPerMinute = DEFAULT_WORDS_PER_MINUT
92
98
  ? 0
93
99
  : Math.max(1, Math.ceil(wordCount / wordsPerMinute));
94
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
+ };