postnhost 0.2.1 → 0.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: eeff5b8e47da4271aa4b1b5240c98fa2e5fcf89ef59ea86f775c41c7fbf3c64e
4
- data.tar.gz: 8784beb69048bba221cfbda8306a57eb1366b470996b02b4325bb2dec8feaacc
3
+ metadata.gz: c20e1f8fa119251d28a2c0fdfd4c14c07a41679a10ea9d070df0c40720303239
4
+ data.tar.gz: e7f466ced7714261754fccb398a3e0ff2d83cbf68024ed85084b7f59827c25a1
5
5
  SHA512:
6
- metadata.gz: 8317f464ba035086b326e0537c157f8957ad250080201d32af7e74955e0909e546f59e13bf2dfcbdd648e4476be75a3bbf6dea0fcee4df3ed90a47fb04c718d0
7
- data.tar.gz: db9ff2f49ee7727d9e8156288de193e01992eef8f0b1cf06aa59fe9a41339b46bc8d5370d9c1cf72f45edceaeac8953bc8dcfd36b717c8194090b443a199dac1
6
+ metadata.gz: ec9849a821de54370d9f1fdf47a10713f060c0c7b3f69fa820b109641c4b9dddbd6d99c96bc8c24fca817859fe3745bc3c0ce77a74ae93d3319b04aa4149e19b
7
+ data.tar.gz: 1e6dbaa8a00af6f3b703b04904044f19a3791bf756ca197746b0d0ba3f674ec55a85f62c0fa76ac8a0be70c01894dab827360afe07bf027ebfc40d56079d26ba
data/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  All notable changes to PostnHost are documented in this file.
4
4
 
5
+ ## [0.2.2] - 2026-11-17
6
+
7
+ ### Fixed
8
+
9
+ - Upload images in pasted article and page content through the configured CarrierWave storage, including S3-compatible destinations, instead of retaining remote image URLs or embedded base64 data. Images use the existing optimized WebP upload pipeline.
10
+ - Preserve pasted text formatting, image order, alt text, and widths. Upload every clipboard image file and avoid duplicate uploads when the clipboard contains both HTML and file representations.
11
+ - Retain surrounding text and report failed image imports without saving the original image sources.
12
+ - Protect remote image imports with authenticated endpoints, SSRF filtering, download timeouts, and a 20 MB limit.
13
+
14
+ ### Upgrading existing blogs
15
+
16
+ From your host application's directory, run `bundle update postnhost` and deploy the updated application with its packaged assets. Update any exact Gemfile pin to allow PostnHost 0.2.2. No database migration or storage configuration change is required.
17
+
18
+ This release affects new pastes. Images already embedded in saved content require a separate content migration to move them into uploaded files.
19
+
5
20
  ## [0.2.1] - 2026-11-03
6
21
 
7
22
  ### Fixed
@@ -63,6 +78,7 @@ First open source release of PostnHost.
63
78
 
64
79
  Authored by Kirill Shevchenko (Ruby/Rails engineering) and Maxim Sova (technical SEO expertise).
65
80
 
81
+ [0.2.2]: https://github.com/postnhost/postnhost/compare/v0.2.1...v0.2.2
66
82
  [0.2.1]: https://github.com/postnhost/postnhost/compare/v0.2.0...v0.2.1
67
83
  [0.2.0]: https://github.com/postnhost/postnhost/compare/v0.1.1...v0.2.0
68
84
  [0.1.1]: https://github.com/postnhost/postnhost/compare/v0.1.0...v0.1.1
@@ -38968,6 +38968,58 @@ var Youtube = Node3.create({
38968
38968
  });
38969
38969
  var src_default13 = Youtube;
38970
38970
 
38971
+ // app/javascript/helpers/image_paste.js
38972
+ function imageClipboardContent(clipboard) {
38973
+ if (!clipboard) return null;
38974
+ const html = clipboard.getData("text/html");
38975
+ const body = new DOMParser().parseFromString(html, "text/html").body;
38976
+ if (body.querySelector("img")) return { body };
38977
+ const files = Array.from(clipboard.files || []).filter((file) => file.type.startsWith("image/"));
38978
+ return files.length ? { files } : null;
38979
+ }
38980
+ async function insertUploadedImages(editor, { body, files }, upload) {
38981
+ let bookmark = editor.state.selection.getBookmark();
38982
+ const mapSelection = ({ transaction }) => {
38983
+ bookmark = bookmark.map(transaction.mapping);
38984
+ };
38985
+ editor.on("transaction", mapSelection);
38986
+ try {
38987
+ const images = body ? Array.from(body.querySelectorAll("img")) : files;
38988
+ let failed = false;
38989
+ const nodes = [];
38990
+ for (const image of images) {
38991
+ try {
38992
+ const source2 = body ? image.getAttribute("src") : image;
38993
+ if (!source2) throw new Error("Missing image source");
38994
+ const url = await upload(source2);
38995
+ if (body) {
38996
+ image.setAttribute("src", url);
38997
+ image.removeAttribute("srcset");
38998
+ image.removeAttribute("sizes");
38999
+ } else {
39000
+ nodes.push({ type: "imageResize", attrs: { src: url } });
39001
+ }
39002
+ } catch {
39003
+ failed = true;
39004
+ if (body) image.replaceWith(document.createTextNode(image.getAttribute("alt") || ""));
39005
+ }
39006
+ if (editor.isDestroyed) return;
39007
+ }
39008
+ const selection = bookmark.resolve(editor.state.doc);
39009
+ const content = body ? body.innerHTML : nodes;
39010
+ if (content.length) {
39011
+ editor.commands.insertContentAt(
39012
+ { from: selection.from, to: selection.to },
39013
+ content,
39014
+ { updateSelection: editor.state.selection.eq(selection) }
39015
+ );
39016
+ }
39017
+ if (failed) throw new Error("Some pasted images could not be uploaded");
39018
+ } finally {
39019
+ editor.off("transaction", mapSelection);
39020
+ }
39021
+ }
39022
+
38971
39023
  // node_modules/devlop/lib/default.js
38972
39024
  function ok() {
38973
39025
  }
@@ -48246,7 +48298,6 @@ var tiptap_editor_controller_default = class extends Controller {
48246
48298
  connect() {
48247
48299
  this.initializeEditor();
48248
48300
  window.addEventListener("resize", this.#positionCodeLanguageControl);
48249
- this.setupPasteHandler();
48250
48301
  this.setupDragAndDropHandler();
48251
48302
  }
48252
48303
  disconnect() {
@@ -48335,6 +48386,7 @@ var tiptap_editor_controller_default = class extends Controller {
48335
48386
  ],
48336
48387
  content: this.contentValue || "",
48337
48388
  editorProps: {
48389
+ handlePaste: (view, event) => this.#handleImagePaste(view, event),
48338
48390
  attributes: {
48339
48391
  class: "prose max-w-none focus:outline-none min-h-[400px] p-4"
48340
48392
  }
@@ -48662,46 +48714,50 @@ var tiptap_editor_controller_default = class extends Controller {
48662
48714
  });
48663
48715
  input.click();
48664
48716
  }
48665
- uploadImage(file) {
48717
+ async uploadImage(file) {
48666
48718
  this.dispatch("upload-start", { bubbles: true });
48719
+ try {
48720
+ const url = await this.#storeImage(file);
48721
+ if (!this.editor.isDestroyed) this.editor.chain().focus().setImage({ src: url }).run();
48722
+ this.dispatch("upload-complete", { bubbles: true });
48723
+ } catch (error2) {
48724
+ console.error("Upload error:", error2);
48725
+ this.dispatch("upload-failed", { bubbles: true });
48726
+ }
48727
+ }
48728
+ async #storeImage(source2) {
48667
48729
  const formData = new FormData();
48668
- formData.append("file", file);
48730
+ if (typeof source2 === "string" && source2.startsWith("data:")) {
48731
+ const blob = await (await fetch(source2)).blob();
48732
+ const extension = blob.type.split("/")[1]?.replace("jpeg", "jpg") || "png";
48733
+ formData.append("file", blob, `pasted-image.${extension}`);
48734
+ } else {
48735
+ formData.append(typeof source2 === "string" ? "url" : "file", source2);
48736
+ }
48669
48737
  const mountPath = this.mountPathValue === "/" ? "" : this.mountPathValue.replace(/\/$/, "");
48670
48738
  const uploadUrl = this.resourceTypeValue === "page" ? `${mountPath}/pages/${this.resourceIdValue}/images` : `${mountPath}/articles/${this.resourceIdValue}/images`;
48671
- fetch(uploadUrl, {
48739
+ const response = await fetch(uploadUrl, {
48672
48740
  method: "POST",
48673
48741
  body: formData,
48674
48742
  headers: {
48675
48743
  "X-CSRF-Token": document.querySelector('[name="csrf-token"]').getAttribute("content")
48676
48744
  }
48677
- }).then((response) => response.json()).then((data) => {
48678
- if (data.url) {
48679
- this.editor.chain().focus().setImage({ src: data.url }).run();
48680
- this.dispatch("upload-complete", { bubbles: true });
48681
- } else {
48682
- this.dispatch("upload-failed", { bubbles: true });
48683
- }
48684
- }).catch((error2) => {
48685
- console.error("Upload error:", error2);
48686
- this.dispatch("upload-failed", { bubbles: true });
48687
48745
  });
48688
- }
48689
- setupPasteHandler() {
48690
- this.editorTarget.addEventListener("paste", (event) => {
48691
- const items = event.clipboardData?.items;
48692
- if (!items) return;
48693
- for (let i2 = 0; i2 < items.length; i2++) {
48694
- const item = items[i2];
48695
- if (item.type.indexOf("image") !== -1) {
48696
- event.preventDefault();
48697
- const file = item.getAsFile();
48698
- if (file) {
48699
- this.uploadImage(file);
48700
- }
48701
- break;
48702
- }
48703
- }
48746
+ const data = await response.json();
48747
+ if (!response.ok || !data.url) throw new Error(data.error || "Image upload failed");
48748
+ return data.url;
48749
+ }
48750
+ #handleImagePaste(view, event) {
48751
+ if (view.state.selection.$from.parent.type.spec.code) return false;
48752
+ const content = imageClipboardContent(event.clipboardData);
48753
+ if (!content) return false;
48754
+ this.dispatch("upload-start", { bubbles: true });
48755
+ insertUploadedImages(this.editor, content, (source2) => this.#storeImage(source2)).then(() => this.dispatch("upload-complete", { bubbles: true })).catch((error2) => {
48756
+ console.error("Paste image upload error:", error2);
48757
+ this.dispatch("upload-failed", { bubbles: true });
48758
+ if (!this.editor.isDestroyed) window.alert("Some pasted images could not be uploaded. Please try pasting those images again.");
48704
48759
  });
48760
+ return true;
48705
48761
  }
48706
48762
  setupDragAndDropHandler() {
48707
48763
  ;
@@ -4,7 +4,7 @@ module Postnhost
4
4
  before_action :load_article
5
5
 
6
6
  def create
7
- file = params[:file]
7
+ file = params[:file].presence || params[:url]
8
8
 
9
9
  if file.present?
10
10
  result = @article.upload_inline_image(file)
@@ -4,7 +4,7 @@ module Postnhost
4
4
  before_action :load_page
5
5
 
6
6
  def create
7
- file = params[:file]
7
+ file = params[:file].presence || params[:url]
8
8
 
9
9
  if file.present?
10
10
  result = @page.upload_inline_image(file)
@@ -87,6 +87,7 @@ import { TableRow } from '@tiptap/extension-table-row'
87
87
  import { TableHeader } from '@tiptap/extension-table-header'
88
88
  import { TableCell } from '@tiptap/extension-table-cell'
89
89
  import Youtube from '@tiptap/extension-youtube'
90
+ import { imageClipboardContent, insertUploadedImages } from '../helpers/image_paste'
90
91
  import { codeLowlight } from '../helpers/code_highlighting'
91
92
  import { applyClasses, removeClasses, EDITOR_STATES } from "../helpers/style_helpers"
92
93
 
@@ -113,7 +114,6 @@ export default class extends Controller {
113
114
  connect() {
114
115
  this.initializeEditor()
115
116
  window.addEventListener('resize', this.#positionCodeLanguageControl)
116
- this.setupPasteHandler()
117
117
  this.setupDragAndDropHandler()
118
118
  }
119
119
 
@@ -205,6 +205,7 @@ export default class extends Controller {
205
205
  ],
206
206
  content: this.contentValue || '',
207
207
  editorProps: {
208
+ handlePaste: (view, event) => this.#handleImagePaste(view, event),
208
209
  attributes: {
209
210
  class: 'prose max-w-none focus:outline-none min-h-[400px] p-4',
210
211
  },
@@ -690,58 +691,59 @@ export default class extends Controller {
690
691
  input.click()
691
692
  }
692
693
 
693
- uploadImage(file) {
694
+ async uploadImage(file) {
694
695
  this.dispatch('upload-start', { bubbles: true })
696
+ try {
697
+ const url = await this.#storeImage(file)
698
+ if (!this.editor.isDestroyed) this.editor.chain().focus().setImage({ src: url }).run()
699
+ this.dispatch('upload-complete', { bubbles: true })
700
+ } catch (error) {
701
+ console.error('Upload error:', error)
702
+ this.dispatch('upload-failed', { bubbles: true })
703
+ }
704
+ }
695
705
 
706
+ async #storeImage(source) {
696
707
  const formData = new FormData()
697
- formData.append('file', file)
708
+ if (typeof source === 'string' && source.startsWith('data:')) {
709
+ const blob = await (await fetch(source)).blob()
710
+ const extension = blob.type.split('/')[1]?.replace('jpeg', 'jpg') || 'png'
711
+ formData.append('file', blob, `pasted-image.${extension}`)
712
+ } else {
713
+ formData.append(typeof source === 'string' ? 'url' : 'file', source)
714
+ }
698
715
 
699
716
  const mountPath = this.mountPathValue === '/' ? '' : this.mountPathValue.replace(/\/$/, '')
700
717
  const uploadUrl = this.resourceTypeValue === 'page'
701
718
  ? `${mountPath}/pages/${this.resourceIdValue}/images`
702
719
  : `${mountPath}/articles/${this.resourceIdValue}/images`
703
720
 
704
- fetch(uploadUrl, {
721
+ const response = await fetch(uploadUrl, {
705
722
  method: 'POST',
706
723
  body: formData,
707
724
  headers: {
708
725
  'X-CSRF-Token': document.querySelector('[name="csrf-token"]').getAttribute('content')
709
726
  }
710
727
  })
711
- .then(response => response.json())
712
- .then(data => {
713
- if (data.url) {
714
- // Insert image at current cursor position
715
- this.editor.chain().focus().setImage({ src: data.url }).run()
716
- this.dispatch('upload-complete', { bubbles: true })
717
- } else {
718
- this.dispatch('upload-failed', { bubbles: true })
719
- }
720
- })
721
- .catch(error => {
722
- console.error('Upload error:', error)
723
- this.dispatch('upload-failed', { bubbles: true })
724
- })
728
+ const data = await response.json()
729
+ if (!response.ok || !data.url) throw new Error(data.error || 'Image upload failed')
730
+ return data.url
725
731
  }
726
732
 
727
- setupPasteHandler() {
728
- this.editorTarget.addEventListener('paste', (event) => {
729
- const items = event.clipboardData?.items
730
- if (!items) return
733
+ #handleImagePaste(view, event) {
734
+ if (view.state.selection.$from.parent.type.spec.code) return false
735
+ const content = imageClipboardContent(event.clipboardData)
736
+ if (!content) return false
731
737
 
732
- for (let i = 0; i < items.length; i++) {
733
- const item = items[i]
734
-
735
- if (item.type.indexOf('image') !== -1) {
736
- event.preventDefault()
737
- const file = item.getAsFile()
738
- if (file) {
739
- this.uploadImage(file)
740
- }
741
- break
742
- }
743
- }
744
- })
738
+ this.dispatch('upload-start', { bubbles: true })
739
+ insertUploadedImages(this.editor, content, source => this.#storeImage(source))
740
+ .then(() => this.dispatch('upload-complete', { bubbles: true }))
741
+ .catch(error => {
742
+ console.error('Paste image upload error:', error)
743
+ this.dispatch('upload-failed', { bubbles: true })
744
+ if (!this.editor.isDestroyed) window.alert('Some pasted images could not be uploaded. Please try pasting those images again.')
745
+ })
746
+ return true
745
747
  }
746
748
 
747
749
  setupDragAndDropHandler() {
@@ -0,0 +1,55 @@
1
+ export function imageClipboardContent(clipboard) {
2
+ if (!clipboard) return null
3
+
4
+ const html = clipboard.getData('text/html')
5
+ // Prefer rich content over file items: browsers may provide both for the same image.
6
+ const body = new DOMParser().parseFromString(html, 'text/html').body
7
+ if (body.querySelector('img')) return { body }
8
+
9
+ const files = Array.from(clipboard.files || []).filter(file => file.type.startsWith('image/'))
10
+ return files.length ? { files } : null
11
+ }
12
+
13
+ export async function insertUploadedImages(editor, { body, files }, upload) {
14
+ let bookmark = editor.state.selection.getBookmark()
15
+ const mapSelection = ({ transaction }) => { bookmark = bookmark.map(transaction.mapping) }
16
+ editor.on('transaction', mapSelection)
17
+
18
+ try {
19
+ const images = body ? Array.from(body.querySelectorAll('img')) : files
20
+ // Upload sequentially to bound memory and keep clipboard order.
21
+ let failed = false
22
+ const nodes = []
23
+ for (const image of images) {
24
+ try {
25
+ const source = body ? image.getAttribute('src') : image
26
+ if (!source) throw new Error('Missing image source')
27
+ const url = await upload(source)
28
+ if (body) {
29
+ image.setAttribute('src', url)
30
+ image.removeAttribute('srcset')
31
+ image.removeAttribute('sizes')
32
+ } else {
33
+ nodes.push({ type: 'imageResize', attrs: { src: url } })
34
+ }
35
+ } catch {
36
+ failed = true
37
+ if (body) image.replaceWith(document.createTextNode(image.getAttribute('alt') || ''))
38
+ }
39
+ if (editor.isDestroyed) return
40
+ }
41
+
42
+ const selection = bookmark.resolve(editor.state.doc)
43
+ const content = body ? body.innerHTML : nodes
44
+ if (content.length) {
45
+ editor.commands.insertContentAt(
46
+ { from: selection.from, to: selection.to },
47
+ content,
48
+ { updateSelection: editor.state.selection.eq(selection) }
49
+ )
50
+ }
51
+ if (failed) throw new Error('Some pasted images could not be uploaded')
52
+ } finally {
53
+ editor.off('transaction', mapSelection)
54
+ }
55
+ }
@@ -5,10 +5,11 @@ module Postnhost::InlineImageUploadable
5
5
  SUPPORTED_CONTENT_TYPES = %w[image/jpeg image/png image/gif image/webp image/heic].freeze
6
6
 
7
7
  def upload_inline_image(file)
8
+ uploader = inline_image_uploader_class.new(self, :inline_image)
9
+ file = Postnhost::InlineImageDownloader.new(uploader).download(file) if file.is_a?(String)
8
10
  return { success: false, error: "Invalid file type" } unless valid_image_file_type?(file)
9
11
  return { success: false, error: "File too large" } if image_file_too_large?(file)
10
12
 
11
- uploader = inline_image_uploader_class.new(self, :inline_image)
12
13
  uploader.store!(file)
13
14
 
14
15
  {
@@ -16,7 +17,7 @@ module Postnhost::InlineImageUploadable
16
17
  url: uploader.url,
17
18
  filename: uploader.identifier
18
19
  }
19
- rescue CarrierWave::ProcessingError, CarrierWave::IntegrityError => e
20
+ rescue CarrierWave::DownloadError, CarrierWave::ProcessingError, CarrierWave::IntegrityError => e
20
21
  Rails.logger.error("CarrierWave inline image error: #{e.message}")
21
22
  { success: false, error: "Invalid image file" }
22
23
  rescue StandardError => e
@@ -0,0 +1,26 @@
1
+ module Postnhost
2
+ class InlineImageDownloader < CarrierWave::Downloader::Base
3
+ def download(url)
4
+ request = nil
5
+ response = SsrfFilter.get(
6
+ process_uri(url),
7
+ scheme_whitelist: %w[http https],
8
+ http_options: { open_timeout: 5, read_timeout: 10 },
9
+ request_proc: ->(value) { request = value }
10
+ ) do |result|
11
+ body = +"".b
12
+ result.read_body do |chunk|
13
+ raise CarrierWave::DownloadError, "File too large" if body.bytesize + chunk.bytesize > InlineImageUploadable::IMAGE_MAX_SIZE
14
+
15
+ body << chunk
16
+ end
17
+ result.body = body
18
+ end
19
+ response.value
20
+ response.uri = request.uri
21
+ CarrierWave::Downloader::RemoteFile.new(response)
22
+ rescue StandardError => e
23
+ raise CarrierWave::DownloadError, e.message
24
+ end
25
+ end
26
+ end
@@ -1,3 +1,3 @@
1
1
  module Postnhost
2
- VERSION = "0.2.1"
2
+ VERSION = "0.2.2"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: postnhost
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.1
4
+ version: 0.2.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Kirill Shevchenko
@@ -178,6 +178,20 @@ dependencies:
178
178
  - - ">="
179
179
  - !ruby/object:Gem::Version
180
180
  version: '0'
181
+ - !ruby/object:Gem::Dependency
182
+ name: ssrf_filter
183
+ requirement: !ruby/object:Gem::Requirement
184
+ requirements:
185
+ - - ">="
186
+ - !ruby/object:Gem::Version
187
+ version: '1.5'
188
+ type: :runtime
189
+ prerelease: false
190
+ version_requirements: !ruby/object:Gem::Requirement
191
+ requirements:
192
+ - - ">="
193
+ - !ruby/object:Gem::Version
194
+ version: '1.5'
181
195
  - !ruby/object:Gem::Dependency
182
196
  name: turbo-rails
183
197
  requirement: !ruby/object:Gem::Requirement
@@ -396,6 +410,7 @@ files:
396
410
  - app/javascript/helpers/auto_save_state.js
397
411
  - app/javascript/helpers/code_highlighting.js
398
412
  - app/javascript/helpers/dom_helpers.js
413
+ - app/javascript/helpers/image_paste.js
399
414
  - app/javascript/helpers/style_helpers.js
400
415
  - app/jobs/postnhost/application_job.rb
401
416
  - app/jobs/postnhost/scheduled_article_job.rb
@@ -497,6 +512,7 @@ files:
497
512
  - app/uploaders/cover_image_uploader.rb
498
513
  - app/uploaders/postnhost/avatar_uploader.rb
499
514
  - app/uploaders/postnhost/inline_article_image_uploader.rb
515
+ - app/uploaders/postnhost/inline_image_downloader.rb
500
516
  - app/uploaders/postnhost/inline_page_image_uploader.rb
501
517
  - app/uploaders/postnhost/setting_asset_uploader.rb
502
518
  - app/views/layouts/postnhost/_favicon.html.erb