static_encrypt 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 634432305d11c47b1ffe73ae7e725f893924f71238981f5365c602927bf3d5b0
4
+ data.tar.gz: 958774bdc70b2eecfde3bf11f4559472aab1ca08d290d0e71b5f03c511051883
5
+ SHA512:
6
+ metadata.gz: 2e58edcff5e9d2c1b8c7dd649579541b023443ea1b284f36259317a6d94304b05b66ddaf41a753428571e7dfd1310b3ee85cc9fc1a66d0c8ecd72a203053f296
7
+ data.tar.gz: da22f8511ee70bbad643845df34b8756e088211c15b389fb58c6bb86c5a0bb4e123f439c0224666e34782fac6730b23b7e741236c569098834dc4a3b7f98e6b3
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Daniël de Vries
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
22
+
data/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # StaticEncrypt
2
+
3
+ Password-protect any file as a single, self-contained HTML page. A Ruby take on
4
+ [StatiCrypt](https://github.com/robinmoisson/staticrypt).
5
+
6
+ The file is encrypted with AES-256-GCM, using a key derived from your password
7
+ with PBKDF2-HMAC-SHA256 (600,000 iterations). The page holds only the
8
+ ciphertext and a small decryptor that runs in the browser with WebCrypto, so you
9
+ can host it anywhere static: GitHub Pages, S3, Netlify.
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ gem install static_encrypt
15
+ ```
16
+
17
+ Or, from a checkout:
18
+
19
+ ```sh
20
+ bundle install
21
+ bundle exec rake install
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ Currently, the only way to use this gem is via Ruby: pass the file's contents,
27
+ a password and the file's name to `Page.build`. It returns the
28
+ password-protected page as a string:
29
+
30
+ ```ruby
31
+ require "static_encrypt"
32
+
33
+ html = StaticEncrypt::Page.build(File.binread("home.html"), "secret", filename: "home.html")
34
+ File.write("home.encrypted.html", html)
35
+ ```
36
+
37
+ Open the page, enter the password, and an HTML file replaces the page; any
38
+ other file (a PDF, an image) is offered as a download under its original name.
39
+ The `filename` is what decides which, its extension sets the download's type.
40
+
41
+ Optional keyword arguments:
42
+
43
+ | Argument | Default |
44
+ |---|---|
45
+ | `title:` | `"Protected Page"` |
46
+ | `instructions:` | `"Enter the password to view this content."` |
47
+ | `iterations:` | `600_000` PBKDF2 iterations |
48
+ | `template:` | The built-in page; see below |
49
+
50
+ To check a page from Ruby, read its payload back and decrypt it. A wrong
51
+ password raises `StaticEncrypt::DecryptionError`:
52
+
53
+ ```ruby
54
+ payload = StaticEncrypt::Page.payload(html)
55
+ StaticEncrypt::Cipher.decrypt(payload, "secret") # => the original bytes
56
+ ```
57
+
58
+ ### Custom templates
59
+
60
+ `template:` takes your own HTML as a string. Start from
61
+ `StaticEncrypt::Page.default_template`, or write one that has:
62
+
63
+ - `{{script}}` exactly once, where the decryptor is inserted
64
+ - elements with `data-static-encrypt="form"`, `"password"` and `"error"`
65
+ (and optionally `"submit"`)
66
+ - optionally `{{title}}` and `{{instructions}}`
67
+
68
+ `Page.build` raises `StaticEncrypt::Error` if any of that is missing.
69
+
70
+ ### Hosting
71
+
72
+ Browsers only decrypt over **HTTPS** (or on `localhost`, or from a local file).
73
+ Anyone can download the page and guess passwords offline, so use a long,
74
+ random one.
75
+
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "securerandom"
5
+
6
+ module StaticEncrypt
7
+ # AES-256-GCM encryption with a PBKDF2-HMAC-SHA256 derived key, laid out the
8
+ # way WebCrypto expects it so the browser can decrypt the result.
9
+ module Cipher
10
+ DEFAULT_ITERATIONS = 600_000
11
+ SALT_BYTES = 16
12
+ IV_BYTES = 12
13
+ TAG_BYTES = 16
14
+
15
+ module_function
16
+
17
+ def encrypt(data, password, iterations: DEFAULT_ITERATIONS)
18
+ raise ArgumentError, "password must not be empty" if password.to_s.empty?
19
+ raise ArgumentError, "iterations must be a positive integer" unless valid_iterations?(iterations)
20
+
21
+ salt = SecureRandom.random_bytes(SALT_BYTES)
22
+ iv = SecureRandom.random_bytes(IV_BYTES)
23
+
24
+ cipher = OpenSSL::Cipher.new("aes-256-gcm").encrypt
25
+ cipher.key = derive_key(password, salt, iterations)
26
+ cipher.iv = iv
27
+ cipher.auth_data = ""
28
+ ciphertext = cipher.update(data) + cipher.final + cipher.auth_tag
29
+
30
+ { salt: encode64(salt), iv: encode64(iv), data: encode64(ciphertext), iterations: iterations }
31
+ end
32
+
33
+ def decrypt(payload, password)
34
+ salt, iv, raw, iterations = parse(payload)
35
+ ciphertext = raw.byteslice(0...-TAG_BYTES)
36
+ tag = raw.byteslice(-TAG_BYTES..)
37
+
38
+ cipher = OpenSSL::Cipher.new("aes-256-gcm").decrypt
39
+ cipher.key = derive_key(password, salt, iterations)
40
+ cipher.iv = iv
41
+ cipher.auth_tag = tag
42
+ cipher.auth_data = ""
43
+ cipher.update(ciphertext) + cipher.final
44
+ rescue OpenSSL::Cipher::CipherError
45
+ raise DecryptionError, "wrong password or corrupted data"
46
+ end
47
+
48
+ def parse(payload)
49
+ payload = payload.to_h.transform_keys(&:to_sym)
50
+ salt, iv, raw = payload.fetch_values(:salt, :iv, :data).map { decode64(_1) }
51
+ iterations = payload.fetch(:iterations)
52
+
53
+ raise DecryptionError, "malformed payload: bad iterations" unless valid_iterations?(iterations)
54
+ raise DecryptionError, "malformed payload: bad salt" if salt.empty?
55
+ raise DecryptionError, "malformed payload: IV must be #{IV_BYTES} bytes" unless iv.bytesize == IV_BYTES
56
+ raise DecryptionError, "malformed payload: data too short" if raw.bytesize < TAG_BYTES
57
+
58
+ [salt, iv, raw, iterations]
59
+ rescue KeyError, ArgumentError, TypeError, NoMethodError => e
60
+ raise DecryptionError, "malformed payload: #{e.message}"
61
+ end
62
+
63
+ def valid_iterations?(iterations) = iterations.is_a?(Integer) && iterations.positive?
64
+
65
+ def derive_key(password, salt, iterations)
66
+ OpenSSL::KDF.pbkdf2_hmac(password, salt: salt, iterations: iterations, length: 32, hash: "sha256")
67
+ end
68
+
69
+ def encode64(bytes) = [bytes].pack("m0")
70
+ def decode64(string) = string.unpack1("m0")
71
+ end
72
+ end
@@ -0,0 +1,120 @@
1
+ // Browser-side decryptor for static_encrypt pages.
2
+ //
3
+ // Page.script wraps this file in a function with `payload` (the encrypted
4
+ // payload) in scope, and injects it at the template's script placeholder. It finds its
5
+ // elements by data attribute, so any template works as long as it has:
6
+ //
7
+ // [data-static-encrypt="form"] the form; submitting it decrypts
8
+ // [data-static-encrypt="password"] the password input
9
+ // [data-static-encrypt="error"] where error messages are shown
10
+ // [data-static-encrypt="submit"] optional; disabled while decrypting
11
+ //
12
+ // Messages can be overridden with data attributes on the form:
13
+ // data-wrong-password-message, data-insecure-message, data-decrypting-message,
14
+ // data-decrypted-message.
15
+ //
16
+ // While decrypting, the form has aria-busy="true" and the error element shows
17
+ // the decrypting message, so templates can style that state.
18
+
19
+ const element = (name) => document.querySelector(`[data-static-encrypt="${name}"]`);
20
+
21
+ function bytes(b64) {
22
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(b64);
23
+ const bin = atob(b64);
24
+ const out = new Uint8Array(bin.length);
25
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
26
+ return out;
27
+ }
28
+
29
+ async function decrypt(password) {
30
+ const base = await crypto.subtle.importKey(
31
+ "raw", new TextEncoder().encode(password), "PBKDF2", false, ["deriveKey"]);
32
+ const key = await crypto.subtle.deriveKey(
33
+ { name: "PBKDF2", salt: bytes(payload.salt), iterations: payload.iterations, hash: "SHA-256" },
34
+ base, { name: "AES-GCM", length: 256 }, false, ["decrypt"]);
35
+ return new Uint8Array(await crypto.subtle.decrypt(
36
+ { name: "AES-GCM", iv: bytes(payload.iv) }, key, bytes(payload.data)));
37
+ }
38
+
39
+ function reveal(plain, form) {
40
+ if (payload.html) {
41
+ document.open();
42
+ document.write(new TextDecoder().decode(plain));
43
+ document.close();
44
+ return;
45
+ }
46
+ const message = document.createElement("p");
47
+ message.textContent = form.dataset.decryptedMessage || "Decrypted successfully.";
48
+ const link = document.createElement("a");
49
+ link.href = URL.createObjectURL(new Blob([plain], { type: payload.mime }));
50
+ link.download = payload.name;
51
+ link.textContent = "Download " + payload.name;
52
+ form.replaceChildren(message, link);
53
+ link.click();
54
+ }
55
+
56
+ function init() {
57
+ const form = element("form");
58
+ const input = element("password");
59
+ const error = element("error");
60
+ if (!form || !input || !error) {
61
+ console.error('static_encrypt: the template needs [data-static-encrypt="form"], [data-static-encrypt="password"] and [data-static-encrypt="error"].');
62
+ return;
63
+ }
64
+ const submit = element("submit");
65
+ const messages = {
66
+ wrongPassword: form.dataset.wrongPasswordMessage || "Wrong password.",
67
+ insecure: form.dataset.insecureMessage || "This page must be opened over HTTPS to decrypt.",
68
+ decrypting: form.dataset.decryptingMessage || "Decrypting…"
69
+ };
70
+ const insecure = !window.isSecureContext || !window.crypto?.subtle;
71
+ let busy = false;
72
+
73
+ const setBusy = (value) => {
74
+ busy = value;
75
+ if (submit) submit.disabled = value;
76
+ if (value) form.setAttribute("aria-busy", "true");
77
+ else form.removeAttribute("aria-busy");
78
+ };
79
+ const fail = (text) => {
80
+ error.textContent = text;
81
+ setBusy(false);
82
+ };
83
+
84
+ if (insecure) {
85
+ error.textContent = messages.insecure;
86
+ if (submit) submit.disabled = true;
87
+ }
88
+
89
+ form.addEventListener("submit", async (event) => {
90
+ event.preventDefault();
91
+ if (insecure || busy) return;
92
+ setBusy(true);
93
+ error.textContent = messages.decrypting;
94
+
95
+ let plain;
96
+ try {
97
+ plain = await decrypt(input.value);
98
+ } catch (e) {
99
+ // AES-GCM reports a failed authentication check as OperationError.
100
+ fail(e.name === "OperationError" ? messages.wrongPassword : "Could not decrypt: " + e.message);
101
+ return;
102
+ }
103
+
104
+ // The password was right; anything failing from here is about showing the result.
105
+ try {
106
+ error.textContent = "";
107
+ reveal(plain, form);
108
+ form.removeAttribute("aria-busy");
109
+ } catch (e) {
110
+ fail("Decrypted, but could not show the result: " + e.message);
111
+ }
112
+ });
113
+ }
114
+
115
+ if (document.readyState === "loading") {
116
+ document.addEventListener("DOMContentLoaded", init);
117
+ } else {
118
+ init();
119
+ }
120
+
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi/escape"
4
+ require "json"
5
+
6
+ module StaticEncrypt
7
+ module Page
8
+ TEMPLATE_PATH = File.expand_path("template.html", __dir__)
9
+ DECRYPTOR_PATH = File.expand_path("decryptor.js", __dir__)
10
+
11
+ DEFAULT_TITLE = "Protected Page"
12
+ DEFAULT_INSTRUCTIONS = "Enter the password to view this content."
13
+
14
+ PLACEHOLDER = /\{\{(\w+)\}\}/
15
+ PLACEHOLDERS = %w[title instructions script].freeze
16
+ REQUIRED_ELEMENTS = %w[form password error].freeze
17
+
18
+ MIME_TYPES = {
19
+ ".html" => "text/html", ".htm" => "text/html", ".txt" => "text/plain",
20
+ ".md" => "text/markdown", ".csv" => "text/csv", ".json" => "application/json",
21
+ ".pdf" => "application/pdf", ".zip" => "application/zip",
22
+ ".png" => "image/png", ".jpg" => "image/jpeg", ".jpeg" => "image/jpeg",
23
+ ".gif" => "image/gif", ".svg" => "image/svg+xml", ".webp" => "image/webp",
24
+ ".mp3" => "audio/mpeg", ".mp4" => "video/mp4"
25
+ }.freeze
26
+
27
+ module_function
28
+
29
+ def build(data, password, filename:, template: default_template, title: DEFAULT_TITLE,
30
+ instructions: DEFAULT_INSTRUCTIONS, iterations: Cipher::DEFAULT_ITERATIONS)
31
+ validate_template!(template)
32
+
33
+ ext = File.extname(filename).downcase
34
+ payload = Cipher.encrypt(data, password, iterations: iterations).merge(
35
+ name: filename,
36
+ mime: MIME_TYPES.fetch(ext, "application/octet-stream"),
37
+ html: %w[.html .htm].include?(ext)
38
+ )
39
+
40
+ values = {
41
+ "title" => CGI.escapeHTML(title),
42
+ "instructions" => CGI.escapeHTML(instructions),
43
+ "script" => script(payload)
44
+ }
45
+ template.gsub(PLACEHOLDER) { values.fetch(Regexp.last_match(1)) }
46
+ end
47
+
48
+ def script(payload)
49
+ json = JSON.generate(payload).gsub("<", "\\u003c")
50
+ "<script>\n(() => {\n\"use strict\";\nconst payload = #{json};\n#{decryptor}})();\n</script>"
51
+ end
52
+
53
+ def validate_template!(template)
54
+ names = template.scan(PLACEHOLDER).flatten
55
+ unknown = names.uniq - PLACEHOLDERS
56
+
57
+ raise Error, "unknown template placeholder(s): #{unknown.map { "{{#{_1}}}" }.join(", ")}" if unknown.any?
58
+ raise Error, "template must contain {{script}} exactly once" unless names.count("script") == 1
59
+
60
+ missing = REQUIRED_ELEMENTS.reject { template.match?(/data-static-encrypt\s*=\s*["']?#{_1}["'\s>]/) }
61
+
62
+ raise Error, "template is missing #{missing.map { %(data-static-encrypt="#{_1}") }.join(", ")}" if missing.any?
63
+
64
+ template
65
+ end
66
+
67
+ def payload(html)
68
+ json = html[/const payload = (\{.*?\});$/, 1] or raise Error, "no encrypted payload found"
69
+ JSON.parse(json, symbolize_names: true)
70
+ end
71
+
72
+ def default_template
73
+ @default_template ||= File.read(TEMPLATE_PATH, encoding: "UTF-8")
74
+ end
75
+
76
+ def decryptor
77
+ @decryptor ||= File.read(DECRYPTOR_PATH, encoding: "UTF-8")
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,49 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="robots" content="noindex">
7
+ <title>{{title}}</title>
8
+ <style>
9
+ :root { --bg: #f4f4f5; --card: #fff; --fg: #18181b; --muted: #71717a;
10
+ --border: #d4d4d8; --accent: #2563eb; --error: #dc2626; }
11
+ @media (prefers-color-scheme: dark) {
12
+ :root { --bg: #09090b; --card: #18181b; --fg: #fafafa; --muted: #a1a1aa;
13
+ --border: #3f3f46; --accent: #3b82f6; --error: #f87171; }
14
+ }
15
+ * { box-sizing: border-box; }
16
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center;
17
+ padding: 16px; background: var(--bg); color: var(--fg);
18
+ font: 16px/1.5 system-ui, -apple-system, sans-serif; }
19
+ form { width: 100%; max-width: 360px; background: var(--card); padding: 28px;
20
+ border: 1px solid var(--border); border-radius: 12px; }
21
+ h1 { font-size: 1.25rem; margin: 0 0 4px; }
22
+ p { color: var(--muted); margin: 0 0 20px; font-size: .9rem; }
23
+ a { color: var(--accent); font-weight: 600; }
24
+ input, button { width: 100%; font: inherit; padding: 10px 12px; border-radius: 8px; }
25
+ input { border: 1px solid var(--border); background: var(--bg); color: var(--fg); }
26
+ button { margin-top: 12px; border: 0; background: var(--accent); color: #fff;
27
+ cursor: pointer; font-weight: 600; }
28
+ button:disabled { opacity: .6; cursor: not-allowed; }
29
+ [data-static-encrypt="error"] { color: var(--error); min-height: 1.5em; margin: 8px 0 0; font-size: .875rem; }
30
+ form[aria-busy="true"] [data-static-encrypt="error"] { color: var(--muted); }
31
+ </style>
32
+ </head>
33
+ <body>
34
+ <!--
35
+ static_encrypt template. See "Custom templates" in the README: the
36
+ placeholders are title, instructions and script (required, once), and the
37
+ decryptor needs elements with data-static-encrypt="form", "password" and "error".
38
+ -->
39
+ <form data-static-encrypt="form">
40
+ <h1>{{title}}</h1>
41
+ <p>{{instructions}}</p>
42
+ <input data-static-encrypt="password" type="password" placeholder="Password" autocomplete="current-password" autofocus required>
43
+ <button data-static-encrypt="submit" type="submit">Decrypt</button>
44
+ <div data-static-encrypt="error" role="alert"></div>
45
+ </form>
46
+ {{script}}
47
+ </body>
48
+ </html>
49
+
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StaticEncrypt
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "static_encrypt/version"
4
+ require_relative "static_encrypt/cipher"
5
+ require_relative "static_encrypt/page"
6
+
7
+ module StaticEncrypt
8
+ class Error < StandardError; end
9
+ class DecryptionError < Error; end
10
+ end
metadata ADDED
@@ -0,0 +1,52 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: static_encrypt
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Daniël de Vries
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: |
13
+ Encrypts a file with AES-256-GCM (PBKDF2-SHA256 key derivation) and wraps it in a
14
+ single HTML page that decrypts in the browser with WebCrypto. Host it anywhere.
15
+ email:
16
+ - contact@danieldevries.eu
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - LICENSE.txt
22
+ - README.md
23
+ - lib/static_encrypt.rb
24
+ - lib/static_encrypt/cipher.rb
25
+ - lib/static_encrypt/decryptor.js
26
+ - lib/static_encrypt/page.rb
27
+ - lib/static_encrypt/template.html
28
+ - lib/static_encrypt/version.rb
29
+ homepage: https://github.com/danieldevries/static_encrypt
30
+ licenses:
31
+ - MIT
32
+ metadata:
33
+ source_code_uri: https://github.com/danieldevries/static_encrypt
34
+ rubygems_mfa_required: 'true'
35
+ rdoc_options: []
36
+ require_paths:
37
+ - lib
38
+ required_ruby_version: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: 3.2.0
43
+ required_rubygems_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ requirements: []
49
+ rubygems_version: 3.7.2
50
+ specification_version: 4
51
+ summary: Password-protect files as self-contained static HTML pages.
52
+ test_files: []