11 Commits

Author SHA1 Message Date
ramvignesh-b f2a1abe7eb refactor: refactor E2E auth helper and mail parsing logic 2026-04-28 19:54:22 +05:30
ramvignesh-b df73fb6b6a refactor: update email notification to account for proper arguments 2026-04-28 18:42:00 +05:30
ramvignesh-b 412abd912c Merge branch 'main' of https://github.com/ramvignesh-b/pi-ku into feature/saajan-persona 2026-04-28 18:34:53 +05:30
ramvignesh-b 72346d8721 fix: remove render test with no value and add aria helper for btn identification 2026-04-28 03:20:48 +05:30
ramvignesh-b ac2c7b0eac feat: add ssajan in lots of flows 2026-04-28 03:12:25 +05:30
ramvignesh-b 935a43c311 refactor: expose props on ui components 2026-04-28 03:11:31 +05:30
ramvignesh-b 4f178a3b03 refactor: add proper props interfaces 2026-04-28 03:10:42 +05:30
ramvignesh-b 867b01bd1e feat: add post seal modal for vault 2026-04-28 03:08:34 +05:30
ramvignesh-b c9ee9f7825 feat: add aesthetic noise background and implement Saajan component in register and login 2026-04-28 03:06:44 +05:30
ramvignesh-b 02070cee4a feat: init saajan component 2026-04-28 01:01:27 +05:30
ramvignesh-b 409fc76619 feat: add template based email content (html + plaintext fallback) 2026-04-28 01:00:34 +05:30
56 changed files with 1122 additions and 1767 deletions
-1
View File
@@ -10,4 +10,3 @@ __pycache__/
docs/ docs/
encrypted-images/ encrypted-images/
logs/
+4 -2
View File
@@ -10,7 +10,9 @@ RUN uv sync --frozen --no-dev
COPY . . COPY . .
# Make the temp log dir writable since server is running rootless
RUN mkdir -p /app/logs && chmod -R 777 /app/logs
EXPOSE 8000 EXPOSE 8000
# NOTE: Exporting env var 'UVICORN_MAIN=true' is required for the scheduler to run on app start. CMD ["sh", "-c", "uv run manage.py migrate && uv run gunicorn --bind 0.0.0.0:8000 --access-logfile - --error-logfile - --capture-output --log-level debug config.wsgi:application"]
CMD ["sh", "-c", "uv run manage.py migrate && UVICORN_MAIN=true uv run gunicorn --bind 0.0.0.0:8000 --access-logfile - --error-logfile - --capture-output --log-level debug config.wsgi:application"]
+10 -17
View File
@@ -1,12 +1,5 @@
from pathlib import Path
import structlog import structlog
BASE_DIR = Path(__file__).resolve().parent.parent
LOGS_DIR = BASE_DIR / "logs"
LOGS_DIR.mkdir(parents=True, exist_ok=True)
structlog.configure( structlog.configure(
processors=[ processors=[
structlog.contextvars.merge_contextvars, structlog.contextvars.merge_contextvars,
@@ -48,22 +41,22 @@ LOGGING = {
}, },
"json_file": { "json_file": {
"class": "logging.handlers.WatchedFileHandler", "class": "logging.handlers.WatchedFileHandler",
"filename": LOGS_DIR / "json.log", "filename": "logs/json.log",
"formatter": "json_formatter", "formatter": "json_formatter",
}, },
"flat_line_file": { "flat_line_file": {
"class": "logging.handlers.WatchedFileHandler", "class": "logging.handlers.WatchedFileHandler",
"filename": LOGS_DIR / "flat_line.log", "filename": "logs/flat_line.log",
"formatter": "key_value", "formatter": "key_value",
}, },
"letters_log": { "letters_log": {
"class": "logging.handlers.WatchedFileHandler", "class": "logging.handlers.WatchedFileHandler",
"filename": LOGS_DIR / "letters.log", "filename": "logs/letters.log",
"formatter": "key_value", "formatter": "key_value",
}, },
"scheduler_log": { "scheduler_log": {
"class": "logging.handlers.WatchedFileHandler", "class": "logging.handlers.WatchedFileHandler",
"filename": LOGS_DIR / "scheduler.log", "filename": "logs/scheduler.log",
"formatter": "key_value", "formatter": "key_value",
}, },
}, },
@@ -78,18 +71,18 @@ LOGGING = {
"level": "DEBUG", "level": "DEBUG",
"propagate": False, "propagate": False,
}, },
"letters.tasks": {
"handlers": ["console", "scheduler_log"],
"level": "INFO",
"propagate": False,
},
"letters": { "letters": {
"handlers": ["console", "flat_line_file", "json_file", "letters_log"], "handlers": ["console", "flat_line_file", "json_file", "letters_log"],
"level": "INFO", "level": "INFO",
"propagate": False, "propagate": False,
}, },
"scheduler": {
"handlers": ["console", "scheduler_log"],
"level": "INFO",
"propagate": False,
},
"": { "": {
"handlers": ["console"], "handlers": ["console", "flat_line_file", "json_file"],
"level": "INFO", "level": "INFO",
}, },
}, },
-3
View File
@@ -16,8 +16,6 @@ from pathlib import Path
import environ import environ
from .logging import LOGGING
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
@@ -56,7 +54,6 @@ SECRET_KEY = env("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False) DEBUG = env.bool("DEBUG", default=False)
LOGGING = LOGGING
# Application definition # Application definition
+2 -6
View File
@@ -10,13 +10,9 @@ class LettersConfig(AppConfig):
""" """
Start the scheduler only when the server is starting. Start the scheduler only when the server is starting.
NOTE: If we don't check for RUN_MAIN, the scheduler triggers for all django operations (migration, test etc.) NOTE: If we don't check for RUN_MAIN, the scheduler triggers for all django operations (migration, test etc.)
NOTE++: For uvicorn, we make sure to set the env var `UVICORN_MAIN` to `true` in the docker command.
""" """
if not (
os.environ.get("RUN_MAIN") == "true" if not (os.environ.get("RUN_MAIN") == "true" or os.environ.get("WERKZEUG_RUN_MAIN") == "true"):
or os.environ.get("WERKZEUG_RUN_MAIN") == "true"
or os.environ.get("UVICORN_MAIN") == "true"
):
return return
from .tasks import start_scheduler from .tasks import start_scheduler
+62 -65
View File
@@ -1,6 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
@@ -8,52 +7,52 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>pi. ku.</title> <title>pi. ku.</title>
</head> </head>
<body style="margin:0; padding:0; background-color:#1a1712;"> <body style="margin:0; padding:0; background-color:#1a1712;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
style="background-color:#1a1712; font-family: 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;"> style="background-color:#1a1712;">
<tr> <tr>
<td align="center" style="padding: 48px 16px;"> <td align="center" style="padding: 48px 16px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
style="max-width:480px; width:100%;"> style="max-width:480px; width:100%;">
{# Logo #} {# Logo #}
<tr> <tr>
<td align="left" style="padding-bottom: 24px;"> <td align="left" style="padding-bottom: 36px;">
<img src="https://cdn.jsdelivr.net/gh/ramvignesh-b/cdn@main/pi-ku_logo.png" width="80" <img src="https://cdn.jsdelivr.net/gh/ramvignesh-b/cdn@main/pi-ku_logo.png" width="100"
alt="Pi.Ku" style="display:block; border:0;"> height="50" alt="Pi.Ku"
</td> style="display:block;">
</tr> </td>
</tr>
{# Body #} {# Body #}
<tr> <tr>
<td style="font-family: 'Trebuchet MS', 'Lucida Sans Unicode', Arial, sans-serif; <td style="font-family: Lora, Georgia, serif;
font-size: 13px; font-size: 16px;
line-height: 1.9; line-height: 1.9;
color: #cdccca; color: #cdccca;
font-style: italic; font-style: italic;
padding-bottom: 24px;"> padding-bottom: 32px;">
{% block content %} {% block content %}
{% endblock %} {% endblock %}
</td> </td>
</tr> </tr>
{# CTA #} {# CTA #}
{% if cta %} {% if cta %}
<tr> <tr>
<td align="left" style="padding-bottom: 24px;"> <td align="left" style="padding-bottom: 32px;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0"> <table role="presentation" cellpadding="0" cellspacing="0" border="0">
<tr> <tr>
<td style="background-color: #301e19; border-radius: 3px;"> <td style="background-color: #301e19; border-radius: 3px;">
<a href='{{ cta.link }}' style="display: inline-block; <a href='{{ cta.link }}'
padding: 12px 24px; style="display: inline-block;
font-family: 'Trebuchet MS', Arial, sans-serif; padding: 12px 28px;
font-size: 13px; font-family: Georgia, serif;
font-size: 14px;
color: #f5e6c8; color: #f5e6c8;
text-decoration: none; text-decoration: none;
letter-spacing: 0.04em; letter-spacing: 0.04em;">
font-weight: bold;">
{{ cta.title }} {{ cta.title }}
</a> </a>
</td> </td>
@@ -61,43 +60,41 @@
</table> </table>
</td> </td>
</tr> </tr>
{% endif %} {% endif %}
{% if footnote %} {% if footnote %}
<tr> <tr>
<td style="font-family: Georgia, 'Times New Roman', Times, serif; <td style="font-family: Lora, Georgia, serif;
font-size: 12px; font-size: 13px;
font-style: italic; font-style: italic;
color: #7a7974; color: #7a7974;
padding-bottom: 40px; padding-bottom: 40px;
line-height: 1.8;"> line-height: 1.8;">
{% block footnote %} {% block footnote %}
{% endblock %} {% endblock %}
</td> </td>
</tr> </tr>
{% endif %} {% endif %}
{# Footer #} {# Footer #}
<tr> <tr>
<td style="border-top: 1px solid #2e2c29; padding-bottom: 24px; font-size: 0; line-height: 0;"> <td style="border-top: 1px solid #2e2c29; padding-bottom: 24px; font-size: 0;">&nbsp;</td>
&nbsp;</td> </tr>
</tr> <tr>
<tr> <td style="font-family: Lora, serif;
<td style="font-family: Georgia, 'Times New Roman', Times, serif; font-size: 13px;
font-size: 12px; font-style: italic;
font-style: italic; color: #5a5957;
color: #5a5957; line-height: 1.8;">
line-height: 1.8;"> {% block footer %}
{% block footer %} {% endblock %}
{% endblock %} </td>
</td> </tr>
</tr>
</table> </table>
</td> </td>
</tr> </tr>
</table> </table>
</body> </body>
</html> </html>
-21
View File
@@ -8,12 +8,8 @@
"@fontsource-variable/jost": "^5.2.8", "@fontsource-variable/jost": "^5.2.8",
"@fontsource-variable/playfair-display": "^5.2.8", "@fontsource-variable/playfair-display": "^5.2.8",
"@fontsource-variable/playwrite-hr-lijeva": "^5.2.7", "@fontsource-variable/playwrite-hr-lijeva": "^5.2.7",
"@fontsource/architects-daughter": "^5.2.7",
"@fontsource/cutive-mono": "^5.2.8", "@fontsource/cutive-mono": "^5.2.8",
"@fontsource/kavivanar": "^5.2.8",
"@fontsource/knewave": "^5.2.7", "@fontsource/knewave": "^5.2.7",
"@fontsource/redacted-script": "^5.2.8",
"@fontsource/space-mono": "^5.2.9",
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^5.2.2",
"@phosphor-icons/react": "^2.1.10", "@phosphor-icons/react": "^2.1.10",
"@tailwindcss/vite": "^4.2.2", "@tailwindcss/vite": "^4.2.2",
@@ -21,7 +17,6 @@
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"fabric": "^7.2.0", "fabric": "^7.2.0",
"idb": "^8.0.3", "idb": "^8.0.3",
"motion": "^12.38.0",
"react": "^19.2.4", "react": "^19.2.4",
"react-dom": "^19.2.4", "react-dom": "^19.2.4",
"react-hook-form": "^7.72.1", "react-hook-form": "^7.72.1",
@@ -123,18 +118,10 @@
"@fontsource-variable/playwrite-hr-lijeva": ["@fontsource-variable/playwrite-hr-lijeva@5.2.7", "", {}, "sha512-cQqbD8HHZDpiKdtgwUxgwAY76TC+GI9iZOxHSW0XkV/L8lA0X18z1wzR+J8yv9XZQYgLJ5WfzBGwzMSLnSLdPA=="], "@fontsource-variable/playwrite-hr-lijeva": ["@fontsource-variable/playwrite-hr-lijeva@5.2.7", "", {}, "sha512-cQqbD8HHZDpiKdtgwUxgwAY76TC+GI9iZOxHSW0XkV/L8lA0X18z1wzR+J8yv9XZQYgLJ5WfzBGwzMSLnSLdPA=="],
"@fontsource/architects-daughter": ["@fontsource/architects-daughter@5.2.7", "", {}, "sha512-W7tHXduV9kRQZDTqcU4Rnc/GtSq9cYUHOnhvcRPjy87u5x/oRqKXPU2PghqbktTECOIh1N0qVZLt9rwqa+aWhg=="],
"@fontsource/cutive-mono": ["@fontsource/cutive-mono@5.2.8", "", {}, "sha512-Y8PKAYfbpl9Empbb1HZBoirlj4W7RtU+G4EhvX27pHzO6RE1sO0I1ElZQH5DMCTS+MSJkMmQT33sJ0+Ji9U8eQ=="], "@fontsource/cutive-mono": ["@fontsource/cutive-mono@5.2.8", "", {}, "sha512-Y8PKAYfbpl9Empbb1HZBoirlj4W7RtU+G4EhvX27pHzO6RE1sO0I1ElZQH5DMCTS+MSJkMmQT33sJ0+Ji9U8eQ=="],
"@fontsource/kavivanar": ["@fontsource/kavivanar@5.2.8", "", {}, "sha512-wbr/9vQ2da9aabUngCpWLbbHM08XZK3nkLDuQ0eX/BhdVvoJx0MSPzaKJ0WIiKpVHy3fUL8ewOqpCyidGZlvEg=="],
"@fontsource/knewave": ["@fontsource/knewave@5.2.7", "", {}, "sha512-uzx8jgcTiQgAwKvQ/hWdX7lOQPwS+K74Eij/WCVzYvAkCX7GRTnWnbxXXx0XsKR6UIN16kH/u40LW4K8aHJb1w=="], "@fontsource/knewave": ["@fontsource/knewave@5.2.7", "", {}, "sha512-uzx8jgcTiQgAwKvQ/hWdX7lOQPwS+K74Eij/WCVzYvAkCX7GRTnWnbxXXx0XsKR6UIN16kH/u40LW4K8aHJb1w=="],
"@fontsource/redacted-script": ["@fontsource/redacted-script@5.2.8", "", {}, "sha512-NOEGJyurXvCx5egCha9yUQB+Tt0IxXriacykYiRlohUvhdbKvisHbucAHQaK8N5/LLB6rlX62SrX8C9+t41PYQ=="],
"@fontsource/space-mono": ["@fontsource/space-mono@5.2.9", "", {}, "sha512-b61faFOHEISQ/pD25G+cfGY9o/WW6lRv6hBQQfpWvEJ4y1V+S4gmth95EVyBE2VL3qDYHeVQ8nBzrplzdXTDDg=="],
"@hookform/resolvers": ["@hookform/resolvers@5.2.2", "", { "dependencies": { "@standard-schema/utils": "^0.3.0" }, "peerDependencies": { "react-hook-form": "^7.55.0" } }, "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA=="], "@hookform/resolvers": ["@hookform/resolvers@5.2.2", "", { "dependencies": { "@standard-schema/utils": "^0.3.0" }, "peerDependencies": { "react-hook-form": "^7.55.0" } }, "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA=="],
"@inquirer/ansi": ["@inquirer/ansi@1.0.2", "", {}, "sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ=="], "@inquirer/ansi": ["@inquirer/ansi@1.0.2", "", {}, "sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ=="],
@@ -415,8 +402,6 @@
"form-data": ["form-data@4.0.5", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="], "form-data": ["form-data@4.0.5", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
"framer-motion": ["framer-motion@12.38.0", "", { "dependencies": { "motion-dom": "^12.38.0", "motion-utils": "^12.36.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g=="],
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="], "fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
@@ -541,12 +526,6 @@
"mkdirp-classic": ["mkdirp-classic@0.5.3", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="], "mkdirp-classic": ["mkdirp-classic@0.5.3", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
"motion": ["motion@12.38.0", "", { "dependencies": { "framer-motion": "^12.38.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-uYfXzeHlgThchzwz5Te47dlv5JOUC7OB4rjJ/7XTUgtBZD8CchMN8qEJ4ZVsUmTyYA44zjV0fBwsiktRuFnn+w=="],
"motion-dom": ["motion-dom@12.38.0", "", { "dependencies": { "motion-utils": "^12.36.0" } }, "sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA=="],
"motion-utils": ["motion-utils@12.36.0", "", {}, "sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"msw": ["msw@2.13.2", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-go2H1TIERKkC48pXiwec5l6sbNqYuvqOk3/vHGo1Zd+pq/H63oFawDQerH+WQdUw/flJFHDG7F+QdWMwhntA/A=="], "msw": ["msw@2.13.2", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-go2H1TIERKkC48pXiwec5l6sbNqYuvqOk3/vHGo1Zd+pq/H63oFawDQerH+WQdUw/flJFHDG7F+QdWMwhntA/A=="],
+5 -11
View File
@@ -34,7 +34,7 @@ test.describe("Letter Drafting (Real Backend)", () => {
await recipientInput.fill(recipientName); await recipientInput.fill(recipientName);
// Initial load: verify textarea value (populated by Fabric when focused) // Initial load: verify textarea value (populated by Fabric when focused)
const canvasInput = page.locator("textarea"); const canvasInput = page.getByLabel("Canvas text input");
await canvasInput.waitFor({ state: "attached" }); await canvasInput.waitFor({ state: "attached" });
await canvasInput.focus(); await canvasInput.focus();
await expect(canvasInput).toHaveValue(/Take a deep breath/i); await expect(canvasInput).toHaveValue(/Take a deep breath/i);
@@ -60,14 +60,8 @@ test.describe("Letter Drafting (Real Backend)", () => {
logger.info(">> [Draft] Reloading to verify persistence..."); logger.info(">> [Draft] Reloading to verify persistence...");
await page.goto(savedUrl); await page.goto(savedUrl);
// Wait for initial load overlay to appear and then definitely disappear // Wait for initial load overlay to disappear
await page await expect(page.getByText(/opening your draft/i)).toBeHidden();
.getByText(/opening your draft/i)
.waitFor({ state: "visible", timeout: 2000 })
.catch(() => {});
await expect(page.getByText(/opening your draft/i)).toBeHidden({
timeout: 10000,
});
// Check recipient // Check recipient
await expect(page.locator("#recipient")).toHaveValue(recipientName); await expect(page.locator("#recipient")).toHaveValue(recipientName);
@@ -98,7 +92,7 @@ test.describe("Letter Drafting (Real Backend)", () => {
await recipientInput.waitFor({ state: "visible", timeout: 10000 }); await recipientInput.waitFor({ state: "visible", timeout: 10000 });
await recipientInput.fill("A Secret Guest"); await recipientInput.fill("A Secret Guest");
const canvasInput = page.locator("textarea"); const canvasInput = page.getByLabel("Canvas text input");
await canvasInput.focus(); await canvasInput.focus();
await canvasInput.fill("This letter will be sealed and shared."); await canvasInput.fill("This letter will be sealed and shared.");
@@ -173,7 +167,7 @@ test.describe("Letter Drafting (Real Backend)", () => {
await recipientInput.waitFor({ state: "visible" }); await recipientInput.waitFor({ state: "visible" });
await recipientInput.fill(recipientName); await recipientInput.fill(recipientName);
const canvasInput = page.locator("textarea"); const canvasInput = page.getByLabel("Canvas text input");
await canvasInput.focus(); await canvasInput.focus();
await canvasInput.fill(letterContent); await canvasInput.fill(letterContent);
+2 -6
View File
@@ -4,14 +4,10 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Pi. Ku. | A safe haven for your unsaid and unsent letters</title> <title>Pi. Ku. | A safe haven for your unsent letters</title>
<meta name="description" <meta name="description"
content="Pi. Ku. is a minimal, secure, and beautiful way to write and seal your unsaid words into digital letters." /> content="Pi. Ku. is a minimal, secure, and beautiful way to write and seal digital letters." />
</head> </head>
<body> <body>
-5
View File
@@ -22,12 +22,8 @@
"@fontsource-variable/jost": "^5.2.8", "@fontsource-variable/jost": "^5.2.8",
"@fontsource-variable/playfair-display": "^5.2.8", "@fontsource-variable/playfair-display": "^5.2.8",
"@fontsource-variable/playwrite-hr-lijeva": "^5.2.7", "@fontsource-variable/playwrite-hr-lijeva": "^5.2.7",
"@fontsource/architects-daughter": "^5.2.7",
"@fontsource/cutive-mono": "^5.2.8", "@fontsource/cutive-mono": "^5.2.8",
"@fontsource/kavivanar": "^5.2.8",
"@fontsource/knewave": "^5.2.7", "@fontsource/knewave": "^5.2.7",
"@fontsource/redacted-script": "^5.2.8",
"@fontsource/space-mono": "^5.2.9",
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^5.2.2",
"@phosphor-icons/react": "^2.1.10", "@phosphor-icons/react": "^2.1.10",
"@tailwindcss/vite": "^4.2.2", "@tailwindcss/vite": "^4.2.2",
@@ -35,7 +31,6 @@
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"fabric": "^7.2.0", "fabric": "^7.2.0",
"idb": "^8.0.3", "idb": "^8.0.3",
"motion": "^12.38.0",
"react": "^19.2.4", "react": "^19.2.4",
"react-dom": "^19.2.4", "react-dom": "^19.2.4",
"react-hook-form": "^7.72.1", "react-hook-form": "^7.72.1",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 862 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

-19
View File
@@ -1,19 +0,0 @@
{
"name": "Pi. Ku.",
"short_name": "Pi. Ku.",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#d4a24f",
"background_color": "#3b1d13",
"display": "standalone"
}
+6 -5
View File
@@ -1,10 +1,12 @@
import { lazy, Suspense, useEffect, useRef } from "react"; import { lazy, Suspense, useEffect } from "react";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom"; import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import { ProtectedRoute, PublicRoute } from "./components/RouteGuards"; import { ProtectedRoute, PublicRoute } from "./components/RouteGuards";
import SplashScreen from "./components/SplashScreen"; import SplashScreen from "./components/SplashScreen";
import { ROUTES } from "./config/routes"; import { ROUTES } from "./config/routes";
import { useAuth } from "./hooks/useAuth"; import { useAuth } from "./hooks/useAuth";
let authInitialized = false;
const Activate = lazy(() => import("./pages/Activate")); const Activate = lazy(() => import("./pages/Activate"));
const Drawer = lazy(() => import("./pages/Drawer")); const Drawer = lazy(() => import("./pages/Drawer"));
const Editor = lazy(() => import("./pages/Editor")); const Editor = lazy(() => import("./pages/Editor"));
@@ -16,12 +18,11 @@ const VerifyEmail = lazy(() => import("./pages/VerifyEmail"));
export default function App() { export default function App() {
const { initialize, isInitializing } = useAuth(); const { initialize, isInitializing } = useAuth();
const authInitialized = useRef<boolean>(false);
useEffect(() => { useEffect(() => {
if (authInitialized.current) return; if (authInitialized) return;
authInitialized.current = true; authInitialized = true;
initialize().then(); initialize();
}, [initialize]); }, [initialize]);
if (isInitializing) { if (isInitializing) {
+10 -9
View File
@@ -2,19 +2,19 @@ import axios from "axios";
import { endpoints } from "../config/endpoints"; import { endpoints } from "../config/endpoints";
import { useAuthStore } from "../store/useAuthStore"; import { useAuthStore } from "../store/useAuthStore";
export const apiServerUrl = import.meta.env.VITE_API_URL;
// publicApi for endpoints that don't need authentication (login, refresh, register) // publicApi for endpoints that don't need authentication (login, refresh, register)
export const publicApi = axios.create({ export const publicApi = axios.create({
baseURL: apiServerUrl, baseURL: import.meta.env.VITE_API_URL,
withCredentials: true, withCredentials: true,
}); });
// api for all authenticated requests // api for all authenticated requests
export const api = axios.create({ export const api = axios.create({
baseURL: apiServerUrl, baseURL: import.meta.env.VITE_API_URL,
withCredentials: true, withCredentials: true,
}); });
// auto-attach access token to authenticated requests
api.interceptors.request.use((config) => { api.interceptors.request.use((config) => {
const token = useAuthStore.getState().accessToken; const token = useAuthStore.getState().accessToken;
if (token) { if (token) {
@@ -22,28 +22,29 @@ api.interceptors.request.use((config) => {
} }
return config; return config;
}); });
// auto handle 401 errors by attempting a silent refresh
// Handle 401 errors by attempting a silent refresh
api.interceptors.response.use( api.interceptors.response.use(
(response) => response, (response) => response,
async (error) => { async (error) => {
const originalRequest = error.config; const originalRequest = error.config;
// if first time 401 and we haven't tried refreshing yet, we proceed with silent refresh // If 401 and we haven't tried refreshing yet
// else it could mean the refresh also 401'd
if (error.response?.status === 401 && !originalRequest._retry) { if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true; originalRequest._retry = true;
try { try {
// Attempt silent refresh
const { data } = await publicApi.post(endpoints.REFRESH); const { data } = await publicApi.post(endpoints.REFRESH);
const newAccessToken = data.access; const newAccessToken = data.access;
// Update store with the latest accesstoken // Update store
const { user, setAuth } = useAuthStore.getState(); const { user, setAuth } = useAuthStore.getState();
if (user) { if (user) {
setAuth(newAccessToken, user); setAuth(newAccessToken, user);
} }
// retry the original request with the new token // Retry the original request with the new token
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`; originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return api(originalRequest); return api(originalRequest);
} catch (refreshError) { } catch (refreshError) {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

+5 -5
View File
@@ -4,9 +4,8 @@ import { useAuth } from "../hooks/useAuth";
import SplashScreen from "./SplashScreen"; import SplashScreen from "./SplashScreen";
/** /**
* Private route guard. * Post-login routes.
* If not authenticated, capture the current url in route * Redirects to /login if not already authenticated.
* state so the Login component can link them back after sign-in
*/ */
export function ProtectedRoute({ children }: { children: React.ReactNode }) { export function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isInitializing } = useAuth(); const { isAuthenticated, isInitializing } = useAuth();
@@ -15,6 +14,7 @@ export function ProtectedRoute({ children }: { children: React.ReactNode }) {
if (isInitializing) return <SplashScreen />; if (isInitializing) return <SplashScreen />;
if (!isAuthenticated) { if (!isAuthenticated) {
// Save the intended location to redirect back after login
return <Navigate to={ROUTES.LOGIN} state={{ from: location }} replace />; return <Navigate to={ROUTES.LOGIN} state={{ from: location }} replace />;
} }
@@ -22,8 +22,8 @@ export function ProtectedRoute({ children }: { children: React.ReactNode }) {
} }
/** /**
* Public - auth route guard. * Pre-login flows.
* If authenticated, redirect all the auth related flows to the drawer * Redirects to /drawer if already authenticated.
*/ */
export function PublicRoute({ children }: { children: React.ReactNode }) { export function PublicRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isInitializing } = useAuth(); const { isAuthenticated, isInitializing } = useAuth();
+1 -1
View File
@@ -15,7 +15,7 @@ export default function SplashScreen() {
/> />
<span className="loading loading-ring loading-xl text-primary"></span> <span className="loading loading-ring loading-xl text-primary"></span>
... ...
<p className="text-xs uppercase font-sans tracking-widester opacity-40"> <p className="text-xs uppercase font-sans tracking-[1em] opacity-40">
Unsealing Unsealing
</p> </p>
</div> </div>
@@ -39,7 +39,7 @@ export function DrawerSection({
> >
<div className="flex-1"> <div className="flex-1">
<div <div
className={`font-sans text-xs tracking-widester uppercase transition-colors duration-800 ${ className={`font-sans text-xs tracking-[0.2em] uppercase transition-colors duration-800 ${
isOpen isOpen
? "text-base-content" ? "text-base-content"
: "text-base-content/40 group-hover:text-base-content/80" : "text-base-content/40 group-hover:text-base-content/80"
+41 -40
View File
@@ -1,5 +1,4 @@
import { LockKeyIcon } from "@phosphor-icons/react"; import { LockKeyIcon } from "@phosphor-icons/react";
import { Modal } from "../ui/Modal";
interface PasskeyModalProps { interface PasskeyModalProps {
onUnlock: (password: string) => Promise<void>; onUnlock: (password: string) => Promise<void>;
@@ -7,45 +6,47 @@ interface PasskeyModalProps {
export function PasskeyModal({ onUnlock }: PasskeyModalProps) { export function PasskeyModal({ onUnlock }: PasskeyModalProps) {
return ( return (
<Modal isOpen={true}> <div className="modal modal-open bg-base-100/20 backdrop-blur-md z-100">
<LockKeyIcon <div className="modal-box p-12 flex flex-col items-center">
size={48} <LockKeyIcon
className="text-primary mx-auto mb-8 animate-pulse" size={48}
/> className="text-primary mx-auto mb-8 animate-pulse"
<h3 className="font-bold text-lg font-display text-primary"> />
Authentication Required <h3 className="font-bold text-lg font-display text-primary">
</h3> Authentication Required
<p className="py-4 font-sans"> </h3>
We need your passkey to open your letters <p className="py-4 font-sans">
</p> We need your passkey to open your letters
<div className="divider w-1/2 mx-auto text-xs text-neutral-content/30 mt-0"></div> </p>
<p className="text-xs text-neutral-content/30 font-mono italic"> <div className="divider w-1/2 mx-auto text-xs text-neutral-content/30 mt-0"></div>
Your passkey is used to decrypt your data locally. <p className="text-xs text-neutral-content/30 font-mono italic">
</p> Your passkey is used to decrypt your data locally.
<div className="modal-action items-center gap-4"> </p>
<form <div className="modal-action items-center gap-4">
className="form-control w-full inline-flex" <form
onSubmit={async (e: React.SubmitEvent<HTMLFormElement>) => { className="form-control w-full inline-flex"
e.preventDefault(); onSubmit={async (e: React.SubmitEvent<HTMLFormElement>) => {
const formData = new FormData(e.currentTarget); e.preventDefault();
const password = formData.get("password") as string; const formData = new FormData(e.currentTarget);
if (!password) return; const password = formData.get("password") as string;
await onUnlock(password); if (!password) return;
}} await onUnlock(password);
> }}
<input >
name="password" <input
required name="password"
type="password" required
placeholder="password" type="password"
className="font-sans validator input input-bordered rounded-r-none" placeholder="password"
/> className="font-sans validator input input-bordered rounded-r-none"
<div className="validator-message text-xs text-error"></div> />
<button type="submit" className="btn btn-primary rounded-l-none"> <div className="validator-message text-xs text-error"></div>
Unlock <button type="submit" className="btn btn-primary rounded-l-none">
</button> Unlock
</form> </button>
</form>
</div>
</div> </div>
</Modal> </div>
); );
} }
+296 -186
View File
@@ -1,12 +1,15 @@
import * as fabric from "fabric"; import * as fabric from "fabric";
import type * as React from "react"; import {
import { useCallback, useEffect, useImperativeHandle, useRef } from "react"; forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useRef,
} from "react";
const PAD = 36; const PAD = 36;
const BASE_WIDTH = 680; const BASE_WIDTH = 680;
const DEFAULT_LOGICAL_HEIGHT = 900; const DEFAULT_LOGICAL_HEIGHT = 900;
const DEFAULT_FONT_FAMILY = "Playfair Display Variable";
const DEFAULT_FONT_COLOR = "#000";
export interface FabricObjectJSON { export interface FabricObjectJSON {
type: string; type: string;
@@ -15,7 +18,6 @@ export interface FabricObjectJSON {
left: number; left: number;
width: number; width: number;
height: number; height: number;
[key: string]: unknown; [key: string]: unknown;
} }
@@ -31,26 +33,121 @@ export interface CanvasJSON {
canvasHeight?: number; canvasHeight?: number;
} }
export interface CanvasStyle {
fontFamily: string;
fontColor: string;
}
export type CanvasTools = { export type CanvasTools = {
addImage: (url: string, file: File) => void; addImage: (url: string, file: File) => void;
getData: () => CanvasJSON; getData: () => CanvasJSON;
getJsonData: () => string;
getImages: () => { src: string; file: File }[]; getImages: () => { src: string; file: File }[];
loadData: (data: CanvasJSON) => Promise<void>; loadData: (data: CanvasJSON) => Promise<void>;
getStyle: () => CanvasStyle;
}; };
export interface FabricImageWithFile extends fabric.FabricImage { export interface FabricImageWithFile extends fabric.FabricImage {
_customRawFile: File; _customRawFile: File;
} }
// NOTE: We use the same canvasData to render on both mobile and desktop viewports. const waitForLayout = (wrapper: HTMLDivElement): Promise<number> => {
// Instead of calculating the entire objects pad again, we apply a zoom multiplier (scale down or up) return new Promise((resolve) => {
// over the last saved canvas size. const check = () => {
const width = wrapper.clientWidth || 0;
if (width > 0) resolve(width);
else requestAnimationFrame(check);
};
check();
});
};
const createMainTextbox = (
text: string,
isReadOnly = false,
): fabric.Textbox => {
return new fabric.Textbox(text, {
name: "main-textbox",
originX: "left",
originY: "top",
left: PAD,
top: PAD,
width: BASE_WIDTH - PAD * 2,
fontSize: 18,
fontWeight: 500,
fontFamily: "Playfair Display Variable",
fill: "#000",
lineHeight: 1.5,
editable: !isReadOnly,
selectable: false,
evented: !isReadOnly,
hasControls: false,
hasBorders: false,
objectCaching: false,
splitByGrapheme: false,
lockMovementX: true,
lockMovementY: true,
lockScalingX: true,
lockScalingY: true,
lockRotation: true,
});
};
const fixFabricA11y = () => {
const textAreas = document.querySelectorAll(
'textarea[data-fabric="textarea"]',
);
for (const area of textAreas) {
if (!area.getAttribute("aria-label")) {
area.setAttribute("aria-label", "Canvas text input");
}
}
};
const initializeCanvas = (
el: HTMLCanvasElement,
width: number,
height: number,
readOnly: boolean,
) => {
const canvas = new fabric.Canvas(el, {
width,
height,
selection: !readOnly,
preserveObjectStacking: true,
allowTouchScrolling: true,
enableRetinaScaling: true,
objectCaching: false,
});
const wrapperEl = canvas.getElement().parentElement;
if (wrapperEl) wrapperEl.style.background = "transparent";
return canvas;
};
const getLogicalSize = (data: CanvasJSON | null) => {
return {
width: data?.canvasWidth ?? BASE_WIDTH,
height: data?.canvasHeight ?? DEFAULT_LOGICAL_HEIGHT,
};
};
const getObjectBottom = (obj: fabric.FabricObject) => {
const top = obj.top ?? 0;
const height =
typeof obj.getScaledHeight === "function"
? obj.getScaledHeight()
: (obj.height ?? 0) * (obj.scaleY ?? 1);
return top + height;
};
const measureLogicalContentHeight = (
canvas: fabric.Canvas,
minimumHeight = DEFAULT_LOGICAL_HEIGHT,
) => {
const maxBottom = canvas
.getObjects()
.reduce((max, obj) => Math.max(max, getObjectBottom(obj)), 0);
return Math.max(minimumHeight, maxBottom + PAD);
};
const applyResponsiveViewport = ( const applyResponsiveViewport = (
canvas: fabric.Canvas, canvas: fabric.Canvas,
wrapper: HTMLDivElement, wrapper: HTMLDivElement,
@@ -58,8 +155,8 @@ const applyResponsiveViewport = (
logicalHeight: number, logicalHeight: number,
) => { ) => {
const physicalWidth = wrapper.clientWidth || logicalWidth; const physicalWidth = wrapper.clientWidth || logicalWidth;
const zoomMultiplier = physicalWidth / logicalWidth; const zoom = physicalWidth / logicalWidth;
const physicalHeight = Math.max(1, logicalHeight * zoomMultiplier); const physicalHeight = Math.max(1, logicalHeight * zoom);
canvas.setDimensions({ canvas.setDimensions({
width: physicalWidth, width: physicalWidth,
@@ -67,45 +164,41 @@ const applyResponsiveViewport = (
}); });
wrapper.style.height = `${physicalHeight}px`; wrapper.style.height = `${physicalHeight}px`;
canvas.setViewportTransform([zoomMultiplier, 0, 0, zoomMultiplier, 0, 0]); canvas.setViewportTransform([zoom, 0, 0, zoom, 0, 0]);
canvas.requestRenderAll(); canvas.requestRenderAll();
}; };
// to find the maximum height of the content to dynamically resize the canvas const focusTextbox = (
// would've been wayyy easier only if canvas supported fit-content like CSS property :) fCanvas: fabric.Canvas,
const measureLogicalContentHeight = ( textbox: fabric.Textbox,
canvas: fabric.Canvas, readOnly: boolean,
minimumHeight = DEFAULT_LOGICAL_HEIGHT,
) => { ) => {
const maxBottom = canvas.getObjects().reduce((maxHeight, currObj) => { if (readOnly) return;
const top = currObj.top;
const height = currObj.getScaledHeight();
return Math.max(maxHeight, top + height);
}, 0);
return Math.max(minimumHeight, maxBottom + PAD); fCanvas.setActiveObject(textbox);
textbox.enterEditing();
const end = textbox.text?.length ?? 0;
textbox.selectionStart = end;
textbox.selectionEnd = end;
fCanvas.requestRenderAll();
fixFabricA11y();
}; };
const DEFAULT_INIT_TEXT = "Take a deep breath..."; const findMainTextbox = (canvas: fabric.Canvas): fabric.Textbox | null => {
const textbox = canvas.getObjects("Textbox")[0];
interface ComposeCanvasProps { return (textbox as fabric.Textbox) ?? null;
readOnly?: boolean; };
initialData?: CanvasJSON | null;
style?: CanvasStyle;
ref?: React.Ref<CanvasTools>;
}
export function ComposeCanvas({ export const ComposeCanvas = forwardRef<
readOnly = false, CanvasTools,
initialData = null, { readOnly?: boolean; initialData?: CanvasJSON | null }
style, >(({ readOnly = false, initialData = null }, ref) => {
ref,
}: ComposeCanvasProps) {
// wrapper is the parent div box
const wrapperRef = useRef<HTMLDivElement>(null); const wrapperRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null); const canvasRef = useRef<HTMLCanvasElement>(null);
const fabricRef = useRef<fabric.Canvas | null>(null); const fabricRef = useRef<fabric.Canvas | null>(null);
const textboxRef = useRef<fabric.Textbox | null>(null); const textboxRef = useRef<fabric.Textbox | null>(null);
const deferredDataRef = useRef<CanvasJSON | null>(null); const deferredDataRef = useRef<CanvasJSON | null>(null);
const logicalSizeRef = useRef({ const logicalSizeRef = useRef({
@@ -113,202 +206,186 @@ export function ComposeCanvas({
height: DEFAULT_LOGICAL_HEIGHT, height: DEFAULT_LOGICAL_HEIGHT,
}); });
// re-calculates height based on content and applies the zoom transform
const syncViewport = useCallback(() => { const syncViewport = useCallback(() => {
if (!(fabricRef.current && wrapperRef.current)) return; if (!(fabricRef.current && wrapperRef.current)) return;
const minHeight = initialData?.canvasHeight ?? DEFAULT_LOGICAL_HEIGHT;
logicalSizeRef.current.height = measureLogicalContentHeight(
fabricRef.current,
minHeight,
);
applyResponsiveViewport( applyResponsiveViewport(
fabricRef.current, fabricRef.current,
wrapperRef.current, wrapperRef.current,
logicalSizeRef.current.width, logicalSizeRef.current.width,
logicalSizeRef.current.height, logicalSizeRef.current.height,
); );
}, []);
fabricRef.current.requestRenderAll(); const updateLogicalHeightFromContent = useCallback(() => {
}, [initialData]); if (!fabricRef.current) return;
// auto focus the cursor into the main textbox no matter the latest element added logicalSizeRef.current.height = measureLogicalContentHeight(
const focusTextbox = useCallback( fabricRef.current,
(textbox: fabric.Textbox) => { logicalSizeRef.current.height,
if (readOnly || !fabricRef.current) return; );
fabricRef.current.setActiveObject(textbox); syncViewport();
textbox.enterEditing(); }, [syncViewport]);
// move the cursor to the end of the text const setupTextboxInteractions = useCallback(
const textLength = textbox.text?.length ?? 0; (fCanvas: fabric.Canvas, textbox: fabric.Textbox) => {
textbox.selectionStart = textLength; textbox.on("changed", () => {
textbox.selectionEnd = textLength; updateLogicalHeightFromContent();
});
fabricRef.current.requestRenderAll(); fCanvas.on("mouse:down", (opt) => {
if (!opt.target || opt.target === textbox) {
focusTextbox(fCanvas, textbox, readOnly);
}
});
if (!readOnly) {
setTimeout(() => {
focusTextbox(fCanvas, textbox, readOnly);
}, 200);
}
}, },
[readOnly], [readOnly, updateLogicalHeightFromContent],
); );
const loadContent = useCallback( const loadContent = useCallback(
async (data: CanvasJSON | null) => { async (
const canvas = fabricRef.current; canvas: fabric.Canvas,
const wrapper = wrapperRef.current; data: CanvasJSON | null,
if (!(canvas && wrapper)) return; wrapper: HTMLDivElement,
): Promise<fabric.Textbox | null> => {
const logicalSize = getLogicalSize(data);
logicalSizeRef.current = logicalSize;
// clean the canvas everytime and set fresh
canvas.clear(); canvas.clear();
let textbox: fabric.Textbox | null = null;
// restore logical size from prev saved data if available (in case of existing letter) let textbox: fabric.Textbox | null = null;
logicalSizeRef.current = {
width: data?.canvasWidth ?? BASE_WIDTH,
height: data?.canvasHeight ?? DEFAULT_LOGICAL_HEIGHT,
};
if (data?.objects?.length) { if (data?.objects?.length) {
await canvas.loadFromJSON(data); await canvas.loadFromJSON(data);
textbox = canvas.getObjects("Textbox")[0] as fabric.Textbox; textbox = findMainTextbox(canvas);
} else { } else {
// Create a fresh letter if no data exists textbox = createMainTextbox("Take a deep breath...", readOnly);
textbox = new fabric.Textbox(DEFAULT_INIT_TEXT, {
name: "main-textbox",
originX: "left",
originY: "top",
left: PAD,
top: PAD,
width: BASE_WIDTH - PAD * 2,
fontSize: 18,
fontWeight: 500,
fontFamily: DEFAULT_FONT_FAMILY,
fill: DEFAULT_FONT_COLOR,
lineHeight: 1.5,
// NOTE: splitByGrapheme is required for word wrap and re-low
// but fabric asks to disable this for clear font?? So we disable it for read view
splitByGrapheme: !readOnly,
lockMovementX: true,
lockMovementY: true,
lockScalingX: true,
lockScalingY: true,
lockRotation: true,
hasControls: false,
hasBorders: false,
objectCaching: false,
noScaleCache: false,
});
canvas.add(textbox); canvas.add(textbox);
} }
if (!textbox) return; if (!textbox) return null;
// readonly contraints applicable for post seal view
textbox.selectable = !readOnly; textbox.selectable = !readOnly;
textbox.evented = !readOnly; textbox.evented = !readOnly;
textbox.editable = !readOnly; textbox.editable = !readOnly;
textbox.hasBorders = false; textbox.hasBorders = false;
textbox.lockMovementX = true;
textbox.lockMovementY = true;
textbox.lockScalingX = true;
textbox.lockScalingY = true;
textbox.lockRotation = true;
textbox.objectCaching = false;
textboxRef.current = textbox; logicalSizeRef.current.height = measureLogicalContentHeight(
canvas,
logicalSize.height,
);
// observe and auto-resize the canvas height whenever typed applyResponsiveViewport(
textbox.on("changed", syncViewport); canvas,
wrapper,
logicalSizeRef.current.width,
logicalSizeRef.current.height,
);
// trapping the focus into the textbox wherever clicked on canvas (except images) if (!(readOnly || data)) {
canvas.on("mouse:down", (e) => { focusTextbox(canvas, textbox, readOnly);
if (!e.target || e.target === textbox) {
focusTextbox(textbox);
}
});
syncViewport();
// Hack: Fabric needs a small initial delay to mount before it will accept focus.
// otherwise it goes to the front
if (!readOnly) {
setTimeout(() => focusTextbox(textbox), 200);
} }
return textbox;
}, },
[readOnly, syncViewport, focusTextbox], [readOnly],
); );
useEffect(() => {
if (style && textboxRef.current) {
const textBox = textboxRef.current;
textBox.fontFamily = style.fontFamily || textBox.fontFamily;
textBox.fill = style.fontColor || textBox.fill;
syncViewport();
}
}, [style, syncViewport]);
useEffect(() => { useEffect(() => {
let isMounted = true; let isMounted = true;
let canvas: fabric.Canvas | null = null;
let resizeObserver: ResizeObserver | null = null; let resizeObserver: ResizeObserver | null = null;
let lastWidth = 0; let lastWidth = 0;
const initCanvas = async () => { const init = async () => {
// HACK: actual font may change the text-width - small ux improvement
await document.fonts.ready; await document.fonts.ready;
if (!(wrapperRef.current && canvasRef.current && isMounted)) return; if (!(wrapperRef.current && canvasRef.current && isMounted)) return;
let width = wrapperRef.current.clientWidth; const finalWidth = await waitForLayout(wrapperRef.current);
if (width === 0) { if (!(isMounted && canvasRef.current && wrapperRef.current)) return;
await new Promise((resolve) => requestAnimationFrame(resolve));
width = wrapperRef.current?.clientWidth || BASE_WIDTH;
}
// init the fabric instance canvas = initializeCanvas(
const canvas = new fabric.Canvas(canvasRef.current, { canvasRef.current,
width, finalWidth,
height: DEFAULT_LOGICAL_HEIGHT, DEFAULT_LOGICAL_HEIGHT,
selection: !readOnly, readOnly,
preserveObjectStacking: true, );
allowTouchScrolling: true,
enableRetinaScaling: true,
objectCaching: false,
});
// remove default fabric background to let our CSS show through
// TODO: provision custom bg (color in scope, but how does img fit?)
const wrapperEl = canvas.getElement().parentElement;
if (wrapperEl) wrapperEl.style.background = "transparent";
fabricRef.current = canvas; fabricRef.current = canvas;
await loadContent(initialData); const textbox = await loadContent(
canvas,
initialData,
wrapperRef.current,
);
// sometimes loadData() may be called before the canvas finished the init render if (textbox) {
// so we retry that stashed render right after the init textboxRef.current = textbox;
if (deferredDataRef.current) { setupTextboxInteractions(canvas, textbox);
await loadContent(deferredDataRef.current);
deferredDataRef.current = null;
} }
// auto window resizing based width canvas.requestRenderAll();
fixFabricA11y();
lastWidth = wrapperRef.current.clientWidth; lastWidth = wrapperRef.current.clientWidth;
resizeObserver = new ResizeObserver(() => { resizeObserver = new ResizeObserver(() => {
const nextWidth = wrapperRef.current?.clientWidth; if (!(fabricRef.current && wrapperRef.current)) return;
const nextWidth = wrapperRef.current.clientWidth;
if (!nextWidth || nextWidth === lastWidth) return; if (!nextWidth || nextWidth === lastWidth) return;
lastWidth = nextWidth; lastWidth = nextWidth;
syncViewport(); syncViewport();
}); });
resizeObserver.observe(wrapperRef.current!);
resizeObserver.observe(wrapperRef.current);
if (deferredDataRef.current) {
const data = deferredDataRef.current;
deferredDataRef.current = null;
const textbox = await loadContent(canvas, data, wrapperRef.current);
if (textbox) {
textboxRef.current = textbox;
setupTextboxInteractions(canvas, textbox);
}
canvas.requestRenderAll();
fixFabricA11y();
}
}; };
initCanvas().then(); init();
return () => { return () => {
isMounted = false; isMounted = false;
resizeObserver?.disconnect(); resizeObserver?.disconnect();
fabricRef.current?.dispose(); canvas?.dispose();
fabricRef.current = null; fabricRef.current = null;
textboxRef.current = null; textboxRef.current = null;
}; };
}, [initialData, loadContent, readOnly, syncViewport]); }, [
initialData,
loadContent,
readOnly,
setupTextboxInteractions,
syncViewport,
]);
// WHY?: fabric doesn't work like react with state and props based optimized re-renders.
// everytime we there's a change in the data, we should force the render,
// so we let the parent Editor component take control of this.
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
addImage: (url: string, file: File) => { addImage: (url: string, file: File) => {
if (!fabricRef.current) return; if (!fabricRef.current) return;
@@ -318,39 +395,69 @@ export function ComposeCanvas({
img.set({ img.set({
originX: "left", originX: "left",
originY: "top", originY: "top",
_customRawFile: file,
left: PAD, left: PAD,
top: PAD, top: PAD,
noScaleCache: false,
objectCaching: false, objectCaching: false,
// WHY?: after image object clean-up, its src becomes local blob://
// but browser won't let us parse this blob:// into file afterwards. so we hold a local copy
_customRawFile: file,
} as Partial<FabricImageWithFile>); } as Partial<FabricImageWithFile>);
fabricRef.current?.add(img); fabricRef.current?.add(img);
fabricRef.current?.setActiveObject(img); fabricRef.current?.setActiveObject(img);
syncViewport(); if (!fabricRef.current) return;
// clean up memory
logicalSizeRef.current.height = measureLogicalContentHeight(
fabricRef.current,
logicalSizeRef.current.height,
);
if (wrapperRef.current) {
applyResponsiveViewport(
fabricRef.current,
wrapperRef.current,
logicalSizeRef.current.width,
logicalSizeRef.current.height,
);
} else {
fabricRef.current?.requestRenderAll();
}
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
}); });
}, },
getData: () => { getData: () => {
if (!fabricRef.current) return { objects: [] }; if (!fabricRef.current) return { objects: [] };
syncViewport();
logicalSizeRef.current.height = measureLogicalContentHeight(
fabricRef.current,
logicalSizeRef.current.height,
);
const json = fabricRef.current.toJSON() as CanvasJSON; const json = fabricRef.current.toJSON() as CanvasJSON;
json.canvasWidth = logicalSizeRef.current.width; json.canvasWidth = logicalSizeRef.current.width;
json.canvasHeight = logicalSizeRef.current.height; json.canvasHeight = logicalSizeRef.current.height;
return json; return json;
}, },
getJsonData: () => {
if (!fabricRef.current) return "";
const json = fabricRef.current.toJSON() as CanvasJSON;
json.canvasWidth = logicalSizeRef.current.width;
json.canvasHeight = logicalSizeRef.current.height;
return JSON.stringify(json);
},
getImages: () => { getImages: () => {
if (!fabricRef.current) return []; if (!fabricRef.current) return [];
const images = fabricRef.current.getObjects( const images = fabricRef.current.getObjects(
"Image", "Image",
) as FabricImageWithFile[]; ) as FabricImageWithFile[];
return images.map((img) => ({ return images.map((img) => ({
src: img.getSrc(), src: img.getSrc(),
file: img._customRawFile, file: img._customRawFile,
@@ -358,21 +465,24 @@ export function ComposeCanvas({
}, },
loadData: async (data: CanvasJSON) => { loadData: async (data: CanvasJSON) => {
// if canvas isn't ready yet, stash the data and let the useEffect pick it up if (!(fabricRef.current && wrapperRef.current)) {
if (!fabricRef.current) {
deferredDataRef.current = data; deferredDataRef.current = data;
return; return;
} }
await loadContent(data);
},
getStyle: () => { const textbox = await loadContent(
const textBox = textboxRef.current; fabricRef.current,
data,
wrapperRef.current,
);
return { if (textbox) {
fontFamily: textBox?.fontFamily || DEFAULT_FONT_FAMILY, textboxRef.current = textbox;
fontColor: (textBox?.fill as string) || DEFAULT_FONT_COLOR, setupTextboxInteractions(fabricRef.current, textbox);
}; }
fabricRef.current.requestRenderAll();
fixFabricA11y();
}, },
})); }));
@@ -388,6 +498,6 @@ export function ComposeCanvas({
/> />
</div> </div>
); );
} });
ComposeCanvas.displayName = "ComposeCanvas"; ComposeCanvas.displayName = "ComposeCanvas";
@@ -1,7 +1,6 @@
import { LockIcon } from "@phosphor-icons/react"; import { LockIcon } from "@phosphor-icons/react";
import type { NavigateFunction } from "react-router-dom"; import type { NavigateFunction } from "react-router-dom";
import { PATHS, ROUTES } from "../../config/routes"; import { PATHS, ROUTES } from "../../config/routes";
import { Modal } from "../ui/Modal";
interface PostSealModalProps { interface PostSealModalProps {
sealedTargetId: string | null; sealedTargetId: string | null;
@@ -14,68 +13,72 @@ export function PostSealModal({
navigate, navigate,
type = "KEPT", type = "KEPT",
}: PostSealModalProps) { }: PostSealModalProps) {
if (!sealedTargetId) return null;
return ( return (
<Modal isOpen={!!sealedTargetId}> <div className="modal modal-open modal-middle bg-base-100/20 backdrop-blur-md z-1000">
<LockIcon size={32} weight="duotone" className="text-primary mt-3" /> <div className="modal-box flex flex-col items-center text-center gap-6">
<h3 className="font-serif text-2xl">Your letter is sealed</h3> <LockIcon size={32} weight="duotone" className="text-primary mt-3" />
<p className="text-base-content/60"> <h3 className="font-serif text-2xl">Your letter is sealed</h3>
It's encrypted and always safe in your drawer. <p className="text-base-content/60">
</p> It's encrypted and always safe in your drawer.
{type === "KEPT" ? (
<p className="text-base-content/80 text-sm font-sans">
When you're ready,
<br />
you can{" "}
<span className="text-primary font-bold font-display">read</span> it,{" "}
<span className="text-accent font-bold font-display">send</span> it to
someone, or{" "}
<span className="text-error font-bold font-display">burn</span> it to
release
</p> </p>
) : (
<p className="text-base-content/80 text-sm font-sans">
Be assured that the letter will find you when the time is right.
<br />
Till then,{" "}
<span className="font-bold font-display text-primary">
take a deep breath
</span>
, <span className="font-bold font-display text-accent">manifest</span>
, and{" "}
<span className="font-bold font-display text-success">
let it rest
</span>
.
</p>
)}
<div className="modal-action w-full justify-center gap-3 mt-4 mb-4">
{type === "KEPT" ? ( {type === "KEPT" ? (
<> <p className="text-base-content/80 text-sm font-sans">
When you're ready,
<br />
you can{" "}
<span className="text-primary font-bold font-display">read</span>{" "}
it, <span className="text-accent font-bold font-display">send</span>{" "}
it to someone, or{" "}
<span className="text-error font-bold font-display">burn</span> it
to release
</p>
) : (
<p className="text-base-content/80 text-sm font-sans">
Be assured that the letter will find you when the time is right.
<br />
Till then,{" "}
<span className="font-bold font-display text-primary">
take a deep breath
</span>
,{" "}
<span className="font-bold font-display text-accent">manifest</span>
, and{" "}
<span className="font-bold font-display text-success">
let it rest
</span>
.
</p>
)}
<div className="modal-action w-full justify-center gap-3 mt-4 mb-4">
{type === "KEPT" ? (
<>
<button
type="button"
className="btn btn-ghost btn-sm"
onClick={() => navigate(ROUTES.DRAWER)}
>
Keep it to myself
</button>
<button
type="button"
className="btn btn-primary btn-sm"
onClick={() => navigate(PATHS.read(sealedTargetId))}
>
View letter
</button>
</>
) : (
<button <button
type="button" type="button"
className="btn btn-ghost btn-sm" className="btn btn-ghost btn-sm"
onClick={() => navigate(ROUTES.DRAWER)} onClick={() => navigate(ROUTES.DRAWER)}
> >
Keep it to myself Step Away...
</button> </button>
<button )}
type="button" </div>
className="btn btn-primary btn-sm"
onClick={() => navigate(PATHS.read(sealedTargetId!))}
>
View letter
</button>
</>
) : (
<button
type="button"
className="btn btn-ghost btn-sm"
onClick={() => navigate(ROUTES.DRAWER)}
>
Step Away...
</button>
)}
</div> </div>
</Modal> </div>
); );
} }
+69 -170
View File
@@ -1,146 +1,49 @@
import { import {
CircleHalfTiltIcon,
ImageIcon, ImageIcon,
LockIcon, LockIcon,
PaintBucketIcon,
QuestionIcon, QuestionIcon,
StampIcon, StampIcon,
TextAUnderlineIcon,
TrayIcon, TrayIcon,
VaultIcon, VaultIcon,
XCircleIcon,
} from "@phosphor-icons/react"; } from "@phosphor-icons/react";
import { Modal } from "../ui/Modal";
import type { CanvasStyle } from "./ComposeCanvas.tsx";
interface ToolBarProps { interface ToolBarProps {
onAddImage: () => void; fileInputRef: React.RefObject<HTMLInputElement | null>;
sealBtnClicked: boolean; sealBtnClicked: boolean;
setSealBtnClicked: (v: boolean) => void; setSealBtnClicked: (v: boolean) => void;
onSave: (status: "SEALED" | "DRAFT" | "VAULT", date?: Date) => Promise<void>; onSave: (status: "SEALED" | "DRAFT" | "VAULT", date?: Date) => Promise<void>;
setConfirmModal: (v: "VAULT" | "SEAL" | null) => void; setConfirmModal: (v: "VAULT" | "SEAL" | null) => void;
onFontChange: (style: CanvasStyle) => void;
latestFontStyle: CanvasStyle;
} }
const FONT_FAMILIES: Map<string, string> = new Map([
["Serif", "Playfair Display Variable"],
["Sans", "Jost Variable"],
["Cursive", "Playwrite HR Lijeva Variable"],
["Handwriting", "Architects Daughter"],
["Slab", "Cutive Mono"],
["Mono", "Space Mono"],
["Tamil", "Kavivanar"],
["Crazy(pls no)", "Redacted Script"],
]);
const FONT_COLORS: Map<string, string> = new Map([
["Black", "#000"],
["Gold", "#866a0e"],
["Purple", "#711caf"],
["Green", "#1f5b1f"],
["Blue", "#111e67"],
]);
export function ToolBar({ export function ToolBar({
onAddImage, fileInputRef,
sealBtnClicked, sealBtnClicked,
setSealBtnClicked, setSealBtnClicked,
onSave, onSave,
setConfirmModal, setConfirmModal,
onFontChange,
latestFontStyle,
}: ToolBarProps) { }: ToolBarProps) {
return ( return (
<div <div
id="writer-toolbar" id="writer-toolbar"
className="relative z-10 flex items-center justify-between mb-8 h-14 bg-base-100/50 backdrop-blur-md rounded-full border border-base-content/5 px-6" className="flex items-center justify-between mb-8 h-14 bg-base-100/50 backdrop-blur-md rounded-full border border-base-content/5 px-6"
> >
<div className="flex gap-4"> <div className="flex gap-4">
{/* Image upload */}
<button <button
type="button" type="button"
className="btn btn-ghost btn-sm group" className="btn btn-ghost btn-sm group"
onClick={onAddImage} onClick={() => fileInputRef.current?.click()}
> >
<ImageIcon size={18} weight="bold" /> <ImageIcon size={18} weight="bold" />
<span className="hidden md:inline group-hover:inline transition-all duration-1000"> <span className="hidden md:inline group-hover:inline transition-all duration-1000">
Add Image Add Image
</span> </span>
</button> </button>
<div className="w-px h-4 bg-base-content/10 mx-2 my-auto hidden md:inline" />
{/* Font Family */}
<div className={"flex items-center gap-2 group"}>
<TextAUnderlineIcon
size={24}
weight="bold"
className={"hidden md:inline"}
/>
<select
className="select select-sm"
onChange={(e) => {
onFontChange({ ...latestFontStyle, fontFamily: e.target.value });
}}
value={latestFontStyle.fontFamily}
>
{Array.from(FONT_FAMILIES.entries()).map(
([fontFamily, fontName]) => {
return (
<option key={fontName} value={fontName}>
{fontFamily}
</option>
);
},
)}
</select>
</div>
<div className="w-px h-4 bg-base-content/10 mx-2 my-auto hidden md:inline" />
{/* Font Color */}
<div className="dropdown dropdown-bottom flex items-center gap-2 group">
<PaintBucketIcon
size={16}
weight="bold"
className={"hidden md:flex"}
/>
<button
className="btn btn-ghost btn-sm px-2 gap-2 flex items-center"
type={"button"}
>
<CircleHalfTiltIcon
size={18}
style={{ color: latestFontStyle.fontColor }}
weight="duotone"
/>
</button>
<ul className="dropdown-content z-50 menu p-2 shadow bg-base-200/95 rounded-full md:ml-4">
{Array.from(FONT_COLORS.entries()).map(([_, colorCode]) => (
<li key={colorCode}>
<button
type="button"
className={`${latestFontStyle.fontColor === colorCode ? "active" : ""}`}
onClick={() => {
onFontChange({ ...latestFontStyle, fontColor: colorCode });
(document.activeElement as HTMLButtonElement)?.blur();
}}
>
<CircleHalfTiltIcon
size={18}
style={{ color: colorCode }}
weight="fill"
/>
</button>
</li>
))}
</ul>
</div>
</div> </div>
{/* Draft */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <button
type="button" type="button"
className="btn btn-ghost btn-sm text-xxs group tracking-widester uppercase font-bold text-base-content/60 hover:text-base-content" className="btn btn-ghost btn-sm text-[10px] group tracking-[0.2em] uppercase font-bold text-base-content/60 hover:text-base-content"
title="Store in your private drawer" title="Store in your private drawer"
onClick={() => onSave("DRAFT")} onClick={() => onSave("DRAFT")}
> >
@@ -150,9 +53,8 @@ export function ToolBar({
</span> </span>
</button> </button>
<div className="w-px h-4 bg-base-content/10 mx-2 hidden md:inline" /> <div className="w-px h-4 bg-base-content/10 mx-2" />
{/*Seal */}
<button <button
type="button" type="button"
className={`btn btn-primary btn-sm rounded-full px-6 group ${sealBtnClicked ? "invisible" : "visible"}`} className={`btn btn-primary btn-sm rounded-full px-6 group ${sealBtnClicked ? "invisible" : "visible"}`}
@@ -172,7 +74,7 @@ export function ToolBar({
</div> </div>
<div <div
className={`flex-col items-center gap-2 absolute right-0 z-10 bg-primary/20 rounded-full p-8 -m-2 ${sealBtnClicked ? "" : "hidden"}`} className={`flex-col items-center gap-2 absolute right-0 z-100000 bg-primary/20 rounded-full p-8 -m-2 ${sealBtnClicked ? "" : "hidden"}`}
> >
<button <button
type="button" type="button"
@@ -198,17 +100,11 @@ export function ToolBar({
<span className="transition-all duration-1000">Vault</span> <span className="transition-all duration-1000">Vault</span>
</button> </button>
</div> </div>
<button
className={`z-100001 absolute right-0 bg-transparent cursor-pointer ${sealBtnClicked ? "" : "hidden"}`}
type="button"
onClick={() => setSealBtnClicked(false)}
>
<XCircleIcon weight="duotone" size={20} className={"text-error"} />
</button>
<button <button
type="button" type="button"
aria-label="Help" aria-label="Help"
className={`bg-transparent cursor-pointer -mt-2 absolute z-100001 right-0 text-primary ${sealBtnClicked ? "" : "hidden"}`} onClick={() => setSealBtnClicked(false)}
className={`bg-transparent cursor-pointer -mt-2 absolute z-1000001 right-0 text-primary ${sealBtnClicked ? "" : "hidden"}`}
> >
<div className="tooltip tooltip-left"> <div className="tooltip tooltip-left">
<div className="tooltip-content -translate-x-38 text-left"> <div className="tooltip-content -translate-x-38 text-left">
@@ -234,7 +130,7 @@ export function LetterHead() {
<div className="flex items-center justify-center mb-8 h-14"> <div className="flex items-center justify-center mb-8 h-14">
<div className="badge badge-outline border-primary/20 bg-primary/5 text-primary gap-2 p-4 rounded-full"> <div className="badge badge-outline border-primary/20 bg-primary/5 text-primary gap-2 p-4 rounded-full">
<LockIcon size={14} weight="fill" /> <LockIcon size={14} weight="fill" />
<span className="text-xxs uppercase tracking-widest font-bold"> <span className="text-[10px] uppercase tracking-widest font-bold">
Sealed & View Only Sealed & View Only
</span> </span>
</div> </div>
@@ -254,62 +150,65 @@ export function VaultConfirmModal({
setUnlockDate, setUnlockDate,
}: VaultConfirmModalProps) { }: VaultConfirmModalProps) {
return ( return (
<Modal isOpen={true}> <div className={"modal modal-open bg-base-100/10 backdrop-blur-md"}>
<VaultIcon <div className="modal-box p-12 flex flex-col items-center bg-base-100/90">
size={48} <VaultIcon
className="text-primary mx-auto mb-8 animate-pulse" size={48}
/> className="text-primary mx-auto mb-8 animate-pulse"
<h3 className="font-serif text-3xl">Take it away, then?</h3>
<p className="text-base-content/60 text-sm text-center mt-4">
By vaulting this letter, you ask me to hold on to this.
<br />
I'll remember to mail you this on the unlock date.
<br />
<span className={"font-bold text-primary"}>
{" "}
But I won't let you read or rewrite this letter until then.
</span>
<br />
</p>
<form
onSubmit={async (e) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const unlockDateStr = formData.get("vault-date") as string;
const newUnlockDate = new Date(unlockDateStr);
setUnlockDate(newUnlockDate);
await onSave("VAULT", newUnlockDate);
setConfirmModal(null);
}}
id="vault-form"
className="min-w-75"
>
<div className={"divider tracking-tightest font-display text-sm"}>
Set an unlock date
</div>
<input
required
type="date"
className="input input-bordered w-full"
name="vault-date"
/> />
<div className="w-full flex justify-center gap-8 mt-4"> <h3 className="font-serif text-3xl">Take it away, then?</h3>
<button <p className="text-base-content/60 text-sm text-center mt-4">
type="button" By vaulting this letter, you ask me to hold on to this.
className="btn btn-ghost btn-sm mt-4" <br />
onClick={() => setConfirmModal(null)} I'll remember to mail you this on the unlock date.
> <br />
I need time <span className={"font-bold text-primary"}>
</button> {" "}
<button But I won't let you read or rewrite this letter until then.
className="btn btn-primary btn-sm mt-4" </span>
type="submit" <br />
form="vault-form" </p>
> <form
Take it onSubmit={async (e) => {
</button> e.preventDefault();
</div> const formData = new FormData(e.currentTarget);
</form> const unlockDateStr = formData.get("vault-date") as string;
</Modal> const newUnlockDate = new Date(unlockDateStr);
console.log(newUnlockDate);
setUnlockDate(newUnlockDate);
await onSave("VAULT", newUnlockDate);
setConfirmModal(null);
}}
id="vault-form"
className="min-w-75"
>
<div className={"divider tracking-tightest font-display text-sm"}>
Set an unlock date
</div>
<input
required
type="date"
className="input input-bordered w-full"
name="vault-date"
/>
<div className="w-full flex justify-center gap-8 mt-4">
<button
type="button"
className="btn btn-ghost btn-sm mt-4"
onClick={() => setConfirmModal(null)}
>
I need time
</button>
<button
className="btn btn-primary btn-sm mt-4"
type="submit"
form="vault-form"
>
Take it
</button>
</div>
</form>
</div>
</div>
); );
} }
@@ -1,85 +0,0 @@
import {
HandPalmIcon,
ShieldCheckIcon,
WarningIcon,
} from "@phosphor-icons/react";
import Logo from "../Logo.tsx";
import { Modal } from "../ui/Modal";
import Saajan from "../ui/Saajan.tsx";
export default function WelcomeModal({
setShowWelcome,
}: {
setShowWelcome: (show: boolean) => void;
}) {
return (
<>
<Modal isOpen={true}>
<div className="flex flex-col items-center text-center gap-4">
<div className="bg-primary/10 p-4 rounded-full animate-pulse">
<ShieldCheckIcon
size={48}
weight="duotone"
className="text-primary"
/>
</div>
<h3 className="font-display text-2xl font-bold text-primary">
Welcome to &nbsp;
<Logo /> &nbsp;!
</h3>
<p className="text-base-content/80 leading-relaxed">
Before we begin, let me make a small promise.
<HandPalmIcon
size={18}
className="inline text-primary"
weight="fill"
/>
<div className="divider my-0"></div>
<br />
Everything you write here is sealed with your password,{" "}
<span className="font-display text-success">cryptographically</span>
, before it leaves your hands.
<br />A fancy way of saying, I couldn't if I tried.
</p>
<div className="alert alert-warning bg-paper/20 border-paper/20 flex items-start gap-3 text-left py-3">
<WarningIcon size={24} weight="fill" className="shrink-0 mt-0.5" />
<p className="text-sm font-medium text-primary-content">
If you ever happen to forget your password, your letters are lost
to time, forever.
<br />
<span className="font-bold mt-2">
I highly, highly recommend storing this password in your{" "}
<a
href="https://www.privacyguides.org/en/passwords/"
target="_blank"
className="link link-primary-content"
rel="noopener"
>
password manager
</a>{" "}
or somewhere safe to remember it.
</span>
</p>
</div>
<div className="modal-action w-full">
<button
type="button"
onClick={() => setShowWelcome(false)}
className="btn btn-primary w-full shadow-lg"
>
I'll remember
</button>
</div>
</div>
</Modal>
<div className="absolute bottom-0 right-0 z-1000 font-sans w-full">
<Saajan
position="top"
message={"I've lost words before.\nI know what it feels like."}
/>
</div>
</>
);
}
+14 -7
View File
@@ -1,12 +1,11 @@
import { CampfireIcon, FlameIcon } from "@phosphor-icons/react"; import { CampfireIcon, FlameIcon, XCircleIcon } from "@phosphor-icons/react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Modal } from "../ui/Modal";
interface BurnModalProps { interface BurnModalProps {
burnLetter: () => void; burnLetter: () => void;
isBurning: boolean; isBurning: boolean;
setShowBurnModal: (show: boolean) => void; setShowBurnModal: (show: boolean) => void;
setRevealState: (state: "SEALED" | "REVEALED" | "BURNING" | "BURNED") => void; setRevealState: (state: "sealed" | "revealed" | "burning" | "burned") => void;
} }
export function BurnModal({ export function BurnModal({
@@ -21,7 +20,7 @@ export function BurnModal({
useEffect(() => { useEffect(() => {
if (!burnClicked) return; if (!burnClicked) return;
if (flameOn === 100) { if (flameOn === 100) {
setRevealState("SEALED"); setRevealState("sealed");
burnLetter(); burnLetter();
} }
const interval = setInterval(() => { const interval = setInterval(() => {
@@ -34,15 +33,23 @@ export function BurnModal({
const burnStyle = flameOn < 30 ? "" : `contrast(${flameOn / 30})`; const burnStyle = flameOn < 30 ? "" : `contrast(${flameOn / 30})`;
return ( return (
<Modal isOpen={true} onClose={() => setShowBurnModal(false)}> <div className="modal modal-open modal-middle bg-base-100/20 backdrop-blur-md">
<div <div
className={`flex flex-col items-center gap-4 text-center transition-all duration-200 ease-in-out ${burnClicked ? "animate-[pulse_15s_linear_infinite]" : ""}`} className={`modal-box flex flex-col items-center gap-4 py-8 text-center transition-all duration-200 ease-in-out ${burnClicked ? "animate-[pulse_15s_linear_infinite]" : ""}`}
style={ style={
{ {
transform: `rotate(${rotate}deg)`, transform: `rotate(${rotate}deg)`,
} as React.CSSProperties } as React.CSSProperties
} }
> >
<button
type="button"
className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
onClick={() => setShowBurnModal(false)}
aria-label="Close"
>
<XCircleIcon size={18} weight="bold" />
</button>
<CampfireIcon <CampfireIcon
size={48} size={48}
weight="duotone" weight="duotone"
@@ -94,6 +101,6 @@ export function BurnModal({
</button> </button>
</div> </div>
</div> </div>
</Modal> </div>
); );
} }
@@ -1,6 +1,5 @@
import { WavesIcon } from "@phosphor-icons/react"; import { WavesIcon } from "@phosphor-icons/react";
import { useEffect, useState } from "react"; import { useEffect, useRef, useState } from "react";
import candle from "../../assets/envelope/candle.png";
import stamp from "../../assets/envelope/stamp.png"; import stamp from "../../assets/envelope/stamp.png";
import waxSeal from "../../assets/envelope/waxSeal.png"; import waxSeal from "../../assets/envelope/waxSeal.png";
@@ -11,7 +10,6 @@ export interface EnvelopeRevealProps {
ignite: boolean; ignite: boolean;
isFlip?: boolean; isFlip?: boolean;
isInteractive?: boolean; isInteractive?: boolean;
openFlap?: boolean;
} }
export function EnvelopeReveal({ export function EnvelopeReveal({
@@ -21,11 +19,9 @@ export function EnvelopeReveal({
ignite, ignite,
isFlip, isFlip,
isInteractive = true, isInteractive = true,
openFlap = false,
}: EnvelopeRevealProps) { }: EnvelopeRevealProps) {
const [revealLetter, setRevealLetter] = useState(false); const [revealLetter, setRevealLetter] = useState(false);
const [isFlipped, setIsFlipped] = useState(!!isFlip); const [isFlipped, setIsFlipped] = useState(!!isFlip);
const [isFlapOpen, setIsFlapOpen] = useState(!!openFlap);
useEffect(() => { useEffect(() => {
setIsFlipped(!!isFlip); setIsFlipped(!!isFlip);
@@ -36,9 +32,7 @@ export function EnvelopeReveal({
height: 0, height: 0,
}); });
useEffect(() => { const flapCheckbox = useRef<HTMLInputElement>(null);
setIsFlapOpen(openFlap);
}, [openFlap]);
useEffect(() => { useEffect(() => {
if (!ignite) { if (!ignite) {
@@ -74,8 +68,7 @@ export function EnvelopeReveal({
<input <input
type="checkbox" type="checkbox"
className="transition checkbox absolute h-full w-full text-transparent bg-transparent z-100" className="transition checkbox absolute h-full w-full text-transparent bg-transparent z-100"
checked={isFlapOpen} ref={flapCheckbox}
onChange={() => setIsFlapOpen((prev) => !prev)}
disabled={!isInteractive} disabled={!isInteractive}
/> />
</div> </div>
@@ -85,8 +78,8 @@ export function EnvelopeReveal({
} }
src={waxSeal} src={waxSeal}
alt="Seal" alt="Seal"
onClick={() => setIsFlapOpen((prev) => !prev)} onClick={() => flapCheckbox.current?.click()}
onKeyDown={() => setIsFlapOpen((prev) => !prev)} onKeyDown={() => flapCheckbox.current?.click()}
/> />
<button <button
type="button" type="button"
@@ -140,20 +133,15 @@ export function EnvelopeReveal({
</button> </button>
</div> </div>
{ignite && ( {ignite && (
<> <div className="absolute w-115 h-70 z-100 overflow-hidden flex align-baseline -translate-y-70 -translate-x-5">
<div className="absolute w-115 h-70 z-100 overflow-hidden flex align-baseline -translate-y-70 -translate-x-5"> <div
<div className="absolute z-1000 border-2 border-amber-200 -bottom-3 -right-3 w-0 h-0 transition-all duration-500 bg-base-100 rounded-tl-full rounded-bl-full origin-bottom-right"
className="absolute z-1000 border-2 border-amber-200 -bottom-3 -right-3 w-0 h-0 transition-all duration-500 bg-base-100 rounded-tl-full rounded-bl-full origin-bottom-right" style={{
style={{ width: 2 * burn.width,
width: 2 * burn.width, height: 2 * burn.height,
height: 2 * burn.height, }}
}} ></div>
></div> </div>
</div>
<div className="absolute z-1001 bottom-0 right-0 translate-x-15 translate-y-20">
<img src={candle} alt="candle" />
</div>
</>
)} )}
</> </>
); );
@@ -2,22 +2,22 @@ import { useNavigate } from "react-router-dom";
import { ROUTES } from "../../config/routes"; import { ROUTES } from "../../config/routes";
interface PostActionOverlayProps { interface PostActionOverlayProps {
revealState: "SEALED" | "REVEALED" | "BURNING" | "BURNED"; revealState: "sealed" | "revealed" | "burning" | "burned";
} }
export function PostActionOverlay({ revealState }: PostActionOverlayProps) { export function PostActionOverlay({ revealState }: PostActionOverlayProps) {
const navigate = useNavigate(); const navigate = useNavigate();
return ( return (
<div <div
className={`flex flex-col items-center justify-center min-h-screen bg-base-100 ${revealState === "BURNED" ? "opacity-100" : "opacity-0"} transition-all delay-1000 duration-1000`} className={`flex flex-col items-center justify-center min-h-screen bg-base-100 ${revealState === "burned" ? "opacity-100" : "opacity-0"} transition-all delay-300 duration-1000`}
> >
<h1 <h1
className={`text-6xl ${revealState === "BURNED" ? "opacity-100" : "opacity-0"} lg:text-9xl italic font-extralight text-base-content animate-[pulse_3s_ease-in-out_3]`} className={`text-6xl ${revealState === "burned" ? "opacity-100" : "opacity-0"} lg:text-9xl italic font-extralight text-base-content animate-[pulse_3s_ease-in-out_3]`}
> >
It is done It is done
</h1> </h1>
<div <div
className={`text-xl ${revealState === "BURNED" ? "opacity-100" : "opacity-0"} lg:text-4xl text-center font-extralight text-base-content font-display mt-8 delay-3000 transition-all duration-2000 tracking-wide`} className={`text-xl ${revealState === "burned" ? "opacity-100" : "opacity-0"} lg:text-4xl text-center font-extralight text-base-content font-display mt-8 delay-3000 transition-all duration-2000 tracking-wide`}
> >
<p className="w-full"> <p className="w-full">
May your <span className="italic text-primary">soul</span> find May your <span className="italic text-primary">soul</span> find
+21 -20
View File
@@ -1,6 +1,8 @@
import { EyeSlashIcon, PaperPlaneTiltIcon } from "@phosphor-icons/react"; import {
import { Modal } from "../ui/Modal"; EyeSlashIcon,
import Saajan from "../ui/Saajan"; PaperPlaneTiltIcon,
XCircleIcon,
} from "@phosphor-icons/react";
interface ShareModalProps { interface ShareModalProps {
shareLink: string | null; shareLink: string | null;
@@ -13,8 +15,16 @@ export function ShareModal({ shareLink, setShareLink }: ShareModalProps) {
await navigator.clipboard.writeText(shareLink); await navigator.clipboard.writeText(shareLink);
}; };
return ( return (
<> <div className="modal modal-open modal-middle bg-base-100/20 backdrop-blur-md z-100">
<Modal isOpen={!!shareLink} onClose={() => setShareLink(null)}> <div className="modal-box bg-base-100 border border-base-content/5 shadow-2xl relative">
<button
type="button"
className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
onClick={() => setShareLink(null)}
aria-label="Close"
>
<XCircleIcon size={18} weight="bold" />
</button>
<div className="flex flex-col items-center justify-center text-center gap-6 py-4"> <div className="flex flex-col items-center justify-center text-center gap-6 py-4">
<div className="space-y-2"> <div className="space-y-2">
<PaperPlaneTiltIcon <PaperPlaneTiltIcon
@@ -24,17 +34,14 @@ export function ShareModal({ shareLink, setShareLink }: ShareModalProps) {
/> />
<h3 className="font-serif text-3xl">Send this letter</h3> <h3 className="font-serif text-3xl">Send this letter</h3>
<p className="text-base-content/80 text-sm font-sans mt-4"> <p className="text-base-content/80 text-sm font-sans mt-4">
You've carried these words long enough. You've carried these words long enough. Send your letter now, and
<br /> let the <span className="text-accent font-display">unsaid</span>{" "}
Send your letter now, and let the{" "} finally find its home.
<span className="text-accent font-display">unsaid</span> finally
find its home.
</p> </p>
<div className="divider mx-auto" /> <div className="divider mx-auto" />
<blockquote className="text-sm info text-neutral-content/60 font-sans"> <blockquote className="text-sm info text-neutral-content/60 font-sans">
They'll receive it exactly as you're seeing it now. The recipient will have the same viewing experience like you do
<br /> now.
Nothing more, nothing less.
</blockquote> </blockquote>
</div> </div>
<div className="w-full flex items-center gap-2 bg-base-300 p-2 rounded-xl"> <div className="w-full flex items-center gap-2 bg-base-300 p-2 rounded-xl">
@@ -62,13 +69,7 @@ export function ShareModal({ shareLink, setShareLink }: ShareModalProps) {
</p> </p>
</div> </div>
</div> </div>
</Modal>
<div className="absolute bottom-0 z-1000 font-sans w-full">
<Saajan
position="top"
message={`Someone once said,\n"To send a letter is a good way to go somewhere without moving anything but your heart."\nThey were not wrong.`}
/>
</div> </div>
</> </div>
); );
} }
+1 -1
View File
@@ -31,7 +31,7 @@ export default function DateDisplay({
return ( return (
<div className={`text-right flex flex-col gap-2 min-w-35 ${className}`}> <div className={`text-right flex flex-col gap-2 min-w-35 ${className}`}>
<span className="text-xxs uppercase tracking-widester text-accent font-bold"> <span className="text-[10px] uppercase tracking-[0.4em] text-accent font-bold">
Date Date
</span> </span>
<span className="text-sm font-serif text-secondary-content italic whitespace-nowrap"> <span className="text-sm font-serif text-secondary-content italic whitespace-nowrap">
+35 -24
View File
@@ -1,5 +1,4 @@
import { WarningIcon } from "@phosphor-icons/react"; import { WarningIcon, XCircleIcon, XIcon } from "@phosphor-icons/react";
import { Modal } from "./Modal";
interface LogModalContent { interface LogModalContent {
status: "WARN" | "ERROR" | "RESET" | "SUCCESS"; status: "WARN" | "ERROR" | "RESET" | "SUCCESS";
@@ -16,28 +15,40 @@ export const LogModal = ({
onClose, onClose,
status, status,
}: LogModalContent) => { }: LogModalContent) => {
return ( return status === "RESET" || !isOpen ? (
<Modal isOpen={isOpen && status !== "RESET"} onClose={onClose}> <div></div>
<div ) : (
className={`alert ${status === "WARN" ? "alert-warning" : "alert-error"} flex flex-col items-center text-center gap-6 py-4`} <div className="modal modal-open modal-middle bg-base-100/20 backdrop-blur-md z-100">
> <div className="modal-box bg-transparent border-none shadow-none relative">
{status === "WARN" && ( <div
<WarningIcon className="text-warning" size={16} weight="duotone" /> className={`alert ${status === "WARN" ? "alert-warning" : "alert-error"} flex flex-col items-center text-center gap-6 py-4`}
)} >
{message} {status === "WARN" && (
{log && ( <WarningIcon className="text-warning" size={16} weight="bold" />
<> )}
<div className="divider text-primary-content text-xs uppercase tracking-widest"> {status === "ERROR" && (
Error Stack <XCircleIcon className="text-error" size={16} weight="bold" />
</div> )}
<div className="mockup-code bg-base-100 text-error w-full"> {message}
<pre> <div className="divider text-primary-content text-xs uppercase tracking-widest">
<code>{String(log)}</code> Error Stack
</pre> </div>
</div> <div className="mockup-code bg-base-100 text-error w-full">
</> <pre>
)} <code>{String(log)}</code>
</pre>
</div>
<form method="dialog">
<button
type="button"
onClick={onClose}
className="btn btn-sm btn-circle btn-ghost absolute right-6 top-6"
>
<XIcon size={6} weight="bold" />
</button>
</form>
</div>
</div> </div>
</Modal> </div>
); );
}; };
-30
View File
@@ -1,30 +0,0 @@
import { XCircleIcon } from "@phosphor-icons/react";
import type { ReactNode } from "react";
interface ModalProps {
isOpen: boolean;
onClose?: () => void;
children: ReactNode;
}
export function Modal({ isOpen, onClose, children }: ModalProps) {
if (!isOpen) return null;
return (
<div className="modal modal-open modal-middle backdrop-blur-md before:absolute before:top-0 before:left-0 before:w-full before:h-full before:content-[''] before:opacity-[0.03] before:z-10 before:pointer-events-none before:bg-[url('assets/noise.gif')]">
<div className="modal-box relative bg-base-100/60 flex flex-col items-center text-center gap-6">
{onClose && (
<button
type="button"
className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2 z-20"
onClick={onClose}
aria-label="Close"
>
<XCircleIcon size={18} weight="bold" />
</button>
)}
{children}
</div>
</div>
);
}
+1 -1
View File
@@ -21,7 +21,7 @@ export const Navbar = ({ child }: { child?: React.ReactNode }) => {
className="text-base-content/40 group-hover:text-primary transition-colors" className="text-base-content/40 group-hover:text-primary transition-colors"
/> />
</div> </div>
<span className="font-sans text-xxs tracking-widester uppercase font-bold text-base-content/30 group-hover:text-base-content transition-colors"> <span className="font-sans text-[10px] tracking-[0.3em] uppercase font-bold text-base-content/30 group-hover:text-base-content transition-colors">
Drawer Drawer
</span> </span>
</button> </button>
+1 -1
View File
@@ -39,7 +39,7 @@ export default function Saajan({ message, position = "right" }: SaajanProps) {
return ( return (
<div className={`relative w-full flex ${alignment}`}> <div className={`relative w-full flex ${alignment}`}>
<div <div
className={`tooltip tooltip-open ${tooltipPosition} before:border before:border-dashed before:border-primary/40 before:max-w-xs before:whitespace-pre-line italic before:text-left`} className={`tooltip tooltip-open ${tooltipPosition} before:max-w-xs before:whitespace-pre-line italic before:text-left`}
data-tip={message} data-tip={message}
> >
<img <img
+4 -4
View File
@@ -9,14 +9,14 @@ export const endpoints = {
LETTERS: "/api/letters/", LETTERS: "/api/letters/",
}; };
// constructs dynamic path params for activate flow // simple utility to handle path params
export const replacePathParams = ( export const replacePathParams = (
url: string, url: string,
params: Record<string, string>, params: Record<string, string>,
): string => { ): string => {
let constructedUrl = url; let result = url;
for (const [key, value] of Object.entries(params)) { for (const [key, value] of Object.entries(params)) {
constructedUrl = constructedUrl.replace(`:${key}`, value); result = result.replace(`:${key}`, value);
} }
return constructedUrl; return result;
}; };
+4 -3
View File
@@ -1,4 +1,4 @@
// Page Route PATTERNS // Route PATTERNS
export const ROUTES = { export const ROUTES = {
HOME: "/", HOME: "/",
ONBOARD: "/onboard", ONBOARD: "/onboard",
@@ -6,12 +6,13 @@ export const ROUTES = {
ACTIVATE: "/activate/:uidb64/:token", ACTIVATE: "/activate/:uidb64/:token",
LOGIN: "/login", LOGIN: "/login",
DRAWER: "/drawer", DRAWER: "/drawer",
WRITE: "/quill/:public_id?", WRITE: "/quill/:public_id?", // ← static pattern
READ: "/read/:public_id", READ: "/read/:public_id",
}; };
// Dynamic path BUILDERS // Path BUILDERS
export const PATHS = { export const PATHS = {
write: (public_id?: string) => `/quill/${public_id ?? ""}`, write: (public_id?: string) => `/quill/${public_id ?? ""}`,
read: (public_id: string) => `/read/${public_id}`, read: (public_id: string) => `/read/${public_id}`,
activate: (uidb64: string, token: string) => `/activate/${uidb64}/${token}`,
}; };
+3 -12
View File
@@ -25,7 +25,7 @@ export interface ProcessedLetter extends Letter {
metadata: LetterMetadata; metadata: LetterMetadata;
} }
async function decryptLettersMetadata( async function decryptLetters(
letters: Letter[], letters: Letter[],
masterKey: CryptoKey, masterKey: CryptoKey,
): Promise<ProcessedLetter[]> { ): Promise<ProcessedLetter[]> {
@@ -56,22 +56,19 @@ async function decryptLettersMetadata(
export function useLetters() { export function useLetters() {
const [letters, setLetters] = useState<ProcessedLetter[]>([]); const [letters, setLetters] = useState<ProcessedLetter[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [isAuthRequired, setIsAuthRequired] = useState<boolean>(false); const [isAuthRequired, setIsAuthRequired] = useState<boolean>(false);
const { masterKey } = useKeyStore(); const { masterKey } = useKeyStore();
// to fetch the letters and decryypt the metadata on load
useEffect(() => { useEffect(() => {
if (!masterKey) { if (!masterKey) {
setIsAuthRequired(true); setIsAuthRequired(true);
return; return;
} }
setIsAuthRequired(false); setIsAuthRequired(false);
setError(null);
setLoading(true); setLoading(true);
api api
.get(endpoints.LETTERS) .get(endpoints.LETTERS)
.then((res) => decryptLettersMetadata(res.data, masterKey)) .then((res) => decryptLetters(res.data, masterKey))
.then((decrypted) => { .then((decrypted) => {
setLetters( setLetters(
decrypted.sort( decrypted.sort(
@@ -81,9 +78,7 @@ export function useLetters() {
), ),
); );
}) })
.catch((err) => { .catch((_err) => {})
setError(err);
})
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, [masterKey]); }, [masterKey]);
@@ -96,10 +91,6 @@ export function useLetters() {
}; };
}, [letters]); }, [letters]);
if (error) {
throw error;
}
return { return {
...drawerItems, ...drawerItems,
loading, loading,
+38 -50
View File
@@ -2,69 +2,57 @@
@plugin "daisyui"; @plugin "daisyui";
@plugin "daisyui/theme" { @plugin "daisyui/theme" {
name: "piku"; name: "piku";
default: true; default: true;
prefersdark: true; prefersdark: true;
color-scheme: dark; color-scheme: dark;
--color-base-100: oklch(14% 0.012 35); --color-base-100: oklch(14% 0.012 35);
--color-base-200: oklch(18% 0.014 33); --color-base-200: oklch(18% 0.014 33);
--color-base-300: oklch(22% 0.016 32); --color-base-300: oklch(22% 0.016 32);
--color-base-content: oklch(82% 0.02 70); --color-base-content: oklch(82% 0.02 70);
--color-primary: oklch(67% 0.11 78); --color-primary: oklch(67% 0.11 78);
--color-primary-content: oklch(15% 0.03 70); --color-primary-content: oklch(15% 0.03 70);
--color-secondary: oklch(48% 0.08 305); --color-secondary: oklch(48% 0.08 305);
--color-secondary-content: oklch(92% 0.01 305); --color-secondary-content: oklch(92% 0.01 305);
--color-accent: oklch(55% 0.06 325); --color-accent: oklch(55% 0.06 325);
--color-accent-content: oklch(18% 0.03 295); --color-accent-content: oklch(18% 0.03 295);
--color-neutral: oklch(28% 0.02 45); --color-neutral: oklch(28% 0.02 45);
--color-neutral-content: oklch(80% 0.015 60); --color-neutral-content: oklch(80% 0.015 60);
--color-info: oklch(60% 0.07 240); --color-info: oklch(60% 0.07 240);
--color-info-content: oklch(95% 0.01 240); --color-info-content: oklch(95% 0.01 240);
--color-success: oklch(60% 0.08 150); --color-success: oklch(60% 0.08 150);
--color-success-content: oklch(16% 0.03 150); --color-success-content: oklch(16% 0.03 150);
--color-warning: oklch(68% 0.08 72); --color-warning: oklch(68% 0.08 72);
--color-warning-content: oklch(18% 0.03 60); --color-warning-content: oklch(18% 0.03 60);
--color-error: oklch(55% 0.1 22); --color-error: oklch(55% 0.1 22);
--color-error-content: oklch(92% 0.01 22); --color-error-content: oklch(92% 0.01 22);
--radius-selector: 0.5rem; --radius-selector: 0.5rem;
--radius-field: 0.375rem; --radius-field: 0.375rem;
--radius-box: 0.5rem; --radius-box: 0.5rem;
--depth: 1; --depth: 1;
--noise: 0.03; --noise: 0.03;
--border: 1px; --border: 1px;
} }
@theme { @theme {
--font-display: "Playwrite HR Lijeva Variable", cursive; --font-display: "Playwrite HR Lijeva Variable", cursive;
--font-sans: "Jost Variable", sans-serif; --font-sans: "Jost Variable", sans-serif;
--font-serif: "Playfair Display Variable", serif; --font-serif: "Playfair Display Variable", serif;
--font-mono: "Space Mono", monospace; --color-glass-bg: rgba(28, 22, 16, 0.45);
--font-tamil: "Kavivanar", sans-serif; --shadow-warm: 0 20px 50px -12px rgba(30, 20, 12, 0.6);
--font-redact: "Redacted Script", cursive; --radius-xl: 1.5rem;
--font-slab: "Cutive Mono", monospace; --color-paper: oklch(97% 0.008 80);
--font-hand: "Architects Daughter", cursive;
--color-glass-bg: rgba(28, 22, 16, 0.45);
--shadow-warm: 0 20px 50px -12px rgba(30, 20, 12, 0.6);
--radius-xl: 1.5rem;
--color-paper: oklch(97% 0.008 80);
--text-xxs: 10px;
--tracking-widester: 0.5em;
--background-image-vig: radial-gradient(
circle at center,
transparent 0%,
rgba(0, 0, 0, 0.4) 100%
);
} }
.glass-card { .glass-card {
@apply bg-glass-bg backdrop-blur-xl border border-white/5 shadow-warm rounded-xl; @apply bg-glass-bg backdrop-blur-xl border border-white/5 shadow-warm rounded-xl;
} }
-3
View File
@@ -1,12 +1,9 @@
import { StrictMode } from "react"; import { StrictMode } from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import "./index.css"; import "./index.css";
import "@fontsource-variable/playwrite-hr-lijeva/wght.css"; import "@fontsource-variable/playwrite-hr-lijeva/wght.css";
import "@fontsource-variable/jost/wght.css"; import "@fontsource-variable/jost/wght.css";
import "@fontsource-variable/playfair-display/wght.css"; import "@fontsource-variable/playfair-display/wght.css";
import App from "./App.tsx"; import App from "./App.tsx";
const root = document.getElementById("root"); const root = document.getElementById("root");
+4 -4
View File
@@ -28,12 +28,12 @@ export default function Drawer() {
return ( return (
<div className="min-h-screen w-full bg-base-100 text-base-content flex flex-col items-center py-12 px-5 pb-32 font-serif transition-colors"> <div className="min-h-screen w-full bg-base-100 text-base-content flex flex-col items-center py-12 px-5 pb-32 font-serif transition-colors">
<div className="fixed inset-0 bg-vig pointer-events-none z-0" /> <div className="fixed inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,rgba(0,0,0,0.5)_100%)] pointer-events-none z-0" />
{isAuthRequired && <PasskeyModal onUnlock={unlock} />} {isAuthRequired && <PasskeyModal onUnlock={unlock} />}
<header className="text-center mb-12 z-10 animate-in fade-in slide-in-from-top-4 duration-500"> <header className="text-center mb-12 z-10 animate-in fade-in slide-in-from-top-4 duration-500">
<Logo /> <Logo />
<div className="font-sans text-xs tracking-widester uppercase text-base-content/40 mt-2"> <div className="font-sans text-xs tracking-[0.3em] uppercase text-base-content/40 mt-2">
Personal Archive Personal Archive
</div> </div>
<div className="mt-6 font-sans text-sm text-base-content flex items-center justify-center gap-2 opacity-60 hover:opacity-100 transition-opacity"> <div className="mt-6 font-sans text-sm text-base-content flex items-center justify-center gap-2 opacity-60 hover:opacity-100 transition-opacity">
@@ -53,7 +53,7 @@ export default function Drawer() {
{loading ? ( {loading ? (
<div className="flex-1 flex flex-col items-center justify-center p-12 gap-4"> <div className="flex-1 flex flex-col items-center justify-center p-12 gap-4">
<span className="loading loading-ring loading-lg text-primary opacity-20"></span> <span className="loading loading-ring loading-lg text-primary opacity-20"></span>
<span className="text-xxs uppercase tracking-widester font-sans text-base-content/20 animate-pulse"> <span className="text-[10px] uppercase tracking-[0.3em] font-sans text-base-content/20 animate-pulse">
Opening your cabinet... Opening your cabinet...
</span> </span>
</div> </div>
@@ -163,7 +163,7 @@ export default function Drawer() {
</span> </span>
</button> </button>
<footer className="mt-25 font-sans text-[0.6rem] tracking-widester uppercase text-base-content/10 z-10"> <footer className="mt-25 font-sans text-[0.6rem] tracking-[0.2em] uppercase text-base-content/10 z-10">
For your unsaid. For your unsaid.
</footer> </footer>
<div className="absolute bottom-0 z-50 font-sans"> <div className="absolute bottom-0 z-50 font-sans">
+96 -140
View File
@@ -12,7 +12,6 @@ import {
} from "react-router-dom"; } from "react-router-dom";
import { api } from "../api/apiClient"; import { api } from "../api/apiClient";
import { import {
type CanvasStyle,
type CanvasTools, type CanvasTools,
ComposeCanvas, ComposeCanvas,
} from "../components/editor/ComposeCanvas"; } from "../components/editor/ComposeCanvas";
@@ -24,7 +23,6 @@ import {
} from "../components/editor/ToolBar"; } from "../components/editor/ToolBar";
import DateDisplay from "../components/ui/DateDisplay"; import DateDisplay from "../components/ui/DateDisplay";
import { LogModal } from "../components/ui/LogModal"; import { LogModal } from "../components/ui/LogModal";
import { Modal } from "../components/ui/Modal";
import { Navbar } from "../components/ui/Navbar"; import { Navbar } from "../components/ui/Navbar";
import { endpoints } from "../config/endpoints"; import { endpoints } from "../config/endpoints";
@@ -34,18 +32,11 @@ import { CryptoUtils } from "../utils/crypto";
import { formatRelativeDate } from "../utils/dateFormat"; import { formatRelativeDate } from "../utils/dateFormat";
import { decryptCanvasImages, encryptCanvasImages } from "../utils/letterLogic"; import { decryptCanvasImages, encryptCanvasImages } from "../utils/letterLogic";
import "@fontsource/kavivanar/index.css"; type SaveOverlay = "idle" | "saving" | "saved" | "error";
import "@fontsource/space-mono/index.css";
import "@fontsource/cutive-mono/index.css";
import "@fontsource/architects-daughter/index.css";
import "@fontsource/redacted-script/index.css";
type SaveOverlay = "IDLE" | "SAVING" | "SAVED" | "ERROR";
const OVERLAY_FADE_MS = 250; const OVERLAY_FADE_MS = 250;
const SAVED_VISIBLE_MS = 1400; const SAVED_VISIBLE_MS = 1400;
const ERROR_VISIBLE_MS = 2400; const ERROR_VISIBLE_MS = 2400;
const STOP_SAVE_DATE_PULSE_AFTER_MS = 10000;
const toPlaceholderList = [ const toPlaceholderList = [
"Someone dear...", "Someone dear...",
@@ -53,7 +44,6 @@ const toPlaceholderList = [
"Something to bear...", "Something to bear...",
]; ];
const MAX_FILE_SIZE = 10 * 1024 * 1024;
export default function Editor() { export default function Editor() {
const navigate = useNavigate(); const navigate = useNavigate();
const navigateRef = useRef<NavigateFunction>(navigate); const navigateRef = useRef<NavigateFunction>(navigate);
@@ -79,14 +69,7 @@ export default function Editor() {
const [lastSavedPulseTick, setLastSavedPulseTick] = useState(0); const [lastSavedPulseTick, setLastSavedPulseTick] = useState(0);
const [sealBtnClicked, setSealBtnClicked] = useState<boolean>(false); const [sealBtnClicked, setSealBtnClicked] = useState<boolean>(false);
const [saveOverlay, setSaveOverlay] = useState<SaveOverlay>("IDLE"); const [saveOverlay, setSaveOverlay] = useState<SaveOverlay>("idle");
const [logStatus, setLogStatus] = useState<{
status: "WARN" | "ERROR" | "RESET";
message: string;
}>({
status: "RESET",
message: "",
});
const [showSaveOverlay, setShowSaveOverlay] = useState(false); const [showSaveOverlay, setShowSaveOverlay] = useState(false);
const [confirmModal, setConfirmModal] = useState<"VAULT" | "SEAL" | null>( const [confirmModal, setConfirmModal] = useState<"VAULT" | "SEAL" | null>(
null, null,
@@ -95,17 +78,13 @@ export default function Editor() {
const [recipient, setRecipient] = useState(""); const [recipient, setRecipient] = useState("");
const [unlockDate, setUnlockDate] = useState<Date | null>(null); const [unlockDate, setUnlockDate] = useState<Date | null>(null);
const [placeholderIndex, setPlaceholderIndex] = useState(0); const [placeholderIndex, setPlaceholderIndex] = useState(0);
const [canvasFontStyle, setCanvasFontStyle] = useState<CanvasStyle>({
fontColor: "",
fontFamily: "",
});
const { masterKey } = useKeyStore(); const { masterKey } = useKeyStore();
const canvasRef = useRef<CanvasTools>(null); const canvasRef = useRef<CanvasTools>(null);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
// to continuously rotate placeholder text of the recipient input // Placeholder rotation
useEffect(() => { useEffect(() => {
const interval = setInterval(() => { const interval = setInterval(() => {
setPlaceholderIndex((prev) => (prev + 1) % toPlaceholderList.length); setPlaceholderIndex((prev) => (prev + 1) % toPlaceholderList.length);
@@ -114,14 +93,13 @@ export default function Editor() {
return () => clearInterval(interval); return () => clearInterval(interval);
}, []); }, []);
// to load existing letter when public_id param and masterKey is available
// NOTE: this has to trigger just once after each save
useEffect(() => { useEffect(() => {
if (!(public_id && masterKey)) return; if (!(public_id && masterKey)) return;
if (justSavedRef.current) { if (justSavedRef.current) {
justSavedRef.current = false; justSavedRef.current = false;
return; return;
} }
const loadExistingLetter = async () => { const loadExistingLetter = async () => {
setIsInitialLoading(true); setIsInitialLoading(true);
const cryptoUtils = new CryptoUtils(); const cryptoUtils = new CryptoUtils();
@@ -160,27 +138,26 @@ export default function Editor() {
); );
const canvasData = JSON.parse(decryptedJsonStr); const canvasData = JSON.parse(decryptedJsonStr);
const { errors, isPartialFailure, canvasDataWithDecryptedImages } = const { isDecryptionPartialFailure, error } = await decryptCanvasImages(
await decryptCanvasImages( canvasData,
canvasData, letterData.images ?? [],
letterData.images ?? [], letterData.encrypted_dek,
letterData.encrypted_dek, masterKey,
masterKey, cryptoUtils,
cryptoUtils, true,
true, );
);
if (isPartialFailure) { if (isDecryptionPartialFailure) {
setDecryptionStatus({ setDecryptionStatus({
status: "WARN", status: "WARN",
message: message:
"Failed to decrypt some elements. Please check the render.", "Failed to decrypt some elements. Please check the render.",
log: errors.toString(), log: error,
}); });
} }
if (canvasRef.current) { if (canvasRef.current) {
await canvasRef.current.loadData(canvasDataWithDecryptedImages); await canvasRef.current.loadData(canvasData);
} }
} catch (_err) { } catch (_err) {
setDecryptionStatus({ setDecryptionStatus({
@@ -192,40 +169,37 @@ export default function Editor() {
setIsInitialLoading(false); setIsInitialLoading(false);
} }
}; };
loadExistingLetter().then((_) => {
if (canvasRef.current) { loadExistingLetter();
setCanvasFontStyle(canvasRef.current.getStyle());
}
});
}, [public_id, masterKey]); }, [public_id, masterKey]);
// to trigger short pulse animation for Last Saved AT element
useEffect(() => { useEffect(() => {
if (lastSavedPulseTick === 0) return; if (lastSavedPulseTick === 0) return;
setIsSaveDatePulsing(true); setIsSaveDatePulsing(true);
const timer = setTimeout(() => { const timer = setTimeout(() => {
setIsSaveDatePulsing(false); setIsSaveDatePulsing(false);
}, STOP_SAVE_DATE_PULSE_AFTER_MS); }, 10000);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [lastSavedPulseTick]); }, [lastSavedPulseTick]);
// to fade in and fade out the save status overlay after each save operation
// Note: otherwise the fade efect is abrupt due to component's immediate unmount
useEffect(() => { useEffect(() => {
if (saveOverlay === "IDLE" || saveOverlay === "SAVING") return; if (saveOverlay === "idle" || saveOverlay === "saving") return;
const visibleTimer = setTimeout( const visibleTimer = setTimeout(
() => { () => {
setShowSaveOverlay(false); setShowSaveOverlay(false);
}, },
saveOverlay === "SAVED" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS, saveOverlay === "saved" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS,
); );
const unmountTimer = setTimeout( const unmountTimer = setTimeout(
() => { () => {
setSaveOverlay("IDLE"); setSaveOverlay("idle");
}, },
(saveOverlay === "SAVED" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS) + (saveOverlay === "saved" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS) +
OVERLAY_FADE_MS, OVERLAY_FADE_MS,
); );
@@ -237,14 +211,9 @@ export default function Editor() {
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => { const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (file && file.size < MAX_FILE_SIZE) { if (file) {
const url = URL.createObjectURL(file); const url = URL.createObjectURL(file);
canvasRef.current?.addImage(url, file); canvasRef.current?.addImage(url, file);
} else {
setLogStatus({
status: "WARN",
message: "Please upload images with size less than 10MB.",
});
} }
}; };
@@ -259,9 +228,9 @@ export default function Editor() {
targetId = crypto.randomUUID(); targetId = crypto.randomUUID();
} }
if (saveOverlay === "SAVING" || !masterKey) return; if (saveOverlay === "saving" || !masterKey) return;
setSaveOverlay("SAVING"); setSaveOverlay("saving");
setShowSaveOverlay(true); setShowSaveOverlay(true);
const cryptoUtils = new CryptoUtils(); const cryptoUtils = new CryptoUtils();
@@ -271,16 +240,15 @@ export default function Editor() {
const canvasData = canvasRef.current?.getData() || { objects: [] }; const canvasData = canvasRef.current?.getData() || { objects: [] };
const canvasImages = canvasRef.current?.getImages() || []; const canvasImages = canvasRef.current?.getImages() || [];
const { encryptedImageFiles, encryptedCanvasData } = const encImageFilesMap = await encryptCanvasImages(
await encryptCanvasImages( canvasData,
canvasData, canvasImages,
canvasImages, masterKey,
masterKey, cryptoUtils,
cryptoUtils, );
);
const encrypted_letter = await cryptoUtils.encryptLetter( const encrypted_letter = await cryptoUtils.encryptLetter(
JSON.stringify(encryptedCanvasData), JSON.stringify(canvasData),
masterKey, masterKey,
); );
@@ -309,7 +277,7 @@ export default function Editor() {
encrypted_metadata.encrypted_content, encrypted_metadata.encrypted_content,
); );
encryptedImageFiles.forEach((blob, filename) => { encImageFilesMap.forEach((blob, filename) => {
formData.append("image_files", blob, filename); formData.append("image_files", blob, filename);
}); });
@@ -328,10 +296,10 @@ export default function Editor() {
if (status === "SEALED" || status === "VAULT") { if (status === "SEALED" || status === "VAULT") {
setSealedTargetId(targetId); setSealedTargetId(targetId);
} }
setSaveOverlay("SAVED"); setSaveOverlay("saved");
setShowSaveOverlay(true); setShowSaveOverlay(true);
} catch (_error) { } catch (_error) {
setSaveOverlay("ERROR"); setSaveOverlay("error");
setShowSaveOverlay(true); setShowSaveOverlay(true);
} }
}; };
@@ -345,8 +313,8 @@ export default function Editor() {
isSaveDatePulsing ? "animate-pulse" : "" isSaveDatePulsing ? "animate-pulse" : ""
}`} }`}
> >
<div className="text-xxs text-neutral-content/30 flex-col justify-end leading-none text-right"> <div className="text-sm text-neutral-content/30 flex-col justify-end leading-none text-right">
<span className="uppercase tracking-widest font-bold"> <span className="text-[10px] uppercase tracking-widest font-bold">
Last Save Last Save
</span> </span>
<br /> <br />
@@ -380,61 +348,67 @@ export default function Editor() {
weight="bold" weight="bold"
className="animate-spin text-primary" className="animate-spin text-primary"
/> />
<p className="text-xxs uppercase tracking-widester font-bold text-base-content/40"> <p className="text-[10px] uppercase tracking-[0.4em] font-bold text-base-content/40">
Opening your draft... Opening your draft...
</p> </p>
</div> </div>
</div> </div>
)} )}
{saveOverlay !== "IDLE" && ( {saveOverlay !== "idle" && (
<Modal isOpen={showSaveOverlay}> <div
{saveOverlay === "SAVING" && ( className={`modal modal-open bg-base-100/20 backdrop-blur-md transition-opacity duration-300 ${
<div showSaveOverlay ? "opacity-100" : "opacity-0"
role="alert" }`}
className={`alert text-center alert-neutral shadow-lg transition-all ease-in-out duration-2000 ${ >
showSaveOverlay <div className="modal-box p-0 bg-transparent shadow-none transition-all duration-300">
? "opacity-100 scale-100 translate-y-0" {saveOverlay === "saving" && (
: "opacity-0 scale-95 translate-y-1" <div
}`} role="alert"
> className={`alert text-center alert-neutral shadow-lg transition-all ease-in-out duration-2000 ${
<SpinnerGapIcon showSaveOverlay
size={18} ? "opacity-100 scale-100 translate-y-0"
weight="bold" : "opacity-0 scale-95 translate-y-1"
className="animate-spin" }`}
/> >
<span className="font-bold">Securing your letter...</span> <SpinnerGapIcon
</div> size={18}
)} weight="bold"
className="animate-spin"
/>
<span className="font-bold">Securing your letter...</span>
</div>
)}
{saveOverlay === "SAVED" && ( {saveOverlay === "saved" && (
<div <div
role="alert" role="alert"
className={`alert alert-success shadow-lg transition-all ease-in-out duration-2000 ${ className={`alert alert-success shadow-lg transition-all ease-in-out duration-2000 ${
showSaveOverlay showSaveOverlay
? "opacity-100 scale-100 translate-y-0" ? "opacity-100 scale-100 translate-y-0"
: "opacity-0 scale-95 translate-y-1" : "opacity-0 scale-95 translate-y-1"
}`} }`}
> >
<DownloadSimpleIcon size={18} weight="bold" /> <DownloadSimpleIcon size={18} weight="bold" />
<span className="font-bold">Your letter is saved!</span> <span className="font-bold">Your letter is saved!</span>
</div> </div>
)} )}
{saveOverlay === "ERROR" && ( {saveOverlay === "error" && (
<div <div
role="alert" role="alert"
className={`alert alert-error shadow-lg transition-all duration-300 ${ className={`alert alert-error shadow-lg transition-all duration-300 ${
showSaveOverlay showSaveOverlay
? "opacity-100 scale-100 translate-y-0" ? "opacity-100 scale-100 translate-y-0"
: "opacity-0 scale-95 translate-y-1" : "opacity-0 scale-95 translate-y-1"
}`} }`}
> >
<XIcon size={18} weight="bold" /> <XIcon size={18} weight="bold" />
<span className="font-bold">Failed to save letter</span> <span className="font-bold">Failed to save letter</span>
</div> </div>
)} )}
</Modal> </div>
</div>
)} )}
{confirmModal === "VAULT" && ( {confirmModal === "VAULT" && (
@@ -457,7 +431,7 @@ export default function Editor() {
<div className="flex flex-col gap-2 flex-1"> <div className="flex flex-col gap-2 flex-1">
<label <label
htmlFor="recipient" htmlFor="recipient"
className="text-xxs uppercase tracking-widester text-secondary-content font-bold" className="text-[10px] uppercase tracking-[0.4em] text-secondary-content font-bold"
> >
Recipient Recipient
</label> </label>
@@ -476,13 +450,11 @@ export default function Editor() {
{status === "DRAFT" ? ( {status === "DRAFT" ? (
<ToolBar <ToolBar
onAddImage={() => fileInputRef.current?.click()} fileInputRef={fileInputRef}
sealBtnClicked={sealBtnClicked} sealBtnClicked={sealBtnClicked}
setSealBtnClicked={setSealBtnClicked} setSealBtnClicked={setSealBtnClicked}
onSave={handleSave} onSave={handleSave}
setConfirmModal={setConfirmModal} setConfirmModal={setConfirmModal}
onFontChange={setCanvasFontStyle}
latestFontStyle={canvasFontStyle}
/> />
) : ( ) : (
<LetterHead /> <LetterHead />
@@ -496,25 +468,9 @@ export default function Editor() {
className="hidden" className="hidden"
/> />
<ComposeCanvas <ComposeCanvas ref={canvasRef} readOnly={status !== "DRAFT"} />
ref={canvasRef}
readOnly={status !== "DRAFT"}
style={canvasFontStyle}
/>
</div> </div>
</section> </section>
<LogModal
status={logStatus.status}
message={logStatus.message}
log={""}
onClose={() =>
setLogStatus({
status: "RESET",
message: "",
})
}
isOpen={logStatus.status !== "RESET"}
/>
</> </>
); );
} }
+3 -389
View File
@@ -1,395 +1,9 @@
import { InfoIcon } from "@phosphor-icons/react";
import {
motion,
useMotionValueEvent,
useScroll,
useSpring,
useTransform,
} from "motion/react";
import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import Logo from "../components/Logo"; import Logo from "../components/Logo";
import { EnvelopeReveal } from "../components/reader/EnvelopeReveal";
import Saajan from "../components/ui/Saajan.tsx";
import { ROUTES } from "../config/routes.ts";
import { formatDate } from "../utils/dateFormat.ts";
export default function Home() { export default function Home() {
const sectionContainer1 = useRef<HTMLDivElement>(null);
const { scrollYProgress: section1ScrollProgress } = useScroll({
target: sectionContainer1,
});
const smoothProgress1 = useSpring(section1ScrollProgress, {
stiffness: 100,
damping: 30,
restDelta: 0.001,
});
const [isEnvelopeFlipped, setIsEnvelopeFlipped] = useState(true);
const [flapOpen, setFlapOpen] = useState(false);
const [recipient, setRecipient] = useState("someone dear");
const [ignite, setIgnite] = useState(false);
const navigate = useNavigate();
useMotionValueEvent(section1ScrollProgress, "change", (latestScrollValue) => {
if (latestScrollValue > 0.54) {
setFlapOpen(false);
} else {
setFlapOpen(true);
}
if (latestScrollValue <= 0.6) {
setIsEnvelopeFlipped(true);
} else {
setIsEnvelopeFlipped(false);
}
if (latestScrollValue > 0.68) {
setRecipient("future me");
} else {
setRecipient("someone dear");
}
if (latestScrollValue > 0.77) {
setIgnite(true);
} else {
setIgnite(false);
}
});
return ( return (
<section <div>
ref={sectionContainer1} <Logo />
className="relative w-full h-[850vh] bg-base-100 font-serif" </div>
>
<div className="sticky top-0 h-screen w-full flex flex-col items-center justify-center overflow-hidden">
{/* Intro */}
<motion.div
className="absolute flex flex-col items-center justify-center pointer-events-none"
style={{
opacity: useTransform(smoothProgress1, [0, 0.12, 1], [1, 0, 0]),
scale: useTransform(smoothProgress1, [0, 0.12], [1, 10]),
}}
>
<h1 className="text-neutral-content/40 text-4xl md:text-6xl text-center px-6">
You've been carrying something
</h1>
<h2 className="text-primary text-5xl md:text-7xl font-extralight mt-4 italic font-display animate-pulse">
unsaid
</h2>
</motion.div>
<motion.div
className="absolute text-center"
style={{
opacity: useTransform(smoothProgress1, [0, 0.15, 0.2], [0, 1, 0]),
y: useTransform(smoothProgress1, [0, 0.15, 0.2], [40, 0, -40]),
scale: useTransform(smoothProgress1, [0, 0.15, 0.2], [0.8, 1, 3]),
}}
>
<div className="mt-6 text-4xl md:text-6xl text-base-content/60 italic">
and that's okay...
</div>
</motion.div>
{/* pi. ku. */}
<motion.div
className="absolute text-center px-6"
style={{
opacity: useTransform(
smoothProgress1,
[0.18, 0.25, 0.3],
[0, 1, 0],
),
y: useTransform(smoothProgress1, [0.18, 0.25, 0.3], [20, 0, -20]),
}}
transition={{ delay: 4 }}
>
<Logo scale={2} />
<motion.div
className="mt-6 text-4xl md:text-6xl text-base-content/60 "
style={{
opacity: useTransform(
smoothProgress1,
[0.22, 0.25, 0.35, 0.4],
[0, 1, 1, 0],
),
y: useTransform(
smoothProgress1,
[0.25, 0.3, 0.35, 0.4],
[20, 0, 0, -20],
),
}}
>
is a{" "}
<span className="font-display text-primary font-extralight">
safe space
</span>
,<br />
<motion.span
className="opacity-0 text-3xl md:text-5xl"
transition={{ delay: 3 }}
whileInView={{ opacity: 1 }}
viewport={{ once: false, amount: 0.3 }}
>
where you can
</motion.span>
</motion.div>
</motion.div>
<div className="relative w-full max-w-5xl h-1/2 flex items-center justify-center mt-20">
<motion.h2
style={{
opacity: useTransform(
smoothProgress1,
[0.3, 0.35, 0.4, 0.45],
[0, 1, 1, 0],
),
y: useTransform(
smoothProgress1,
[0.3, 0.35, 0.4, 0.45],
[40, 0, 0, -40],
),
}}
className="absolute text-4xl md:text-6xl text-center px-10 leading-tight"
>
pen down your unsaid words into{" "}
<span className="font-display text-primary font-extralight">
letters
</span>
.
</motion.h2>
{/* Seal */}
<motion.h2
style={{
opacity: useTransform(
smoothProgress1,
[0.45, 0.5, 0.55, 0.6],
[0, 1, 1, 0],
),
y: useTransform(
smoothProgress1,
[0.45, 0.5, 0.55, 0.6],
[40, 0, 0, -40],
),
}}
className="absolute text-4xl md:text-6xl text-center px-10 leading-tight"
>
seal it{" "}
<span className="text-secondary font-display italic font-extralight">
secure
</span>{" "}
and{" "}
<span className="text-secondary font-display font-extralight italic">
private
</span>
.
</motion.h2>
{/* Send / vault */}
<motion.h2
style={{
opacity: useTransform(
smoothProgress1,
[0.6, 0.63, 0.72, 0.75],
[0, 1, 1, 0],
),
y: useTransform(
smoothProgress1,
[0.6, 0.63, 0.72, 0.75],
[40, 0, 0, -40],
),
}}
className="absolute text-4xl md:text-6xl text-center px-10 leading-tight"
>
send it to{" "}
<motion.span
className="font-display text-accent"
style={{
color: useTransform(
smoothProgress1,
[0.67, 1],
["var(--color-accent)", "var(--color-neutral)"],
),
}}
>
someone dear
</motion.span>
<motion.span
style={{
opacity: useTransform(smoothProgress1, [0.66, 0.7], [0, 1]),
}}
>
<motion.span
className="font-display text-accent"
style={{
color: useTransform(
smoothProgress1,
[0.67, 1],
["var(--color-accent)", "var(--color-neutral)"],
),
}}
>
{" "}
or{" "}
</motion.span>
<span className="font-display text-success">
yourself in the future
</span>
.
</motion.span>
</motion.h2>
{/* Burn */}
<motion.h2
style={{
opacity: useTransform(
smoothProgress1,
[0.75, 0.8, 0.85, 0.9],
[0, 1, 1, 0],
),
y: useTransform(
smoothProgress1,
[0.75, 0.8, 0.85, 0.9],
[40, 0, 0, -40],
),
}}
className="absolute text-4xl md:text-6xl text-center px-10 leading-tight"
>
and even <span className="font-display text-error">burn it</span> to
release the burden.
</motion.h2>
{/* Outro */}
<motion.h2
className={
"italic absolute text-4xl md:text-6xl text-center px-10 leading-tight"
}
style={{
opacity: useTransform(smoothProgress1, [0.9, 1], [0, 1]),
y: useTransform(smoothProgress1, [0.9, 1], [80, 0]),
}}
>
You've been carrying it long enough.
</motion.h2>
{/* CTA */}
<motion.div
className={
"z-100 absolute -bottom-12 md:bottom-0 font-display flex flex-wrap md:flex-nowrap gap-4 md:gap-12 justify-center"
}
style={{
opacity: useTransform(smoothProgress1, [0.98, 1], [0, 1]),
y: useTransform(smoothProgress1, [0.98, 1], [80, 0]),
display: useTransform(
smoothProgress1,
[0.96, 1],
["none", "flex"],
),
}}
>
<button
className={
"md:opacity-50 hover:opacity-100 btn btn-ghost btn-wide md:btn-xl rounded-full font-extralight md:grayscale hover:grayscale-0 hover:-translate-y-1 transition-all duration-1000"
}
type={"button"}
>
<InfoIcon className={"text-primary"} />
Tell me More
</button>
<button
className={
"md:opacity-50 hover:opacity-100 btn rounded-full btn-primary btn-wide md:btn-xl md:grayscale hover:grayscale-0 hover:-translate-y-1 transition-all duration-1000"
}
type={"button"}
onClick={() => navigate(ROUTES.ONBOARD, { replace: true })}
>
I'm ready
</button>
</motion.div>
</div>
<div className="relative h-1/4 w-full flex flex-col items-center justify-center pointer-events-none">
<motion.div
className={"z-21 absolute"}
style={{
opacity: useTransform(
smoothProgress1,
[0.3, 0.4, 0.5, 0.52],
[0, 1, 0.1, 0],
),
y: useTransform(smoothProgress1, [0.3, 0.45, 0.5], [300, 0, 200]),
scale: useTransform(
smoothProgress1,
[0.3, 0.4, 0.5],
[1, 1, 0.6],
),
}}
>
<div className="mockup-phone w-[75vw] border-primary">
<div className="mockup-phone-camera"></div>
<div className="mockup-phone-display">
<img alt="letter" src="/screenshots/letter.webp" />
</div>
</div>
</motion.div>
{/* Envelope */}
<motion.div
className="absolute scale-50 md:scale-80 z-10"
style={{
opacity: useTransform(
smoothProgress1,
[0.4, 0.45, 0.5, 0.7, 0.9, 1],
[0, 0.6, 1, 1, 0.3, 0],
),
y: useTransform(smoothProgress1, [0.45, 0.5, 1], [600, 200, 0]),
}}
>
<EnvelopeReveal
isInteractive={false}
ignite={ignite}
recipient={recipient}
date={formatDate(new Date().toISOString())}
onRevealComplete={() => {}}
isFlip={isEnvelopeFlipped}
openFlap={flapOpen}
/>
</motion.div>
{/* Saajan */}
<motion.div
className="fixed bottom-0 z-10 font-sans -mb-6 scale-85 md:scale-100 md:mb-0"
style={{
opacity: useTransform(
smoothProgress1,
[0.98, 0.995, 1],
[0, 0.5, 1],
),
y: useTransform(smoothProgress1, [0.98, 1], [50, -10]),
}}
>
<Saajan
message={
"I think we forget things\nif there is nobody to tell them."
}
position={"top"}
/>
</motion.div>
{/* Orb */}
<motion.div
className="w-48 z-100 h-48 rounded-full blur-3xl opacity-20"
transition={{
backgroundColor: { ease: "easeIn", duration: 2 },
}}
style={{
backgroundColor: useTransform(
smoothProgress1,
[0.45, 0.5, 0.7, 0.75, 1],
[
"var(--color-primary)",
"var(--color-secondary)",
"var(--color-accent)",
"var(--color-success)",
"var(--color-error)",
],
),
scale: useTransform(smoothProgress1, [0, 1], [0.6, 2.5]),
}}
/>
<div className="absolute border border-primary/5 w-64 h-64 rounded-full backdrop-blur-[1px]" />
</div>
</div>
</section>
); );
} }
+83 -3
View File
@@ -1,5 +1,9 @@
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import {
HandPalmIcon,
ShieldCheckIcon,
WarningIcon,
} from "@phosphor-icons/react";
import axios from "axios"; import axios from "axios";
import { useState } from "react"; import { useState } from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
@@ -7,7 +11,6 @@ import { useLocation, useNavigate } from "react-router-dom";
import { z } from "zod"; import { z } from "zod";
import { api, publicApi } from "../api/apiClient"; import { api, publicApi } from "../api/apiClient";
import Logo from "../components/Logo"; import Logo from "../components/Logo";
import WelcomeModal from "../components/login/WelcomeModal.tsx";
import FormField from "../components/ui/FormField"; import FormField from "../components/ui/FormField";
import Saajan from "../components/ui/Saajan"; import Saajan from "../components/ui/Saajan";
import { endpoints } from "../config/endpoints"; import { endpoints } from "../config/endpoints";
@@ -22,6 +25,82 @@ const loginSchema = z.object({
type LoginInputs = z.infer<typeof loginSchema>; type LoginInputs = z.infer<typeof loginSchema>;
function WelcomeModal({
setShowWelcome,
}: {
setShowWelcome: (show: boolean) => void;
}) {
return (
<div className="modal modal-open backdrop-blur-sm transition-all duration-1000">
<div className="absolute bottom-1">
<Saajan
message={"I've lost words before.\nI know what it feels like."}
/>
</div>
<div className="modal-box border bg-base-100/20 border-primary/20 shadow-2xl p-8">
<div className="flex flex-col items-center text-center gap-4">
<div className="bg-primary/10 p-4 rounded-full animate-pulse">
<ShieldCheckIcon
size={48}
weight="duotone"
className="text-primary"
/>
</div>
<h3 className="font-display text-2xl font-bold text-primary">
Welcome to &nbsp;
<Logo /> &nbsp;!
</h3>
<p className="text-base-content/80 leading-relaxed">
Before we begin, let me make a small promise.
<HandPalmIcon
size={18}
className="inline text-primary"
weight="fill"
/>
<div className="divider my-0"></div>
<br />
Everything you write here is sealed with your password,{" "}
<span className="font-display text-success">cryptographically</span>
, before it leaves your hands.
<br />A fancy way of saying, I couldn't if I tried.
</p>
<div className="alert alert-warning bg-paper/20 border-paper/20 flex items-start gap-3 text-left py-3">
<WarningIcon size={24} weight="fill" className="shrink-0 mt-0.5" />
<p className="text-sm font-medium text-primary-content">
If you ever happen to forget your password, your letters are lost
to time, forever.
<br />
<span className="font-bold mt-2">
I highly, highly recommend storing this password in your{" "}
<a
href="https://www.privacyguides.org/en/passwords/"
target="_blank"
className="link link-primary-content"
rel="noopener"
>
password manager
</a>{" "}
or somewhere safe to remember it.
</span>
</p>
</div>
<div className="modal-action w-full">
<button
type="button"
onClick={() => setShowWelcome(false)}
className="btn btn-primary w-full shadow-lg"
>
I'll remember
</button>
</div>
</div>
</div>
</div>
);
}
export default function Login() { export default function Login() {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
@@ -46,7 +125,7 @@ export default function Login() {
setIsLoading(true); setIsLoading(true);
setApiError(null); setApiError(null);
try { try {
// client side key derivation for e2e encryption // client side key derivation for 0 knowledge
const { masterKey, authHash } = await CryptoUtils.deriveKeyBundle( const { masterKey, authHash } = await CryptoUtils.deriveKeyBundle(
data.password, data.password,
data.email, data.email,
@@ -62,6 +141,7 @@ export default function Login() {
headers: { Authorization: `Bearer ${authData.access}` }, headers: { Authorization: `Bearer ${authData.access}` },
}); });
// store the auth related data
await setAuthStore(authData.access, userData, masterKey); await setAuthStore(authData.access, userData, masterKey);
navigate(nextRoute, { replace: true }); navigate(nextRoute, { replace: true });
+42 -35
View File
@@ -33,7 +33,6 @@ interface LetterMetadata {
updated_at?: string; updated_at?: string;
} }
const WAIT_FOR_BURN_MS = 18000;
export default function Reader() { export default function Reader() {
const { public_id } = useParams(); const { public_id } = useParams();
const location = useLocation(); const location = useLocation();
@@ -45,10 +44,13 @@ export default function Reader() {
const [isDecrypting, setIsDecrypting] = useState(true); const [isDecrypting, setIsDecrypting] = useState(true);
const [revealState, setRevealState] = useState< const [revealState, setRevealState] = useState<
"SEALED" | "REVEALED" | "BURNED" | "BURNING" "sealed" | "revealed" | "burned" | "burning"
>("SEALED"); >("sealed");
const [logTrace, setLogTrace] = useState<{ const [error, setError] = useState<{
type: "WARN" | "ERROR"; message: string;
log: string;
} | null>(null);
const [warning, setWarning] = useState<{
message: string; message: string;
log: string; log: string;
} | null>(null); } | null>(null);
@@ -90,8 +92,8 @@ export default function Reader() {
setShowBurnModal(false); setShowBurnModal(false);
setIgnite(true); setIgnite(true);
setTimeout(() => { setTimeout(() => {
setRevealState("BURNED"); setRevealState("burned");
}, WAIT_FOR_BURN_MS); }, 13000);
} }
}; };
@@ -178,30 +180,30 @@ export default function Reader() {
); );
} }
} catch (err) { } catch (err) {
setLogTrace({ setWarning({
message: message:
"Failed to decrypt elements. Images might not render in the letter as intended.", "Failed to decrypt elements. Images might not render in the letter as intended.",
log: err instanceof Error ? err.message : "Unknown error", log: err instanceof Error ? err.message : "Unknown error",
type: "WARN",
}); });
} }
setDecryptedCanvasData(canvasData); setDecryptedCanvasData(canvasData);
} catch (err) { } catch (err) {
setLogTrace({ setError({
message: `Failed to load letter `, message: `Failed to load letter :(`,
log: err instanceof Error ? err.message : "Unknown error", log: err instanceof Error ? err.message : "Unknown error",
type: "ERROR",
}); });
} finally {
setIsDecrypting(false);
} }
}; };
loadAndDecrypt().then(() => setIsDecrypting(false)); loadAndDecrypt();
}, [public_id, sharingKey, masterKey]); }, [public_id, sharingKey, masterKey]);
useEffect(() => { useEffect(() => {
if ( if (
!isDecrypting && !isDecrypting &&
revealState === "REVEALED" && revealState === "revealed" &&
decryptedCanvasData && decryptedCanvasData &&
canvasRef.current canvasRef.current
) { ) {
@@ -211,13 +213,13 @@ export default function Reader() {
if (isDecrypting) { if (isDecrypting) {
return ( return (
<div className="flex items-center h-screen w-screen justify-center bg-base-100 font-sans"> <div className="flex items-center justify-center bg-base-100 font-serif">
<div className="fixed inset-0 bg-vig pointer-events-none" /> <div className="fixed inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,rgba(0,0,0,0.4)_100%)] pointer-events-none z-0" />
<div className="text-center space-y-6 z-10"> <div className="text-center space-y-6 z-10">
<Logo /> <Logo />
<div className="flex flex-col items-center gap-2"> <div className="flex flex-col items-center gap-2">
<span className="loading loading-ring loading-md text-primary/40"></span> <span className="loading loading-ring loading-md text-primary/40"></span>
<p className="text-xs uppercase tracking-widest text-base-content/20 animate-pulse"> <p className="text-[10px] uppercase tracking-[0.4em] text-base-content/20 animate-pulse">
Breaking the seal... Breaking the seal...
</p> </p>
</div> </div>
@@ -226,32 +228,29 @@ export default function Reader() {
); );
} }
if (logTrace) { if (error) {
return ( return (
<LogModal <LogModal
isOpen={!!logTrace} isOpen={!!error}
onClose={() => { onClose={() => (window.location.href = "/")}
if (logTrace.type === "ERROR") window.location.href = "/"; message={error.message}
setLogTrace(null); log={error.log}
}} status="ERROR"
message={logTrace.message}
log={logTrace.log}
status={logTrace.type}
/> />
); );
} }
return ( return (
<section className="min-h-fit w-full bg-base-100 px-4 py-8 md:py-16 font-serif relative overflow-hidden"> <section className="min-h-fit w-full bg-base-100 px-4 py-8 md:py-16 font-serif relative overflow-hidden">
<div className="fixed inset-0 bg-vig pointer-events-none z-0" /> <div className="fixed inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,rgba(0,0,0,0.5)_100%)] pointer-events-none z-0" />
<div <div
className={`transition-all delay-300 duration-1000 relative ${ className={`transition-all delay-300 duration-1000 relative ${
revealState === "REVEALED" revealState === "revealed"
? "opacity-0 w-0 h-0 overflow-hidden invisible" ? "opacity-0 w-0 h-0 overflow-hidden invisible"
: "opacity-100" : "opacity-100"
}`} }`}
> >
{revealState === "SEALED" && ( {revealState === "sealed" && (
<div className="h-[80vh] mx-auto flex-col items-center flex justify-center"> <div className="h-[80vh] mx-auto flex-col items-center flex justify-center">
<div className="perspective-distant scale-80 duration-1000 transition-all animate-[pulse_2s_linear_1]"> <div className="perspective-distant scale-80 duration-1000 transition-all animate-[pulse_2s_linear_1]">
<EnvelopeReveal <EnvelopeReveal
@@ -261,7 +260,7 @@ export default function Reader() {
? formatDate(new Date(metadata.updated_at)) ? formatDate(new Date(metadata.updated_at))
: undefined : undefined
} }
onRevealComplete={() => setRevealState("REVEALED")} onRevealComplete={() => setRevealState("revealed")}
ignite={ignite} ignite={ignite}
/> />
</div> </div>
@@ -271,8 +270,16 @@ export default function Reader() {
{ignite && <PostActionOverlay revealState={revealState} />} {ignite && <PostActionOverlay revealState={revealState} />}
{revealState === "REVEALED" && ( <LogModal
<div className="max-w-180 m-8 mx-auto space-y-8 h-full relative inset-0 z-100"> isOpen={!!warning}
onClose={() => setWarning(null)}
message={warning?.message || ""}
log={warning?.log || ""}
status="WARN"
/>
{revealState === "revealed" && (
<div className="max-w-4xl m-8 mx-auto space-y-8 h-full relative inset-0 z-100">
<div className="relative group perspective-1000"> <div className="relative group perspective-1000">
<div className="absolute inset-0 bg-primary/5 blur-3xl rounded-full scale-75 opacity-0 group-hover:opacity-100 transition-opacity duration-1000 pointer-events-none" /> <div className="absolute inset-0 bg-primary/5 blur-3xl rounded-full scale-75 opacity-0 group-hover:opacity-100 transition-opacity duration-1000 pointer-events-none" />
@@ -282,7 +289,7 @@ export default function Reader() {
</div> </div>
{metadata?.recipient && ( {metadata?.recipient && (
<p className="text-center sm:hidden text-xxs uppercase tracking-widester text-base-content/20 mt-8"> <p className="text-center sm:hidden text-[10px] uppercase tracking-[0.3em] text-base-content/20 mt-8">
For {metadata.recipient} For {metadata.recipient}
</p> </p>
)} )}
@@ -302,7 +309,7 @@ export default function Reader() {
/> />
)} )}
{isAuthor && revealState !== "BURNED" && ( {isAuthor && revealState !== "burned" && (
<div className="flex justify-center gap-2 mt-8 z-10 relative"> <div className="flex justify-center gap-2 mt-8 z-10 relative">
<button <button
id="share-letter-btn" id="share-letter-btn"
@@ -330,7 +337,7 @@ export default function Reader() {
)} )}
<footer className="mt-16 text-center z-10 opacity-10 pointer-events-none"> <footer className="mt-16 text-center z-10 opacity-10 pointer-events-none">
<p className="text-xs font-sans uppercase tracking-widester"> <p className="text-xs font-sans uppercase tracking-[0.5em]">
Read. Remember. Release. Read. Remember. Release.
</p> </p>
</footer> </footer>
+4 -2
View File
@@ -13,6 +13,7 @@ import { endpoints } from "../config/endpoints";
import { ROUTES } from "../config/routes"; import { ROUTES } from "../config/routes";
import { CryptoUtils } from "../utils/crypto"; import { CryptoUtils } from "../utils/crypto";
// validation logic
const registerSchema = z const registerSchema = z
.object({ .object({
full_name: z.string().min(2, "Name must be at least 2 characters"), full_name: z.string().min(2, "Name must be at least 2 characters"),
@@ -48,7 +49,7 @@ export default function Register() {
setIsLoading(true); setIsLoading(true);
setApiError(null); setApiError(null);
try { try {
// we generate the key bundle here to get the authHash (password) to be haSHed and stored in the db. // We generate the key bundle here to get the authHash (password) for the server.
const { authHash } = await CryptoUtils.deriveKeyBundle( const { authHash } = await CryptoUtils.deriveKeyBundle(
data.password, data.password,
data.email, data.email,
@@ -99,7 +100,7 @@ export default function Register() {
<FormField <FormField
label="Email" label="Email"
type="email" type="email"
placeholder="f.kafka@wrongtrain.com" placeholder="f.kafka@email.com"
registration={register("email")} registration={register("email")}
error={errors.email?.message} error={errors.email?.message}
handleFocus={() => handleFocus={() =>
@@ -135,6 +136,7 @@ export default function Register() {
} }
/> />
{/* Warning */}
<div className="alert alert-warning items-start text-left p-3 gap-2 rounded-md border-warning/20"> <div className="alert alert-warning items-start text-left p-3 gap-2 rounded-md border-warning/20">
<InfoIcon size={20} weight="duotone" className="mt-0.5 shrink-0" /> <InfoIcon size={20} weight="duotone" className="mt-0.5 shrink-0" />
<p className="text-sm font-semibold"> <p className="text-sm font-semibold">
+2 -2
View File
@@ -17,7 +17,7 @@ describe("deriveKeyBundle", () => {
expect(masterKey.type).toBe("secret"); expect(masterKey.type).toBe("secret");
expect(masterKey).toBeInstanceOf(CryptoKey); expect(masterKey).toBeInstanceOf(CryptoKey);
expect(authHash).toHaveLength(64); expect(authHash).toHaveLength(64); // SHA-256 hex
expect(typeof authHash).toBe("string"); expect(typeof authHash).toBe("string");
}); });
@@ -216,7 +216,7 @@ describe("extractSharingKey", () => {
}); });
it("extracted key should decrypt the ciphertext produced by encryptLetter", async () => { it("extracted key should decrypt the ciphertext produced by encryptLetter", async () => {
const plaintext = "hello"; const plaintext = "hello from the owner";
const encrypted = await utils.encryptLetter(plaintext, masterKey); const encrypted = await utils.encryptLetter(plaintext, masterKey);
const extracted = await utils.extractSharingKey( const extracted = await utils.extractSharingKey(
+65 -114
View File
@@ -1,3 +1,7 @@
/**
* 0 knowledge cryptography. No Server involved in encryption/decryption
*/
export interface EncryptedLetter { export interface EncryptedLetter {
encrypted_content: string; encrypted_content: string;
encrypted_dek: string; encrypted_dek: string;
@@ -7,7 +11,6 @@ export interface EncryptedLetter {
export interface EncryptedLetterMetadata { export interface EncryptedLetterMetadata {
encrypted_content: string; encrypted_content: string;
encrypted_dek: string; encrypted_dek: string;
sharingKey?: string | null;
} }
export interface EncryptedImageUpload { export interface EncryptedImageUpload {
@@ -22,88 +25,59 @@ interface SealedEnvelope {
sharingKey: string; sharingKey: string;
} }
// we use a class here to keep track of instantiations (use 1 and the same DEK per letter content and metadata)
// TODO: try refactoring into a pure function for consistency
export class CryptoUtils { export class CryptoUtils {
private dek!: CryptoKey; private dek: CryptoKey = {} as CryptoKey;
private static readonly PBKDF2_ITERATIONS = private static readonly PBKDF2_ITERATIONS = 100_000;
Number(import.meta.env.VITE_PBKDF2_ITERATIONS) || 600_000; private static readonly AES_GCM = { name: "AES-GCM", length: 256 };
// NOTE: https://www.w3.org/TR/webcrypto/#aes-gcm
private static readonly AES_ALGO = { name: "AES-GCM", length: 256 };
private static readonly IV_BYTE_LENGTH = 12;
// NOTE: this MUST be called once, per letter, for all operations in a session to a fresh Data Encryption Key (DEK) // Generates a fresh Data Encryption Key (DEK)
async initialize() { async initialize() {
this.dek = await crypto.subtle.generateKey(CryptoUtils.AES_ALGO, true, [ this.dek = await crypto.subtle.generateKey(CryptoUtils.AES_GCM, true, [
"encrypt", "encrypt",
"decrypt", "decrypt",
]); ]);
} }
private toBase64 = (buffer: Uint8Array): string => { // base64 conversion for transit
// convert buffer to raw string toBase64 = (buf: Uint8Array): string =>
let binaryFileString = ""; btoa(buf.reduce((s, b) => s + String.fromCharCode(b), ""));
for (let i = 0; i < buffer.byteLength; i++) {
binaryFileString += String.fromCharCode(buffer[i]);
}
return btoa(binaryFileString);
};
private fromBase64 = (b64String: string): Uint8Array<ArrayBuffer> => { fromBase64 = (b64: string): Uint8Array<ArrayBuffer> => {
const decodedString = atob(b64String); const str = atob(b64);
const arr = new Uint8Array(decodedString.length); const arr = new Uint8Array(str.length);
for (let i = 0; i < decodedString.length; i++) for (let i = 0; i < str.length; i++) arr[i] = str.charCodeAt(i);
arr[i] = decodedString.charCodeAt(i);
return arr; return arr;
}; };
// Required structure: [12 bytes IV][Cipher text][16 bytes Auth Tag] // bundle IV + data into a single base64 string
// NOTE: Web Crypto API auto appends the auth tag, so we focus on IV and cipher packWithIv = (iv: Uint8Array, data: ArrayBuffer): string => {
private packWithIv = (iv: Uint8Array, ciphertext: ArrayBuffer): string => { const packed = new Uint8Array(iv.length + data.byteLength);
// create a buffer large enough to hold both iv and cipher text (12 + x bytes) packed.set(iv);
const combinedPayload = new Uint8Array( packed.set(new Uint8Array(data), iv.length);
CryptoUtils.IV_BYTE_LENGTH + ciphertext.byteLength, return this.toBase64(packed);
);
// place the iv at the start
combinedPayload.set(iv, 0);
// place the ciphertext after the iv
combinedPayload.set(new Uint8Array(ciphertext), CryptoUtils.IV_BYTE_LENGTH);
// convert the buffer to Base64 for transit
return this.toBase64(combinedPayload);
}; };
// For decryption: extracts the IV and the data from the base64 string, easy because we know the size of iv already. unpackWithIv = (
private unpackWithIv = ( b64: string,
encodedString: string, ): [Uint8Array<ArrayBuffer>, Uint8Array<ArrayBuffer>] => {
): { iv: Uint8Array<ArrayBuffer>; ciphertext: Uint8Array<ArrayBuffer> } => { const buf = this.fromBase64(b64);
// decode from base64 to array buffer return [new Uint8Array(buf.buffer, 0, 12), new Uint8Array(buf.buffer, 12)];
const fullBuffer = this.fromBase64(encodedString);
// extract first 12 bytes for iv
const iv = fullBuffer.slice(0, CryptoUtils.IV_BYTE_LENGTH);
// extract rest for cipher text
const ciphertext = fullBuffer.slice(CryptoUtils.IV_BYTE_LENGTH);
return { iv: new Uint8Array(iv), ciphertext: new Uint8Array(ciphertext) };
}; };
/** /**
* Derive a key bundle (Masterkey + authHash) from email + (plain) password combo * Derives a Key Bundle (MasterKey + AuthHash) from a password + email.
* WHY?: This is much secure than relying on server to hash and store the password. Also ensures absolute 0 knowledge * Absolute zero knowledge!!
*/ */
public static async deriveKeyBundle( public static async deriveKeyBundle(
password: string, password: string,
email: string, email: string,
): Promise<{ masterKey: CryptoKey; authHash: string }> { ): Promise<{ masterKey: CryptoKey; authHash: string }> {
const encoder = new TextEncoder(); const enc = new TextEncoder();
const salt = encoder.encode(email.toLowerCase()); const salt = enc.encode(email.toLowerCase());
const baseKey = await crypto.subtle.importKey( const baseKey = await crypto.subtle.importKey(
"raw", "raw",
encoder.encode(password), enc.encode(password),
"PBKDF2", "PBKDF2",
false, false,
["deriveBits", "deriveKey"], ["deriveBits", "deriveKey"],
@@ -117,61 +91,49 @@ export class CryptoUtils {
hash: "SHA-256", hash: "SHA-256",
}, },
baseKey, baseKey,
512, 512, // 512 bits to split
); );
// first 256 bits for masterkey, last 256 bits for authHash (password sent in REST) // first 256 bits for MasterKey, last 256 bits for AuthHash
const masterKeyBytes = masterSeed.slice(0, 32); const masterKeyBytes = masterSeed.slice(0, 32);
const authHashBytes = masterSeed.slice(32, 64); const authHashBytes = masterSeed.slice(32, 64);
// Create the masterkey for client-side encryption // Create the MasterKey for client-side encryption
const masterKey = await crypto.subtle.importKey( const masterKey = await crypto.subtle.importKey(
"raw", "raw",
masterKeyBytes, masterKeyBytes,
CryptoUtils.AES_ALGO, CryptoUtils.AES_GCM,
false, false,
["encrypt", "decrypt", "wrapKey", "unwrapKey"], ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
); );
// convert bytes in to hex string // Create the hex AuthHash for server-side verification
let authHash = ""; const authHash = Array.from(new Uint8Array(authHashBytes))
const authHashBuffer = new Uint8Array(authHashBytes); .map((b) => b.toString(16).padStart(2, "0"))
.join("");
for (let i = 0; i < authHashBuffer.byteLength; i++) {
// we force every bytes converted to string to be min 2 chars (otherwise 00 0a will be just a and not "000a")
authHash += authHashBuffer[i].toString(16).padStart(2, "0");
}
return { masterKey, authHash }; return { masterKey, authHash };
} }
/* // Internal helper to encrypt data and wrap the key
* Envelope Encryption - Decryption
* WHY?: for guest access where we don't have to share the masterkey just the dek.
* This way, raw dek never leaves browser (db stores the encrypted version)
*/
// encrypt the plaintext with a DEK and then encrypt (wrap) that DEK with the user's masterkey.
private async sealEnvelope( private async sealEnvelope(
input: Uint8Array, input: Uint8Array,
masterKey: CryptoKey, masterKey: CryptoKey,
): Promise<SealedEnvelope> { ): Promise<SealedEnvelope> {
if (!this.dek) {
throw new Error("DEK is not available (forgot to .initialize()?)");
}
const plainBytes = new Uint8Array(input); const plainBytes = new Uint8Array(input);
const contentIv = crypto.getRandomValues(new Uint8Array(12));
const dekIv = crypto.getRandomValues(new Uint8Array(12));
// encrypt the content with the DEK
const contentIv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt( const ciphertext = await crypto.subtle.encrypt(
{ name: CryptoUtils.AES_ALGO.name, iv: contentIv }, { name: "AES-GCM", iv: contentIv },
this.dek, this.dek,
plainBytes, plainBytes,
); );
// wrap the DEK with the Master Key (for self access) // wrap the DEK with the Master Key (for self/owner access)
const dekIv = crypto.getRandomValues(new Uint8Array(12));
const wrappedDek = await crypto.subtle.wrapKey("raw", this.dek, masterKey, { const wrappedDek = await crypto.subtle.wrapKey("raw", this.dek, masterKey, {
name: CryptoUtils.AES_ALGO.name, name: "AES-GCM",
iv: dekIv, iv: dekIv,
}); });
@@ -185,27 +147,26 @@ export class CryptoUtils {
}; };
} }
// Unwrap the DEK with the master key to get the key back. Decrypt the content with the DEK. // Internal helper to unwrap the key and decrypt data
private async openEnvelope( private async openEnvelope(
encryptedContent: string, encryptedContent: string,
encrypted_dek: string, encrypted_dek: string,
masterKey: CryptoKey, masterKey: CryptoKey,
): Promise<Uint8Array<ArrayBuffer>> { ): Promise<Uint8Array<ArrayBuffer>> {
const { iv: dekIv, ciphertext: wrappedDek } = const [dekIv, wrappedDek] = this.unpackWithIv(encrypted_dek);
this.unpackWithIv(encrypted_dek);
const dek = await crypto.subtle.unwrapKey( const dek = await crypto.subtle.unwrapKey(
"raw", "raw",
wrappedDek, wrappedDek,
masterKey, masterKey,
{ name: CryptoUtils.AES_ALGO.name, iv: dekIv }, { name: "AES-GCM", iv: dekIv },
CryptoUtils.AES_ALGO, CryptoUtils.AES_GCM,
false, false,
["decrypt"], ["decrypt"],
); );
const { iv: contentIv, ciphertext } = this.unpackWithIv(encryptedContent); const [contentIv, ciphertext] = this.unpackWithIv(encryptedContent);
const plainBytes = await crypto.subtle.decrypt( const plainBytes = await crypto.subtle.decrypt(
{ name: CryptoUtils.AES_ALGO.name, iv: contentIv }, { name: "AES-GCM", iv: contentIv },
dek, dek,
ciphertext, ciphertext,
); );
@@ -221,14 +182,14 @@ export class CryptoUtils {
const dek = await crypto.subtle.importKey( const dek = await crypto.subtle.importKey(
"raw", "raw",
dekBytes, dekBytes,
CryptoUtils.AES_ALGO, CryptoUtils.AES_GCM,
false, false,
["decrypt"], ["decrypt"],
); );
const { iv: contentIv, ciphertext } = this.unpackWithIv(encryptedContent); const [contentIv, ciphertext] = this.unpackWithIv(encryptedContent);
const plainBytes = await crypto.subtle.decrypt( const plainBytes = await crypto.subtle.decrypt(
{ name: CryptoUtils.AES_ALGO.name, iv: contentIv }, { name: "AES-GCM", iv: contentIv },
dek, dek,
ciphertext, ciphertext,
); );
@@ -245,7 +206,6 @@ export class CryptoUtils {
): Promise<EncryptedLetter> { ): Promise<EncryptedLetter> {
const { encryptedContent, encrypted_dek, sharingKey } = const { encryptedContent, encrypted_dek, sharingKey } =
await this.sealEnvelope(new TextEncoder().encode(plaintext), masterKey); await this.sealEnvelope(new TextEncoder().encode(plaintext), masterKey);
return { encrypted_content: encryptedContent, encrypted_dek, sharingKey }; return { encrypted_content: encryptedContent, encrypted_dek, sharingKey };
} }
@@ -258,7 +218,6 @@ export class CryptoUtils {
encrypted_dek, encrypted_dek,
masterKey, masterKey,
); );
return new TextDecoder().decode(bytes); return new TextDecoder().decode(bytes);
} }
@@ -270,20 +229,18 @@ export class CryptoUtils {
encrypted_content, encrypted_content,
sharingKey, sharingKey,
); );
return new TextDecoder().decode(bytes); return new TextDecoder().decode(bytes);
} }
public async encryptMetadata( public async encryptMetadata(
metadata: Record<string, any>, metadata: Record<string, any>,
masterKey: CryptoKey, masterKey: CryptoKey,
): Promise<EncryptedLetterMetadata> { ): Promise<EncryptedLetter> {
const { encryptedContent, encrypted_dek, sharingKey } = const { encryptedContent, encrypted_dek, sharingKey } =
await this.sealEnvelope( await this.sealEnvelope(
new TextEncoder().encode(JSON.stringify(metadata)), new TextEncoder().encode(JSON.stringify(metadata)),
masterKey, masterKey,
); );
return { encrypted_content: encryptedContent, encrypted_dek, sharingKey }; return { encrypted_content: encryptedContent, encrypted_dek, sharingKey };
} }
@@ -296,7 +253,6 @@ export class CryptoUtils {
encrypted_metadata.encrypted_dek, encrypted_metadata.encrypted_dek,
masterKey, masterKey,
); );
return JSON.parse(new TextDecoder().decode(bytes)); return JSON.parse(new TextDecoder().decode(bytes));
} }
@@ -308,7 +264,6 @@ export class CryptoUtils {
encrypted_content, encrypted_content,
sharingKey, sharingKey,
); );
return JSON.parse(new TextDecoder().decode(bytes)); return JSON.parse(new TextDecoder().decode(bytes));
} }
@@ -335,13 +290,12 @@ export class CryptoUtils {
masterKey: CryptoKey, masterKey: CryptoKey,
): Promise<string> { ): Promise<string> {
const encryptedBytes = new Uint8Array(await encryptedBlob.arrayBuffer()); const encryptedBytes = new Uint8Array(await encryptedBlob.arrayBuffer());
const plainBytes = await this.openEnvelope( const bytes = await this.openEnvelope(
this.toBase64(encryptedBytes), this.toBase64(encryptedBytes),
encrypted_dek, encrypted_dek,
masterKey, masterKey,
); );
return URL.createObjectURL(new Blob([bytes]));
return URL.createObjectURL(new Blob([plainBytes]));
} }
public async decryptImageWithSharingKey( public async decryptImageWithSharingKey(
@@ -349,31 +303,28 @@ export class CryptoUtils {
sharingKey: string, sharingKey: string,
): Promise<string> { ): Promise<string> {
const encryptedBytes = new Uint8Array(await encryptedBlob.arrayBuffer()); const encryptedBytes = new Uint8Array(await encryptedBlob.arrayBuffer());
const plainBytes = await this.openEnvelopeWithSharingKey( const bytes = await this.openEnvelopeWithSharingKey(
this.toBase64(encryptedBytes), this.toBase64(encryptedBytes),
sharingKey, sharingKey,
); );
return URL.createObjectURL(new Blob([bytes]));
return URL.createObjectURL(new Blob([plainBytes]));
} }
// derive raw DEK on demand (browser only, not sent to server) for guest access // Re-derives the sharing key (raw DEK) on demand (browser only, not sent to server).
public async extractSharingKey( public async extractSharingKey(
encrypted_dek: string, encrypted_dek: string,
masterKey: CryptoKey, masterKey: CryptoKey,
): Promise<string> { ): Promise<string> {
const { iv: dekIv, ciphertext: wrappedDek } = const [dekIv, wrappedDek] = this.unpackWithIv(encrypted_dek);
this.unpackWithIv(encrypted_dek);
const rawDek = await crypto.subtle.unwrapKey( const rawDek = await crypto.subtle.unwrapKey(
"raw", "raw",
wrappedDek, wrappedDek,
masterKey, masterKey,
{ name: CryptoUtils.AES_ALGO.name, iv: dekIv }, { name: "AES-GCM", iv: dekIv },
CryptoUtils.AES_ALGO, CryptoUtils.AES_GCM,
true, true,
["decrypt"], ["decrypt"],
); );
return this.toBase64( return this.toBase64(
new Uint8Array(await crypto.subtle.exportKey("raw", rawDek)), new Uint8Array(await crypto.subtle.exportKey("raw", rawDek)),
); );
+1 -1
View File
@@ -1,6 +1,6 @@
import { openDB } from "idb"; import { openDB } from "idb";
// we use indexedDB to securely store master key for easier access across tabs (better UX than having to store in session) // we use this to store master key in browser - secure and good UX
const db = openDB("piku-keys", 1, { const db = openDB("piku-keys", 1, {
upgrade(db) { upgrade(db) {
db.createObjectStore("master-key"); db.createObjectStore("master-key");
+29 -28
View File
@@ -12,7 +12,6 @@ vi.mock("../api/apiClient", () => ({
api: { api: {
get: vi.fn(), get: vi.fn(),
}, },
apiServerUrl: "https://remote",
})); }));
vi.mock("./fileUtils", () => ({ vi.mock("./fileUtils", () => ({
@@ -22,6 +21,7 @@ vi.mock("./fileUtils", () => ({
describe("letterLogic image helpers", () => { describe("letterLogic image helpers", () => {
let masterKey: CryptoKey; let masterKey: CryptoKey;
let crypto: CryptoUtils; let crypto: CryptoUtils;
beforeEach(async () => { beforeEach(async () => {
const keyBundle = await CryptoUtils.deriveKeyBundle( const keyBundle = await CryptoUtils.deriveKeyBundle(
"password123", "password123",
@@ -58,13 +58,15 @@ describe("letterLogic image helpers", () => {
const encryptImageSpy = vi.spyOn(CryptoUtils.prototype, "encryptImage"); const encryptImageSpy = vi.spyOn(CryptoUtils.prototype, "encryptImage");
const { encryptedImageFiles: uploads, encryptedCanvasData } = const uploads = await encryptCanvasImages(
await encryptCanvasImages(canvasData, [], masterKey, crypto); canvasData,
[],
masterKey,
crypto,
);
expect(encryptImageSpy).not.toHaveBeenCalled(); expect(encryptImageSpy).not.toHaveBeenCalled();
expect(encryptedCanvasData.objects[0].src).toBe( expect(canvasData.objects[0].src).toBe("already-encrypted.png.bin");
"already-encrypted.png.bin",
);
expect(uploads.size).toBe(0); expect(uploads.size).toBe(0);
}); });
@@ -97,11 +99,15 @@ describe("letterLogic image helpers", () => {
filename: "photo.png.bin", filename: "photo.png.bin",
}); });
const { encryptedImageFiles: uploads, encryptedCanvasData } = const uploads = await encryptCanvasImages(
await encryptCanvasImages(canvasData, canvasImages, masterKey, crypto); canvasData,
canvasImages,
masterKey,
crypto,
);
expect(CryptoUtils.prototype.encryptImage).toHaveBeenCalledTimes(1); expect(CryptoUtils.prototype.encryptImage).toHaveBeenCalledTimes(1);
expect(encryptedCanvasData.objects[0].src).toBe("photo.png.bin"); expect(canvasData.objects[0].src).toBe("photo.png.bin");
expect(uploads.size).toBe(1); expect(uploads.size).toBe(1);
expect(uploads.has("photo.png.bin")).toBe(true); expect(uploads.has("photo.png.bin")).toBe(true);
}); });
@@ -130,7 +136,7 @@ describe("letterLogic image helpers", () => {
], ],
}; };
const remoteImages = [ const remoteImages = [
{ file_name: "photo.png.bin", file: `https://remote/photo.png.bin` }, { file_name: "photo.png.bin", file: "https://remote/photo.png.bin" },
]; ];
vi.mocked(api.get).mockResolvedValue({ data: new Blob(["encrypted"]) }); vi.mocked(api.get).mockResolvedValue({ data: new Blob(["encrypted"]) });
@@ -138,7 +144,7 @@ describe("letterLogic image helpers", () => {
"blob:http://localhost/decrypted", "blob:http://localhost/decrypted",
); );
const { canvasDataWithDecryptedImages } = await decryptCanvasImages( await decryptCanvasImages(
canvasData, canvasData,
remoteImages, remoteImages,
"wrapped-dek", "wrapped-dek",
@@ -147,7 +153,7 @@ describe("letterLogic image helpers", () => {
); );
expect(api.get).toHaveBeenCalledWith( expect(api.get).toHaveBeenCalledWith(
`https://remote/photo.png.bin`, "https://remote/photo.png.bin",
expect.objectContaining({ responseType: "blob" }), expect.objectContaining({ responseType: "blob" }),
); );
expect(CryptoUtils.prototype.decryptImage).toHaveBeenCalledWith( expect(CryptoUtils.prototype.decryptImage).toHaveBeenCalledWith(
@@ -155,10 +161,8 @@ describe("letterLogic image helpers", () => {
"wrapped-dek", "wrapped-dek",
masterKey, masterKey,
); );
expect(canvasDataWithDecryptedImages.objects[0].src).toBe( expect(canvasData.objects[0].src).toBe("blob:http://localhost/decrypted");
"blob:http://localhost/decrypted", expect(canvasData.objects[1].text).toBe("hello");
);
expect(canvasDataWithDecryptedImages.objects[1].text).toBe("hello");
}); });
it("should include raw file when includeRawFile is true", async () => { it("should include raw file when includeRawFile is true", async () => {
@@ -187,7 +191,7 @@ describe("letterLogic image helpers", () => {
new File(["raw"], "photo.png.bin"), new File(["raw"], "photo.png.bin"),
); );
const { canvasDataWithDecryptedImages } = await decryptCanvasImages( await decryptCanvasImages(
canvasData, canvasData,
remoteImages, remoteImages,
"wrapped-dek", "wrapped-dek",
@@ -200,9 +204,7 @@ describe("letterLogic image helpers", () => {
"blob:http://localhost/decrypted", "blob:http://localhost/decrypted",
"photo.png.bin", "photo.png.bin",
); );
expect( expect(canvasData.objects[0]._customRawFile).toBeInstanceOf(File);
canvasDataWithDecryptedImages.objects[0]._customRawFile,
).toBeInstanceOf(File);
}); });
}); });
@@ -230,13 +232,12 @@ describe("letterLogic image helpers", () => {
"decryptImageWithSharingKey", "decryptImageWithSharingKey",
).mockResolvedValue("blob:http://localhost/decrypted-shared"); ).mockResolvedValue("blob:http://localhost/decrypted-shared");
const { canvasDataWithDecryptedImages } = await decryptCanvasImagesWithSharingKey(
await decryptCanvasImagesWithSharingKey( canvasData,
canvasData, remoteImages,
remoteImages, "raw-sharing-key",
"raw-sharing-key", crypto,
crypto, );
);
expect(api.get).toHaveBeenCalledWith( expect(api.get).toHaveBeenCalledWith(
"https://remote/photo.png.bin", "https://remote/photo.png.bin",
@@ -245,7 +246,7 @@ describe("letterLogic image helpers", () => {
expect( expect(
CryptoUtils.prototype.decryptImageWithSharingKey, CryptoUtils.prototype.decryptImageWithSharingKey,
).toHaveBeenCalledWith(expect.any(Blob), "raw-sharing-key"); ).toHaveBeenCalledWith(expect.any(Blob), "raw-sharing-key");
expect(canvasDataWithDecryptedImages.objects[0].src).toBe( expect(canvasData.objects[0].src).toBe(
"blob:http://localhost/decrypted-shared", "blob:http://localhost/decrypted-shared",
); );
}); });
+80 -147
View File
@@ -1,4 +1,4 @@
import { api, apiServerUrl, publicApi } from "../api/apiClient"; import { api } from "../api/apiClient";
import type { import type {
CanvasJSON, CanvasJSON,
FabricImageJSON, FabricImageJSON,
@@ -11,35 +11,6 @@ export interface CanvasImageRef {
file: File; file: File;
} }
export interface DecryptedFabricImageJSON extends FabricImageJSON {
_customRawFile?: File;
}
export interface DecryptionResult {
canvasDataWithDecryptedImages: CanvasJSON;
isPartialFailure: boolean;
errors: string[];
}
export interface EncryptionResult {
encryptedImageFiles: Map<string, Blob>;
encryptedCanvasData: CanvasJSON;
}
async function fetchEncryptedBlobFromRemote(remoteUrl: string): Promise<Blob> {
// IF served statically from server, we need proper CORS setup
if (remoteUrl.includes(apiServerUrl)) {
const res = await api.get(remoteUrl, { responseType: "blob" });
return res.data;
}
// Note: S3 Storage fetch (external url) has to bypass our existing CORS setup
const res = await publicApi.get(remoteUrl, {
responseType: "blob",
withCredentials: false,
});
return res.data;
}
export async function decryptCanvasImages( export async function decryptCanvasImages(
canvasData: CanvasJSON, canvasData: CanvasJSON,
remoteImages: { file_name: string; file: string }[], remoteImages: { file_name: string; file: string }[],
@@ -47,66 +18,51 @@ export async function decryptCanvasImages(
masterKey: CryptoKey, masterKey: CryptoKey,
cryptoUtils: CryptoUtils, cryptoUtils: CryptoUtils,
includeRawFile = false, includeRawFile = false,
): Promise<DecryptionResult> { ): Promise<{ isDecryptionPartialFailure: boolean; error: string }> {
if (!canvasData?.objects) { if (!canvasData?.objects)
return { return { isDecryptionPartialFailure: false, error: "" };
canvasDataWithDecryptedImages: canvasData, let isDecryptionPartialFailure = false;
isPartialFailure: false, let error = "";
errors: [],
};
}
const imageMap = new Map( const imageMap = new Map(
remoteImages.map((img) => [img.file_name, img.file]), remoteImages.map((img) => [img.file_name, img.file]),
); );
const errors: string[] = []; const imageDecryptionPromises = canvasData.objects.map(async (obj, index) => {
const processedObjects = await Promise.all( if (obj.type !== "Image") return;
canvasData.objects.map(async (obj) => { const imgObj = obj as FabricImageJSON;
if (obj.type !== "Image") return obj; const remoteUrl = imageMap.get(imgObj.src);
if (!remoteUrl) return;
const imgObj = obj as FabricImageJSON; try {
const remoteUrl = imageMap.get(imgObj.src); // HACK: For S3 Storage fetch and avoiding CORS error
if (!remoteUrl) return obj; const res = await api.get(remoteUrl, {
responseType: "blob",
withCredentials: false,
});
const originalSrc = imgObj.src;
try { const blobUrl = await cryptoUtils.decryptImage(
const blob = await fetchEncryptedBlobFromRemote(remoteUrl); res.data,
const blobUrl = await cryptoUtils.decryptImage( encrypted_dek,
blob, masterKey,
encrypted_dek, );
masterKey,
);
const decryptedObj: DecryptedFabricImageJSON = { imgObj.src = blobUrl;
...imgObj,
src: blobUrl,
};
if (includeRawFile) { if (includeRawFile) {
decryptedObj._customRawFile = await blobUrlToFile( imgObj._customRawFile = await blobUrlToFile(blobUrl, originalSrc);
blobUrl,
imgObj.src,
);
}
return decryptedObj;
} catch (err) {
errors.push(
`Failed to decrypt ${imgObj.src}: ${err instanceof Error ? err.message : "Unknown error"}`,
);
return null;
} }
}), } catch (_error) {
); delete canvasData.objects[index];
isDecryptionPartialFailure = true;
error = _error instanceof Error ? _error.message : "Unknown error";
}
});
return { await Promise.all(imageDecryptionPromises);
canvasDataWithDecryptedImages: { canvasData.objects = canvasData.objects.filter(Boolean);
...canvasData, return { isDecryptionPartialFailure, error };
objects: processedObjects.filter((obj) => !!obj),
},
isPartialFailure: errors.length > 0,
errors,
};
} }
export async function decryptCanvasImagesWithSharingKey( export async function decryptCanvasImagesWithSharingKey(
@@ -114,53 +70,41 @@ export async function decryptCanvasImagesWithSharingKey(
remoteImages: { file_name: string; file: string }[], remoteImages: { file_name: string; file: string }[],
sharingKey: string, sharingKey: string,
cryptoUtils: CryptoUtils, cryptoUtils: CryptoUtils,
): Promise<DecryptionResult> { ): Promise<{ isDecryptionPartialFailure: boolean; error: string }> {
if (!canvasData?.objects) { if (!canvasData?.objects)
return { return { isDecryptionPartialFailure: false, error: "" };
canvasDataWithDecryptedImages: canvasData, let isDecryptionPartialFailure = false;
isPartialFailure: false, let error = "";
errors: [],
};
}
const imageMap = new Map( const imageMap = new Map(
remoteImages.map((img) => [img.file_name, img.file]), remoteImages.map((img) => [img.file_name, img.file]),
); );
const errors: string[] = [];
const processedObjects = await Promise.all( const decryptionPromises = canvasData.objects.map(async (obj, index) => {
canvasData.objects.map(async (obj) => { if (obj.type !== "Image") return;
if (obj.type !== "Image") return obj;
const imgObj = obj as FabricImageJSON; const imgObj = obj as FabricImageJSON;
const remoteUrl = imageMap.get(imgObj.src); const remoteUrl = imageMap.get(imgObj.src);
if (!remoteUrl) return obj; if (!remoteUrl) return;
try { try {
const blob = await fetchEncryptedBlobFromRemote(remoteUrl); const res = await api.get(remoteUrl, {
const blobUrl = await cryptoUtils.decryptImageWithSharingKey( responseType: "blob",
blob, withCredentials: false,
sharingKey, });
); imgObj.src = await cryptoUtils.decryptImageWithSharingKey(
res.data,
sharingKey,
);
} catch (_error) {
delete canvasData.objects[index];
isDecryptionPartialFailure = true;
error = _error instanceof Error ? _error.message : "Unknown error";
}
});
return { ...imgObj, src: blobUrl }; await Promise.all(decryptionPromises);
} catch (err) { canvasData.objects = canvasData.objects.filter(Boolean);
errors.push( return { isDecryptionPartialFailure, error };
`Failed to decrypt ${imgObj.src}: ${err instanceof Error ? err.message : "Unknown error"}`,
);
return null;
}
}),
);
return {
canvasDataWithDecryptedImages: {
...canvasData,
objects: processedObjects.filter((obj) => !!obj),
},
isPartialFailure: errors.length > 0,
errors,
};
} }
export async function encryptCanvasImages( export async function encryptCanvasImages(
@@ -168,34 +112,23 @@ export async function encryptCanvasImages(
canvasImages: CanvasImageRef[], canvasImages: CanvasImageRef[],
masterKey: CryptoKey, masterKey: CryptoKey,
cryptoUtils: CryptoUtils, cryptoUtils: CryptoUtils,
): Promise<EncryptionResult> { ) {
const encryptedImageFiles = new Map<string, Blob>(); const encryptedFiles = new Map<string, Blob>();
const filenameMapping = new Map<string, string>(); const filenameMapping = new Map<string, string>();
// filter out already encrypted images for (const img of canvasImages) {
const imagesToEncrypt = canvasImages.filter( if (img.src.endsWith(".bin")) continue;
(img) => img.file && !img.src.endsWith(".bin"), if (!img.file) continue;
); const { filename, encryptedBlob } = await cryptoUtils.encryptImage(
img.file,
masterKey,
);
filenameMapping.set(img.src, filename);
encryptedFiles.set(filename, encryptedBlob);
}
// encrypt images parallelly if (canvasData?.objects) {
await Promise.all( canvasData.objects = canvasData.objects.map((obj) => {
imagesToEncrypt.map(async (img) => {
const { filename, encryptedBlob } = await cryptoUtils.encryptImage(
img.file,
masterKey,
);
// map the og image url to the encrypted file name and filename to the encrypted source
filenameMapping.set(img.src, filename);
encryptedImageFiles.set(filename, encryptedBlob);
}),
);
if (!canvasData?.objects)
return { encryptedImageFiles, encryptedCanvasData: canvasData };
const newCanvasData = {
...canvasData,
objects: canvasData.objects.map((obj) => {
if (obj.type === "Image") { if (obj.type === "Image") {
const imgObj = obj as FabricImageJSON; const imgObj = obj as FabricImageJSON;
if (filenameMapping.has(imgObj.src)) { if (filenameMapping.has(imgObj.src)) {
@@ -206,8 +139,8 @@ export async function encryptCanvasImages(
} }
} }
return obj; return obj;
}), });
}; }
return { encryptedImageFiles, encryptedCanvasData: newCanvasData }; return encryptedFiles;
} }
-2
View File
@@ -9,8 +9,6 @@ export default defineConfig({
env: { env: {
VITE_API_URL: "http://piku-server", VITE_API_URL: "http://piku-server",
TZ: "Asia/Kolkata", TZ: "Asia/Kolkata",
// using the actual 600_000 iterations causes timeout in tests
VITE_PBKDF2_ITERATIONS: "1",
}, },
include: ["**/*.test.ts", "**/*.test.tsx"], include: ["**/*.test.ts", "**/*.test.tsx"],
environment: "jsdom", environment: "jsdom",