ep_media_upload 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 DCastelone
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
191
+
package/README.md ADDED
@@ -0,0 +1,266 @@
1
+ # ep_media_upload – BETA: Etherpad Media Upload Plugin
2
+
3
+ ## Overview
4
+
5
+ A lightweight Etherpad plugin that adds file upload capability via an S3 presigned URL workflow. Upon successful upload, a hyperlink is inserted into the document using the same format as `ep_hyperlinked_text`, making the two plugins fully compatible.
6
+
7
+ ---
8
+
9
+ ## Features
10
+
11
+ ### Toolbar Integration
12
+ - **Paperclip icon** button in the left editbar menu
13
+ - Button is **hidden in read-only mode** (uses `acl-write` class)
14
+ - Triggers native file picker dialog on click
15
+
16
+ ### Upload Workflow
17
+ - **Client-side presigned URL pattern** (identical to ep_images_extended)
18
+ 1. Client requests presigned PUT URL from Etherpad server
19
+ 2. Server generates presigned URL using AWS SDK v3 (credentials from environment variables, not settings.json)
20
+ 3. Client uploads file directly to S3 (server never touches file)
21
+ 4. On success, client inserts hyperlink into document
22
+ - **No base64 or local storage options** – S3 only
23
+ - **Scalable & secure**: Server only generates presigned URLs, no file handling
24
+
25
+ ### File Restrictions
26
+ - **Allowed file types**: Configurable via `settings.json` (array of extensions without dots)
27
+ - **Maximum file size**: Configurable via `settings.json` (in bytes)
28
+
29
+ ### Document Integration
30
+ - On upload success, inserts a **hyperlink** into the document
31
+ - **Link text**: Original filename (e.g., "quarterly-report.pdf")
32
+ - **Link URL**: S3 public/CDN URL for direct download
33
+ - **Hyperlink format**: 100% compatible with `ep_hyperlinked_text` plugin
34
+ - Uses `hyperlink` attribute with URL value
35
+ - Renders as clickable `<a>` tag with `target="_blank"`
36
+
37
+ ### Upload Feedback UI
38
+ - **Progress modal** during upload:
39
+ - Shows "Uploading..." message
40
+ - Basic visual indicator (e.g., spinner or progress text)
41
+ - **Success state**: Brief confirmation, then modal dismisses
42
+ - **Error state**: Shows error message with dismiss button
43
+ - Modal positioned center-screen (similar to ep_images_extended loader)
44
+
45
+ ---
46
+
47
+ ## Configuration (settings.json)
48
+
49
+ ```jsonc
50
+ "ep_media_upload": {
51
+ "storage": {
52
+ "type": "s3_presigned", // Only supported type
53
+ "region": "us-east-1", // AWS region
54
+ "bucket": "my-bucket-name", // S3 bucket name
55
+ "keyPrefix": "uploads/", // Optional S3 key prefix (for CloudFront path-based routing)
56
+ "publicURL": "https://cdn.example.com/uploads/", // Optional CDN URL (should include prefix if using keyPrefix)
57
+ "expires": 900 // Presigned URL expiry in seconds (default 600)
58
+ },
59
+ "fileTypes": ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "mp3", "mp4", "wav", "mov", "zip", "txt"],
60
+ "maxFileSize": 52428800 // 50 MB in bytes
61
+ }
62
+ ```
63
+
64
+ ### Storage Options Explained
65
+
66
+ | Option | Description |
67
+ |--------|-------------|
68
+ | `type` | Must be `"s3_presigned"` (only supported storage type) |
69
+ | `region` | AWS region (e.g., `"us-east-1"`) |
70
+ | `bucket` | S3 bucket name |
71
+ | `keyPrefix` | Optional prefix for S3 keys (e.g., `"uploads/"` → keys become `uploads/padId/uuid.ext`) |
72
+ | `publicURL` | Optional CDN/custom URL base. If using `keyPrefix`, include it in this URL. |
73
+ | `expires` | Presigned URL expiry in seconds (default: 600) |
74
+
75
+ **Example with CloudFront path-based routing:**
76
+ ```jsonc
77
+ "storage": {
78
+ "type": "s3_presigned",
79
+ "region": "us-east-1",
80
+ "bucket": "my-bucket",
81
+ "keyPrefix": "uploads/", // S3 key: uploads/padId/uuid.pdf
82
+ "publicURL": "https://d123.cloudfront.net/uploads/" // Public URL includes prefix
83
+ }
84
+ ```
85
+
86
+ ### Environment Variables (AWS Credentials)
87
+ - `AWS_ACCESS_KEY_ID`
88
+ - `AWS_SECRET_ACCESS_KEY`
89
+ - `AWS_SESSION_TOKEN` (optional, for temporary credentials)
90
+
91
+ ---
92
+
93
+ ## File Structure
94
+
95
+ ```
96
+ ep_media_upload/
97
+ ├── ep.json # Plugin manifest (hooks registration)
98
+ ├── index.js # Server-side hooks (presign endpoint, clientVars)
99
+ ├── package.json # NPM package definition
100
+ ├── locales/
101
+ │ └── en.json # English translations
102
+ ├── static/
103
+ │ ├── css/
104
+ │ │ └── ep_media_upload.css # Modal styles
105
+ │ └── js/
106
+ │ └── clientHooks.js # Client-side upload logic
107
+ └── templates/
108
+ ├── uploadButton.ejs # Toolbar button HTML
109
+ └── uploadModal.ejs # Progress/error modal HTML
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Hook Registration (ep.json)
115
+
116
+ ### Client Hooks
117
+ - `postToolbarInit` – Register toolbar button command
118
+ - `postAceInit` – (Optional) Any initialization after editor ready
119
+
120
+ ### Server Hooks
121
+ - `eejsBlock_editbarMenuLeft` – Inject toolbar button HTML
122
+ - `eejsBlock_body` – Inject modal HTML
123
+ - `expressConfigure` – Register `/p/:padId/pluginfw/ep_media_upload/s3_presign` endpoint
124
+ - `clientVars` – Pass config to client (fileTypes, maxFileSize, storageType)
125
+ - `loadSettings` – Sync settings to runtime
126
+
127
+ ---
128
+
129
+ ## Server Endpoint: Presign
130
+
131
+ ### Route
132
+ ```
133
+ GET /p/:padId/pluginfw/ep_media_upload/s3_presign?name=<filename>&type=<mimetype>
134
+ ```
135
+
136
+ ### Authentication
137
+ - Validates session (cookie-based or express session)
138
+ - Rate limiting: Max 30 requests per IP per minute (configurable)
139
+
140
+ ### Response
141
+ ```json
142
+ {
143
+ "signedUrl": "https://bucket.s3.region.amazonaws.com/padId/uuid.ext?...",
144
+ "publicUrl": "https://cdn.example.com/padId/uuid.ext"
145
+ }
146
+ ```
147
+
148
+ ### Security
149
+ - File extension validated against allowed `fileTypes`
150
+ - Unique filename generated: `<padId>/<uuid>.<ext>`
151
+ - MIME type passed to S3 for proper Content-Type header
152
+
153
+ ---
154
+
155
+ ## Client Upload Flow
156
+
157
+ 1. User clicks paperclip button
158
+ 2. File picker opens (native `<input type="file">`)
159
+ 3. User selects file
160
+ 4. **Validation** (client-side):
161
+ - Check file extension against `clientVars.ep_media_upload.fileTypes`
162
+ - Check file size against `clientVars.ep_media_upload.maxFileSize`
163
+ - Show error modal if validation fails
164
+ 5. **Show upload modal** with "Uploading..." state
165
+ 6. **Request presigned URL** from server
166
+ 7. **PUT file to S3** using presigned URL
167
+ 8. **On success**:
168
+ - Show brief success message
169
+ - Dismiss modal
170
+ - Insert hyperlink at cursor position using `ace_doInsertMediaLink()`
171
+ 9. **On failure**:
172
+ - Show error message in modal
173
+ - User dismisses manually
174
+
175
+ ---
176
+
177
+ ## Hyperlink Insertion
178
+
179
+ Uses the same mechanism as `ep_hyperlinked_text`:
180
+
181
+ ```javascript
182
+ // Insert text with hyperlink attribute
183
+ const filename = file.name; // e.g., "report.pdf"
184
+ const url = publicUrl; // e.g., "https://cdn.example.com/padId/abc123.pdf"
185
+
186
+ // Insert filename text at cursor
187
+ editorInfo.ace_replaceRange(cursorPos, cursorPos, filename);
188
+
189
+ // Apply hyperlink attribute to the inserted text
190
+ docMan.setAttributesOnRange(
191
+ [cursorPos[0], cursorPos[1]],
192
+ [cursorPos[0], cursorPos[1] + filename.length],
193
+ [['hyperlink', url]]
194
+ );
195
+ ```
196
+
197
+ This ensures:
198
+ - Full compatibility with ep_hyperlinked_text rendering
199
+ - Clickable links that open in new tab
200
+ - Proper HTML export with `<a>` tags
201
+
202
+ ---
203
+
204
+ ## Error Handling
205
+
206
+ | Error | User Message |
207
+ |-------|--------------|
208
+ | Invalid file type | "File type not allowed. Allowed types: pdf, doc, ..." |
209
+ | File too large | "File is too large. Maximum size: 50 MB." |
210
+ | Presign request failed | "Upload failed. Please try again." |
211
+ | S3 upload failed | "Upload failed. Please try again." |
212
+ | Network error | "Network error. Please check your connection." |
213
+
214
+ ---
215
+
216
+ ## Compatibility Notes
217
+
218
+ - **Etherpad version**: Requires >= 1.8.6 (for ESM Settings module compatibility)
219
+ - **Node.js version**: >= 18.0.0
220
+ - **ep_hyperlinked_text**: Fully compatible – inserted links render/export identically
221
+ - **Read-only pads**: Upload button automatically hidden
222
+
223
+ ---
224
+
225
+ ## Security Considerations
226
+
227
+ 1. **No server-side file handling**: Files never touch the Etherpad server
228
+ 2. **Authentication required**: Presign endpoint validates session
229
+ 3. **Rate limiting**: Prevents presign endpoint abuse
230
+ 4. **File type allowlist**: Only configured extensions accepted
231
+ 5. **Unique filenames**: UUIDs prevent enumeration/overwrites
232
+ 6. **CORS on S3**: Bucket must allow PUT from pad origins
233
+
234
+ ---
235
+
236
+ ## S3 Bucket CORS Configuration
237
+
238
+ Required CORS policy for the S3 bucket:
239
+
240
+ ```json
241
+ [
242
+ {
243
+ "AllowedOrigins": ["https://your-etherpad-domain.com"],
244
+ "AllowedMethods": ["PUT"],
245
+ "AllowedHeaders": ["Content-Type"],
246
+ "MaxAgeSeconds": 3000
247
+ }
248
+ ]
249
+ ```
250
+
251
+ ---
252
+
253
+ ## Dependencies
254
+
255
+ ```json
256
+ {
257
+ "dependencies": {
258
+ "@aws-sdk/client-s3": "^3.555.0",
259
+ "@aws-sdk/s3-request-presigner": "^3.555.0"
260
+ },
261
+ "peerDependencies": {
262
+ "ep_etherpad-lite": ">=1.8.6"
263
+ }
264
+ }
265
+ ```
266
+
package/ep.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "parts": [
3
+ {
4
+ "name": "main",
5
+ "client_hooks": {
6
+ "postToolbarInit": "ep_media_upload/static/js/clientHooks",
7
+ "aceInitialized": "ep_media_upload/static/js/clientHooks",
8
+ "postAceInit": "ep_media_upload/static/js/clientHooks"
9
+ },
10
+ "hooks": {
11
+ "eejsBlock_editbarMenuLeft": "ep_media_upload/index",
12
+ "eejsBlock_body": "ep_media_upload/index",
13
+ "expressConfigure": "ep_media_upload/index",
14
+ "clientVars": "ep_media_upload/index",
15
+ "loadSettings": "ep_media_upload/index"
16
+ }
17
+ }
18
+ ]
19
+ }
20
+
package/index.js ADDED
@@ -0,0 +1,361 @@
1
+ 'use strict';
2
+
3
+ const eejs = require('ep_etherpad-lite/node/eejs/');
4
+ // Compat: Etherpad 2.4+ uses ESM for Settings. Support both CJS and ESM.
5
+ const settingsModule = require('ep_etherpad-lite/node/utils/Settings');
6
+ const settings = settingsModule.default || settingsModule;
7
+ const { randomUUID } = require('crypto');
8
+ const path = require('path');
9
+ const url = require('url');
10
+
11
+ // Security Manager for pad access verification
12
+ let securityManager;
13
+ try {
14
+ securityManager = require('ep_etherpad-lite/node/db/SecurityManager');
15
+ } catch (e) {
16
+ console.warn('[ep_media_upload] SecurityManager not available');
17
+ }
18
+
19
+ // AWS SDK v3 for presigned URLs
20
+ let S3Client, PutObjectCommand, getSignedUrl;
21
+ try {
22
+ ({ S3Client, PutObjectCommand } = require('@aws-sdk/client-s3'));
23
+ ({ getSignedUrl } = require('@aws-sdk/s3-request-presigner'));
24
+ } catch (e) {
25
+ console.warn('[ep_media_upload] AWS SDK not installed; s3_presigned storage will not work.');
26
+ }
27
+
28
+ // Simple logger
29
+ const logger = {
30
+ debug: console.debug.bind(console),
31
+ info: console.info.bind(console),
32
+ warn: console.warn.bind(console),
33
+ error: console.error.bind(console),
34
+ };
35
+
36
+ // ============================================================================
37
+ // Rate Limiter with Periodic Cleanup
38
+ // ============================================================================
39
+ const _presignRateStore = new Map();
40
+ const PRESIGN_RATE_WINDOW_MS = 60 * 1000; // 1 minute
41
+ const PRESIGN_RATE_MAX = 30; // max 30 presigns per IP per min
42
+ const RATE_CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // cleanup every 5 minutes
43
+
44
+ // Periodic cleanup to prevent memory leak from stale IPs
45
+ setInterval(() => {
46
+ const now = Date.now();
47
+ for (const [ip, stamps] of _presignRateStore.entries()) {
48
+ const validStamps = stamps.filter((t) => t > now - PRESIGN_RATE_WINDOW_MS);
49
+ if (validStamps.length === 0) {
50
+ _presignRateStore.delete(ip);
51
+ } else {
52
+ _presignRateStore.set(ip, validStamps);
53
+ }
54
+ }
55
+ }, RATE_CLEANUP_INTERVAL_MS).unref(); // unref() so it doesn't prevent process exit
56
+
57
+ // Utility: basic per-IP sliding-window rate limit
58
+ const _rateLimitCheck = (ip) => {
59
+ const now = Date.now();
60
+ let stamps = _presignRateStore.get(ip) || [];
61
+ stamps = stamps.filter((t) => t > now - PRESIGN_RATE_WINDOW_MS);
62
+ if (stamps.length >= PRESIGN_RATE_MAX) return false;
63
+ stamps.push(now);
64
+ _presignRateStore.set(ip, stamps);
65
+ return true;
66
+ };
67
+
68
+ // ============================================================================
69
+ // Input Validation Helpers
70
+ // ============================================================================
71
+
72
+ /**
73
+ * Validate padId to prevent path traversal and injection attacks.
74
+ * Returns true if valid, false if invalid.
75
+ */
76
+ const isValidPadId = (padId) => {
77
+ if (!padId || typeof padId !== 'string') return false;
78
+ // Reject path traversal sequences
79
+ if (padId.includes('..')) return false;
80
+ // Reject null bytes
81
+ if (padId.includes('\0')) return false;
82
+ // Allow alphanumeric, hyphens, underscores, and $ (for group pads)
83
+ // This is permissive but still prevents dangerous characters
84
+ const safePattern = /^[a-zA-Z0-9_\-$]+$/;
85
+ return safePattern.test(padId);
86
+ };
87
+
88
+ /**
89
+ * Validate filename extension.
90
+ * Returns the extension (without dot, lowercase) or null if invalid.
91
+ */
92
+ const getValidExtension = (filename) => {
93
+ if (!filename || typeof filename !== 'string') return null;
94
+ const ext = path.extname(filename);
95
+ if (!ext || ext === '.') return null; // No extension or just a dot
96
+ return ext.slice(1).toLowerCase(); // Remove leading dot
97
+ };
98
+
99
+ /**
100
+ * MIME type to extension mapping for validation.
101
+ * Maps file extensions to their valid MIME types.
102
+ */
103
+ const EXTENSION_MIME_MAP = {
104
+ // Documents
105
+ pdf: ['application/pdf'],
106
+ doc: ['application/msword'],
107
+ docx: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
108
+ xls: ['application/vnd.ms-excel'],
109
+ xlsx: ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
110
+ ppt: ['application/vnd.ms-powerpoint'],
111
+ pptx: ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],
112
+ txt: ['text/plain'],
113
+ rtf: ['application/rtf', 'text/rtf'],
114
+ csv: ['text/csv', 'text/plain', 'application/csv'],
115
+
116
+ // Images
117
+ jpg: ['image/jpeg'],
118
+ jpeg: ['image/jpeg'],
119
+ png: ['image/png'],
120
+ gif: ['image/gif'],
121
+ webp: ['image/webp'],
122
+ bmp: ['image/bmp'],
123
+ svg: ['image/svg+xml'],
124
+
125
+ // Audio
126
+ mp3: ['audio/mpeg', 'audio/mp3'],
127
+ wav: ['audio/wav', 'audio/wave', 'audio/x-wav'],
128
+ ogg: ['audio/ogg'],
129
+ m4a: ['audio/mp4', 'audio/x-m4a'],
130
+ flac: ['audio/flac'],
131
+
132
+ // Video
133
+ mp4: ['video/mp4'],
134
+ mov: ['video/quicktime'],
135
+ avi: ['video/x-msvideo'],
136
+ mkv: ['video/x-matroska'],
137
+ webm: ['video/webm'],
138
+
139
+ // Archives
140
+ zip: ['application/zip', 'application/x-zip-compressed'],
141
+ rar: ['application/vnd.rar', 'application/x-rar-compressed'],
142
+ '7z': ['application/x-7z-compressed'],
143
+ tar: ['application/x-tar'],
144
+ gz: ['application/gzip', 'application/x-gzip'],
145
+ };
146
+
147
+ /**
148
+ * Validate that the MIME type matches the file extension.
149
+ * Returns true if valid, false if mismatch detected.
150
+ * If extension is not in our map, we allow it (permissive for unknown types).
151
+ */
152
+ const isValidMimeForExtension = (extension, mimeType) => {
153
+ if (!extension || !mimeType) return false;
154
+
155
+ const allowedMimes = EXTENSION_MIME_MAP[extension.toLowerCase()];
156
+
157
+ // If we don't have a mapping for this extension, allow any MIME type
158
+ // (permissive approach for uncommon file types)
159
+ if (!allowedMimes) return true;
160
+
161
+ // Check if the provided MIME type matches any allowed MIME for this extension
162
+ const normalizedMime = mimeType.toLowerCase().split(';')[0].trim(); // Handle "text/plain; charset=utf-8"
163
+ return allowedMimes.some(allowed => allowed === normalizedMime);
164
+ };
165
+
166
+ // ============================================================================
167
+ // Hooks
168
+ // ============================================================================
169
+
170
+ /**
171
+ * loadSettings hook
172
+ * Sync ep_media_upload config into the runtime Settings singleton
173
+ */
174
+ exports.loadSettings = (hookName, args, cb) => {
175
+ try {
176
+ const runtimeSettings = settingsModule.default || settingsModule;
177
+ if (args && args.settings && args.settings.ep_media_upload) {
178
+ runtimeSettings.ep_media_upload = args.settings.ep_media_upload;
179
+ }
180
+ } catch (e) {
181
+ console.warn('[ep_media_upload] Failed to sync settings:', e);
182
+ }
183
+ cb();
184
+ };
185
+
186
+ /**
187
+ * clientVars hook
188
+ * Exposes plugin settings to client code via clientVars
189
+ */
190
+ exports.clientVars = (hookName, args, cb) => {
191
+ const pluginSettings = {
192
+ storageType: 's3_presigned',
193
+ };
194
+
195
+ if (!settings.ep_media_upload) {
196
+ settings.ep_media_upload = {};
197
+ }
198
+
199
+ // Pass allowed file types
200
+ if (settings.ep_media_upload.fileTypes) {
201
+ pluginSettings.fileTypes = settings.ep_media_upload.fileTypes;
202
+ }
203
+
204
+ // Pass max file size
205
+ if (settings.ep_media_upload.maxFileSize) {
206
+ pluginSettings.maxFileSize = settings.ep_media_upload.maxFileSize;
207
+ }
208
+
209
+ return cb({ ep_media_upload: pluginSettings });
210
+ };
211
+
212
+ /**
213
+ * eejsBlock_editbarMenuLeft hook
214
+ * Inject toolbar button
215
+ */
216
+ exports.eejsBlock_editbarMenuLeft = (hookName, args, cb) => {
217
+ if (args.renderContext.isReadOnly) return cb();
218
+ args.content += eejs.require('ep_media_upload/templates/uploadButton.ejs');
219
+ return cb();
220
+ };
221
+
222
+ /**
223
+ * eejsBlock_body hook
224
+ * Inject modal HTML and CSS
225
+ */
226
+ exports.eejsBlock_body = (hookName, args, cb) => {
227
+ const modal = eejs.require('ep_media_upload/templates/uploadModal.ejs');
228
+ args.content += modal;
229
+ args.content += "<link href='../static/plugins/ep_media_upload/static/css/ep_media_upload.css' rel='stylesheet'>";
230
+ return cb();
231
+ };
232
+
233
+ /**
234
+ * expressConfigure hook
235
+ * Register the S3 presign endpoint
236
+ */
237
+ exports.expressConfigure = (hookName, context) => {
238
+ logger.info('[ep_media_upload] Registering presign endpoint');
239
+
240
+ // Route: GET /p/:padId/pluginfw/ep_media_upload/s3_presign
241
+ context.app.get('/p/:padId/pluginfw/ep_media_upload/s3_presign', async (req, res) => {
242
+ const { padId } = req.params;
243
+
244
+ /* ------------------ Validate padId ------------------ */
245
+ if (!isValidPadId(padId)) {
246
+ return res.status(400).json({ error: 'Invalid pad ID' });
247
+ }
248
+
249
+ /* ------------------ Pad Access Verification ------------------ */
250
+ // Use Etherpad's SecurityManager to verify user has access to this pad
251
+ if (securityManager) {
252
+ try {
253
+ const sessionCookie = req.cookies?.sessionID || null;
254
+ const token = req.cookies?.token || null;
255
+ const user = req.session?.user || null;
256
+
257
+ const accessResult = await securityManager.checkAccess(padId, sessionCookie, token, user);
258
+ if (accessResult.accessStatus !== 'grant') {
259
+ return res.status(403).json({ error: 'Access denied to this pad' });
260
+ }
261
+ } catch (authErr) {
262
+ logger.error('[ep_media_upload] Access check error:', authErr);
263
+ return res.status(500).json({ error: 'Access verification failed' });
264
+ }
265
+ } else {
266
+ // Fallback: basic cookie check if SecurityManager unavailable
267
+ const hasExpressSession = req.session && (req.session.user || req.session.authorId);
268
+ const hasPadCookie = req.cookies && (req.cookies.sessionID || req.cookies.token);
269
+ if (!hasExpressSession && !hasPadCookie) {
270
+ return res.status(401).json({ error: 'Authentication required' });
271
+ }
272
+ }
273
+
274
+ /* ------------------ Rate limiting --------------------- */
275
+ const ip = req.ip || req.headers['x-forwarded-for'] || req.connection?.remoteAddress || 'unknown';
276
+ if (!_rateLimitCheck(ip)) {
277
+ return res.status(429).json({ error: 'Too many presign requests' });
278
+ }
279
+
280
+ try {
281
+ const storageCfg = settings.ep_media_upload && settings.ep_media_upload.storage;
282
+ if (!storageCfg || storageCfg.type !== 's3_presigned') {
283
+ return res.status(400).json({ error: 's3_presigned storage not configured' });
284
+ }
285
+
286
+ if (!S3Client || !PutObjectCommand || !getSignedUrl) {
287
+ return res.status(500).json({ error: 'AWS SDK not available on server' });
288
+ }
289
+
290
+ const { bucket, region, publicURL, expires, keyPrefix } = storageCfg;
291
+ if (!bucket || !region) {
292
+ return res.status(500).json({ error: 'Invalid S3 configuration: missing bucket or region' });
293
+ }
294
+
295
+ const { name, type } = req.query;
296
+ if (!name || !type) {
297
+ return res.status(400).json({ error: 'Missing name or type query parameters' });
298
+ }
299
+
300
+ /* ------------- Extension validation ------------ */
301
+ const extName = getValidExtension(name);
302
+ if (!extName) {
303
+ return res.status(400).json({ error: 'Invalid filename: missing extension' });
304
+ }
305
+
306
+ /* ------------- Extension allow-list ------------ */
307
+ if (settings.ep_media_upload && settings.ep_media_upload.fileTypes && Array.isArray(settings.ep_media_upload.fileTypes)) {
308
+ const allowedExts = settings.ep_media_upload.fileTypes;
309
+ if (!allowedExts.includes(extName)) {
310
+ return res.status(400).json({ error: 'File type not allowed' });
311
+ }
312
+ }
313
+
314
+ /* ------------- MIME type validation ------------ */
315
+ // Prevent MIME type spoofing (e.g., uploading .txt with Content-Type: text/html)
316
+ if (!isValidMimeForExtension(extName, type)) {
317
+ logger.warn(`[ep_media_upload] MIME mismatch: ext=${extName}, type=${type}`);
318
+ return res.status(400).json({ error: 'MIME type does not match file extension' });
319
+ }
320
+
321
+ // Build S3 key with optional prefix for path-based routing (e.g., CloudFront origins)
322
+ const prefix = keyPrefix || '';
323
+ const safeExt = `.${extName}`;
324
+ const objectPath = `${padId}/${randomUUID()}${safeExt}`; // e.g., "myPad/abc123.pdf"
325
+ const key = `${prefix}${objectPath}`; // e.g., "uploads/myPad/abc123.pdf"
326
+
327
+ const s3Client = new S3Client({ region }); // credentials from env / IAM role
328
+
329
+ // Extract original filename for Content-Disposition header
330
+ // This ensures files download with their original name instead of the UUID
331
+ const originalFilename = path.basename(name);
332
+ const safeFilename = originalFilename.replace(/[^\w\-_.]/g, '_'); // Sanitize for header
333
+
334
+ const putCommand = new PutObjectCommand({
335
+ Bucket: bucket,
336
+ Key: key,
337
+ ContentType: type,
338
+ // Force download instead of opening in browser
339
+ ContentDisposition: `attachment; filename="${safeFilename}"`,
340
+ });
341
+
342
+ const signedUrl = await getSignedUrl(s3Client, putCommand, { expiresIn: expires || 600 });
343
+
344
+ // Build public URL:
345
+ // - If custom publicURL is set (e.g., CDN), it already includes the prefix path
346
+ // - If no publicURL, use direct S3 URL with full key
347
+ let publicUrl;
348
+ if (publicURL) {
349
+ publicUrl = new url.URL(objectPath, publicURL).toString();
350
+ } else {
351
+ const s3Base = `https://${bucket}.s3.${region}.amazonaws.com/`;
352
+ publicUrl = new url.URL(key, s3Base).toString();
353
+ }
354
+
355
+ return res.json({ signedUrl, publicUrl });
356
+ } catch (err) {
357
+ logger.error('[ep_media_upload] S3 presign error', err);
358
+ return res.status(500).json({ error: 'Failed to generate presigned URL' });
359
+ }
360
+ });
361
+ };
@@ -0,0 +1,12 @@
1
+ {
2
+ "ep_media_upload.toolbar.upload.title": "Upload File",
3
+ "ep_media_upload.error.title": "Upload Error",
4
+ "ep_media_upload.error.fileType": "File type not allowed.",
5
+ "ep_media_upload.error.fileSize": "File is too large. Maximum size is {{maxallowed}} MB.",
6
+ "ep_media_upload.error.uploadFailed": "Upload failed. Please try again.",
7
+ "ep_media_upload.error.networkError": "Network error. Please check your connection.",
8
+ "ep_media_upload.status.uploading": "Uploading...",
9
+ "ep_media_upload.status.success": "Upload complete!",
10
+ "ep_media_upload.button.close": "Close"
11
+ }
12
+
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "ep_media_upload",
3
+ "description": "beta - Upload files to S3 and insert hyperlinks into the pad. Compatible with ep_hyperlinked_text.",
4
+ "version": "0.1.0",
5
+ "author": {
6
+ "name": "DCastelone",
7
+ "url": "https://github.com/dcastelone"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "dependencies": {
11
+ "@aws-sdk/client-s3": "^3.555.0",
12
+ "@aws-sdk/s3-request-presigner": "^3.555.0"
13
+ },
14
+ "peerDependencies": {
15
+ "ep_etherpad-lite": ">=1.8.6"
16
+ },
17
+ "engines": {
18
+ "node": ">=18.0.0"
19
+ },
20
+ "keywords": [
21
+ "etherpad",
22
+ "plugin",
23
+ "ep",
24
+ "media",
25
+ "upload",
26
+ "s3",
27
+ "file",
28
+ "attachment"
29
+ ],
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/dcastelone/ep_media_upload"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/dcastelone/ep_media_upload/issues"
36
+ },
37
+ "homepage": "https://github.com/dcastelone/ep_media_upload"
38
+ }
39
+
@@ -0,0 +1,115 @@
1
+ /* ep_media_upload Modal Styles */
2
+
3
+ .ep-media-upload-modal {
4
+ display: none;
5
+ position: fixed;
6
+ top: 0;
7
+ left: 0;
8
+ width: 100%;
9
+ height: 100%;
10
+ background-color: rgba(0, 0, 0, 0.5);
11
+ z-index: 10000;
12
+ justify-content: center;
13
+ align-items: center;
14
+ }
15
+
16
+ .ep-media-upload-modal.visible {
17
+ display: flex;
18
+ }
19
+
20
+ .ep-media-upload-modal-content {
21
+ background: #fff;
22
+ border-radius: 8px;
23
+ padding: 32px 48px;
24
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25);
25
+ text-align: center;
26
+ min-width: 280px;
27
+ max-width: 400px;
28
+ }
29
+
30
+ .ep-media-upload-state {
31
+ display: flex;
32
+ flex-direction: column;
33
+ align-items: center;
34
+ gap: 16px;
35
+ }
36
+
37
+ /* Spinner */
38
+ .ep-media-upload-spinner {
39
+ width: 40px;
40
+ height: 40px;
41
+ border: 4px solid #e0e0e0;
42
+ border-top-color: #1a73e8;
43
+ border-radius: 50%;
44
+ animation: ep-media-upload-spin 1s linear infinite;
45
+ }
46
+
47
+ @keyframes ep-media-upload-spin {
48
+ to {
49
+ transform: rotate(360deg);
50
+ }
51
+ }
52
+
53
+ /* Icons */
54
+ .ep-media-upload-icon {
55
+ width: 48px;
56
+ height: 48px;
57
+ border-radius: 50%;
58
+ display: flex;
59
+ align-items: center;
60
+ justify-content: center;
61
+ font-size: 24px;
62
+ font-weight: bold;
63
+ }
64
+
65
+ .ep-media-upload-icon-success {
66
+ background-color: #e6f4ea;
67
+ color: #1e8e3e;
68
+ }
69
+
70
+ .ep-media-upload-icon-error {
71
+ background-color: #fce8e6;
72
+ color: #d93025;
73
+ }
74
+
75
+ /* Message text */
76
+ .ep-media-upload-message {
77
+ margin: 0;
78
+ font-size: 16px;
79
+ color: #202124;
80
+ font-weight: 500;
81
+ }
82
+
83
+ .ep-media-upload-error-text {
84
+ color: #d93025;
85
+ }
86
+
87
+ /* Button */
88
+ .ep-media-upload-btn {
89
+ margin-top: 8px;
90
+ padding: 8px 24px;
91
+ font-size: 14px;
92
+ font-weight: 500;
93
+ color: #fff;
94
+ background-color: #1a73e8;
95
+ border: none;
96
+ border-radius: 4px;
97
+ cursor: pointer;
98
+ transition: background-color 0.2s;
99
+ }
100
+
101
+ .ep-media-upload-btn:hover {
102
+ background-color: #1557b0;
103
+ }
104
+
105
+ .ep-media-upload-btn:focus {
106
+ outline: 2px solid #1a73e8;
107
+ outline-offset: 2px;
108
+ }
109
+
110
+ /* Toolbar button icon - paperclip */
111
+ .buttonicon-attachment::before {
112
+ content: "📎";
113
+ font-size: 16px;
114
+ }
115
+
@@ -0,0 +1,277 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * ep_media_upload - Client-side hooks
5
+ *
6
+ * Handles file selection, S3 upload via presigned URL, and hyperlink insertion
7
+ * compatible with ep_hyperlinked_text.
8
+ */
9
+
10
+ console.log('[ep_media_upload] Client hooks loaded');
11
+
12
+ // Store ace context for hyperlink insertion
13
+ let _aceContext = null;
14
+
15
+ /**
16
+ * Modal management functions
17
+ */
18
+ const showModal = (state = 'progress') => {
19
+ const modal = $('#mediaUploadModal');
20
+ const progressEl = $('#mediaUploadProgress');
21
+ const successEl = $('#mediaUploadSuccess');
22
+ const errorEl = $('#mediaUploadError');
23
+
24
+ // Hide all states
25
+ progressEl.hide();
26
+ successEl.hide();
27
+ errorEl.hide();
28
+
29
+ // Show requested state
30
+ if (state === 'progress') {
31
+ progressEl.show();
32
+ } else if (state === 'success') {
33
+ successEl.show();
34
+ } else if (state === 'error') {
35
+ errorEl.show();
36
+ }
37
+
38
+ modal.addClass('visible');
39
+ };
40
+
41
+ const hideModal = () => {
42
+ $('#mediaUploadModal').removeClass('visible');
43
+ };
44
+
45
+ const showError = (message) => {
46
+ $('.ep-media-upload-error-text').text(message);
47
+ showModal('error');
48
+ };
49
+
50
+ const showSuccess = () => {
51
+ showModal('success');
52
+ // Auto-hide after 1.5 seconds
53
+ setTimeout(() => {
54
+ hideModal();
55
+ }, 1500);
56
+ };
57
+
58
+ /**
59
+ * Validate file against configured restrictions
60
+ */
61
+ const validateFile = (file) => {
62
+ const config = clientVars.ep_media_upload || {};
63
+
64
+ // Check file type
65
+ if (config.fileTypes && Array.isArray(config.fileTypes)) {
66
+ const nameParts = file.name.split('.');
67
+ if (nameParts.length < 2) {
68
+ const errorMsg = html10n.get('ep_media_upload.error.fileType') || 'File type not allowed.';
69
+ return { valid: false, error: `${errorMsg} File must have an extension.` };
70
+ }
71
+ const ext = nameParts.pop().toLowerCase();
72
+ if (!config.fileTypes.includes(ext)) {
73
+ const allowedTypes = config.fileTypes.join(', ');
74
+ const errorMsg = html10n.get('ep_media_upload.error.fileType') || 'File type not allowed.';
75
+ return { valid: false, error: `${errorMsg} Allowed: ${allowedTypes}` };
76
+ }
77
+ }
78
+
79
+ // Check file size
80
+ if (config.maxFileSize && file.size > config.maxFileSize) {
81
+ const maxMB = (config.maxFileSize / (1024 * 1024)).toFixed(1);
82
+ const errorMsg = html10n.get('ep_media_upload.error.fileSize', { maxallowed: maxMB })
83
+ || `File is too large. Maximum size is ${maxMB} MB.`;
84
+ return { valid: false, error: errorMsg };
85
+ }
86
+
87
+ return { valid: true };
88
+ };
89
+
90
+ /**
91
+ * Upload file to S3 using presigned URL
92
+ */
93
+ const uploadToS3 = async (file) => {
94
+ // Step 1: Get presigned URL from server
95
+ const queryParams = $.param({ name: file.name, type: file.type });
96
+ const presignResponse = await $.getJSON(
97
+ `${encodeURIComponent(clientVars.padId)}/pluginfw/ep_media_upload/s3_presign?${queryParams}`
98
+ );
99
+
100
+ if (!presignResponse || !presignResponse.signedUrl || !presignResponse.publicUrl) {
101
+ throw new Error('Invalid presign response from server');
102
+ }
103
+
104
+ // Step 2: Upload directly to S3
105
+ const uploadResponse = await fetch(presignResponse.signedUrl, {
106
+ method: 'PUT',
107
+ headers: { 'Content-Type': file.type },
108
+ body: file,
109
+ });
110
+
111
+ if (!uploadResponse.ok) {
112
+ throw new Error(`S3 upload failed with status ${uploadResponse.status}`);
113
+ }
114
+
115
+ return presignResponse.publicUrl;
116
+ };
117
+
118
+ /**
119
+ * Insert hyperlink at cursor position
120
+ * Compatible with ep_hyperlinked_text format
121
+ */
122
+ const doInsertMediaLink = function(url, linkText) {
123
+ const editorInfo = this.editorInfo;
124
+ const docMan = this.documentAttributeManager;
125
+ const rep = editorInfo.ace_getRep();
126
+
127
+ if (!editorInfo || !rep || !rep.selStart || !docMan || !url || !linkText) {
128
+ console.error('[ep_media_upload] Missing context for hyperlink insertion');
129
+ return;
130
+ }
131
+
132
+ const cursorPos = rep.selStart;
133
+ const ZWSP = '\u200B'; // Zero-Width Space for boundary
134
+
135
+ // Insert: ZWSP + linkText + ZWSP (same pattern as ep_hyperlinked_text)
136
+ const textToInsert = ZWSP + linkText + ZWSP;
137
+ editorInfo.ace_replaceRange(cursorPos, cursorPos, textToInsert);
138
+
139
+ // Apply hyperlink attribute to the linkText portion (excluding ZWSPs)
140
+ const linkStart = [cursorPos[0], cursorPos[1] + ZWSP.length];
141
+ const linkEnd = [cursorPos[0], cursorPos[1] + ZWSP.length + linkText.length];
142
+
143
+ docMan.setAttributesOnRange(linkStart, linkEnd, [['hyperlink', url]]);
144
+
145
+ // Move cursor after the inserted content
146
+ const finalPos = [cursorPos[0], cursorPos[1] + textToInsert.length];
147
+ editorInfo.ace_performSelectionChange(finalPos, finalPos, false);
148
+
149
+ console.log('[ep_media_upload] Inserted hyperlink:', linkText, '->', url);
150
+ };
151
+
152
+ /**
153
+ * Handle file selection and upload
154
+ */
155
+ const handleFileUpload = async (file, aceContext) => {
156
+ // Validate file
157
+ const validation = validateFile(file);
158
+ if (!validation.valid) {
159
+ showError(validation.error);
160
+ return;
161
+ }
162
+
163
+ // Show progress modal
164
+ showModal('progress');
165
+
166
+ try {
167
+ // Upload to S3
168
+ const publicUrl = await uploadToS3(file);
169
+
170
+ // Insert hyperlink into document
171
+ aceContext.callWithAce((ace) => {
172
+ ace.ace_doInsertMediaLink(publicUrl, file.name);
173
+ }, 'insertMediaLink', true);
174
+
175
+ // Show success
176
+ showSuccess();
177
+
178
+ } catch (err) {
179
+ console.error('[ep_media_upload] Upload failed:', err);
180
+ const errorMsg = html10n.get('ep_media_upload.error.uploadFailed') || 'Upload failed. Please try again.';
181
+ showError(errorMsg);
182
+ }
183
+ };
184
+
185
+ /**
186
+ * aceInitialized hook
187
+ * Bind the hyperlink insertion function to ace context
188
+ */
189
+ exports.aceInitialized = (hook, context) => {
190
+ context.editorInfo.ace_doInsertMediaLink = doInsertMediaLink.bind(context);
191
+ };
192
+
193
+ /**
194
+ * postAceInit hook
195
+ * Set up modal close button handler
196
+ */
197
+ exports.postAceInit = (hook, context) => {
198
+ _aceContext = context.ace;
199
+
200
+ // Close button handler for error modal
201
+ $(document).on('click', '#mediaUploadErrorClose', () => {
202
+ hideModal();
203
+ });
204
+
205
+ // Click outside modal to close (only for error state)
206
+ $(document).on('click', '#mediaUploadModal', (e) => {
207
+ if (e.target.id === 'mediaUploadModal' && $('#mediaUploadError').is(':visible')) {
208
+ hideModal();
209
+ }
210
+ });
211
+ };
212
+
213
+ /**
214
+ * postToolbarInit hook
215
+ * Register the mediaUpload toolbar command
216
+ */
217
+ exports.postToolbarInit = (hook, context) => {
218
+ const toolbar = context.toolbar;
219
+
220
+ toolbar.registerCommand('mediaUpload', () => {
221
+ // Remove any existing file input (cleanup from previous attempts)
222
+ $('#mediaUploadFileInput').remove();
223
+
224
+ // Create hidden file input
225
+ const fileInput = $('<input>')
226
+ .attr({
227
+ type: 'file',
228
+ id: 'mediaUploadFileInput',
229
+ style: 'position:absolute;left:-9999px;'
230
+ });
231
+
232
+ // Add accept attribute if file types are configured
233
+ if (clientVars.ep_media_upload && clientVars.ep_media_upload.fileTypes) {
234
+ const accept = clientVars.ep_media_upload.fileTypes
235
+ .map(ext => `.${ext}`)
236
+ .join(',');
237
+ fileInput.attr('accept', accept);
238
+ }
239
+
240
+ $('body').append(fileInput);
241
+
242
+ // Cleanup function to remove file input
243
+ const cleanup = () => {
244
+ fileInput.off(); // Remove all event handlers
245
+ fileInput.remove();
246
+ };
247
+
248
+ // Handle file selection - use 'one' so it only fires once
249
+ fileInput.one('change', (e) => {
250
+ const files = e.target.files;
251
+ if (!files || files.length === 0) {
252
+ cleanup();
253
+ return;
254
+ }
255
+
256
+ const file = files[0];
257
+ handleFileUpload(file, context.ace);
258
+ cleanup();
259
+ });
260
+
261
+ // Handle cancel (user closes file picker without selecting)
262
+ // The blur/focus trick: when file picker closes, window regains focus
263
+ $(window).one('focus', () => {
264
+ // Small delay to allow change event to fire first if file was selected
265
+ setTimeout(() => {
266
+ if ($('#mediaUploadFileInput').length > 0) {
267
+ cleanup();
268
+ }
269
+ }, 300);
270
+ });
271
+
272
+ // Trigger file picker
273
+ fileInput.trigger('click');
274
+ });
275
+
276
+ console.log('[ep_media_upload] Toolbar command registered');
277
+ };
@@ -0,0 +1,8 @@
1
+ <li class="separator acl-write"></li>
2
+
3
+ <li data-type="button" data-key="mediaUpload" class="acl-write" data-l10n-id="ep_media_upload.toolbar.upload.title">
4
+ <a class="grouped-left ep_media_upload" data-l10n-id="ep_media_upload.toolbar.upload.title" title="Upload File" aria-label="Upload File">
5
+ <button class="buttonicon ep_media_upload media_upload buttonicon-attachment" aria-label="Upload File"></button>
6
+ </a>
7
+ </li>
8
+
@@ -0,0 +1,18 @@
1
+ <div id="mediaUploadModal" class="ep-media-upload-modal">
2
+ <div class="ep-media-upload-modal-content">
3
+ <div id="mediaUploadProgress" class="ep-media-upload-state">
4
+ <div class="ep-media-upload-spinner"></div>
5
+ <p class="ep-media-upload-message" data-l10n-id="ep_media_upload.status.uploading">Uploading...</p>
6
+ </div>
7
+ <div id="mediaUploadSuccess" class="ep-media-upload-state" style="display: none;">
8
+ <div class="ep-media-upload-icon ep-media-upload-icon-success">✓</div>
9
+ <p class="ep-media-upload-message" data-l10n-id="ep_media_upload.status.success">Upload complete!</p>
10
+ </div>
11
+ <div id="mediaUploadError" class="ep-media-upload-state" style="display: none;">
12
+ <div class="ep-media-upload-icon ep-media-upload-icon-error">✕</div>
13
+ <p class="ep-media-upload-message ep-media-upload-error-text"></p>
14
+ <button id="mediaUploadErrorClose" class="ep-media-upload-btn" data-l10n-id="ep_media_upload.button.close">Close</button>
15
+ </div>
16
+ </div>
17
+ </div>
18
+