Files
museion/Museion/Micropub.swift
T
AlexKucera 5bf09552f6
CI / ci (push) Canceled after 0s
refactor(posts): route every library write through one rail
#179: every library-reflecting store write (draft save, session-born
post, rename, move to project, archive/restore, trash, convert,
project creation, import batch, pass advance) now rides one internal
seam — performWrite pairs the write with exactly one rescan and owns
the error strip (cleared BEFORE the write so importFiles' per-file
failure messages survive the success tail; a nil-Home refusal writes
nothing). The model owns the Home: watchedHome is private(set), set
only by bind (construction + the Settings repoint); no public method
takes a Home parameter — 14 view call sites and ~115 test call sites
swept, dead home plumbing cut. The editor's debounced flush, the card
closes, the pass substrate and the micropub publish stay off the rail
by design (own error semantics, no library regroup).

A converged review finding is closed with a guard: the pass advance
re-resolves watchedHome after the engine's minutes-long turn, so a
mid-pass Settings repoint now refuses the advance with an honest strip
message instead of silently stamping pass state into the repointed
library (wrong-piece write on a slug collision). createProject
failures now surface in the sheet AND the strip — the rail-owns-the-
strip posture supersedes the #108 sheet-only rule.

Five rail pins (PostsModelWriteRailTests, suite members): write → one
library refresh + strip cleared, failed write owns the strip, nil-Home
refusal, import batch keeps per-file messages, mid-pass repoint
refuses the advance — the last two flip-verified against their guards.
ScriptedEngine gains endHeldPrompt (release a held turn as ended).

Verification: suite 657/657 the evening this landed; the next-morning
re-run could not start — both test runners hung before establishing
connection (#134 testmanagerd wedge; an untouched control suite hangs
identically — machine state, not this diff; reboot pending). Rail pins
5/5 isolated after the last test-only edit; swiftlint at baseline
parity; swiftformat clean.

Closes #179

[Generated by AI]
2026-11-10 08:45:04 +01:00

387 lines
16 KiB
Swift

//
// Micropub.swift
// Museion
//
// #33 (S6.1): the Micro.blog Micropub client + the app-token store.
// Two-step publish (G2/G11): create with `post-status: draft`, review,
// then `action=update` flips the draft to published. Bearer app-token
// auth — no OAuth in v1; the token lives in the Keychain, entered
// once. Frontmatter `category:` is permitted but inert (v1 never
// sends it — the request carries name + content only).
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the
// media surface (parse/upload/config/rewrite) lives in
// MicropubMedia.swift, the orchestration in micropubSendDraft below.
//
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the
// draft's final URL arrives in the Location header, the body carries
// url + preview; update is JSON-only action/replace.
//
import Foundation
import Security
nonisolated enum Micropub {
/// Micro.blog's Micropub endpoint (G2: the fixed v1 target — no
/// discovery, no per-blog config).
static let endpoint = URL(string: "https://micro.blog/micropub")!
enum Outcome: Equatable {
/// Create landed; `url` is the draft's final URL (Location
/// header, body url as fallback) — what `publish` targets and
/// what the piece remembers.
case drafted(url: String, preview: String?)
case published
/// No open saved piece (model guard) — nothing went out.
case refused(String)
case authFailed(String)
case requestFailed(status: Int, detail: String)
case unreachable(String)
}
// MARK: Transport (ProviderProbe seam: canned in tests, URLSession live)
typealias Transport = @Sendable (_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
static let urlSessionTransport: Transport = { request in
let (data, response) = try await URLSession.shared.data(for: request)
guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
return (data, http)
}
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic)
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
// h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
// illustration refs, which REWRITE to their uploaded URLs on
// the WIRE (position and alt are the writer's; the piece on
// disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1.
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
] as [String: Any],
], options: [.sortedKeys])
return request
}
static func makePublishRequest(url: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"action": "update",
"url": url,
"replace": ["post-status": ["published"]],
], options: [.sortedKeys])
return request
}
// MARK: The two steps
/// Step 1: send the piece as a draft. The piece's Title is the
/// entry's name; the markdown body is the content; #34's uploaded
/// illustrations already rewrote their refs in the body.
static func sendDraft(
title: String,
body: String,
token: String,
transport: Transport = urlSessionTransport,
) async -> Outcome {
await run(makeDraftRequest(title: title, body: body, token: token), transport: transport, decodeDraftURL: true)
}
/// Step 2: publish the draft — flip its post-status. Needs the
/// draft's URL from step 1 (the piece's remembered `micropub_url`).
static func publish(
url: String,
token: String,
transport: Transport = urlSessionTransport,
) async -> Outcome {
guard !url.isEmpty else { return .refused("No draft URL on this piece — send it as a draft first.") }
return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false)
}
/// One POST + the honest decode: 2xx → drafted/published (drafts
/// need a URL — Location header first, body `url` second; the
/// preview link is display-only, never the publish target; a create
/// with no trustworthy URL is a request failure, never a silent
/// success), 401/403 → authFailed, other statuses carry Micropub's
/// `error_description`, transport throws → unreachable.
private static func run(
_ request: URLRequest,
transport: Transport,
decodeDraftURL: Bool,
) async -> Outcome {
do {
let (data, response) = try await transport(request)
guard (200 ..< 300).contains(response.statusCode) else {
return decodeFailure(status: response.statusCode, body: data)
}
guard decodeDraftURL else { return .published }
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
// #33 audit: the URL is trust-boundary data — it lands in
// frontmatter and drives a later publish. Location first,
// body url second; both must pass the format guard.
let url = response.value(forHTTPHeaderField: "Location") ?? root["url"] as? String
guard let url, trustworthyURL(url) else {
return .requestFailed(status: response.statusCode, detail: "no trustworthy URL in the response")
}
return .drafted(url: url, preview: root["preview"] as? String)
} catch {
return .unreachable(error.localizedDescription)
}
}
/// A draft URL Museion will persist and act on: https, a host, no
/// line/control characters — a `\n---` riding this value would close
/// the frontmatter block on the next parse and re-parse as BODY
/// (arbitrary markdown in the writer's piece, shipped under their
/// token by the next send). Applied at both ends: the decode above
/// and `Post.scan`'s read-back (imported frontmatter rides verbatim).
/// Format-only by design — ponytail: a well-formed foreign URL still
/// passes (the label shows its full text); host-allowlist when v2's
/// q=config surface names the blog's real domains.
static func trustworthyURL(_ string: String) -> Bool {
guard !string.isEmpty,
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
let url = URL(string: string),
url.scheme?.lowercased() == "https",
url.host != nil
else { return false }
return true
}
/// Internal for MicropubMedia's media steps (#34) — the one failure
/// decode this client speaks; extensions share it rather than fork it.
static func decodeFailure(status: Int, body: Data) -> Outcome {
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
let detail = (root["error_description"] as? String) ?? (root["error"] as? String) ?? "HTTP \(status)"
if status == 401 || status == 403 {
return .authFailed(detail)
}
return .requestFailed(status: status, detail: detail)
}
}
/// The Micro.blog app token — Museion's OWN credential, read only by
/// this app (ADR-0014's no-Keychain rule covers provider keys hermes
/// must read from `.env`; this token has no engine consumer).
/// Entered once, stored in the login keychain (the legacy file-based
/// store — no `kSecUseDataProtectionKeychain`, which needs
/// keychain-access-groups from a provisioning profile this
/// not-yet-distributed app doesn't sign with).
nonisolated enum MicropubTokenStore {
private static let service = "com.babylondreams.Museion.micropub"
/// The production slot. Tests pass their own account — the suite
/// must never touch (or, on a locked keychain, delete) a real
/// live token (#33 audit).
private static let account = "micro.blog"
/// `account` is overridable for tests only; production callers use
/// the default.
static func read(account: String = account) -> String? {
var query = baseQuery(account: account)
query[kSecReturnData as String] = true
query[kSecMatchLimit as String] = kSecMatchLimitOne
var out: CFTypeRef?
guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess,
let data = out as? Data
else { return nil }
return String(data: data, encoding: .utf8)
}
/// Add-or-replace (rotation replaces, never duplicates). An empty
/// token is never stored.
static func save(_ token: String, account: String = account) {
guard !token.isEmpty else { return }
let data = Data(token.utf8)
var update = baseQuery(account: account)
update[kSecValueData as String] = data
if SecItemUpdate(update as CFDictionary, [kSecValueData as String: data] as CFDictionary) == errSecItemNotFound {
var add = update
add[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
SecItemAdd(add as CFDictionary, nil)
}
}
static func delete(account: String = account) {
SecItemDelete(baseQuery(account: account) as CFDictionary)
}
private static func baseQuery(account: String) -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
}
}
// MARK: - #33 (S6.1) Micropub draft → publish
extension PostsModel {
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// as a draft (h=entry, name = Title, markdown content, post-status
/// draft — category frontmatter never travels). runPass's guard set
/// minus the engine gates (no engine involved); flush-first so the
/// wire carries the editor's latest. On success the piece remembers
/// the draft URL (`micropub_url` stamp) — a stamp failure never
/// un-sends the draft; it lands in lastError while the outcome stays
/// honest. Publishing (step 2) is stateless: the sheet calls
/// `Micropub.publish` against the remembered URL directly.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSendDraft(
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
return .refused("Open a saved post to publish.")
}
guard flushOrAbort(id) else {
return .refused(lastError ?? "Couldn't save the piece before sending.")
}
// Disk is the truth post-flush — ONE read serves both wire fields:
// Title (heading markers stripped — it publishes as the entry's
// name) and the frontmatter-stripped body (the stamp is
// bookkeeping, never prose; the body itself is never stripped,
// GLOSSARY). No scan dependency: the list can lag the open piece.
guard let home = watchedHome,
let dir = PostStore.folder(of: id, home: home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
return .refused("Couldn't read the piece before sending.")
}
let body = PostStore.splitFrontmatter(raw).body
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return .refused("This piece has no text to send.")
}
// #34 (S6.2): illustrations travel with it (the rail below
// owns the floor, the uploads, and the REWRITTEN wire body —
// G12: the mentor is never consulted about images).
var wireBody = body
if !Micropub.illustrations(in: body).isEmpty {
switch await uploadIllustrations(dir: dir, body: body, token: token, transport: transport) {
case let .ready(rewritten):
wireBody = rewritten
case let .blocked(outcome):
return outcome
}
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
body: wireBody,
token: token,
transport: transport,
)
if case let .drafted(url, _) = outcome {
// Remember the draft URL for the publish step. A stamp
// failure can't un-send the draft; the sheet still holds
// the URL for this session — the piece just loses the
// memory across a reopen (re-send the draft then). Kept
// quiet: lastError's setter stays PostsModel-file-private,
// and the same disk accepted the flush moments before.
try? PostStore.stampMicropubURL(id: id, url: url, home: home)
}
return outcome
}
/// #34 (S6.2): the illustration rail of `micropubSendDraft`. The
/// FLOOR first (G12): a photo without alt text never ships, and
/// nothing touches the wire until every illustration clears it —
/// the ONLY gate (the only way an image ships is a parsed body ref,
/// and every send routes through here). Then one upload per PNG
/// (q=config → multipart → Location) and `ready`'s body is the
/// wire content with each ref REWRITTEN to its uploaded URL — the
/// image renders exactly where the writer placed it, alt travels
/// in the markdown (the piece on disk never changes). Style
/// judgment stays with the author.
private enum IllustrationRail {
case ready(String) // the rewritten wire body
case blocked(Micropub.Outcome)
}
private func uploadIllustrations(
dir: URL,
body: String,
token: String,
transport: Micropub.Transport,
) async -> IllustrationRail {
let illustrations = Micropub.illustrations(in: body)
if let bare = illustrations.first(where: { $0.alt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) {
return .blocked(.refused("\(bare.destination) has no alt text — a photo never ships without it."))
}
// Pre-flight: every file in hand (and inside this piece — a
// `../` ref or a symlinked asset is out of shape) before the
// first upload. One payload per FILE: duplicate refs to one
// destination upload once and share the URL.
struct Payload {
let destination: String
let mimeType: String
let data: Data
}
let root = dir.resolvingSymlinksInPath().path + "/"
var payloads: [Payload] = []
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
guard let mimeType = Micropub.mimeType(forDestination: illustration.destination) else {
return .blocked(.refused("\(illustration.destination) is not a PNG/JPEG/GIF/WebP/SVG — Micro.blog can't host it."))
}
let fileURL = dir.appendingPathComponent(illustration.destination)
guard fileURL.resolvingSymlinksInPath().path.hasPrefix(root),
let data = try? Data(contentsOf: fileURL)
else {
return .blocked(.refused("Couldn't read \(illustration.destination) from this piece's assets."))
}
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
}
// ponytail: a re-send re-uploads (Micro.blog keeps both
// copies) — dedup via q=source listing is v2's call.
let mediaEndpoint: String
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named):
mediaEndpoint = named
case let .failed(outcome):
return .blocked(outcome)
}
var uploaded: [String: String] = [:]
for payload in payloads {
let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
mimeType: payload.mimeType,
data: payload.data,
token: token,
transport: transport,
)
switch outcome {
case let .url(url):
uploaded[payload.destination] = url
case let .failed(failure):
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece
}
}
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploaded))
}
}