Skip to content

Commit

Permalink
feat: allow to set password-protected notes
Browse files Browse the repository at this point in the history
  • Loading branch information
dynamotn committed Oct 10, 2024
1 parent af14ca7 commit 440d910
Show file tree
Hide file tree
Showing 38 changed files with 583 additions and 7 deletions.
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ This part of the configuration concerns anything that can affect the whole site.
- `pageTitleSuffix`: a string added to the end of the page title. This only applies to the browser tab title, not the title shown at the top of the page.
- `enableSPA`: whether to enable [[SPA Routing]] on your site.
- `enablePopovers`: whether to enable [[popover previews]] on your site.
- `enablePassProtected`: whether to enable [[Password protected]] on your site.
- `analytics`: what to use for analytics on your site. Values can be
- `null`: don't use analytics;
- `{ provider: 'google', tagId: '<your-google-tag>' }`: use Google Analytics;
Expand Down
31 changes: 31 additions & 0 deletions docs/features/Password Protected.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
title: Password Protected
---

Some notes may be sensitive, i.e. non-public personal projects, contacts, meeting notes and such. It would be really useful to be able to protect some pages or group of pages so they don't appear to everyone, while still allowing them to be published.

By adding a password to your note's frontmatter, you can create an extra layer of security, ensuring that only authorized individuals can access your content. Whether you're safeguarding personal journals, project plans, this feature provides the peace of mind you need.

## How it works

Simply add a password field to your note's frontmatter and set your desired password. When you try to view the note, you'll be prompted to enter the password. If the password is correct, the note will be unlocked. Once unlocked, you can access the note until you clear your browser cookies.

### Security techniques

- Key Derivation: Utilizes PBKDF2 for generating secure encryption keys.
- Unique Salt for Each Encryption: A unique salt is generated every time the encrypt method is used, enhancing security.
- Encryption/Decryption: Implements AES-GCM for robust data encryption and decryption.
- Encoding/Decoding: Use base64 to convert non-textual encrypted data in HTML

### Disclaimer

- Use it at your own risk
- You need to choose a strong password and share it only to trusted users
- You need to secure your notes and Quartz repository in private mode on Github/Gitlab/Bitbucket... or use your own Git server
- You can use other WAF tools to enhance security, based on URL of notes that Quartz build for you, e.g. Cloudflare WAF, AWS WAF, Google Cloud Armor...

## Configuration

- Disable password protected notes: set the `enablePasswordProtected` field in `quartz.config.ts` to be `false`.
- Style: `quartz/components/styles/passwordProtected.scss`
- Script: `quartz/components/scripts/decrypt.inline.ts`
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.1",
"remark-smartypants": "^3.0.2",
"rfc4648": "^1.5.3",
"rfdc": "^1.4.1",
"rimraf": "^6.0.1",
"serve-handler": "^6.1.5",
Expand Down
1 change: 1 addition & 0 deletions quartz.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const config: QuartzConfig = {
pageTitleSuffix: "",
enableSPA: true,
enablePopovers: true,
enablePassProtected: true,
analytics: {
provider: "plausible",
},
Expand Down
2 changes: 2 additions & 0 deletions quartz/cfg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export interface GlobalConfiguration {
enableSPA: boolean
/** Whether to display Wikipedia-style popovers when hovering over links */
enablePopovers: boolean
/** Whether to enable password protected page rendering */
enablePassProtected: boolean
/** Analytics mode */
analytics: Analytics
/** Glob patterns to not search */
Expand Down
45 changes: 45 additions & 0 deletions quartz/components/pages/EncryptedContent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "../types"
import { i18n } from "../../i18n"

const EncryptedContent: QuartzComponent = ({
iteration,
encryptedContent,
cfg,
}: QuartzComponentProps) => {
return (
<>
<div id="lock">
<div
id="msg"
data-wrong={i18n(cfg.locale).pages.encryptedContent.wrongPassword}
data-modern={i18n(cfg.locale).pages.encryptedContent.modernBrowser}
data-empty={i18n(cfg.locale).pages.encryptedContent.noPayload}
>
{i18n(cfg.locale).pages.encryptedContent.enterPassword}
</div>
<div id="load">
<p class="spinner"></p>
<p id="load-text" data-decrypt={i18n(cfg.locale).pages.encryptedContent.decrypting}>
{i18n(cfg.locale).pages.encryptedContent.loading}
</p>
</div>
<form class="hidden">
<input
type="password"
class="pwd"
name="pwd"
aria-label={i18n(cfg.locale).pages.encryptedContent.password}
autofocus
/>
<input type="submit" value={i18n(cfg.locale).pages.encryptedContent.submit} />
</form>
<pre class="hidden" data-i={iteration}>
{encryptedContent}
</pre>
</div>
<article id="content"></article>
</>
)
}

export default (() => EncryptedContent) satisfies QuartzComponentConstructor
20 changes: 17 additions & 3 deletions quartz/components/renderPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { render } from "preact-render-to-string"
import { QuartzComponent, QuartzComponentProps } from "./types"
import HeaderConstructor from "./Header"
import BodyConstructor from "./Body"
import EncryptedContent from "./pages/EncryptedContent"
import { JSResourceToScriptElement, StaticResources } from "../util/resources"
import { getEncryptedPayload } from "../util/encrypt"
import { clone, FullSlug, RelativeURL, joinSegments, normalizeHastElement } from "../util/path"
import { visit } from "unist-util-visit"
import { Root, Element, ElementContent } from "hast"
Expand Down Expand Up @@ -53,13 +55,13 @@ export function pageResources(
}
}

export function renderPage(
export async function renderPage(
cfg: GlobalConfiguration,
slug: FullSlug,
componentData: QuartzComponentProps,
components: RenderComponents,
pageResources: StaticResources,
): string {
): Promise<string> {
// make a deep copy of the tree so we don't remove the transclusion references
// for the file cached in contentMap in build.ts
const root = clone(componentData.tree) as Root
Expand Down Expand Up @@ -195,6 +197,7 @@ export function renderPage(
} = components
const Header = HeaderConstructor()
const Body = BodyConstructor()
const Encrypted = EncryptedContent()

const LeftComponent = (
<div class="left sidebar">
Expand All @@ -213,6 +216,17 @@ export function renderPage(
)

const lang = componentData.fileData.frontmatter?.lang ?? cfg.locale?.split("-")[0] ?? "en"

let content = <Content {...componentData} />
if (componentData.fileData.frontmatter?.password) {
componentData.iteration = 2e6
componentData.encryptedContent = await getEncryptedPayload(
render(content),
JSON.stringify(componentData.fileData.frontmatter.password),
componentData.iteration,
)
content = <Encrypted {...componentData} />
}
const doc = (
<html lang={lang}>
<Head {...componentData} />
Expand All @@ -233,7 +247,7 @@ export function renderPage(
))}
</div>
</div>
<Content {...componentData} />
{content}
<hr />
<div class="page-footer">
{afterBody.map((BodyComponent) => (
Expand Down
168 changes: 168 additions & 0 deletions quartz/components/scripts/decrypt.inline.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { base64 } from "rfc4648"

// @ts-ignore:next-line
function find<T>(selector: string): T {
const element = document.querySelector(selector) as T
if (element) return element
}

let salt: Uint8Array, iv: Uint8Array, ciphertext: Uint8Array, iterations: number

async function decryptHTML() {
const pl = find<HTMLPreElement>("pre[data-i]")
if (!pl) {
return
}

const form = find<HTMLFormElement>("form")
if (!form) {
return
}

const pwd = find<HTMLInputElement>(".pwd")
if (!pwd) {
return
}

form.addEventListener("submit", async (event) => {
event.preventDefault()
await decrypt()
})
if (!subtle) {
error("modern")
pwd.disabled = true
}

show(find<HTMLDivElement>("#lock"))
if (!pl.innerHTML) {
pwd.disabled = true
error("empty")
return
}
iterations = Number(pl.dataset.i)
const bytes = base64.parse(pl.innerHTML)
salt = bytes.slice(0, 32)
iv = bytes.slice(32, 32 + 16)
ciphertext = bytes.slice(32 + 16)

if (location.hash) {
const parts = location.href.split("#")
pwd.value = parts[1]
history.replaceState(null, "", parts[0])
}

if (sessionStorage[document.body.dataset.slug!] || pwd.value) {
await decrypt()
} else {
hide(find<HTMLDivElement>("#load"))
show(form)
pwd.focus()
}
}

document.addEventListener("DOMContentLoaded", decryptHTML)
document.addEventListener("nav", decryptHTML)

const subtle =
window.crypto?.subtle ||
(window.crypto as unknown as { webkitSubtle: Crypto["subtle"] })?.webkitSubtle

function show(element: Element) {
element.classList.remove("hidden")
}

function hide(element: Element) {
element.classList.add("hidden")
}

function error(code: string) {
const msg = find<HTMLParagraphElement>("#msg")
msg.innerText = msg.getAttribute("data-" + code) || ""
}

async function sleep(milliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}

async function decrypt() {
const loadText = find<HTMLElement>("#load-text")
loadText.innerText = loadText.getAttribute("data-decrypt") || ""
show(find<HTMLDivElement>("#load"))
hide(find<HTMLFormElement>("form"))
const pwd = find<HTMLInputElement>(".pwd")
await sleep(60)

try {
const decrypted = await decryptFile({ salt, iv, ciphertext, iterations }, pwd.value)

const article = find<HTMLElement>("#content")
article.innerHTML = decrypted
hide(find<HTMLDivElement>("#lock"))
} catch (e) {
hide(find<HTMLDivElement>("#load"))
show(find<HTMLFormElement>("form"))

if (sessionStorage[document.body.dataset.slug!]) {
sessionStorage.removeItem(document.body.dataset.slug!)
} else {
error("wrong")
}

pwd.value = ""
pwd.focus()
}
}

async function deriveKey(
salt: Uint8Array,
password: string,
iterations: number,
): Promise<CryptoKey> {
const encoder = new TextEncoder()
const baseKey = await subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, [
"deriveKey",
])
return await subtle.deriveKey(
{ name: "PBKDF2", salt, iterations, hash: "SHA-256" },
baseKey,
{ name: "AES-GCM", length: 256 },
true,
["decrypt"],
)
}

async function importKey(key: JsonWebKey) {
return subtle.importKey("jwk", key, "AES-GCM", true, ["decrypt"])
}

async function decryptFile(
{
salt,
iv,
ciphertext,
iterations,
}: {
salt: Uint8Array
iv: Uint8Array
ciphertext: Uint8Array
iterations: number
},
password: string,
) {
const decoder = new TextDecoder()

const key = sessionStorage[document.body.dataset.slug!]
? await importKey(JSON.parse(sessionStorage[document.body.dataset.slug!]))
: await deriveKey(salt, password, iterations)

const data = new Uint8Array(await subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext))
if (!data) throw "Malformed data"

try {
sessionStorage[document.body.dataset.slug!] = JSON.stringify(await subtle.exportKey("jwk", key))
} catch (e) {
console.error(e)
}

return decoder.decode(data)
}
30 changes: 30 additions & 0 deletions quartz/components/styles/passProtected.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
.hidden {
display: none;
}

.pwd {
box-sizing: border-box;
font-family: var(--bodyFont);
color: var(--dark);
border: 1px solid var(--lightgray);
padding: 0.5em 1em;
background: var(--light);
border-radius: 7px;
width: 70%;
margin-bottom: 2em;
margin-right: 2em;
}

.pwd + input {
font-style: normal;
font-weight: 700;
font-size: 15px;
line-height: 1;
color: var(--light);
padding: 7px 15px;
background-color: var(--dark);
margin-top: 1px;
border-radius: 7px;
position: relative;
padding: 0.6em 1em;
}
Loading

0 comments on commit 440d910

Please sign in to comment.