Skip to content

Page Encryption Module

Cryptographic primitives, the at-rest envelope format, build-time page helpers, the git filter protocol, and git repository operations behind page encryption and the mkdocs-note crypt commands.

Called from plugin core during the build and from the CLI for crypt init / status / check / uninstall and the hidden filter commands.

Cryptographic primitives for mkdocs-note page encryption.

Two independent layers are used:

at rest Encrypts the body of a note before it enters git. The password is stored in the same file's clear frontmatter, so a fast HKDF is deliberate: a slow KDF would add build cost without protecting anything the reader cannot already see.

site Encrypts the rendered page for the browser. When a private repository publishes a public site the frontmatter is not public, so the slow PBKDF2-HMAC-SHA256 stretch is what protects the password.

Both layers use AES-256-GCM with a synthetic nonce derived through HMAC. A synthetic nonce keeps encryption deterministic, which gives stable git status output and reproducible builds; the AAD binds a payload to its page or key field.

CryptoError

Bases: Exception

Base class for encryption/decryption failures.

Source code in src/mkdocs_note/utils/crypt/keys.py
52
53
class CryptoError(Exception):
	"""Base class for encryption/decryption failures."""

DecryptError

Bases: CryptoError

The password is wrong or the ciphertext was tampered with.

Source code in src/mkdocs_note/utils/crypt/keys.py
60
61
class DecryptError(CryptoError):
	"""The password is wrong or the ciphertext was tampered with."""

PasswordError

Bases: CryptoError

The frontmatter does not define a usable password.

Source code in src/mkdocs_note/utils/crypt/keys.py
56
57
class PasswordError(CryptoError):
	"""The frontmatter does not define a usable password."""

PasswordSource dataclass

The frontmatter field a password was taken from.

Source code in src/mkdocs_note/utils/crypt/keys.py
64
65
66
67
68
69
@dataclass(frozen=True)
class PasswordSource:
	"""The frontmatter field a password was taken from."""

	field: str
	password: str

at_rest_aad(key_field)

Additional authenticated data for an at-rest envelope.

Source code in src/mkdocs_note/utils/crypt/keys.py
159
160
161
def at_rest_aad(key_field: str) -> bytes:
	"""Additional authenticated data for an at-rest envelope."""
	return f"mkdocs-note:v1:{key_field}".encode("utf-8")

is_encrypted(meta)

Return whether a page's frontmatter opts into encryption.

Source code in src/mkdocs_note/utils/crypt/keys.py
96
97
98
def is_encrypted(meta: Mapping[str, Any]) -> bool:
	"""Return whether a page's frontmatter opts into encryption."""
	return bool(meta.get("encrypt", False))

normalize_password(value)

Normalize a password the same way Python and JavaScript do.

A Unicode NFC form plus surrounding-whitespace stripping keeps a password typed in a browser equal to the YAML value even when the source contains combining characters or accidental spacing.

Source code in src/mkdocs_note/utils/crypt/keys.py
72
73
74
75
76
77
78
79
80
def normalize_password(value: Any) -> str:
	"""Normalize a password the same way Python and JavaScript do.

	A Unicode NFC form plus surrounding-whitespace stripping keeps a password
	typed in a browser equal to the YAML value even when the source contains
	combining characters or accidental spacing.
	"""
	text = value if isinstance(value, str) else str(value)
	return unicodedata.normalize("NFC", text).strip()

open_at_rest(password, key_field, payload)

Decrypt an at-rest payload produced by :func:seal_at_rest.

Source code in src/mkdocs_note/utils/crypt/keys.py
200
201
202
203
204
def open_at_rest(password: str, key_field: str, payload: bytes) -> bytes:
	"""Decrypt an at-rest payload produced by :func:`seal_at_rest`."""
	ikm = password.encode("utf-8")
	enc_key = _hkdf(ikm, salt=AT_REST_SALT, info=AT_REST_INFO_ENC)
	return _open(enc_key, payload, at_rest_aad(key_field))

open_site(password, src_uri, payload, iterations=DEFAULT_ITERATIONS)

Decrypt a browser payload (used by tests and tooling).

Source code in src/mkdocs_note/utils/crypt/keys.py
260
261
262
263
264
265
266
267
268
269
def open_site(
	password: str,
	src_uri: str,
	payload: bytes,
	iterations: int = DEFAULT_ITERATIONS,
) -> bytes:
	"""Decrypt a browser payload (used by tests and tooling)."""
	salt = site_salt(src_uri)
	key = site_key(password, salt, iterations)
	return _open(key, payload, site_aad(src_uri))

password_for_field(meta, field)

Read the password stored in an explicit frontmatter field.

Used for envelopes, whose header records which field was used when the ciphertext was created. Raises :class:PasswordError when the field is missing or empty.

Source code in src/mkdocs_note/utils/crypt/keys.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def password_for_field(meta: Mapping[str, Any], field: str) -> str:
	"""Read the password stored in an explicit frontmatter *field*.

	Used for envelopes, whose header records which field was used when the
	ciphertext was created. Raises :class:`PasswordError` when the field is
	missing or empty.
	"""
	if field not in PASSWORD_FIELDS:
		raise PasswordError(
			f"Unsupported encryption key field {field!r}; expected one of "
			f"{', '.join(PASSWORD_FIELDS)}."
		)
	value = meta.get(field)
	if value is None:
		raise PasswordError(
			f"Frontmatter field {field!r} is missing; it is the password for "
			"this encrypted note."
		)
	password = normalize_password(value)
	if not password:
		raise PasswordError(
			f"Frontmatter field {field!r} is empty; it is the password for this "
			"encrypted note."
		)
	_warn_non_string(field, value)
	return password

resolve_password(meta)

Resolve a page's password: password first, then permalink.

Raises:

Type Description
PasswordError

when neither field is present and non-empty.

Source code in src/mkdocs_note/utils/crypt/keys.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def resolve_password(meta: Mapping[str, Any]) -> PasswordSource:
	"""Resolve a page's password: ``password`` first, then ``permalink``.

	Raises:
		PasswordError: when neither field is present and non-empty.
	"""
	for field in PASSWORD_FIELDS:
		value = meta.get(field)
		if value is None:
			continue
		password = normalize_password(value)
		if not password:
			continue
		_warn_non_string(field, value)
		return PasswordSource(field=field, password=password)
	raise PasswordError(
		"encrypt: true requires a non-empty 'password' or 'permalink' in the "
		"frontmatter."
	)

seal_at_rest(password, key_field, plaintext)

Encrypt a note body for storage in git.

Returns nonce || ciphertext || tag. The encryption is deterministic for the same (password, key_field, plaintext) triple.

Source code in src/mkdocs_note/utils/crypt/keys.py
188
189
190
191
192
193
194
195
196
197
def seal_at_rest(password: str, key_field: str, plaintext: bytes) -> bytes:
	"""Encrypt a note body for storage in git.

	Returns ``nonce || ciphertext || tag``. The encryption is deterministic for
	the same ``(password, key_field, plaintext)`` triple.
	"""
	ikm = password.encode("utf-8")
	enc_key = _hkdf(ikm, salt=AT_REST_SALT, info=AT_REST_INFO_ENC)
	nonce_key = _hkdf(ikm, salt=AT_REST_SALT, info=AT_REST_INFO_NONCE)
	return _seal(enc_key, nonce_key, plaintext, at_rest_aad(key_field))

seal_site(password, src_uri, plaintext, iterations=DEFAULT_ITERATIONS)

Encrypt a rendered page for the browser.

Returns (salt, aad, nonce || ciphertext || tag).

Source code in src/mkdocs_note/utils/crypt/keys.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def seal_site(
	password: str,
	src_uri: str,
	plaintext: bytes,
	iterations: int = DEFAULT_ITERATIONS,
) -> tuple[bytes, bytes, bytes]:
	"""Encrypt a rendered page for the browser.

	Returns ``(salt, aad, nonce || ciphertext || tag)``.
	"""
	salt = site_salt(src_uri)
	aad = site_aad(src_uri)
	key = site_key(password, salt, iterations)
	return salt, aad, _seal(key, site_nonce_key(key), plaintext, aad)

site_aad(src_uri)

Additional authenticated data for a browser payload.

Source code in src/mkdocs_note/utils/crypt/keys.py
207
208
209
def site_aad(src_uri: str) -> bytes:
	"""Additional authenticated data for a browser payload."""
	return (SITE_AAD_PREFIX + src_uri).encode("utf-8")

site_key(password, salt, iterations)

Derive the browser AES key with PBKDF2-HMAC-SHA256.

Results are cached per process so mkdocs serve rebuilds do not pay the 600k-iteration cost again for an unchanged page.

Source code in src/mkdocs_note/utils/crypt/keys.py
228
229
230
231
232
233
234
235
236
def site_key(password: str, salt: bytes, iterations: int) -> bytes:
	"""Derive the browser AES key with PBKDF2-HMAC-SHA256.

	Results are cached per process so ``mkdocs serve`` rebuilds do not pay the
	600k-iteration cost again for an unchanged page.
	"""
	if iterations < 1:
		raise CryptoError("kdf_iterations must be a positive integer.")
	return _pbkdf2(password, salt, iterations)

site_nonce_key(key)

Derive the HMAC key used for deterministic site-payload nonces.

Source code in src/mkdocs_note/utils/crypt/keys.py
239
240
241
def site_nonce_key(key: bytes) -> bytes:
	"""Derive the HMAC key used for deterministic site-payload nonces."""
	return _hkdf(key, salt=b"mkdocs-note/v1/site", info=SITE_INFO_NONCE)

site_salt(src_uri)

Stable per-page PBKDF2 salt.

The salt only has to separate pages, not to be secret; deriving it from the stable src_uri keeps a remembered browser key valid across deploys.

Source code in src/mkdocs_note/utils/crypt/keys.py
212
213
214
215
216
217
218
def site_salt(src_uri: str) -> bytes:
	"""Stable per-page PBKDF2 salt.

	The salt only has to separate pages, not to be secret; deriving it from the
	stable ``src_uri`` keeps a remembered browser key valid across deploys.
	"""
	return hashlib.sha256(site_aad(src_uri)).digest()[:16]

At-rest envelope format: clear frontmatter plus an encrypted body.

An envelope keeps the note's YAML frontmatter readable so MkDocs, the plugin scanner, GitHub and git diff can work without a key, and encrypts only the body::

    ---
    title: Example
    permalink: example
    encrypt: true
    ---

    > 🔒 This note is encrypted by mkdocs-note. Read it on the published site.

    <!-- mkdocs-note:encrypted v1 key=permalink
    <base64 of nonce | ciphertext | tag, wrapped at 76 columns>
    -->

The format is deterministic and fixed per version, which keeps git status stable and makes a byte-exact smudge possible.

Envelope dataclass

A parsed at-rest envelope.

Source code in src/mkdocs_note/utils/crypt/envelope.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@dataclass(frozen=True)
class Envelope:
	"""A parsed at-rest envelope."""

	frontmatter: str
	"""The original frontmatter block, including the ``---`` delimiters."""

	meta: dict[str, Any]
	"""Frontmatter parsed from :attr:`frontmatter`."""

	key_field: str
	"""Frontmatter field that holds the password (``password``/``permalink``)."""

	payload: bytes
	"""``nonce || ciphertext || tag``."""

	body: str
	"""Everything after the frontmatter, including the notice and comment."""

body instance-attribute

Everything after the frontmatter, including the notice and comment.

frontmatter instance-attribute

The original frontmatter block, including the --- delimiters.

key_field instance-attribute

Frontmatter field that holds the password (password/permalink).

meta instance-attribute

Frontmatter parsed from :attr:frontmatter.

payload instance-attribute

nonce || ciphertext || tag.

EnvelopeError

Bases: CryptoError

The note looks like an envelope but cannot be parsed.

Source code in src/mkdocs_note/utils/crypt/envelope.py
50
51
class EnvelopeError(keys.CryptoError):
	"""The note looks like an envelope but cannot be parsed."""

build_envelope(text, key_field, password)

Encrypt the body of text and return the envelope representation.

Source code in src/mkdocs_note/utils/crypt/envelope.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def build_envelope(text: str, key_field: str, password: str) -> str:
	"""Encrypt the body of *text* and return the envelope representation."""
	split = split_frontmatter(text)
	if split is None:
		raise EnvelopeError(
			"Cannot encrypt a note without YAML frontmatter delimited by '---'."
		)
	frontmatter, body, _meta = split
	payload = keys.seal_at_rest(password, key_field, body.encode("utf-8"))
	encoded = base64.b64encode(payload).decode("ascii")
	wrapped = "\n".join(textwrap.wrap(encoded, WRAP_COLUMNS))
	return (
		f"{frontmatter}\n{NOTICE}\n\n"
		f"<!-- {MARKER} v{FORMAT_VERSION} key={key_field}\n{wrapped}\n-->\n"
	)

clean_bytes(data)

Git clean filter: plaintext note bytes -> envelope bytes.

Files that are not flagged (or are not valid UTF-8) pass through byte-for-byte. Flagged files are normalized to UTF-8 without BOM and with LF line endings so the envelope is stable across platforms.

Source code in src/mkdocs_note/utils/crypt/envelope.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def clean_bytes(data: bytes) -> bytes:
	"""Git clean filter: plaintext note bytes -> envelope bytes.

	Files that are not flagged (or are not valid UTF-8) pass through
	byte-for-byte. Flagged files are normalized to UTF-8 without BOM and with LF
	line endings so the envelope is stable across platforms.
	"""
	try:
		text = data.decode("utf-8")
	except UnicodeDecodeError:
		return data
	normalized = normalize_text(text)
	split = split_frontmatter(normalized)
	if split is None:
		return data
	_frontmatter, body, meta = split
	if not keys.is_encrypted(meta):
		return data
	if _marker_in_body(body) is not None:
		# Already an envelope; clean is idempotent.
		return normalized.encode("utf-8")
	source = keys.resolve_password(meta)
	envelope = build_envelope(normalized, source.field, source.password)
	return envelope.encode("utf-8")

decrypt_body(body, meta, password=None)

Decrypt the body of a page when MkDocs already removed its frontmatter.

The password is taken from meta using the key field recorded in the envelope header. A body without a marker is returned unchanged.

Source code in src/mkdocs_note/utils/crypt/envelope.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def decrypt_body(
	body: str,
	meta: dict[str, Any],
	password: str | None = None,
) -> str:
	"""Decrypt the body of a page when MkDocs already removed its frontmatter.

	The password is taken from *meta* using the key field recorded in the
	envelope header. A body without a marker is returned unchanged.
	"""
	match = _marker_in_body(body)
	if match is None:
		return body
	key_field = match.group("field")
	if password is None:
		password = keys.password_for_field(meta, key_field)
	payload = _decode_payload(match)
	plaintext = keys.open_at_rest(password, key_field, payload)
	try:
		return plaintext.decode("utf-8")
	except UnicodeDecodeError as exc:
		raise EnvelopeError("Decrypted body is not valid UTF-8.") from exc

decrypt_envelope(text, password=None)

Decrypt a whole-file envelope.

When password is omitted it is read from the frontmatter field recorded in the envelope header.

Source code in src/mkdocs_note/utils/crypt/envelope.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def decrypt_envelope(text: str, password: str | None = None) -> str:
	"""Decrypt a whole-file envelope.

	When *password* is omitted it is read from the frontmatter field recorded in
	the envelope header.
	"""
	envelope = parse_envelope(text)
	if envelope is None:
		return text
	if password is None:
		password = keys.password_for_field(envelope.meta, envelope.key_field)
	plaintext = keys.open_at_rest(password, envelope.key_field, envelope.payload)
	try:
		body = plaintext.decode("utf-8")
	except UnicodeDecodeError as exc:
		raise EnvelopeError("Decrypted body is not valid UTF-8.") from exc
	return envelope.frontmatter + body

looks_encrypted(text)

Return whether text is an at-rest envelope (notice + marker header).

Source code in src/mkdocs_note/utils/crypt/envelope.py
118
119
120
121
122
def looks_encrypted(text: str) -> bool:
	"""Return whether *text* is an at-rest envelope (notice + marker header)."""
	split = split_frontmatter(text)
	body = split[1] if split is not None else text
	return _marker_in_body(body) is not None

normalize_text(text)

Drop a UTF-8 BOM and convert CRLF/CR line endings to LF.

Source code in src/mkdocs_note/utils/crypt/envelope.py
74
75
76
77
78
def normalize_text(text: str) -> str:
	"""Drop a UTF-8 BOM and convert CRLF/CR line endings to LF."""
	if text.startswith(""):
		text = text[1:]
	return text.replace("\r\n", "\n").replace("\r", "\n")

parse_envelope(text)

Parse an envelope, or return None when text is not one.

Raises:

Type Description
EnvelopeError

when the marker exists but the payload or version is invalid.

Source code in src/mkdocs_note/utils/crypt/envelope.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def parse_envelope(text: str) -> Envelope | None:
	"""Parse an envelope, or return ``None`` when *text* is not one.

	Raises:
		EnvelopeError: when the marker exists but the payload or version is
			invalid.
	"""
	split = split_frontmatter(text)
	if split is None:
		return None
	frontmatter, body, meta = split
	match = _marker_in_body(body)
	if match is None:
		return None
	version = int(match.group("version"))
	if version != FORMAT_VERSION:
		raise EnvelopeError(
			f"Unsupported encrypted envelope version {version}; "
			f"this mkdocs-note understands v{FORMAT_VERSION}."
		)
	return Envelope(
		frontmatter=frontmatter,
		meta=meta,
		key_field=match.group("field"),
		payload=_decode_payload(match),
		body=body,
	)

smudge_bytes(data)

Git smudge filter: envelope bytes -> plaintext note bytes.

A checkout must never fail because of a password problem, so an undecryptable envelope is emitted unchanged with a single stderr warning.

Source code in src/mkdocs_note/utils/crypt/envelope.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def smudge_bytes(data: bytes) -> bytes:
	"""Git smudge filter: envelope bytes -> plaintext note bytes.

	A checkout must never fail because of a password problem, so an
	undecryptable envelope is emitted unchanged with a single stderr warning.
	"""
	try:
		text = data.decode("utf-8")
	except UnicodeDecodeError:
		return data
	normalized = normalize_text(text)
	try:
		envelope = parse_envelope(normalized)
	except EnvelopeError as exc:
		_warn_smudge(exc)
		return data
	if envelope is None:
		return data
	try:
		password = keys.password_for_field(envelope.meta, envelope.key_field)
		plaintext = keys.open_at_rest(password, envelope.key_field, envelope.payload)
		body = plaintext.decode("utf-8")
	except (keys.CryptoError, UnicodeDecodeError) as exc:
		_warn_smudge(exc)
		return data
	return (envelope.frontmatter + body).encode("utf-8")

split_frontmatter(text)

Split YAML frontmatter from a note with MkDocs' own boundary rules.

Returns:

Type Description
tuple[str, str, dict[str, Any]] | None

(frontmatter, body, meta) with the frontmatter text kept verbatim,

tuple[str, str, dict[str, Any]] | None

or None when the file has no YAML frontmatter.

Source code in src/mkdocs_note/utils/crypt/envelope.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def split_frontmatter(text: str) -> tuple[str, str, dict[str, Any]] | None:
	"""Split YAML frontmatter from a note with MkDocs' own boundary rules.

	Returns:
		``(frontmatter, body, meta)`` with the frontmatter text kept verbatim,
		or ``None`` when the file has no YAML frontmatter.
	"""
	match = mkdocs_meta.YAML_RE.match(text)
	if match is None:
		return None
	try:
		loaded = yaml.safe_load(match.group(1))
	except yaml.YAMLError:
		loaded = None
	meta = loaded if isinstance(loaded, dict) else {}
	return match.group(0), text[match.end() :], meta

Build-time helpers for encrypted pages.

The browser payload is a UTF-8 JSON document encrypted with AES-256-GCM; the page HTML only ever contains the locked stub and that ciphertext. The helpers here also render the Material-compatible table of contents that travels inside the payload and collect plaintext canaries for the post-build leak audit.

Leak dataclass

A plaintext canary found outside its own page in the built site.

Source code in src/mkdocs_note/utils/crypt/page.py
280
281
282
283
284
285
286
@dataclass(frozen=True)
class Leak:
	"""A plaintext canary found outside its own page in the built site."""

	src_uri: str
	canary: str
	files: tuple[str, ...]

audit_plaintext_leaks(site_dir, pages)

Search the built site for plaintext of encrypted pages.

Parameters:

Name Type Description Default
site_dir str | PathLike[str]

Built site directory.

required
pages Mapping[str, Sequence[Any]]

Mapping of src_uri to (dest_uri, canaries).

required

Returns:

Type Description
list[Leak]

Leaks found outside each page's own output file.

Source code in src/mkdocs_note/utils/crypt/page.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def audit_plaintext_leaks(
	site_dir: str | os.PathLike[str],
	pages: Mapping[str, Sequence[Any]],
) -> list[Leak]:
	"""Search the built site for plaintext of encrypted pages.

	Args:
		site_dir: Built site directory.
		pages: Mapping of ``src_uri`` to ``(dest_uri, canaries)``.

	Returns:
		Leaks found outside each page's own output file.
	"""
	root = Path(site_dir)
	targets = [
		path
		for path in root.rglob("*")
		if path.is_file() and path.suffix.lower() in {".html", ".json", ".xml"}
	]
	leaks: list[Leak] = []
	for src_uri, entry in pages.items():
		dest_uri, canaries = entry[0], list(entry[1])
		if not canaries:
			continue
		own_output = (root / str(dest_uri)).resolve()
		canary_variants = [(canary, _variants(canary)) for canary in canaries]
		hits: dict[str, list[str]] = {canary: [] for canary in canaries}
		for path in targets:
			try:
				if path.resolve() == own_output:
					continue
				if path.stat().st_size > MAX_AUDIT_FILE_BYTES:
					continue
				text = path.read_text(encoding="utf-8", errors="ignore")
			except OSError:
				continue
			for canary, variants in canary_variants:
				if any(variant in text for variant in variants):
					hits[canary].append(str(path.relative_to(root)))
		for canary, files in hits.items():
			if files:
				leaks.append(Leak(src_uri, canary, tuple(files)))
	return leaks

build_site_payload(src_uri, content, toc_html, password, iterations=keys.DEFAULT_ITERATIONS)

Encrypt the rendered page and return the JSON-safe browser payload.

Source code in src/mkdocs_note/utils/crypt/page.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def build_site_payload(
	src_uri: str,
	content: str,
	toc_html: str,
	password: str,
	iterations: int = keys.DEFAULT_ITERATIONS,
) -> dict[str, Any]:
	"""Encrypt the rendered page and return the JSON-safe browser payload."""
	plaintext = json.dumps(
		{"v": 1, "content": content, "toc": toc_html},
		ensure_ascii=False,
		separators=(",", ":"),
	).encode("utf-8")
	salt, aad, sealed = keys.seal_site(password, src_uri, plaintext, iterations)
	return {
		"v": 1,
		"iter": int(iterations),
		"salt": _b64(salt),
		"iv": _b64(sealed[: keys.NONCE_SIZE]),
		"aad": _b64(aad),
		"ct": _b64(sealed[keys.NONCE_SIZE :]),
	}

build_stub(title, payload, labels)

Return the locked page HTML with the encrypted payload attached.

Source code in src/mkdocs_note/utils/crypt/page.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def build_stub(
	title: str,
	payload: Mapping[str, Any],
	labels: Mapping[str, str],
) -> str:
	"""Return the locked page HTML with the encrypted payload attached."""
	escaped_title = html.escape(title)
	payload_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
	return (
		f'<div class="{STUB_CLASS}" data-mkdocs-note-encrypted>'
		f"<h1>{escaped_title}</h1>"
		f'<p class="{STUB_CLASS}__title">{label(labels, "title")}</p>'
		f'<form class="{STUB_CLASS}__form" autocomplete="off">'
		f'<p class="{STUB_CLASS}__prompt">'
		f"{label_with_breaks(labels, 'prompt')}</p>"
		f'<label class="{STUB_CLASS}__label" for="{PASSWORD_INPUT_ID}">'
		f"{label(labels, 'placeholder')}</label>"
		f'<div class="{STUB_CLASS}__row">'
		f'<input id="{PASSWORD_INPUT_ID}" class="{STUB_CLASS}__input" '
		f'type="password" name="password" '
		f'placeholder="{label(labels, "placeholder")}" '
		'autocomplete="current-password" required>'
		f'<button class="md-button md-button--primary {STUB_CLASS}__submit" '
		f'type="submit">{label(labels, "submit")}</button>'
		"</div>"
		f'<p class="{STUB_CLASS}__error" role="alert" aria-live="polite"></p>'
		"</form>"
		f'<noscript><p class="{STUB_CLASS}__noscript">'
		f"{label(labels, 'noscript')}</p></noscript>"
		f'<script type="application/json" class="{PAYLOAD_CLASS}">'
		f"{payload_json}</script>"
		"</div>"
	)

build_toc_html(toc, labels)

Render page.toc with Material's markup, ready for the sidebar.

Source code in src/mkdocs_note/utils/crypt/page.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def build_toc_html(
	toc: TableOfContents | Iterable[Any],
	labels: Mapping[str, str],
) -> str:
	"""Render ``page.toc`` with Material's markup, ready for the sidebar."""
	items = list(toc)
	if not items:
		return ""
	first = items[0]
	# Material skips a leading level-1 entry (the page title) and lists its
	# children instead, see partials/toc.html.
	if getattr(first, "level", 0) == 1:
		items = list(getattr(first, "children", ()) or ())
		if not items:
			return ""
	toc_label = html.escape(labels.get("toc", DEFAULT_LABELS["toc"]))
	return (
		'<label class="md-nav__title" for="__toc">'
		'<span class="md-nav__icon md-icon"></span>'
		f"{toc_label}</label>"
		'<ul class="md-nav__list" data-md-component="toc" data-md-scrollfix>'
		f"{_toc_items(items)}"
		"</ul>"
	)

build_unavailable_stub(title, labels)

Return a stub for a page that could not be decrypted during the build.

Source code in src/mkdocs_note/utils/crypt/page.py
236
237
238
239
240
241
242
243
244
def build_unavailable_stub(title: str, labels: Mapping[str, str]) -> str:
	"""Return a stub for a page that could not be decrypted during the build."""
	return (
		f'<div class="{STUB_CLASS} {STUB_CLASS}--unavailable" '
		"data-mkdocs-note-encrypted>"
		f"<h1>{html.escape(title)}</h1>"
		f'<p class="{STUB_CLASS}__error">{label(labels, "unavailable")}</p>'
		"</div>"
	)

collect_canaries(body, limit=MAX_CANARIES_PER_PAGE)

Pick distinctive plaintext snippets for the post-build leak audit.

Heading lines are skipped because the page title is intentionally public. Markdown inline formatting is removed so a canary also matches the rendered HTML form.

Source code in src/mkdocs_note/utils/crypt/page.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def collect_canaries(body: str, limit: int = MAX_CANARIES_PER_PAGE) -> list[str]:
	"""Pick distinctive plaintext snippets for the post-build leak audit.

	Heading lines are skipped because the page title is intentionally public.
	Markdown inline formatting is removed so a canary also matches the rendered
	HTML form.
	"""
	canaries: list[str] = []
	seen: set[str] = set()
	for raw_line in body.splitlines():
		line = raw_line.strip()
		if len(line) < 20 or line.startswith("#"):
			continue
		candidate = _strip_inline_markdown(line).strip()
		if len(candidate) < 20:
			continue
		candidate = candidate[:MAX_CANARY_LENGTH]
		if candidate in seen:
			continue
		seen.add(candidate)
		canaries.append(candidate)
		if len(canaries) >= limit:
			break
	return canaries

copy_encrypt_static_assets(static_dir, config)

Copy encrypt.js / encrypt.css into the site directory.

Source code in src/mkdocs_note/utils/crypt/page.py
269
270
271
272
273
274
275
276
277
def copy_encrypt_static_assets(static_dir: str, config: Any) -> None:
	"""Copy ``encrypt.js`` / ``encrypt.css`` into the site directory."""
	js_output_dir = os.path.join(config["site_dir"], "js")
	os.makedirs(js_output_dir, exist_ok=True)
	shutil.copy(os.path.join(static_dir, "encrypt.js"), js_output_dir)

	css_output_dir = os.path.join(config["site_dir"], "css")
	os.makedirs(css_output_dir, exist_ok=True)
	shutil.copy(os.path.join(static_dir, "encrypt.css"), css_output_dir)

ensure_heading(content, title)

Prepend the page title when Material would have added it itself.

Material's content.html adds <h1>{{ page.title }}</h1> only when the rendered content has no literal <h1. Since the real content is encrypted and replaced by a stub, that heading has to travel inside the payload.

Source code in src/mkdocs_note/utils/crypt/page.py
72
73
74
75
76
77
78
79
80
81
def ensure_heading(content: str, title: str) -> str:
	"""Prepend the page title when Material would have added it itself.

	Material's ``content.html`` adds ``<h1>{{ page.title }}</h1>`` only when the
	rendered content has no literal ``<h1``. Since the real content is encrypted
	and replaced by a stub, that heading has to travel inside the payload.
	"""
	if "<h1" in content:
		return content
	return f"<h1>{html.escape(title)}</h1>\n{content}"

inject_encrypt_assets(output, page_url, options)

Inject the encryption stylesheet, script and runtime options.

Source code in src/mkdocs_note/utils/crypt/page.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def inject_encrypt_assets(
	output: str,
	page_url: str,
	options: Mapping[str, Any],
) -> str:
	"""Inject the encryption stylesheet, script and runtime options."""
	css_url = html.escape(get_relative_url("css/encrypt.css", page_url))
	js_url = html.escape(get_relative_url("js/encrypt.js", page_url))
	payload = json.dumps(options, ensure_ascii=False).replace("</", "<\\/")
	scripts = (
		f"<script>window.mkdocs_note_encrypt_options = {payload};</script>"
		f'<script src="{js_url}" defer></script>'
	)
	if "</head>" in output:
		output = output.replace(
			"</head>", f'<link rel="stylesheet" href="{css_url}"></head>', 1
		)
	if "</body>" in output:
		output = output.replace("</body>", f"{scripts}</body>", 1)
	return output

label(labels, key)

Return an escaped UI label.

Source code in src/mkdocs_note/utils/crypt/page.py
58
59
60
def label(labels: Mapping[str, str], key: str) -> str:
	"""Return an escaped UI label."""
	return html.escape(labels.get(key, DEFAULT_LABELS.get(key, "")))

label_with_breaks(labels, key)

Return an escaped label with newlines rendered as <br>.

HTML collapses newlines in text, and mkdocs-minify removes them entirely, so a multi-line label needs explicit line breaks.

Source code in src/mkdocs_note/utils/crypt/page.py
63
64
65
66
67
68
69
def label_with_breaks(labels: Mapping[str, str], key: str) -> str:
	"""Return an escaped label with newlines rendered as ``<br>``.

	HTML collapses newlines in text, and mkdocs-minify removes them entirely,
	so a multi-line label needs explicit line breaks.
	"""
	return label(labels, key).replace("\n", "<br>")

labels_with_defaults(labels)

Merge user labels over the built-in English strings.

Source code in src/mkdocs_note/utils/crypt/page.py
49
50
51
52
53
54
55
def labels_with_defaults(labels: Mapping[str, Any] | None) -> dict[str, str]:
	"""Merge user labels over the built-in English strings."""
	merged = dict(DEFAULT_LABELS)
	for key, value in (labels or {}).items():
		if isinstance(value, str) and value:
			merged[str(key)] = value
	return merged

Git clean/smudge filter for encrypted note bodies.

Implements the long-running filter process protocol, version 2, documented in gitattributes(5) under "Long Running Filter Process", plus the single-shot clean and smudge helpers used as fallbacks. Protocol data is the only thing written to stdout; every diagnostic goes to stderr.

FilterProtocolError

Bases: RuntimeError

The peer sent data that is not valid pkt-line filter protocol.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
27
28
class FilterProtocolError(RuntimeError):
	"""The peer sent data that is not valid pkt-line filter protocol."""

FilterRequest dataclass

One clean or smudge request from git.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
90
91
92
93
94
95
96
@dataclass(frozen=True)
class FilterRequest:
	"""One ``clean`` or ``smudge`` request from git."""

	command: str
	pathname: str
	data: bytes

PacketReader

Read pkt-line packets from a binary stream.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class PacketReader:
	"""Read pkt-line packets from a binary stream."""

	def __init__(self, stream: BinaryIO) -> None:
		self._stream = stream

	def read_packet(self) -> bytes | None:
		"""Read one packet; ``None`` means a flush/delimiter packet.

		Raises:
			EOFError: at end of stream.
			FilterProtocolError: on a malformed length header.
		"""
		header = self._stream.read(4)
		if not header:
			raise EOFError
		if len(header) != 4:
			raise FilterProtocolError("truncated pkt-line header")
		if header in (FLUSH_PACKET, DELIM_PACKET, RESPONSE_END_PACKET):
			return None
		try:
			size = int(header, 16)
		except ValueError as exc:
			raise FilterProtocolError(f"invalid pkt-line length {header!r}") from exc
		if size < 4:
			raise FilterProtocolError(f"invalid pkt-line length {size}")
		data = self._stream.read(size - 4)
		if len(data) != size - 4:
			raise FilterProtocolError("truncated pkt-line payload")
		return data

read_packet()

Read one packet; None means a flush/delimiter packet.

Raises:

Type Description
EOFError

at end of stream.

FilterProtocolError

on a malformed length header.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def read_packet(self) -> bytes | None:
	"""Read one packet; ``None`` means a flush/delimiter packet.

	Raises:
		EOFError: at end of stream.
		FilterProtocolError: on a malformed length header.
	"""
	header = self._stream.read(4)
	if not header:
		raise EOFError
	if len(header) != 4:
		raise FilterProtocolError("truncated pkt-line header")
	if header in (FLUSH_PACKET, DELIM_PACKET, RESPONSE_END_PACKET):
		return None
	try:
		size = int(header, 16)
	except ValueError as exc:
		raise FilterProtocolError(f"invalid pkt-line length {header!r}") from exc
	if size < 4:
		raise FilterProtocolError(f"invalid pkt-line length {size}")
	data = self._stream.read(size - 4)
	if len(data) != size - 4:
		raise FilterProtocolError("truncated pkt-line payload")
	return data

PacketWriter

Write pkt-line packets to a binary stream.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class PacketWriter:
	"""Write pkt-line packets to a binary stream."""

	def __init__(self, stream: BinaryIO) -> None:
		self._stream = stream

	def write_packet(self, data: bytes) -> None:
		"""Write one packet, splitting payloads larger than the pkt-line limit."""
		for start in range(0, len(data), MAX_PACKET_DATA):
			chunk = data[start : start + MAX_PACKET_DATA]
			self._stream.write(f"{len(chunk) + 4:04x}".encode("ascii"))
			self._stream.write(chunk)

	def write_content(self, data: bytes) -> None:
		"""Write file content; empty content is represented by the flush alone."""
		if data:
			self.write_packet(data)

	def write_flush(self) -> None:
		"""Write a flush packet."""
		self._stream.write(FLUSH_PACKET)

	def flush(self) -> None:
		"""Flush the underlying stream."""
		self._stream.flush()

flush()

Flush the underlying stream.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
85
86
87
def flush(self) -> None:
	"""Flush the underlying stream."""
	self._stream.flush()

write_content(data)

Write file content; empty content is represented by the flush alone.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
76
77
78
79
def write_content(self, data: bytes) -> None:
	"""Write file content; empty content is represented by the flush alone."""
	if data:
		self.write_packet(data)

write_flush()

Write a flush packet.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
81
82
83
def write_flush(self) -> None:
	"""Write a flush packet."""
	self._stream.write(FLUSH_PACKET)

write_packet(data)

Write one packet, splitting payloads larger than the pkt-line limit.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
69
70
71
72
73
74
def write_packet(self, data: bytes) -> None:
	"""Write one packet, splitting payloads larger than the pkt-line limit."""
	for start in range(0, len(data), MAX_PACKET_DATA):
		chunk = data[start : start + MAX_PACKET_DATA]
		self._stream.write(f"{len(chunk) + 4:04x}".encode("ascii"))
		self._stream.write(chunk)

run_filter_process()

Run the long-running filter process on stdin/stdout.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
259
260
261
262
263
264
def run_filter_process() -> int:
	"""Run the long-running filter process on stdin/stdout."""
	return serve(
		PacketReader(sys.stdin.buffer),
		PacketWriter(sys.stdout.buffer),
	)

run_single(kind, *, stdin=None, stdout=None, stderr=None)

Run a single-shot clean or smudge transform.

Returns:

Type Description
int

Process exit status.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def run_single(
	kind: str,
	*,
	stdin: BinaryIO | None = None,
	stdout: BinaryIO | None = None,
	stderr: object | None = None,
) -> int:
	"""Run a single-shot ``clean`` or ``smudge`` transform.

	Returns:
		Process exit status.
	"""
	source = stdin if stdin is not None else sys.stdin.buffer
	sink = stdout if stdout is not None else sys.stdout.buffer
	err = stderr if stderr is not None else sys.stderr
	data = source.read()
	try:
		output = (
			envelope.clean_bytes(data)
			if kind == "clean"
			else envelope.smudge_bytes(data)
		)
	except Exception as exc:  # noqa: BLE001 - the CLI turns this into stderr + exit 1
		print(f"mkdocs-note {kind}: {exc}", file=err)
		return 1
	sink.write(output)
	sink.flush()
	return 0

serve(reader, writer, *, stderr=None, clean=envelope.clean_bytes, smudge=envelope.smudge_bytes)

Serve filter requests until git closes the stream.

Parameters:

Name Type Description Default
reader PacketReader

Packet source (git's stdout end).

required
writer PacketWriter

Packet sink (git's stdin end).

required
stderr object | None

Diagnostic stream (defaults to sys.stderr).

None
clean Callable[[bytes], bytes]

Plaintext -> envelope transform.

clean_bytes
smudge Callable[[bytes], bytes]

Envelope -> plaintext transform.

smudge_bytes

Returns:

Type Description
int

Process exit status.

Source code in src/mkdocs_note/utils/crypt/gitfilter.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def serve(
	reader: PacketReader,
	writer: PacketWriter,
	*,
	stderr: object | None = None,
	clean: Callable[[bytes], bytes] = envelope.clean_bytes,
	smudge: Callable[[bytes], bytes] = envelope.smudge_bytes,
) -> int:
	"""Serve filter requests until git closes the stream.

	Args:
		reader: Packet source (git's stdout end).
		writer: Packet sink (git's stdin end).
		stderr: Diagnostic stream (defaults to ``sys.stderr``).
		clean: Plaintext -> envelope transform.
		smudge: Envelope -> plaintext transform.

	Returns:
		Process exit status.
	"""
	err = stderr if stderr is not None else sys.stderr
	handlers = {"clean": clean, "smudge": smudge}
	try:
		_handshake(reader, writer, frozenset(handlers))
	except EOFError:
		return 0
	except FilterProtocolError as exc:
		print(f"mkdocs-note: filter handshake failed: {exc}", file=err)
		return 1

	while True:
		try:
			request = _read_request(reader)
		except EOFError:
			return 0
		except FilterProtocolError as exc:
			print(f"mkdocs-note: filter protocol error: {exc}", file=err)
			return 1
		if request is None:
			continue

		handler = handlers.get(request.command)
		if handler is None:
			message = f"unsupported filter command {request.command!r}"
			print(f"mkdocs-note: {message}", file=err)
			_write_error(writer, message)
			continue
		try:
			output = handler(request.data)
		except Exception as exc:  # noqa: BLE001 - report every failure to git
			prefix = f"{request.pathname}: " if request.pathname else ""
			message = f"{prefix}{exc}"
			print(f"mkdocs-note: {message}", file=err)
			_write_error(writer, message)
			continue

		writer.write_packet(b"status=success")
		writer.write_flush()
		writer.write_content(output)
		writer.write_flush()
		# An empty second status list keeps "status=success" unchanged.
		writer.write_flush()
		writer.flush()

Minimal git plumbing for the encryption filter and CLI.

Every helper runs git with core.quotepath=false so non-ASCII note paths come back as raw UTF-8 instead of quoted octal escapes (the same reason the 3.4.2 link-preview fix sets it). None of the helpers assume that the calling process' working directory is the repository root.

GitError

Bases: RuntimeError

A git command failed.

Source code in src/mkdocs_note/utils/crypt/gitops.py
25
26
class GitError(RuntimeError):
	"""A git command failed."""

blob_bytes(cwd, path, rev=':')

Read a blob from the index (:) or a ref (HEAD), or None.

path must be relative to the repository root, with forward slashes.

Source code in src/mkdocs_note/utils/crypt/gitops.py
142
143
144
145
146
147
148
149
150
151
def blob_bytes(cwd: Path | str, path: str, rev: str = ":") -> bytes | None:
	"""Read a blob from the index (``:``) or a ref (``HEAD``), or ``None``.

	``path`` must be relative to the repository root, with forward slashes.
	"""
	spec = f":{path}" if rev in ("", ":") else f"{rev}:{path}"
	result = run_git_bytes(cwd, "show", spec, check=False)
	if result.returncode != 0:
		return None
	return result.stdout

check_attr(cwd, path, attr='filter')

Return the git attribute value for path, or None when unset.

path must be relative to the repository root.

Source code in src/mkdocs_note/utils/crypt/gitops.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def check_attr(cwd: Path | str, path: str, attr: str = "filter") -> str | None:
	"""Return the git attribute value for *path*, or ``None`` when unset.

	``path`` must be relative to the repository root.
	"""
	result = run_git(cwd, "check-attr", "-z", attr, "--", path, check=False)
	if result.returncode != 0:
		return None
	parts = result.stdout.split("\0")
	if len(parts) < 3:
		return None
	value = parts[2]
	if value in ("unspecified", "unset", ""):
		return None
	return value

config_get(cwd, key)

Return a git config value, or None when it is not set.

Source code in src/mkdocs_note/utils/crypt/gitops.py
105
106
107
108
109
110
111
def config_get(cwd: Path | str, key: str) -> str | None:
	"""Return a git config value, or ``None`` when it is not set."""
	result = run_git(cwd, "config", "--get", key, check=False)
	if result.returncode != 0:
		return None
	value = result.stdout.strip()
	return value or None

config_set(cwd, key, value)

Set a local git config value.

Source code in src/mkdocs_note/utils/crypt/gitops.py
114
115
116
def config_set(cwd: Path | str, key: str, value: str) -> None:
	"""Set a local git config value."""
	run_git(cwd, "config", key, value)

config_unset(cwd, key)

Unset every value of a git config key; return whether one was set.

Source code in src/mkdocs_note/utils/crypt/gitops.py
119
120
121
122
def config_unset(cwd: Path | str, key: str) -> bool:
	"""Unset every value of a git config key; return whether one was set."""
	result = run_git(cwd, "config", "--unset-all", key, check=False)
	return result.returncode == 0

git_available()

Return whether a git executable is on PATH.

Source code in src/mkdocs_note/utils/crypt/gitops.py
29
30
31
def git_available() -> bool:
	"""Return whether a ``git`` executable is on PATH."""
	return shutil.which("git") is not None

git_path(cwd, name)

Resolve a path inside the git directory (hooks, info, ...).

Used instead of hardcoding .git so the helper also works in submodules and linked worktrees.

Source code in src/mkdocs_note/utils/crypt/gitops.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def git_path(cwd: Path | str, name: str) -> Path:
	"""Resolve a path inside the git directory (``hooks``, ``info``, ...).

	Used instead of hardcoding ``.git`` so the helper also works in submodules
	and linked worktrees.
	"""
	result = run_git(cwd, "rev-parse", "--git-path", name)
	path = Path(result.stdout.strip())
	if not path.is_absolute():
		path = Path(cwd) / path
	return path

inside_work_tree(cwd)

Return whether cwd is inside a git work tree.

Source code in src/mkdocs_note/utils/crypt/gitops.py
76
77
78
79
80
81
def inside_work_tree(cwd: Path | str) -> bool:
	"""Return whether *cwd* is inside a git work tree."""
	if not git_available():
		return False
	result = run_git(cwd, "rev-parse", "--is-inside-work-tree", check=False)
	return result.returncode == 0 and result.stdout.strip() == "true"

repo_relative(repo_root_path, path)

Return path as a POSIX path relative to repo_root_path.

Source code in src/mkdocs_note/utils/crypt/gitops.py
160
161
162
def repo_relative(repo_root_path: Path, path: Path) -> str:
	"""Return *path* as a POSIX path relative to *repo_root_path*."""
	return path.resolve().relative_to(repo_root_path.resolve()).as_posix()

repo_root(cwd)

Return the root of the work tree that contains cwd.

Source code in src/mkdocs_note/utils/crypt/gitops.py
84
85
86
87
88
89
def repo_root(cwd: Path | str) -> Path:
	"""Return the root of the work tree that contains *cwd*."""
	result = run_git(cwd, "rev-parse", "--show-toplevel", check=False)
	if result.returncode != 0 or not result.stdout.strip():
		raise GitError(f"not inside a git work tree: {cwd}")
	return Path(result.stdout.strip()).resolve()

run_git(cwd, *args, check=True)

Run git with text output.

Source code in src/mkdocs_note/utils/crypt/gitops.py
62
63
64
65
66
def run_git(
	cwd: Path | str, *args: str, check: bool = True
) -> subprocess.CompletedProcess[str]:
	"""Run git with text output."""
	return _run(cwd, args, text=True, check=check)

run_git_bytes(cwd, *args, check=True)

Run git with binary output (blobs must not be decoded).

Source code in src/mkdocs_note/utils/crypt/gitops.py
69
70
71
72
73
def run_git_bytes(
	cwd: Path | str, *args: str, check: bool = True
) -> subprocess.CompletedProcess[bytes]:
	"""Run git with binary output (blobs must not be decoded)."""
	return _run(cwd, args, text=False, check=check)

staged_paths(cwd)

Return repo-relative paths staged for the next commit.

Source code in src/mkdocs_note/utils/crypt/gitops.py
154
155
156
157
def staged_paths(cwd: Path | str) -> list[str]:
	"""Return repo-relative paths staged for the next commit."""
	result = run_git(cwd, "diff", "--cached", "--name-only", "--diff-filter=ACMR", "-z")
	return [path for path in result.stdout.split("\0") if path]

Repository operations behind mkdocs-note crypt.

The click commands live in :mod:mkdocs_note.cli; this module contains the testable behavior: discovering the repository and docs directory, installing the git filter and hook, and reporting the state of encrypted notes in the worktree, the index and HEAD.

CheckReport dataclass

Result of mkdocs-note crypt check --staged.

Source code in src/mkdocs_note/utils/crypt/cli.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@dataclass(frozen=True)
class CheckReport:
	"""Result of ``mkdocs-note crypt check --staged``."""

	checked: tuple[str, ...]
	errors: tuple[str, ...]

	@property
	def ok(self) -> bool:
		"""Return whether every staged encrypted note is valid."""
		return not self.errors

ok property

Return whether every staged encrypted note is valid.

CryptCliError

Bases: RuntimeError

A crypt command cannot proceed (not a git repo, ephemeral Python, ...).

Source code in src/mkdocs_note/utils/crypt/cli.py
27
28
class CryptCliError(RuntimeError):
	"""A crypt command cannot proceed (not a git repo, ephemeral Python, ...)."""

InstallReport dataclass

Result of mkdocs-note crypt init.

Source code in src/mkdocs_note/utils/crypt/cli.py
78
79
80
81
82
83
84
85
86
87
@dataclass(frozen=True)
class InstallReport:
	"""Result of ``mkdocs-note crypt init``."""

	commands: Mapping[str, str]
	attributes_changed: bool
	hook_status: str
	hook_path: Path
	hook_line: str
	plaintext_index: tuple[str, ...]

NoteStatus dataclass

State of one flagged note in the worktree, index and HEAD.

Source code in src/mkdocs_note/utils/crypt/cli.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@dataclass(frozen=True)
class NoteStatus:
	"""State of one flagged note in the worktree, index and HEAD."""

	rel: str
	key_field: str | None
	worktree: str
	index: str
	head: str
	errors: tuple[str, ...]

	@property
	def ok(self) -> bool:
		"""Return whether this note has no blocking problem."""
		return not self.errors

ok property

Return whether this note has no blocking problem.

Repository dataclass

Resolved locations for one docs tree inside a git work tree.

Source code in src/mkdocs_note/utils/crypt/cli.py
31
32
33
34
35
36
37
38
39
40
@dataclass(frozen=True)
class Repository:
	"""Resolved locations for one docs tree inside a git work tree."""

	project_root: Path
	repo_root: Path
	docs_dir: Path
	docs_rel: str
	attributes_file: Path
	attributes_pattern: str

StatusReport dataclass

Result of mkdocs-note crypt status.

Source code in src/mkdocs_note/utils/crypt/cli.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@dataclass(frozen=True)
class StatusReport:
	"""Result of ``mkdocs-note crypt status``."""

	commands: Mapping[str, str | None]
	required: bool
	attribute: str | None
	attribute_sample: str
	hook_installed: bool
	notes: tuple[NoteStatus, ...]
	problems: tuple[str, ...]

	@property
	def ok(self) -> bool:
		"""Return whether the repository is fully consistent."""
		return not self.problems

ok property

Return whether the repository is fully consistent.

UninstallReport dataclass

Result of mkdocs-note crypt uninstall.

Source code in src/mkdocs_note/utils/crypt/cli.py
103
104
105
106
107
108
109
@dataclass(frozen=True)
class UninstallReport:
	"""Result of ``mkdocs-note crypt uninstall``."""

	removed_keys: tuple[str, ...]
	hook_removed: bool
	hook_kept: bool

check_staged(repo)

Verify that staged encrypted notes are valid envelopes.

Source code in src/mkdocs_note/utils/crypt/cli.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def check_staged(repo: Repository) -> CheckReport:
	"""Verify that staged encrypted notes are valid envelopes."""
	prefix = f"{repo.docs_rel}/" if repo.docs_rel else ""
	checked: list[str] = []
	errors: list[str] = []
	for rel in gitops.staged_paths(repo.repo_root):
		if not rel.endswith(".md"):
			continue
		if prefix and not rel.startswith(prefix):
			continue
		abs_path = repo.repo_root / rel
		try:
			raw = abs_path.read_text(encoding="utf-8")
		except (OSError, UnicodeDecodeError) as exc:
			errors.append(f"{rel}: cannot read the worktree copy ({exc})")
			checked.append(rel)
			continue
		split = envelope.split_frontmatter(envelope.normalize_text(raw))
		if split is None:
			continue
		meta = split[2]
		checked.append(rel)

		staged = gitops.blob_bytes(repo.repo_root, rel, ":")
		if staged is None:
			errors.append(f"{rel}: the staged copy is missing; re-add the file")
			continue
		try:
			staged_text = staged.decode("utf-8")
		except UnicodeDecodeError:
			errors.append(f"{rel}: the staged copy is not valid UTF-8")
			continue
		staged_encrypted = envelope.looks_encrypted(staged_text)

		if keys.is_encrypted(meta):
			try:
				keys.resolve_password(meta)
			except keys.PasswordError as exc:
				errors.append(f"{rel}: {exc}")
				continue
			if not staged_encrypted:
				errors.append(
					f"{rel}: staged as plaintext. Run 'mkdocs-note crypt init', "
					f"then 'git add --renormalize -- {rel}'."
				)
				continue
			try:
				envelope.decrypt_envelope(staged_text)
			except keys.CryptoError as exc:
				errors.append(
					f"{rel}: the staged envelope is corrupt or cannot be decrypted "
					f"({exc}); stage the whole file with 'git add -- {rel}'."
				)
		elif staged_encrypted:
			errors.append(
				f"{rel}: the staged copy is an envelope but the note no longer "
				f"has 'encrypt: true'; re-add it with 'git add -- {rel}'."
			)
	return CheckReport(checked=tuple(checked), errors=tuple(errors))

filter_commands(python)

Build the four filter.mkdocs-note.* config values.

Forward slashes and double quotes keep the command valid in git's shell on Windows, where the interpreter path may contain spaces.

Source code in src/mkdocs_note/utils/crypt/cli.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def filter_commands(python: str) -> dict[str, str]:
	"""Build the four ``filter.mkdocs-note.*`` config values.

	Forward slashes and double quotes keep the command valid in git's shell on
	Windows, where the interpreter path may contain spaces.
	"""
	executable = python.replace("\\", "/")
	base = f'"{executable}" -m mkdocs_note crypt'
	return {
		gitops.PROCESS_KEY: f"{base} filter-process",
		gitops.CLEAN_KEY: f"{base} clean",
		gitops.SMUDGE_KEY: f"{base} smudge",
		gitops.REQUIRED_KEY: "true",
	}

flagged_notes(repo)

Return (rel, meta, text) for every note with encrypt: true.

Source code in src/mkdocs_note/utils/crypt/cli.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def flagged_notes(repo: Repository) -> list[tuple[str, dict[str, Any], str]]:
	"""Return ``(rel, meta, text)`` for every note with ``encrypt: true``."""
	notes: list[tuple[str, dict[str, Any], str]] = []
	for path in sorted(repo.docs_dir.rglob("*.md")):
		try:
			raw = path.read_text(encoding="utf-8")
		except (OSError, UnicodeDecodeError):
			continue
		text = envelope.normalize_text(raw)
		split = envelope.split_frontmatter(text)
		if split is None or not keys.is_encrypted(split[2]):
			continue
		rel = gitops.repo_relative(repo.repo_root, path)
		notes.append((rel, split[2], text))
	return notes

install(repo, python)

Configure the filter, .gitattributes and the pre-commit hook.

Source code in src/mkdocs_note/utils/crypt/cli.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def install(repo: Repository, python: str) -> InstallReport:
	"""Configure the filter, ``.gitattributes`` and the pre-commit hook."""
	if is_ephemeral_python(python):
		raise CryptCliError(
			"refusing to configure a filter that points into an ephemeral uvx "
			"environment; install mkdocs-note in a project or user environment "
			"first"
		)
	if not Path(python).is_file():
		raise CryptCliError(f"interpreter does not exist: {python}")

	commands = filter_commands(python)
	try:
		for key, value in commands.items():
			gitops.config_set(repo.repo_root, key, value)
	except gitops.GitError as exc:
		raise CryptCliError(str(exc)) from exc

	attributes_changed = _ensure_attributes(
		repo.attributes_file, repo.attributes_pattern
	)

	hooks_dir = gitops.git_path(repo.repo_root, "hooks")
	hook_path = hooks_dir / "pre-commit"
	executable = python.replace("\\", "/")
	hook_line = f'"{executable}" -m mkdocs_note crypt check --staged'
	if hook_path.is_file():
		try:
			existing = hook_path.read_text(encoding="utf-8", errors="replace")
		except OSError:
			existing = ""
		hook_status = "present" if HOOK_SIGNATURE in existing else "existing"
	else:
		_write_text(hook_path, _hook_script(python), mode=0o755)
		hook_status = "installed"

	return InstallReport(
		commands=commands,
		attributes_changed=attributes_changed,
		hook_status=hook_status,
		hook_path=hook_path,
		hook_line=hook_line,
		plaintext_index=tuple(notes_with_plaintext_index(repo)),
	)

is_ephemeral_python(python)

Return whether python belongs to an ephemeral uvx/tool environment.

A filter command that points into uvx's cache breaks as soon as that cache is cleaned, which would make git add fail in every clone.

Source code in src/mkdocs_note/utils/crypt/cli.py
153
154
155
156
157
158
159
160
def is_ephemeral_python(python: str) -> bool:
	"""Return whether *python* belongs to an ephemeral uvx/tool environment.

	A filter command that points into ``uvx``'s cache breaks as soon as that
	cache is cleaned, which would make ``git add`` fail in every clone.
	"""
	normalized = python.replace("\\", "/")
	return "/uv/archive-" in normalized or "/uv/tools/" in normalized

make_repository(project_root, docs_dir=None)

Resolve the repository, docs directory and attributes pattern.

Parameters:

Name Type Description Default
project_root Path

Directory containing mkdocs.yml.

required
docs_dir Path | str | None

Docs directory; relative paths are resolved against project_root. Defaults to docs.

None

Raises:

Type Description
CryptCliError

when the docs directory is outside the git work tree.

Source code in src/mkdocs_note/utils/crypt/cli.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def make_repository(
	project_root: Path,
	docs_dir: Path | str | None = None,
) -> Repository:
	"""Resolve the repository, docs directory and attributes pattern.

	Args:
		project_root: Directory containing ``mkdocs.yml``.
		docs_dir: Docs directory; relative paths are resolved against
			``project_root``. Defaults to ``docs``.

	Raises:
		CryptCliError: when the docs directory is outside the git work tree.
	"""
	project_root = project_root.resolve()
	repo = gitops.repo_root(project_root)
	docs = Path(docs_dir) if docs_dir is not None else Path("docs")
	if not docs.is_absolute():
		docs = project_root / docs
	docs = docs.resolve()
	try:
		relative = docs.relative_to(repo)
	except ValueError as exc:
		raise CryptCliError(
			f"docs directory {docs} is outside the git repository {repo}"
		) from exc
	docs_rel = "" if relative == Path() else relative.as_posix()
	if docs_rel:
		pattern = f"/{docs_rel}/**/*.md filter={gitops.FILTER_NAME}"
	else:
		pattern = f"**/*.md filter={gitops.FILTER_NAME}"
	return Repository(
		project_root=project_root,
		repo_root=repo,
		docs_dir=docs,
		docs_rel=docs_rel,
		attributes_file=repo / ".gitattributes",
		attributes_pattern=pattern,
	)

notes_with_plaintext_index(repo)

Return flagged notes whose staged copy is still plaintext.

Source code in src/mkdocs_note/utils/crypt/cli.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def notes_with_plaintext_index(repo: Repository) -> list[str]:
	"""Return flagged notes whose staged copy is still plaintext."""
	result: list[str] = []
	for rel, _meta, _text in flagged_notes(repo):
		blob = gitops.blob_bytes(repo.repo_root, rel, ":")
		if blob is None:
			continue
		try:
			staged = blob.decode("utf-8")
		except UnicodeDecodeError:
			result.append(rel)
			continue
		if not envelope.looks_encrypted(staged):
			result.append(rel)
	return result

python_executable()

Return the interpreter that should host the filter commands.

Source code in src/mkdocs_note/utils/crypt/cli.py
488
489
490
def python_executable() -> str:
	"""Return the interpreter that should host the filter commands."""
	return sys.executable

status(repo)

Inspect the filter configuration and every flagged note.

Source code in src/mkdocs_note/utils/crypt/cli.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def status(repo: Repository) -> StatusReport:
	"""Inspect the filter configuration and every flagged note."""
	commands = {
		key: gitops.config_get(repo.repo_root, key) for key in gitops.FILTER_CONFIG_KEYS
	}
	required = commands.get(gitops.REQUIRED_KEY) == "true"
	hook_path = gitops.git_path(repo.repo_root, "hooks") / "pre-commit"
	try:
		hook_text = hook_path.read_text(encoding="utf-8", errors="replace")
	except OSError:
		hook_text = ""
	hook_installed = HOOK_SIGNATURE in hook_text

	notes: list[NoteStatus] = []
	for rel, meta, text in flagged_notes(repo):
		worktree, work_error = _text_state(text)
		index, index_error = _blob_state(gitops.blob_bytes(repo.repo_root, rel, ":"))
		head, head_error = _blob_state(gitops.blob_bytes(repo.repo_root, rel, "HEAD"))
		errors: list[str] = []
		if work_error:
			errors.append(f"worktree: {work_error}")
		if index in (PLAINTEXT, CORRUPT):
			detail = f" ({index_error})" if index_error else ""
			errors.append(
				f"index: {index}{detail}; re-add with 'git add --renormalize -- {rel}'"
			)
		if head in (PLAINTEXT, CORRUPT):
			detail = f" ({head_error})" if head_error else ""
			errors.append(
				f"HEAD: {head}{detail}; plaintext already committed, rewrite history "
				"if it matters"
			)
		notes.append(
			NoteStatus(
				rel=rel,
				key_field=_key_field(meta),
				worktree=worktree,
				index=index,
				head=head,
				errors=tuple(errors),
			)
		)

	problems: list[str] = []
	if commands.get(gitops.PROCESS_KEY) is None:
		problems.append(
			"filter.mkdocs-note.process is not configured; run 'mkdocs-note crypt init'"
		)
	if not required:
		problems.append(
			"filter.mkdocs-note.required is not true; a missing filter would "
			"silently store plaintext"
		)
	sample = (
		notes[0].rel
		if notes
		else (f"{repo.docs_rel}/index.md" if repo.docs_rel else "index.md")
	)
	attribute = gitops.check_attr(repo.repo_root, sample)
	if attribute != gitops.FILTER_NAME:
		problems.append(
			f".gitattributes does not set 'filter={gitops.FILTER_NAME}' for "
			f"{sample}; run 'mkdocs-note crypt init' and commit .gitattributes"
		)
	for note in notes:
		problems.extend(f"{note.rel}: {error}" for error in note.errors)

	return StatusReport(
		commands=commands,
		required=required,
		attribute=attribute,
		attribute_sample=sample,
		hook_installed=hook_installed,
		notes=tuple(notes),
		problems=tuple(problems),
	)

uninstall(repo)

Remove the filter configuration and the hook installed by init.

Source code in src/mkdocs_note/utils/crypt/cli.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def uninstall(repo: Repository) -> UninstallReport:
	"""Remove the filter configuration and the hook installed by ``init``."""
	removed: list[str] = []
	for key in gitops.FILTER_CONFIG_KEYS:
		if gitops.config_unset(repo.repo_root, key):
			removed.append(key)

	hook_path = gitops.git_path(repo.repo_root, "hooks") / "pre-commit"
	hook_removed = False
	hook_kept = False
	if hook_path.is_file():
		try:
			text = hook_path.read_text(encoding="utf-8", errors="replace")
		except OSError:
			text = ""
		if HOOK_SIGNATURE in text:
			try:
				hook_path.unlink()
				hook_removed = True
			except OSError:
				hook_kept = True
		else:
			hook_kept = True

	return UninstallReport(
		removed_keys=tuple(removed),
		hook_removed=hook_removed,
		hook_kept=hook_kept,
	)