mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-26 09:56:17 -05:00
Move One-Time Pad encryption to the browser (#479)
* Move One-Time Pad encryption to the browser; delete backend OTP module OTP encryption/decryption is now performed entirely in the browser so messages, keys, and generated pads never leave the originating device. - Add app/src/components/otp.js: a JS port of the former modules/otp/lib.py (encrypt/decrypt, message formatting, validation, and secure pad generation via crypto.getRandomValues with rejection sampling). - Encrypt/Decrypt now run live as the user types or pastes, with inline error messages instead of submit buttons. - Generate New Pad builds the printable HTML locally (blob URL) instead of hitting /api/otp/html. - Migrate all backend OTP tests to app/src/components/otp.test.js with identical data. - Delete the modules/otp backend module and its blueprint registration. * Revoke the One-Time Pad blob URL after the new tab loads Addresses a minor blob-handle leak: handleGenerateNewPad created an object URL on every click but never released it. * Let users choose the One-Time Pad character set Add an "Advanced" accordion under the buttons with three options: A-Z, A-Z/0-9 (default, unchanged), and a custom character set. The chosen set is shared by encrypt, decrypt, and pad generation. - otp.js: parameterize encrypt/decrypt/generate on the alphabet (default OTP_CHARS for back-compat); add OTP_CHARS_ALPHA and validateCharset; input is auto-uppercased only when the set is all-uppercase, so custom sets with lowercase are case-sensitive; the printable pad is labeled with its set. - Apps.js: lift charset state into OTP(); gate encrypt/decrypt/generate on a valid set with inline validation errors. - otp.test.js: add A-Z, custom round-trip, auto-uppercase, validateCharset, and pad-label tests. * Scope inverted-accordion dark background to direct children The rule forcing #171616 on .ui.inverted.accordion .title/.content used a descendant selector, so it leaked onto any nested element using the `content` class — e.g. an ErrorMessage's Message.Content rendered inside SimpleAccordion got a dark band behind its text. Scope to direct children so the accordion still styles its own title/content but not nested components. * Add optional error-detection checksum to the One-Time Pad Adapts the position-weighted checksum from otp-checksum.md to the frontend-only OTP. checksum = sum(position * value) mod N, parameterized on the selected character set (N = chars.length), so it follows whichever pad alphabet is chosen. Position weighting catches transposition errors. - otp.js: add calculateChecksum/appendChecksum/verifyChecksum. - Apps.js: opt-in "Append error-detection checksum" toggle in Advanced (default off). When on, encrypt appends a checksum char; decrypt verifies it, warns on mismatch, and still shows the decrypted text. - otp.test.js: checksum unit tests, charset-variation, and end-to-end vectors. * Show compact checksum status instead of a large warning box Replace the bulky semantic-ui WarningMessage on decrypt with a small inline status line: a green check + "Checksum is valid" or a red x + "Checksum is invalid", shown whenever the checksum option is on and a message is being decrypted. * Fix checksum-mode decrypt truncating messages without a checksum When the "Append error-detection checksum" option was on, Decrypt always stripped the last ciphertext character before decrypting, so a message that carried no trailing checksum (wrong sender setting, body pasted alone, etc.) lost its final character and decrypted to garbage. Add stripChecksum(received, chars), which removes the trailing character only when it actually verifies as the checksum of the preceding characters; a message without a valid checksum is returned intact and flagged invalid. The decrypt UI now uses it. Also broaden test coverage: - stripChecksum tests, including a regression for the truncation bug. - validation error classes (InvalidOTP/Plaintext/Ciphertext) and the longer-than-OTP length guards. - deterministic encrypt/decrypt roundtrip fuzz across several character sets. - generateMessage character-count and charset-membership checks. - end-to-end checksummed encrypt -> format -> strip -> decrypt flow. Use a dedicated InvalidMessage error for the checksum helpers instead of the misleading InvalidPlaintext. Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
fb23fe1f61
commit
657a5bd561
16 changed files with 752 additions and 496 deletions
|
|
@ -2,6 +2,5 @@ from .archive import api
|
|||
from .docs import api
|
||||
from .inventory import api
|
||||
from .map import api
|
||||
from .otp import api
|
||||
from .videos import api
|
||||
from .zim import api, test
|
||||
|
|
|
|||
|
|
@ -1,36 +0,0 @@
|
|||
from sanic import response, Blueprint
|
||||
from sanic.request import Request
|
||||
from sanic_ext import validate
|
||||
from sanic_ext.extensions.openapi import openapi
|
||||
|
||||
from . import lib, schema
|
||||
|
||||
otp_bp = Blueprint('OTP', '/api/otp')
|
||||
|
||||
|
||||
@otp_bp.post('/encrypt_otp')
|
||||
@openapi.definition(
|
||||
summary='Encrypt a message with OTP.',
|
||||
body=schema.EncryptOTPRequest,
|
||||
)
|
||||
@validate(schema.EncryptOTPRequest)
|
||||
async def post_encrypt_otp(_: Request, body: schema.EncryptOTPRequest):
|
||||
data = lib.encrypt_otp(body.otp, body.plaintext)
|
||||
return response.json(data)
|
||||
|
||||
|
||||
@otp_bp.post('/decrypt_otp')
|
||||
@openapi.definition(
|
||||
summary='Decrypt a message with OTP.',
|
||||
body=schema.DecryptOTPRequest,
|
||||
)
|
||||
@validate(schema.DecryptOTPRequest)
|
||||
async def post_decrypt_otp(_: Request, body: schema.DecryptOTPRequest):
|
||||
data = lib.decrypt_otp(body.otp, body.ciphertext)
|
||||
return response.json(data)
|
||||
|
||||
|
||||
@otp_bp.get('/html')
|
||||
async def get_new_otp_html(_: Request):
|
||||
body = lib.generate_html()
|
||||
return response.html(body)
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
from http import HTTPStatus
|
||||
|
||||
from wrolpi.errors import APIError
|
||||
|
||||
|
||||
class InvalidOTP(APIError):
|
||||
code = 'INVALID_OTP'
|
||||
summary = 'OTP has invalid characters'
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
class InvalidPlaintext(APIError):
|
||||
code = 'INVALID_PLAINTEXT'
|
||||
summary = 'Plaintext has invalid characters'
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
class InvalidCiphertext(APIError):
|
||||
code = 'INVALID_CIPHERTEXT'
|
||||
summary = 'Ciphertext has invalid characters'
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
|
|
@ -1,135 +0,0 @@
|
|||
import secrets
|
||||
from functools import partial
|
||||
from typing import Dict
|
||||
|
||||
from modules.otp.errors import InvalidOTP, InvalidPlaintext, InvalidCiphertext
|
||||
from wrolpi.common import chunks, remove_whitespace, logger
|
||||
|
||||
# These are the only characters we support.
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
OTP_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
|
||||
# The number of characters in each group, separated by spaces.
|
||||
GROUP_SIZE = 5
|
||||
# The groups in each row of a message, separated by newlines. This is small to allow for mobile phones.
|
||||
GROUP_COUNT = 5
|
||||
|
||||
|
||||
def format_message(message: str, group_count: int = GROUP_COUNT) -> str:
|
||||
"""
|
||||
Formats messages in the style of a One-Time-Pad. Usually 5 characters per group.
|
||||
|
||||
>>> format_message('SOMEMESSAGE')
|
||||
'SOMEM ESSAG E'
|
||||
"""
|
||||
groups = [''.join(i) for i in chunks(message, GROUP_SIZE)]
|
||||
rows = chunks(groups, group_count)
|
||||
message = '\n'.join(' '.join(group for group in groups) for groups in rows)
|
||||
return message
|
||||
|
||||
|
||||
generate_char = partial(secrets.choice, OTP_CHARS)
|
||||
|
||||
|
||||
def generate_message():
|
||||
"""
|
||||
Create a OTP message. Format it for ease of use.
|
||||
"""
|
||||
# Use 20 messages per line because this page will be printed.
|
||||
return format_message(''.join(generate_char() for _ in range(320)), 16)
|
||||
|
||||
|
||||
PAGE_HTML = '''
|
||||
<html>
|
||||
<title>One Time Pad - Unique, just for you</title>
|
||||
<style>
|
||||
/* Remove decoration from links so they are readable when printed */
|
||||
a {{ text-decoration: none; }} // escaped for python
|
||||
</style>
|
||||
<body>
|
||||
{messages}
|
||||
|
||||
|
||||
Print this page and distribute the copies (along with the <a href="https://lrnsr.co/aY6m">One Time Pad Cheat Sheet
|
||||
https://lrnsr.co/aY6m</a>) to all members of your group that you trust to receive your encrypted messages. Every
|
||||
person must have their OWN copy of this "One Time Pad" to encrypt and decrypt messages.
|
||||
<br>
|
||||
<b>Use each message ONLY ONCE.</b> Cut off and burn each message from this paper as it is used.
|
||||
<br>
|
||||
To learn how to use this page, please visit: <a href="https://lrnsr.co/H7Za">https://lrnsr.co/H7Za</a>
|
||||
</body>
|
||||
</html>
|
||||
'''
|
||||
|
||||
|
||||
def generate_html() -> str:
|
||||
"""
|
||||
Create an HTML One-Time Pad page. This page will have instructions on how to use the OTP.
|
||||
"""
|
||||
messages = [generate_message() for _ in range(8)]
|
||||
messages = '\n\n'.join(f'<pre>MESSAGE {i}</pre><pre>{j}</pre>' for i, j in enumerate(messages, 1))
|
||||
return PAGE_HTML.format(messages=messages)
|
||||
|
||||
|
||||
def validate_message(otp, error_class):
|
||||
otp = otp.upper()
|
||||
otp = remove_whitespace(otp)
|
||||
|
||||
if not all(i in OTP_CHARS for i in otp):
|
||||
raise error_class()
|
||||
|
||||
return otp
|
||||
|
||||
|
||||
CHARS_LEN = len(OTP_CHARS)
|
||||
|
||||
|
||||
def encrypt_char(plaintext: str, otp: str) -> str:
|
||||
calculated = (OTP_CHARS.index(plaintext) + OTP_CHARS.index(otp)) % CHARS_LEN
|
||||
return OTP_CHARS[calculated]
|
||||
|
||||
|
||||
def decrypt_char(ciphertext: str, otp: str) -> str:
|
||||
calculated = (OTP_CHARS.index(ciphertext) - OTP_CHARS.index(otp)) % CHARS_LEN
|
||||
return OTP_CHARS[calculated]
|
||||
|
||||
|
||||
def encrypt_otp(otp: str, plaintext: str) -> Dict[str, str]:
|
||||
"""
|
||||
Encrypt a plaintext message using an OTP.
|
||||
"""
|
||||
otp = validate_message(otp, InvalidOTP)
|
||||
plaintext = validate_message(plaintext, InvalidPlaintext)
|
||||
|
||||
if len(plaintext) > len(otp):
|
||||
raise InvalidPlaintext('Plaintext is longer than OTP')
|
||||
|
||||
ciphertext = ''.join(encrypt_char(p, o) for p, o in zip(plaintext, otp))
|
||||
|
||||
data = dict(
|
||||
ciphertext=format_message(ciphertext),
|
||||
otp=format_message(otp),
|
||||
plaintext=format_message(plaintext),
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def decrypt_otp(otp: str, ciphertext: str) -> Dict[str, str]:
|
||||
"""
|
||||
Decrypt an encrypted message that was encrypted with an OTP.
|
||||
"""
|
||||
otp = validate_message(otp, InvalidOTP)
|
||||
ciphertext = validate_message(ciphertext, InvalidCiphertext)
|
||||
|
||||
if len(ciphertext) > len(otp):
|
||||
raise InvalidCiphertext('Ciphertext is longer than OTP')
|
||||
|
||||
plaintext = ''.join(decrypt_char(c, o) for c, o in zip(ciphertext, otp))
|
||||
data = dict(
|
||||
plaintext=format_message(plaintext),
|
||||
ciphertext=format_message(ciphertext),
|
||||
otp=format_message(otp),
|
||||
)
|
||||
return data
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class EncryptOTPRequest:
|
||||
otp: str
|
||||
plaintext: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class DecryptOTPRequest:
|
||||
otp: str
|
||||
ciphertext: str
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import json
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encrypt(async_client):
|
||||
body = dict(otp='asdf', plaintext='asdf')
|
||||
request, response = await async_client.post('/api/otp/encrypt_otp', content=json.dumps(body))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json == dict(
|
||||
ciphertext='AAGK',
|
||||
otp='ASDF',
|
||||
plaintext='ASDF',
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_decrypt(async_client):
|
||||
body = dict(otp='asdf', ciphertext='aagk')
|
||||
request, response = await async_client.post('/api/otp/decrypt_otp', content=json.dumps(body))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json == dict(
|
||||
ciphertext='AAGK',
|
||||
otp='ASDF',
|
||||
plaintext='ASDF',
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_html(async_client):
|
||||
request, response = await async_client.get('/api/otp/html')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
|
@ -1,101 +0,0 @@
|
|||
import pytest
|
||||
|
||||
from modules.otp import lib
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'otp,plaintext,ciphertext',
|
||||
[
|
||||
('', '', ''),
|
||||
('A', 'A', 'A'),
|
||||
('B', 'B', 'C'),
|
||||
('9', '9', '8'),
|
||||
('W', 'H', '3'),
|
||||
('W', 'H', '3'),
|
||||
('W8JD7', 'HELLO', '3CUOL'),
|
||||
('XMCKL', 'HELLO', '4QNVZ'),
|
||||
(
|
||||
# This message says: TEST THE ENCRYPTION OF A LONG MESSAGE THE SPACES SHOULDNT MATTER
|
||||
# The message is shorter than the OTP, this is fine. The ciphertext should be the same
|
||||
# length as the message.
|
||||
'V4YPT RCJLZ QZVSD 0U2E6 OOKNU\nZDH8F 4XQ76 OR6EK J0TRG 0G0HU\nS4BUJ',
|
||||
'TESTT HEENC RYPTI ONOFA LONGM\nESSAG ETHES PACES SHOUL DNTMA\nTTER',
|
||||
'E8G8C YGNY1 7NABL E7GJ6 Z2XT6\n3VZ8L 8GXBO 3R8I2 177BR 3TJTU\nBNFB'
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_encrypt_otp(otp, plaintext, ciphertext):
|
||||
result = lib.encrypt_otp(otp, plaintext)
|
||||
expected = dict(
|
||||
otp=otp,
|
||||
plaintext=plaintext,
|
||||
ciphertext=ciphertext,
|
||||
)
|
||||
assert result == expected
|
||||
|
||||
# Whitespace is ignored
|
||||
plaintext = f'\t {plaintext}'
|
||||
otp = f'\n {otp} '
|
||||
result = lib.encrypt_otp(otp, plaintext)
|
||||
expected = dict(
|
||||
otp=otp.strip(),
|
||||
plaintext=plaintext.strip(),
|
||||
ciphertext=ciphertext,
|
||||
)
|
||||
assert result == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'otp,ciphertext,plaintext',
|
||||
[
|
||||
('', '', ''),
|
||||
('A', 'A', 'A'),
|
||||
('B', 'C', 'B'),
|
||||
('W', '3', 'H'),
|
||||
('9', '8', '9'),
|
||||
('W8JD7', '3CUOL', 'HELLO'),
|
||||
('XMCKL', '4QNVZ', 'HELLO'),
|
||||
(
|
||||
'V4YPT RCJLZ QZVSD 0U2E6 OOKNU\nZDH8F 4XQ76 OR6EK J0TRG 0G0HU\nS4BUJ',
|
||||
'E8G8C YGNY1 7NABL E7GJ6 Z2XT6\n3VZ8L 8GXBO 3R8I2 177BR 3TJTU\nBNFB',
|
||||
'TESTT HEENC RYPTI ONOFA LONGM\nESSAG ETHES PACES SHOUL DNTMA\nTTER',
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_decrypt_otp(otp, ciphertext, plaintext):
|
||||
result = lib.decrypt_otp(otp, ciphertext)
|
||||
expected = dict(
|
||||
otp=otp,
|
||||
plaintext=plaintext,
|
||||
ciphertext=ciphertext,
|
||||
)
|
||||
assert result == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'message,expected',
|
||||
[
|
||||
('ABC', 'ABC'),
|
||||
('ABCDEFG', 'ABCDE FG'),
|
||||
('SOMEMESSAGE', 'SOMEM ESSAG E'),
|
||||
(
|
||||
'ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890',
|
||||
'ABCDE FGHIJ KLMNO PQRST UVWXY\nZ0123 45678 90',
|
||||
),
|
||||
(
|
||||
''.join('A' for _ in range(94)),
|
||||
'AAAAA AAAAA AAAAA AAAAA AAAAA\n'
|
||||
'AAAAA AAAAA AAAAA AAAAA AAAAA\n'
|
||||
'AAAAA AAAAA AAAAA AAAAA AAAAA\n'
|
||||
'AAAAA AAAAA AAAAA AAAA'
|
||||
),
|
||||
]
|
||||
)
|
||||
def test_format_message(message, expected):
|
||||
result = lib.format_message(message)
|
||||
assert result == expected
|
||||
|
||||
|
||||
def test_get_new_otp_html():
|
||||
"""Generate a OTP HTML page."""
|
||||
assert lib.generate_html()
|
||||
Loading…
Add table
Add a link
Reference in a new issue