@alepha/ui 0.25.1 → 0.25.2

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 (74) hide show
  1. package/package.json +3 -3
  2. package/src/components/account/__tests__/account-router.spec.ts +201 -0
  3. package/src/components/account/account-connections.tsx +103 -0
  4. package/src/components/account/account-delete-dialog.tsx +184 -0
  5. package/src/components/account/account-header.tsx +57 -0
  6. package/src/components/account/account-keys.tsx +221 -0
  7. package/src/components/account/account-layout.tsx +63 -0
  8. package/src/components/account/account-password-dialog.tsx +152 -0
  9. package/src/components/account/account-profile.tsx +229 -0
  10. package/src/components/account/account-router-options.tsx +74 -0
  11. package/src/components/account/account-router-page.tsx +69 -0
  12. package/src/components/account/account-router.tsx +214 -0
  13. package/src/components/account/account-security.tsx +150 -0
  14. package/src/components/account/account-sessions.tsx +140 -0
  15. package/src/components/admin/__tests__/admin-keys-token-dialog.browser.spec.tsx +62 -0
  16. package/src/components/admin/__tests__/admin-layout.browser.spec.tsx +82 -0
  17. package/src/components/admin/__tests__/admin-router-page.spec.ts +54 -0
  18. package/src/components/admin/__tests__/admin-router.spec.ts +208 -0
  19. package/src/components/admin/__tests__/admin-user-cell.browser.spec.tsx +99 -0
  20. package/src/components/admin/__tests__/admin-user-detail.spec.ts +29 -0
  21. package/src/components/admin/admin-analytics-query-panel.tsx +149 -0
  22. package/src/components/admin/admin-analytics-results.tsx +95 -0
  23. package/src/components/admin/admin-analytics.tsx +104 -0
  24. package/src/components/admin/admin-audits.tsx +12 -15
  25. package/src/components/admin/admin-files.tsx +10 -18
  26. package/src/components/admin/admin-jobs-executions-panel.tsx +2 -1
  27. package/src/components/admin/admin-jobs.tsx +3 -1
  28. package/src/components/admin/admin-keys-token-dialog.tsx +123 -0
  29. package/src/components/admin/admin-keys.tsx +54 -3
  30. package/src/components/admin/admin-layout.tsx +107 -0
  31. package/src/components/admin/admin-payments.tsx +4 -5
  32. package/src/components/admin/admin-router-options.tsx +130 -0
  33. package/src/components/admin/admin-router-page.tsx +74 -0
  34. package/src/components/admin/admin-router.tsx +379 -0
  35. package/src/components/admin/admin-sessions.tsx +2 -16
  36. package/src/components/admin/admin-user-cell.tsx +70 -0
  37. package/src/components/admin/admin-user-detail-overview-tab.tsx +28 -0
  38. package/src/components/admin/admin-user-detail-profile-policy.spec.ts +146 -0
  39. package/src/components/admin/admin-user-detail-profile-policy.ts +147 -0
  40. package/src/components/admin/admin-user-detail-security-tab.tsx +1 -1
  41. package/src/components/admin/admin-user-detail.tsx +76 -32
  42. package/src/components/admin/admin-users-status-filter.tsx +2 -0
  43. package/src/components/admin/admin-workflows-execution-sheet.tsx +277 -0
  44. package/src/components/admin/admin-workflows-executions-panel.tsx +170 -0
  45. package/src/components/admin/admin-workflows-status-badge.tsx +40 -0
  46. package/src/components/admin/admin-workflows.tsx +207 -0
  47. package/src/components/alepha-table/alepha-table.tsx +73 -17
  48. package/src/components/app-actions/__tests__/app-actions.browser.spec.tsx +79 -0
  49. package/src/components/app-actions/app-actions.tsx +113 -0
  50. package/src/components/app-shell/app-shell.tsx +122 -0
  51. package/src/components/auth/auth-reset-password.tsx +81 -8
  52. package/src/components/button-user/button-user.tsx +58 -1
  53. package/src/components/control/control.tsx +14 -71
  54. package/src/components/control-password/control-password.tsx +87 -0
  55. package/src/components/control-select/__tests__/control-select-clear-label.browser.spec.tsx +101 -0
  56. package/src/components/control-select/__tests__/control-select-searchable.browser.spec.tsx +142 -0
  57. package/src/components/control-select/control-select.tsx +78 -111
  58. package/src/components/control-upload/control-upload.tsx +27 -1
  59. package/src/components/markdown-view/markdown-view.tsx +6 -0
  60. package/src/components/nav-shell/nav-page.tsx +3 -3
  61. package/src/components/settings/__tests__/settings-nav.browser.spec.tsx +123 -0
  62. package/src/components/settings/__tests__/settings-section.browser.spec.tsx +130 -0
  63. package/src/components/settings/settings-danger-section.tsx +59 -0
  64. package/src/components/settings/settings-layout.tsx +56 -0
  65. package/src/components/settings/settings-nav.tsx +131 -0
  66. package/src/components/settings/settings-row.tsx +81 -0
  67. package/src/components/settings/settings-section.tsx +64 -0
  68. package/src/components/ui/dropdown-menu.tsx +9 -1
  69. package/src/lib/__tests__/rehype-safe-img.spec.ts +121 -0
  70. package/src/lib/i18n-fr.ts +68 -0
  71. package/src/lib/rehype-safe-img.ts +150 -0
  72. package/src/lib/resize-image.ts +135 -0
  73. package/src/styles.css +126 -1
  74. /package/src/components/{admin/admin-user-detail-provider-labels.ts → auth/provider-labels.ts} +0 -0
@@ -41,7 +41,15 @@ function DropdownMenuContent({
41
41
  <MenuPrimitive.Popup
42
42
  data-slot="dropdown-menu-content"
43
43
  className={cn(
44
- "cn-menu-target cn-menu-translucent z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",
44
+ // LOCAL PATCH — `w-(--anchor-width)` → `w-auto`. Upstream sizes a
45
+ // menu to its anchor, which is right for a select (the popup IS the
46
+ // field) and wrong for a menu, where the trigger is often a 32px
47
+ // icon button and the content is prose: every label past `min-w-32`
48
+ // wrapped. `min-w-32` stays as the floor so a lone "Edit" does not
49
+ // produce a sliver. Re-applied by `scripts/sync.mjs` — this file is
50
+ // overwritten wholesale on the next registry sync, so a comment
51
+ // alone would not survive.
52
+ "cn-menu-target cn-menu-translucent z-50 max-h-(--available-height) w-auto max-w-(--available-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",
45
53
  className,
46
54
  )}
47
55
  {...props}
@@ -0,0 +1,121 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseSafeImg } from "../rehype-safe-img.ts";
3
+
4
+ /**
5
+ * This is the whole XSS surface of the markdown reader, so it is tested
6
+ * directly rather than through a render.
7
+ *
8
+ * The reader deliberately does NOT use `rehype-raw`: folio content is
9
+ * user-authored, and this codebase escapes raw HTML everywhere else on
10
+ * purpose. `parseSafeImg` is the single exception carved out for `<img>`,
11
+ * which is what MDXEditor emits once an image has been resized — so what it
12
+ * accepts, and only that, becomes renderable markup.
13
+ */
14
+ describe("parseSafeImg", () => {
15
+ describe("accepts", () => {
16
+ it("a relative assets/ image", () => {
17
+ expect(parseSafeImg('<img src="assets/photo.webp" />')).toEqual({
18
+ src: "assets/photo.webp",
19
+ });
20
+ });
21
+
22
+ it("a same-origin file URL", () => {
23
+ expect(parseSafeImg('<img src="/api/files/abc" />')).toEqual({
24
+ src: "/api/files/abc",
25
+ });
26
+ });
27
+
28
+ it("the allowlisted attributes", () => {
29
+ expect(
30
+ parseSafeImg(
31
+ '<img src="assets/a.png" alt="A cat" title="Tip" width="600" height="400">',
32
+ ),
33
+ ).toEqual({
34
+ src: "assets/a.png",
35
+ alt: "A cat",
36
+ title: "Tip",
37
+ width: "600",
38
+ height: "400",
39
+ });
40
+ });
41
+
42
+ it("single-quoted and unquoted attribute values", () => {
43
+ expect(parseSafeImg("<img src='assets/a.png' width=600>")).toEqual({
44
+ src: "assets/a.png",
45
+ width: "600",
46
+ });
47
+ });
48
+ });
49
+
50
+ describe("drops attributes outside the allowlist", () => {
51
+ it("an inline event handler", () => {
52
+ expect(
53
+ parseSafeImg('<img src="assets/a.png" onerror="alert(1)">'),
54
+ ).toEqual({ src: "assets/a.png" });
55
+ });
56
+
57
+ it("onload, style, class and srcset", () => {
58
+ expect(
59
+ parseSafeImg(
60
+ '<img src="assets/a.png" onload="x()" style="position:fixed" class="evil" srcset="https://evil.test/a 1x">',
61
+ ),
62
+ ).toEqual({ src: "assets/a.png" });
63
+ });
64
+
65
+ it("a non-numeric width", () => {
66
+ // Width reaches a DOM attribute, so anything but digits is refused
67
+ // rather than passed along to be interpreted.
68
+ expect(parseSafeImg('<img src="assets/a.png" width="600px">')).toEqual({
69
+ src: "assets/a.png",
70
+ });
71
+ });
72
+ });
73
+
74
+ describe("refuses the whole element", () => {
75
+ const rejected = [
76
+ ["a javascript: src", '<img src="javascript:alert(1)">'],
77
+ ["an uppercase JavaScript: src", '<img src="JaVaScRiPt:alert(1)">'],
78
+ [
79
+ "a javascript: src with an embedded newline",
80
+ '<img src="java\nscript:alert(1)">',
81
+ ],
82
+ ["a data: src", '<img src="data:image/svg+xml;base64,PHN2Zz4=">'],
83
+ ["a remote http src", '<img src="http://evil.test/a.png">'],
84
+ ["a remote https src", '<img src="https://evil.test/a.png">'],
85
+ ["a protocol-relative src", '<img src="//evil.test/a.png">'],
86
+ ["a src that escapes the folio", '<img src="../../etc/passwd">'],
87
+ ["no src at all", '<img alt="nothing">'],
88
+ ["an empty src", '<img src="">'],
89
+ ] as const;
90
+
91
+ for (const [label, html] of rejected) {
92
+ it(label, () => {
93
+ expect(parseSafeImg(html)).toBeUndefined();
94
+ });
95
+ }
96
+ });
97
+
98
+ describe("refuses anything that is not a lone img", () => {
99
+ const rejected = [
100
+ ["a script tag", "<script>alert(1)</script>"],
101
+ ["an iframe", '<iframe src="/x"></iframe>'],
102
+ ["an svg", '<svg onload="alert(1)"></svg>'],
103
+ [
104
+ "an img followed by a script",
105
+ '<img src="assets/a.png"><script>x</script>',
106
+ ],
107
+ ["a tag that merely starts with img", '<image src="assets/a.png">'],
108
+ ["plain text", "not html at all"],
109
+ [
110
+ "an anchor wrapping an img",
111
+ '<a href="/x"><img src="assets/a.png"></a>',
112
+ ],
113
+ ] as const;
114
+
115
+ for (const [label, html] of rejected) {
116
+ it(label, () => {
117
+ expect(parseSafeImg(html)).toBeUndefined();
118
+ });
119
+ }
120
+ });
121
+ });
@@ -193,6 +193,17 @@ export const uiFr: Record<string, string> = {
193
193
 
194
194
  // The `@alepha/ui/admin` back office: users, sessions, API keys, files, jobs,
195
195
  // audits, notifications, payments and parameters.
196
+ "admin.analytics.empty": "Aucune donnée pour cette requête.",
197
+ "admin.analytics.estimated": "Estimé (échantillonné ×$1)",
198
+ "admin.analytics.exactSample": "Exact (aucun échantillonnage sur la fenêtre)",
199
+ "admin.analytics.filters": "Filtres",
200
+ "admin.analytics.groupBy": "Grouper par",
201
+ "admin.analytics.noDatasets":
202
+ "Aucun jeu de données analytics n'est déclaré dans cette application.",
203
+ "admin.analytics.pickDataset": "Choisir un jeu de données",
204
+ "admin.analytics.rowCount": "$1 lignes",
205
+ "admin.analytics.run": "Lancer la requête",
206
+ "admin.analytics.since": "Depuis (jour UTC)",
196
207
  "admin.audits.actionAll": "Toutes les actions",
197
208
  "admin.audits.bulkDelete": "Supprimer la sélection",
198
209
  "admin.audits.bulkDeleteConfirm":
@@ -275,12 +286,26 @@ export const uiFr: Record<string, string> = {
275
286
  "admin.keys.colOwner": "Propriétaire",
276
287
  "admin.keys.colPrefix": "Préfixe",
277
288
  "admin.keys.colScopes": "Rôles",
289
+ "admin.keys.copy": "Copier",
290
+ "admin.keys.copyFailed": "Impossible de copier",
291
+ "admin.keys.create": "Ajouter une clé d'API",
292
+ "admin.keys.createConfirm": "Créer",
293
+ "admin.keys.createDescription":
294
+ "La clé est créée pour votre compte et porte vos rôles actuels.",
295
+ "admin.keys.createNameLabel": "Nom",
296
+ "admin.keys.createNamePlaceholder": "ex. pipeline CI",
297
+ "admin.keys.createNameRequired": "Le nom est requis",
298
+ "admin.keys.createTitle": "Ajouter une clé d'API",
278
299
  "admin.keys.noneSelected": "Aucune clé active dans la sélection",
279
300
  "admin.keys.revoke": "Révoquer",
280
301
  "admin.keys.revokeConfirm":
281
302
  "Révoquer « $1 » ? Les applications qui utilisent cette clé perdront l'accès.",
282
303
  "admin.keys.revokeTitle": "Révoquer la clé d'API",
283
304
  "admin.keys.revoked": "Clé d'API révoquée",
305
+ "admin.keys.tokenDescription":
306
+ "Copiez ce jeton maintenant — il n'est affiché qu'une seule fois et ne peut pas être récupéré.",
307
+ "admin.keys.tokenDone": "Terminé",
308
+ "admin.keys.tokenTitle": "Clé d'API créée",
284
309
  "admin.notifications.bulkDelete": "Supprimer la sélection",
285
310
  "admin.notifications.bulkDeleteConfirm":
286
311
  "Supprimer $1 notification(s) ? L'opération est irréversible.",
@@ -398,6 +423,8 @@ export const uiFr: Record<string, string> = {
398
423
  "admin.userDetail.disabled": "Utilisateur désactivé",
399
424
  "admin.userDetail.disabledBadge": "Désactivé",
400
425
  "admin.userDetail.email": "Adresse e-mail",
426
+ "admin.userDetail.emailCannotBeCleared":
427
+ "L'adresse e-mail ne peut pas être supprimée une fois renseignée",
401
428
  "admin.userDetail.emailRequired": "L'adresse e-mail est requise",
402
429
  "admin.userDetail.emailVerified": "Adresse vérifiée",
403
430
  "admin.userDetail.enable": "Réactiver",
@@ -448,6 +475,8 @@ export const uiFr: Record<string, string> = {
448
475
  "admin.userDetail.tabSessions": "Sessions",
449
476
  "admin.userDetail.thisUser": "cet utilisateur",
450
477
  "admin.userDetail.username": "Identifiant",
478
+ "admin.userDetail.usernameCannotBeCleared":
479
+ "L'identifiant ne peut pas être supprimé une fois renseigné",
451
480
  "admin.userDetail.usernameRequired": "L'identifiant est requis",
452
481
  "admin.userDetail.verified": "Vérifié",
453
482
  "admin.users.active": "Actif",
@@ -497,4 +526,43 @@ export const uiFr: Record<string, string> = {
497
526
  "admin.users.thisUser": "cet utilisateur",
498
527
  "admin.users.verified": "Vérifié",
499
528
  "admin.users.viewProfile": "Voir le profil",
529
+ "admin.workflows.cancel": "Annuler",
530
+ "admin.workflows.cancelConfirm":
531
+ "Arrêter cette exécution ? Les étapes restantes ne seront pas exécutées.",
532
+ "admin.workflows.cancelTitle": "Annuler le workflow",
533
+ "admin.workflows.cancelled": "Workflow annulé",
534
+ "admin.workflows.colCreated": "Créé le",
535
+ "admin.workflows.colDuration": "Durée",
536
+ "admin.workflows.colError": "Erreur",
537
+ "admin.workflows.colFailed": "Échecs",
538
+ "admin.workflows.colName": "Nom",
539
+ "admin.workflows.colOnError": "En cas d'erreur",
540
+ "admin.workflows.colPending": "En attente",
541
+ "admin.workflows.colPriority": "Priorité",
542
+ "admin.workflows.colRunning": "En cours",
543
+ "admin.workflows.colStatus": "Statut",
544
+ "admin.workflows.colStep": "Étape",
545
+ "admin.workflows.colSteps": "Étapes",
546
+ "admin.workflows.colTriggeredBy": "Déclenché par",
547
+ "admin.workflows.compensate": "Compenser",
548
+ "admin.workflows.compensateConfirm":
549
+ "Exécuter les fonctions de compensation de chaque étape terminée, en ordre inverse ?",
550
+ "admin.workflows.compensateTitle": "Compenser le workflow",
551
+ "admin.workflows.compensated": "Compensation lancée",
552
+ "admin.workflows.execsDescription": "Exécutions de ce workflow.",
553
+ "admin.workflows.noExecs": "Aucune exécution pour l'instant.",
554
+ "admin.workflows.none": "Aucun workflow enregistré.",
555
+ "admin.workflows.restart": "Redémarrer",
556
+ "admin.workflows.restartConfirm":
557
+ "Démarrer une nouvelle exécution avec la même charge utile ?",
558
+ "admin.workflows.restartTitle": "Redémarrer le workflow",
559
+ "admin.workflows.restarted": "Workflow redémarré",
560
+ "admin.workflows.retried": "Workflow relancé",
561
+ "admin.workflows.retry": "Relancer",
562
+ "admin.workflows.retryConfirm":
563
+ "Reprendre cette exécution à partir de l'étape en échec ?",
564
+ "admin.workflows.retryTitle": "Relancer le workflow",
565
+ "admin.workflows.searchPlaceholder": "Rechercher…",
566
+ "admin.workflows.statusAll": "Tous les statuts",
567
+ "admin.workflows.viewExecutions": "Voir les exécutions",
500
568
  };
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The attributes an `<img>` may carry through. Everything else — event
3
+ * handlers, `style`, `class`, `srcset`, `usemap` — is dropped.
4
+ */
5
+ const ALLOWED = new Set(["src", "alt", "title", "width", "height"]);
6
+
7
+ /**
8
+ * One `<img …>` tag and nothing else: optional whitespace, the tag, its
9
+ * attributes, an optional self-closing slash, and the end of the string.
10
+ *
11
+ * Anchored at both ends deliberately. A pattern that merely *found* an
12
+ * `<img>` would accept `<img src="a"><script>…</script>` and promote the
13
+ * whole raw node, carrying the script into the document as markup.
14
+ */
15
+ const LONE_IMG = /^\s*<img\s+([^>]*?)\/?>\s*$/i;
16
+
17
+ /**
18
+ * `name="value"`, `name='value'` or `name=value`.
19
+ */
20
+ const ATTRIBUTE = /([a-zA-Z-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g;
21
+
22
+ /**
23
+ * A `src` this reader is willing to load.
24
+ *
25
+ * Allowed: a relative `assets/…` path (what folio content stores) and a
26
+ * same-origin absolute path (`/api/files/…`). Nothing else — no `data:`,
27
+ * no `javascript:`, no remote host, and no `//` protocol-relative URL,
28
+ * which is a remote host wearing a local-looking prefix.
29
+ */
30
+ const isSafeSrc = (src: string): boolean => {
31
+ // Drop every C0 control character and space before looking for a scheme.
32
+ // Browsers ignore them while parsing a URL, so a literal tab or newline
33
+ // inside the attribute would otherwise walk `java\nscript:` past a naive
34
+ // prefix check and still execute.
35
+ //
36
+ // Done by code point rather than by a regex character class: a class
37
+ // spanning control characters is unreadable and linters reject it
38
+ // outright. The bound says what it means.
39
+ let stripped = "";
40
+ for (const character of src) {
41
+ if ((character.codePointAt(0) ?? 0) > 0x20) stripped += character;
42
+ }
43
+ const normalized = stripped.toLowerCase();
44
+ if (!normalized) return false;
45
+ if (normalized.includes(":")) return false;
46
+ if (normalized.startsWith("//")) return false;
47
+ // `..` would address something outside the folio's own assets.
48
+ if (normalized.includes("..")) return false;
49
+ return normalized.startsWith("assets/") || normalized.startsWith("/");
50
+ };
51
+
52
+ /**
53
+ * Parse a raw HTML string into the attributes of a safe `<img>`, or
54
+ * `undefined` if it is anything else.
55
+ *
56
+ * Exported and tested directly because this is the entire XSS surface of the
57
+ * markdown reader: `MarkdownView` renders user-authored content and does NOT
58
+ * use `rehype-raw`, so raw HTML is escaped to text everywhere except here.
59
+ *
60
+ * Deliberately string-based rather than `innerHTML`-based: this runs during
61
+ * SSR where there is no DOM, and a parser that only ever produces an
62
+ * allowlisted attribute bag cannot be tricked into producing a different
63
+ * element.
64
+ */
65
+ export const parseSafeImg = (
66
+ html: string,
67
+ ): Record<string, string> | undefined => {
68
+ const match = LONE_IMG.exec(html);
69
+ if (!match) return undefined;
70
+
71
+ const attributes: Record<string, string> = {};
72
+ ATTRIBUTE.lastIndex = 0;
73
+ let found: RegExpExecArray | null = ATTRIBUTE.exec(match[1]);
74
+ while (found) {
75
+ const name = found[1].toLowerCase();
76
+ const value = found[2] ?? found[3] ?? found[4] ?? "";
77
+ if (ALLOWED.has(name)) {
78
+ // `width`/`height` reach a DOM attribute, so only digits pass —
79
+ // anything else is refused rather than handed over to be interpreted.
80
+ if (name === "width" || name === "height") {
81
+ if (/^\d+$/.test(value)) attributes[name] = value;
82
+ } else {
83
+ attributes[name] = value;
84
+ }
85
+ }
86
+ found = ATTRIBUTE.exec(match[1]);
87
+ }
88
+
89
+ if (!attributes.src || !isSafeSrc(attributes.src)) return undefined;
90
+ return attributes;
91
+ };
92
+
93
+ /**
94
+ * Minimal shape of the hast nodes this plugin walks. Typed locally rather
95
+ * than pulled from `@types/hast` — the package is not a dependency here, and
96
+ * this is the whole of what the transform touches.
97
+ */
98
+ interface RawNode {
99
+ type: string;
100
+ value?: string;
101
+ tagName?: string;
102
+ properties?: Record<string, unknown>;
103
+ children?: RawNode[];
104
+ }
105
+
106
+ /**
107
+ * Promote `<img …>` raw HTML into a real element, and leave every other raw
108
+ * node alone.
109
+ *
110
+ * ## Why not `rehype-raw`
111
+ *
112
+ * `rehype-raw` re-parses ALL raw HTML into elements, which is the correct
113
+ * tool when the markdown is trusted. Folio content is written by users and
114
+ * rendered to other project members, so enabling it would turn every
115
+ * markdown surface in the app into an HTML injection point — against the
116
+ * explicit posture of the rest of this codebase.
117
+ *
118
+ * This plugin is the narrow alternative: exactly one tag, an attribute
119
+ * allowlist, and a `src` scheme check. It exists because MDXEditor
120
+ * serialises a *resized* image as `<img width="600" src="…" />` (an
121
+ * un-resized one stays plain `![alt](src)` markdown), so without it a resize
122
+ * would render as escaped text.
123
+ *
124
+ * React-markdown converts any surviving raw node to a text node, so anything
125
+ * this transform declines keeps the existing, safe behaviour.
126
+ */
127
+ export const rehypeSafeImg = () => {
128
+ const visit = (node: RawNode): void => {
129
+ const children = node.children;
130
+ if (!children) return;
131
+ for (let i = 0; i < children.length; i++) {
132
+ const child = children[i];
133
+ if (child.type === "raw" && typeof child.value === "string") {
134
+ const attributes = parseSafeImg(child.value);
135
+ if (attributes) {
136
+ children[i] = {
137
+ type: "element",
138
+ tagName: "img",
139
+ properties: attributes,
140
+ children: [],
141
+ };
142
+ }
143
+ continue;
144
+ }
145
+ visit(child);
146
+ }
147
+ };
148
+
149
+ return (tree: RawNode): void => visit(tree);
150
+ };
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Bounds and encoding for a browser-side downscale.
3
+ */
4
+ export interface ResizeImageOptions {
5
+ /**
6
+ * Widest the result may be, in pixels.
7
+ */
8
+ maxWidth: number;
9
+
10
+ /**
11
+ * Tallest the result may be. Defaults to `maxWidth`.
12
+ */
13
+ maxHeight?: number;
14
+
15
+ /**
16
+ * Output MIME type. WebP by default: the browser's encoder is **lossy** and
17
+ * keeps the alpha channel, which no wasm build available to the server can
18
+ * do — a transparent logo at 128px is a few kilobytes here and roughly five
19
+ * times that server-side.
20
+ *
21
+ * @default "image/webp"
22
+ */
23
+ type?: string;
24
+
25
+ /**
26
+ * Encoder quality, 0-1.
27
+ *
28
+ * @default 0.82
29
+ */
30
+ quality?: number;
31
+ }
32
+
33
+ /**
34
+ * Downscales an image in the browser before it is uploaded.
35
+ *
36
+ * Worth doing even though the server enforces the same bounds: this is what
37
+ * stops the megabytes leaving the machine at all. Production project icons
38
+ * averaged 667 KB and reached the full 2 MB cap to fill a 32px box, so the
39
+ * upload itself was the slow part of setting one.
40
+ *
41
+ * **Returns the input untouched** when it is not a raster image, when it
42
+ * already fits, or when the browser lacks `OffscreenCanvas`/`createImageBitmap`
43
+ * — including SVG, which has no pixels to resample and would be rasterised into
44
+ * something worse than it started. So this is a best-effort downscale, not a
45
+ * gate: the storage's `maxSize` is what bounds the pathological case.
46
+ *
47
+ * The browser is also the *better* encoder here, which is why the work belongs
48
+ * on this side. `convertToBlob` produces lossy WebP with an alpha channel;
49
+ * the wasm codecs available to an edge runtime offer lossless WebP (roughly
50
+ * five times the bytes) or JPEG, which has no alpha at all and turns a
51
+ * transparent logo's background black.
52
+ */
53
+ export const resizeImage = async (
54
+ file: File,
55
+ options: ResizeImageOptions,
56
+ ): Promise<File> => {
57
+ if (!file.type.startsWith("image/") || file.type === "image/svg+xml") {
58
+ return file;
59
+ }
60
+
61
+ if (
62
+ typeof createImageBitmap !== "function" ||
63
+ typeof OffscreenCanvas !== "function"
64
+ ) {
65
+ return file;
66
+ }
67
+
68
+ const maxWidth = options.maxWidth;
69
+ const maxHeight = options.maxHeight ?? options.maxWidth;
70
+ const type = options.type ?? "image/webp";
71
+
72
+ let bitmap: ImageBitmap | undefined;
73
+
74
+ try {
75
+ bitmap = await createImageBitmap(file);
76
+
77
+ const scale = Math.min(
78
+ 1,
79
+ maxWidth / bitmap.width,
80
+ maxHeight / bitmap.height,
81
+ );
82
+ if (scale === 1) {
83
+ return file;
84
+ }
85
+
86
+ // A dimension can round to 0 on an extreme aspect ratio, and a
87
+ // zero-pixel canvas throws.
88
+ const width = Math.max(1, Math.round(bitmap.width * scale));
89
+ const height = Math.max(1, Math.round(bitmap.height * scale));
90
+
91
+ const canvas = new OffscreenCanvas(width, height);
92
+ const context = canvas.getContext("2d");
93
+ if (!context) {
94
+ return file;
95
+ }
96
+
97
+ context.imageSmoothingEnabled = true;
98
+ context.imageSmoothingQuality = "high";
99
+ context.drawImage(bitmap, 0, 0, width, height);
100
+
101
+ const blob = await canvas.convertToBlob({
102
+ type,
103
+ quality: options.quality ?? 0.82,
104
+ });
105
+
106
+ // A browser that does not support the requested encoder silently falls
107
+ // back to PNG, which on a photo is bigger than the JPEG it came from.
108
+ // Handing back the original is the honest outcome.
109
+ if (blob.type !== type || blob.size >= file.size) {
110
+ return file;
111
+ }
112
+
113
+ return new File([blob], renameFor(file.name, blob.type), {
114
+ type: blob.type,
115
+ lastModified: file.lastModified,
116
+ });
117
+ } catch {
118
+ // A corrupt or unsupported image must not cost the user their upload —
119
+ // let the server have its say about the original.
120
+ return file;
121
+ } finally {
122
+ bitmap?.close();
123
+ }
124
+ };
125
+
126
+ /**
127
+ * Swaps the extension so the name matches the bytes. A file still called
128
+ * `.png` that is really WebP confuses everything downstream that trusts it.
129
+ */
130
+ const renameFor = (name: string, type: string): string => {
131
+ const extension = type.split("/")[1]?.replace("jpeg", "jpg") ?? "bin";
132
+ const dot = name.lastIndexOf(".");
133
+ const stem = dot > 0 ? name.slice(0, dot) : name;
134
+ return `${stem}.${extension}`;
135
+ };