ep_images_extended 1.0.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.
@@ -0,0 +1,135 @@
1
+ # Contributor Guidelines
2
+ (Please talk to people on the mailing list before you change this page, see our section on [how to get in touch](https://github.com/ether/etherpad-lite#get-in-touch))
3
+
4
+ ## Pull requests
5
+
6
+ * the commit series in the PR should be _linear_ (it **should not contain merge commits**). This is necessary because we want to be able to [bisect](https://en.wikipedia.org/wiki/Bisection_(software_engineering)) bugs easily. Rewrite history/perform a rebase if necessary
7
+ * PRs should be issued against the **develop** branch: we never pull directly into **master**
8
+ * PRs **should not have conflicts** with develop. If there are, please resolve them rebasing and force-pushing
9
+ * when preparing your PR, please make sure that you have included the relevant **changes to the documentation** (preferably with usage examples)
10
+ * contain meaningful and detailed **commit messages** in the form:
11
+ ```
12
+ submodule: description
13
+
14
+ longer description of the change you have made, eventually mentioning the
15
+ number of the issue that is being fixed, in the form: Fixes #someIssueNumber
16
+ ```
17
+ * if the PR is a **bug fix**:
18
+ * the first commit in the series must be a test that shows the failure
19
+ * subsequent commits will fix the bug and make the test pass
20
+ * the final commit message should include the text `Fixes: #xxx` to link it to its bug report
21
+ * think about stability: code has to be backwards compatible as much as possible. Always **assume your code will be run with an older version of the DB/config file**
22
+ * if you want to remove a feature, **deprecate it instead**:
23
+ * write an issue with your deprecation plan
24
+ * output a `WARN` in the log informing that the feature is going to be removed
25
+ * remove the feature in the next version
26
+ * if you want to add a new feature, put it under a **feature flag**:
27
+ * once the new feature has reached a minimal level of stability, do a PR for it, so it can be integrated early
28
+ * expose a mechanism for enabling/disabling the feature
29
+ * the new feature should be **disabled** by default. With the feature disabled, the code path should be exactly the same as before your contribution. This is a __necessary condition__ for early integration
30
+ * think of the PR not as something that __you wrote__, but as something that __someone else is going to read__. The commit series in the PR should tell a novice developer the story of your thoughts when developing it
31
+
32
+ ## How to write a bug report
33
+
34
+ * Please be polite, we all are humans and problems can occur.
35
+ * Please add as much information as possible, for example
36
+ * client os(s) and version(s)
37
+ * browser(s) and version(s), is the problem reproducible on different clients
38
+ * special environments like firewalls or antivirus
39
+ * host os and version
40
+ * npm and nodejs version
41
+ * Logfiles if available
42
+ * steps to reproduce
43
+ * what you expected to happen
44
+ * what actually happened
45
+ * Please format logfiles and code examples with markdown see github Markdown help below the issue textarea for more information.
46
+
47
+ If you send logfiles, please set the loglevel switch DEBUG in your settings.json file:
48
+
49
+ ```
50
+ /* The log level we are using, can be: DEBUG, INFO, WARN, ERROR */
51
+ "loglevel": "DEBUG",
52
+ ```
53
+
54
+ The logfile location is defined in startup script or the log is directly shown in the commandline after you have started etherpad.
55
+
56
+ ## General goals of Etherpad
57
+ To make sure everybody is going in the same direction:
58
+ * easy to install for admins and easy to use for people
59
+ * easy to integrate into other apps, but also usable as standalone
60
+ * lightweight and scalable
61
+ * extensible, as much functionality should be extendable with plugins so changes don't have to be done in core.
62
+ Also, keep it maintainable. We don't wanna end up as the monster Etherpad was!
63
+
64
+ ## How to work with git?
65
+ * Don't work in your master branch.
66
+ * Make a new branch for every feature you're working on. (This ensures that you can work you can do lots of small, independent pull requests instead of one big one with complete different features)
67
+ * Don't use the online edit function of github (this only creates ugly and not working commits!)
68
+ * Try to make clean commits that are easy readable (including descriptive commit messages!)
69
+ * Test before you push. Sounds easy, it isn't!
70
+ * Don't check in stuff that gets generated during build or runtime
71
+ * Make small pull requests that are easy to review but make sure they do add value by themselves / individually
72
+
73
+ ## Coding style
74
+ * Do write comments. (You don't have to comment every line, but if you come up with something that's a bit complex/weird, just leave a comment. Bear in mind that you will probably leave the project at some point and that other people will read your code. Undocumented huge amounts of code are worthless!)
75
+ * Never ever use tabs
76
+ * Indentation: JS/CSS: 2 spaces; HTML: 4 spaces
77
+ * Don't overengineer. Don't try to solve any possible problem in one step, but try to solve problems as easy as possible and improve the solution over time!
78
+ * Do generalize sooner or later! (if an old solution, quickly hacked together, poses more problems than it solves today, refactor it!)
79
+ * Keep it compatible. Do not introduce changes to the public API, db schema or configurations too lightly. Don't make incompatible changes without good reasons!
80
+ * If you do make changes, document them! (see below)
81
+ * Use protocol independent urls "//"
82
+
83
+ ## Branching model / git workflow
84
+ see git flow http://nvie.com/posts/a-successful-git-branching-model/
85
+
86
+ ### `master` branch
87
+ * the stable
88
+ * This is the branch everyone should use for production stuff
89
+
90
+ ### `develop`branch
91
+ * everything that is READY to go into master at some point in time
92
+ * This stuff is tested and ready to go out
93
+
94
+ ### release branches
95
+ * stuff that should go into master very soon
96
+ * only bugfixes go into these (see http://nvie.com/posts/a-successful-git-branching-model/ for why)
97
+ * we should not be blocking new features to develop, just because we feel that we should be releasing it to master soon. This is the situation that release branches solve/handle.
98
+
99
+ ### hotfix branches
100
+ * fixes for bugs in master
101
+
102
+ ### feature branches (in your own repos)
103
+ * these are the branches where you develop your features in
104
+ * If it's ready to go out, it will be merged into develop
105
+
106
+ Over the time we pull features from feature branches into the develop branch. Every month we pull from develop into master. Bugs in master get fixed in hotfix branches. These branches will get merged into master AND develop. There should never be commits in master that aren't in develop
107
+
108
+ ## Documentation
109
+ The docs are in the `doc/` folder in the git repository, so people can easily find the suitable docs for the current git revision.
110
+
111
+ Documentation should be kept up-to-date. This means, whenever you add a new API method, add a new hook or change the database model, pack the relevant changes to the docs in the same pull request.
112
+
113
+ You can build the docs e.g. produce html, using `make docs`. At some point in the future we will provide an online documentation. The current documentation in the github wiki should always reflect the state of `master` (!), since there are no docs in master, yet.
114
+
115
+ ## Testing
116
+
117
+ Front-end tests are found in the `src/tests/frontend/` folder in the repository.
118
+ Run them by pointing your browser to `<yourdomainhere>/tests/frontend`.
119
+
120
+ Back-end tests can be run from the `src` directory, via `npm test`.
121
+
122
+ ## Things you can help with
123
+ Etherpad is much more than software. So if you aren't a developer then worry not, there is still a LOT you can do! A big part of what we do is community engagement. You can help in the following ways
124
+ * Triage bugs (applying labels) and confirming their existence
125
+ * Testing fixes (simply applying them and seeing if it fixes your issue or not) - Some git experience required
126
+ * Notifying large site admins of new releases
127
+ * Writing Changelogs for releases
128
+ * Creating Windows packages
129
+ * Creating releases
130
+ * Bumping dependencies periodically and checking they don't break anything
131
+ * Write proposals for grants
132
+ * Co-Author and Publish CVEs
133
+ * Work with SFC to maintain legal side of project
134
+ * Maintain TODO page - https://github.com/ether/etherpad-lite/wiki/TODO#IMPORTANT_TODOS
135
+
package/LICENSE.md ADDED
@@ -0,0 +1,14 @@
1
+ Copyright 2021 John McLear
2
+ Copyright 2021 Ilmar Türk
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # ep_images_extended – Extended image content for etherpad
2
+
3
+ **Insert, resize, float, copy, cut & delete images.**
4
+ `ep_images_extended` builds on `ep_image_insert` and other image upload plugins.
5
+ The main difference is that images are built as custom span structures using the CSS background image attribute. This bypasses the Content Collector which always requires images to be block-level styles (so they couldn't share the line with text). As a result, we can now type around images, which allows the creation of more interactive pad content. The plugin includes some other features like click + drag resize, image float, and cut/copy/delete through a context menu. It was designed for compatibility with my forthcoming tables plugin. It's a pretty heavyweight plugin (some would say overengineered), because I was prioritizing meeting functional requirements for my project. Etherpad wizards might have tips for optimization, it would surely be appreciated.
6
+
7
+ ---
8
+
9
+ ## Installation
10
+
11
+ Install via the plugins menu or through:
12
+
13
+ pnpm run plugins i ep_images_extended
14
+
15
+ in your etherpad-lite directory.
16
+
17
+ ---
18
+
19
+ ## Configuration (settings.json)
20
+
21
+ Create (or merge) an **`ep_images_extended`** block at the root of `settings.json`.
22
+
23
+ | key | type | default | description |
24
+ |-----|------|---------|-------------|
25
+ | `fileTypes` | Array&lt;string&gt; | _none_ | List of **extensions** (no dot) that are allowed to upload. If omitted any MIME that starts with `image/` is accepted. |
26
+ | `maxFileSize` | Number (bytes) | _unlimited_ | Reject files larger than this size. |
27
+ | `storage` | Object | `{ "type": "base64" }` | Where the image binary ends up. See below. |
28
+
29
+ ### Storage strategies
30
+
31
+ 1. **Embedded Base-64** (default – zero config)
32
+ ```jsonc
33
+ "ep_images_extended": {
34
+ "fileTypes": ["jpeg", "jpg", "png", "gif", "bmp", "webp"],
35
+ "maxFileSize": 5000000
36
+ }
37
+ ```
38
+ Images are converted to data-URIs and live inside the pad. This has a pretty big performance impact.
39
+
40
+ 2. **Amazon S3 with presigned uploads**
41
+ ```jsonc
42
+ "ep_images_extended": {
43
+ "storage": {
44
+ "type": "s3_presigned",
45
+ "region": "us-east-1",
46
+ "bucket": "my-etherpad-images",
47
+ "publicURL": "https://cdn.example.com/", // optional – defaults to the S3 URL
48
+ "expires": 900 // optional – seconds (default 600)
49
+ },
50
+ "fileTypes": ["png", "jpg", "webp"],
51
+ "maxFileSize": 10485760
52
+ }
53
+ ```
54
+ The browser asks the Etherpad server for a presigned **PUT** URL, then uploads straight to S3 –
55
+ the file never touches your app server. Access keys are **not** read from `settings.json`.* The AWS SDK picks them up from environment variables.
56
+
57
+ * `AWS_ACCESS_KEY_ID`
58
+ * `AWS_SECRET_ACCESS_KEY`
59
+ * `AWS_SESSION_TOKEN` (if using temporary credentials)
60
+
61
+
62
+ ---
63
+
64
+ ## Option reference – quick lookup
65
+
66
+ ```text
67
+ fileTypes ↠ Allowed extensions (array of strings)
68
+ maxFileSize ↠ Maximum upload size in bytes
69
+ storage.type ↠ "base64" | "s3_presigned"
70
+ ├─ bucket ↠ S3 bucket name (s3_presigned only)
71
+ ├─ region ↠ AWS region (s3_presigned only)
72
+ ├─ publicURL ↠ CDN / CloudFront base URL (optional)
73
+ └─ expires ↠ URL lifetime in seconds (optional)
74
+ ```
75
+ All other values are ignored.
76
+
77
+ ---
78
+
79
+ ## Contributing
80
+
81
+ This was mostly made by LLMs (my requirements in this project were far beyond my coding ability at this time). Bug reports & PRs are welcome! See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the coding guidelines and branching model.
82
+
83
+ ---
package/editbar.js ADDED
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ const eejs = require('ep_etherpad-lite/node/eejs/');
4
+
5
+ exports.eejsBlock_editbarMenuLeft = (hookName, args, cb) => {
6
+ if (args.renderContext.isReadOnly) return cb();
7
+ // There is a way to do this with classes too using acl-write I think?
8
+ args.content += eejs.require('ep_images_extended/templates/editbarButton.ejs');
9
+ return cb();
10
+ };
package/ep.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "parts": [
3
+ {
4
+ "name": "main",
5
+ "client_hooks": {
6
+ "postToolbarInit": "ep_images_extended/static/js/toolbar",
7
+ "aceAttribsToClasses" : "ep_images_extended/static/js/clientHooks",
8
+ "postAceInit": "ep_images_extended/static/js/clientHooks",
9
+ "aceInitialized": "ep_images_extended/static/js/clientHooks",
10
+ "aceCreateDomLine": "ep_images_extended/static/js/clientHooks",
11
+ "aceAttribClasses": "ep_images_extended/static/js/clientHooks",
12
+ "aceEditorCSS": "ep_images_extended/static/js/clientHooks",
13
+ "acePostWriteDomLineHTML": "ep_images_extended/static/js/clientHooks",
14
+ "collectContentPre": "ep_images_extended/static/js/contentCollection",
15
+ "collectContentPost": "ep_images_extended/static/js/clientHooks",
16
+ "aceKeyEvent": "ep_images_extended/static/js/clientHooks"
17
+ },
18
+ "hooks":{
19
+ "clientVars": "ep_images_extended/index",
20
+ "eejsBlock_body": "ep_images_extended/index",
21
+ "getLineHTMLForExport": "ep_images_extended/exportHTML",
22
+ "stylesForExport": "ep_images_extended/exportHTML",
23
+ "expressConfigure": "ep_images_extended/index",
24
+ "eejsBlock_editbarMenuLeft": "ep_images_extended/editbar",
25
+ "loadSettings": "ep_images_extended/settings",
26
+ "padRemove": "ep_images_extended/index",
27
+ "collectContentPre": "ep_images_extended/static/js/contentCollection",
28
+ "eejsBlock_styles": "ep_images_extended/index",
29
+ "eejsBlock_timesliderStyles": "ep_images_extended/index",
30
+ "ccRegisterBlockElements": "ep_images_extended/index"
31
+ }
32
+ }
33
+ ]
34
+ }
package/exportHTML.js ADDED
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ const Changeset = require('ep_etherpad-lite/static/js/Changeset');
4
+ const Security = require('ep_etherpad-lite/static/js/security');
5
+
6
+ exports.getLineHTMLForExport = async (hook, context) => {
7
+ const attribLine = context.attribLine;
8
+ const apool = context.apool;
9
+
10
+ if (attribLine) {
11
+ let generatedHTML = '';
12
+ let currentPos = 0;
13
+ const opIter = Changeset.opIterator(attribLine);
14
+
15
+ while (opIter.hasNext()) {
16
+ const op = opIter.next();
17
+ const opChars = op.chars;
18
+ const textSegment = context.text.substring(currentPos, currentPos + opChars);
19
+
20
+ let htmlSegment = Security.escapeHTML(textSegment); // Default: escaped text
21
+
22
+ // Check for our image attribute
23
+ const imageSrcAttrib = Changeset.opAttributeValue(op, 'image', apool);
24
+ const imageWidthAttrib = Changeset.opAttributeValue(op, 'image-width', apool);
25
+ const imageHeightAttrib = Changeset.opAttributeValue(op, 'image-height', apool);
26
+ const imageIdAttrib = Changeset.opAttributeValue(op, 'image-id', apool);
27
+ // const imageAspectRatioAttrib = Changeset.opAttributeValue(op, 'imageCssAspectRatio', apool); // Not directly used for img tag but good to know it exists
28
+
29
+ if (imageSrcAttrib) {
30
+ try {
31
+ const decodedSrc = decodeURIComponent(imageSrcAttrib);
32
+ if (decodedSrc && (decodedSrc.startsWith('data:') || decodedSrc.startsWith('http') || decodedSrc.startsWith('/'))) {
33
+ let imgTag = `<img src="${Security.escapeHTML(decodedSrc)}"`;
34
+
35
+ let styles = 'display:inline-block; max-width:100%; height:auto;'; // Default styles
36
+
37
+ if (imageWidthAttrib) {
38
+ const widthValue = imageWidthAttrib.replace(/px$/, '');
39
+ imgTag += ` width="${Security.escapeHTMLAttribute(widthValue)}"`;
40
+ styles += ` width:${Security.escapeHTMLAttribute(imageWidthAttrib)};`;
41
+ }
42
+ if (imageHeightAttrib) {
43
+ const heightValue = imageHeightAttrib.replace(/px$/, '');
44
+ imgTag += ` height="${Security.escapeHTMLAttribute(heightValue)}"`;
45
+ // If height is set, override height:auto
46
+ styles = styles.replace('height:auto;', `height:${Security.escapeHTMLAttribute(imageHeightAttrib)};`);
47
+ }
48
+
49
+ if (imageIdAttrib) {
50
+ imgTag += ` data-image-id="${Security.escapeHTMLAttribute(imageIdAttrib)}"`;
51
+ }
52
+
53
+ imgTag += ` style="${styles}"`;
54
+ imgTag += `>`;
55
+ htmlSegment = imgTag;
56
+ } else {
57
+ console.warn(`[ep_images_extended exportHTML] Invalid unescaped image src: ${decodedSrc}`);
58
+ // Keep default htmlSegment (escaped placeholder text) or specific error
59
+ htmlSegment = '[Invalid Image Src]';
60
+ }
61
+ } catch (e) {
62
+ console.error(`[ep_images_extended exportHTML] Error processing image attribute: ${imageSrcAttrib}`, e);
63
+ htmlSegment = '[Image Processing Error]';
64
+ }
65
+ }
66
+
67
+
68
+ generatedHTML += htmlSegment;
69
+ currentPos += opChars;
70
+ }
71
+ context.lineContent = generatedHTML;
72
+ } else {
73
+ // Line has no attributes, just escape the text
74
+ context.lineContent = Security.escapeHTML(context.text);
75
+ }
76
+
77
+ };
78
+
79
+ exports.stylesForExport = (hook, padId, cb) => {
80
+ cb('img { max-width: 100%; vertical-align: middle; }');
81
+ };
package/index.js ADDED
@@ -0,0 +1,183 @@
1
+ 'use strict';
2
+
3
+ const eejs = require('ep_etherpad-lite/node/eejs/');
4
+ const settings = require('ep_etherpad-lite/node/utils/Settings');
5
+ const { randomUUID } = require('crypto');
6
+ const path = require('path');
7
+ const url = require('url');
8
+ const fs = require('fs');
9
+ const fsp = fs.promises;
10
+ const { JSDOM } = require('jsdom');
11
+ const log4js = require('log4js');
12
+ const { exec } = require('child_process');
13
+ const util = require('util');
14
+ const execPromise = util.promisify(exec);
15
+ const mimetypes = require('mime-db');
16
+ // AWS SDK v3 for presigned URLs
17
+ let S3Client, PutObjectCommand, getSignedUrl;
18
+ try {
19
+ ({ S3Client, PutObjectCommand } = require('@aws-sdk/client-s3'));
20
+ ({ getSignedUrl } = require('@aws-sdk/s3-request-presigner'));
21
+ } catch (e) {
22
+ // AWS SDK might be optional if s3_presigned storage is not used
23
+ console.warn('[ep_images_extended] AWS SDK not installed; s3_presigned storage will not work.');
24
+ }
25
+
26
+ const logger = log4js.getLogger('ep_images_extended');
27
+
28
+ // Simple in-memory IP rate limiter
29
+ const _presignRateStore = new Map();
30
+ const PRESIGN_RATE_WINDOW_MS = 60 * 1000; // 1 minute
31
+ const PRESIGN_RATE_MAX = 30; // max 30 presigns per IP per min
32
+
33
+ // Utility: basic per-IP sliding-window rate limit
34
+ const _rateLimitCheck = (ip) => {
35
+ const now = Date.now();
36
+ let stamps = _presignRateStore.get(ip) || [];
37
+ stamps = stamps.filter((t) => t > now - PRESIGN_RATE_WINDOW_MS);
38
+ if (stamps.length >= PRESIGN_RATE_MAX) return false;
39
+ stamps.push(now);
40
+ _presignRateStore.set(ip, stamps);
41
+ return true;
42
+ };
43
+
44
+ /**
45
+ * ClientVars hook
46
+ *
47
+ * Exposes plugin settings from settings.json to client code inside clientVars variable
48
+ * to be accessed from client side hooks
49
+ *
50
+ * @param {string} hookName Hook name ("clientVars").
51
+ * @param {object} args Object containing the arguments passed to hook. {pad: {object}}
52
+ * @param {function} cb Callback
53
+ *
54
+ * @returns {*} callback
55
+ *
56
+ * @see {@link http://etherpad.org/doc/v1.5.7/#index_clientvars}
57
+ */
58
+ exports.clientVars = (hookName, args, cb) => {
59
+ const pluginSettings = {
60
+ storageType: 'local',
61
+ };
62
+ if (!settings.ep_images_extended) {
63
+ settings.ep_images_extended = {};
64
+ }
65
+ const keys = Object.keys(settings.ep_images_extended);
66
+ keys.forEach((key) => {
67
+ if (key !== 'storage') {
68
+ pluginSettings[key] = settings.ep_images_extended[key];
69
+ }
70
+ });
71
+ if (settings.ep_images_extended.storage)
72
+ {
73
+ pluginSettings.storageType = settings.ep_images_extended.storage.type;
74
+ }
75
+
76
+ pluginSettings.mimeTypes = mimetypes;
77
+
78
+ return cb({ep_images_extended: pluginSettings});
79
+ };
80
+
81
+ exports.eejsBlock_styles = (hookName, args, cb) => {
82
+ args.content += "<link href='../static/plugins/ep_images_extended/static/css/ace.css' rel='stylesheet'>";
83
+ return cb();
84
+ };
85
+
86
+ exports.eejsBlock_timesliderStyles = (hookName, args, cb) => {
87
+ args.content += "<link href='../../static/plugins/ep_images_extended/static/css/ace.css' rel='stylesheet'>";
88
+ args.content += '<style>.control-container{display:none}</style>';
89
+ return cb();
90
+ };
91
+
92
+ exports.eejsBlock_body = (hookName, args, cb) => {
93
+ const modal = eejs.require('ep_images_extended/templates/modal.ejs');
94
+ const imageFormatMenu = eejs.require('ep_images_extended/templates/imageFormatMenu.ejs');
95
+ args.content += modal;
96
+ args.content += imageFormatMenu;
97
+
98
+ return cb();
99
+ };
100
+
101
+ exports.expressConfigure = (hookName, context) => {
102
+ /* ------------------------------------------------------------------
103
+ * New endpoint: GET /p/:padId/pluginfw/ep_images_extended/s3_presign
104
+ * ------------------------------------------------------------------
105
+ * Returns: { signedUrl: string, publicUrl: string }
106
+ * Only active when settings.ep_images_extended.storage.type === 's3_presigned'
107
+ */
108
+ context.app.get('/p/:padId/pluginfw/ep_images_extended/s3_presign', async (req, res) => {
109
+ /* ------------------ Basic auth check ------------------ */
110
+ const hasExpressSession = req.session && (req.session.user || req.session.authorId);
111
+ const hasPadCookie = req.cookies && (req.cookies.sessionID || req.cookies.token);
112
+ if (!hasExpressSession && !hasPadCookie) {
113
+ return res.status(401).json({ error: 'Authentication required' });
114
+ }
115
+
116
+ /* ------------------ Rate limiting --------------------- */
117
+ const ip = req.ip || req.headers['x-forwarded-for'] || req.connection?.remoteAddress || 'unknown';
118
+ if (!_rateLimitCheck(ip)) {
119
+ return res.status(429).json({ error: 'Too many presign requests' });
120
+ }
121
+
122
+ try {
123
+ const storageCfg = settings.ep_images_extended && settings.ep_images_extended.storage;
124
+ if (!storageCfg || storageCfg.type !== 's3_presigned') {
125
+ return res.status(400).json({ error: 's3_presigned storage not enabled' });
126
+ }
127
+
128
+ if (!S3Client || !PutObjectCommand || !getSignedUrl) {
129
+ return res.status(500).json({ error: 'AWS SDK not available on server' });
130
+ }
131
+
132
+ const { bucket, region, publicURL, expires } = storageCfg;
133
+ if (!bucket || !region) {
134
+ return res.status(500).json({ error: 'Invalid S3 configuration' });
135
+ }
136
+
137
+ const { padId } = req.params;
138
+ const { name, type } = req.query;
139
+ if (!name || !type) {
140
+ return res.status(400).json({ error: 'Missing name or type' });
141
+ }
142
+
143
+ /* ------------- MIME / extension allow-list ------------ */
144
+ if (settings.ep_images_extended && settings.ep_images_extended.fileTypes && Array.isArray(settings.ep_images_extended.fileTypes)) {
145
+ const allowedExts = settings.ep_images_extended.fileTypes;
146
+ const extName = path.extname(name).replace('.', '').toLowerCase();
147
+ if (!allowedExts.includes(extName)) {
148
+ return res.status(400).json({ error: 'File type not allowed' });
149
+ }
150
+ }
151
+
152
+ const ext = path.extname(name);
153
+ // Ensure ext starts with '.'; if not, prefix it
154
+ const safeExt = ext.startsWith('.') ? ext : `.${ext}`;
155
+ const key = `${padId}/${randomUUID()}${safeExt}`;
156
+
157
+ const s3Client = new S3Client({ region }); // credentials from env / IAM role
158
+
159
+ const putCommand = new PutObjectCommand({
160
+ Bucket: bucket,
161
+ Key: key,
162
+ ContentType: type,
163
+ });
164
+
165
+ const signedUrl = await getSignedUrl(s3Client, putCommand, { expiresIn: expires || 600 });
166
+
167
+ const basePublic = publicURL || `https://${bucket}.s3.${region}.amazonaws.com/`;
168
+ const publicUrl = new url.URL(key, basePublic).toString();
169
+
170
+ return res.json({ signedUrl, publicUrl });
171
+ } catch (err) {
172
+ logger.error('[ep_images_extended] S3 presign error', err);
173
+ return res.status(500).json({ error: 'Failed to generate presigned URL' });
174
+ }
175
+ });
176
+ };
177
+
178
+ /**
179
+ * Hook to tell Etherpad that 'img' tags are supported during import.
180
+ */
181
+ exports.ccRegisterBlockElements = (hookName, context, cb) => {
182
+ return cb(['img']);
183
+ };
@@ -0,0 +1,6 @@
1
+ {
2
+ "ep_image_insert.toolbar.image_upload.title": "Upload image",
3
+ "ep_image_insert.error.title": "Error",
4
+ "ep_image_insert.error.fileSize": "File is too large! Maximum allowed size is {{maxallowed}} MB.",
5
+ "ep_image_insert.error.fileType": "Invalid file type!"
6
+ }
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "ep_images_extended",
3
+ "description": "Insert images inline with text, float them, resize them, and more.",
4
+ "version": "1.0.0",
5
+ "author": {
6
+ "name": "DCastelone",
7
+ "email": "daniel.m.castelone@gmail.com",
8
+ "url": "https://github.com/dcastelone"
9
+ },
10
+ "contributors": [],
11
+ "dependencies": {
12
+ "mime-db": "1.49.0",
13
+ "@aws-sdk/client-s3": "^3.555.0",
14
+ "@aws-sdk/s3-request-presigner": "^3.555.0"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/dcastelone/ep_images_extended.git"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/dcastelone/ep_images_extended/issues"
22
+ },
23
+ "homepage": "https://github.com/dcastelone/ep_images_extended",
24
+ "peerDependencies": {
25
+ "ep_etherpad-lite": ">=1.8.6"
26
+ },
27
+ "engines": {
28
+ "node": ">=11.14.0"
29
+ }
30
+ }
package/settings.js ADDED
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+
3
+ exports.loadSettings = (hookName, settings, cb) => {
4
+ if (!settings.settings.socketIo) {
5
+ console.warn('Please update Etherpad to >=1.8.8');
6
+ } else {
7
+ // Setting maxHttpBufferSize to 10 MiB :)
8
+ settings.settings.socketIo.maxHttpBufferSize = 100000000;
9
+ }
10
+ cb();
11
+ };