// // 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 micropubSend below. // #206: a piece that remembers its post re-sends as an IN-PLACE // update (action=update + replace name/content — never a second // post), Publish is remembered on the piece (`micropub_published`), // and a 404 forgets the link. Wire facts live-verified 2026-12-04 // (microblog.dev/api/posting): `replace` sets name and content; // updates answer 200 with an empty body, 404 when the URL is gone. // // 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?) /// #206: an in-place update landed — `url` is the post the piece /// already remembered (a draft refreshed, a live post edited). /// No second post, no new URL. case updated(url: String) case published /// No open saved piece (model guard) — nothing went out. case refused(String) /// #206 (model-level): Micro.blog answered 404 — the post is gone /// there. The piece has forgotten it (both stamps cleared); the /// payload says so. The next send is a fresh draft. case forgotten(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) /// The one JSON POST shape every request rides: the fixed endpoint, /// Bearer token, 30 s, sorted keys. private static func jsonPost(_ object: [String: Any], 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: object, options: [.sortedKeys]) return request } static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest { // 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. jsonPost([ "type": ["h-entry"], "properties": [ "name": [title], "content": [body], "post-status": ["draft"], ] as [String: Any], ], token: token) } static func makePublishRequest(url: String, token: String) -> URLRequest { jsonPost([ "action": "update", "url": url, "replace": ["post-status": ["published"]], ], token: token) } /// #206: refresh the post the piece remembers — title and content /// replaced IN PLACE over the remembered URL (wire-verified /// 2026-12-04: `replace` sets name and content, JSON-only). Never /// a status flip: a draft stays a draft, a published post stays live. static func makeUpdateRequest(url: String, title: String, body: String, token: String) -> URLRequest { jsonPost([ "action": "update", "url": url, "replace": [ "name": [title], "content": [body], ], ], token: token) } // MARK: The 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) } /// #206: step 1 again, in place — the piece's current title and /// body replace the remembered post's (a draft refreshed for /// review; a live post edited). Needs the remembered URL. static func update( url: String, title: String, body: String, token: String, transport: Transport = urlSessionTransport, ) async -> Outcome { let outcome = await run(makeUpdateRequest(url: url, title: title, body: body, token: token), transport: transport, decodeDraftURL: false) // `run` has one success word for the URL-less steps; the update's // carries the URL it touched. if outcome == .published { return .updated(url: url) } return outcome } /// 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. Format-only by design — ownership is /// settled upstream, not here: the import boundary drops the micropub /// keys (`PostFrontmatter.micropubKeys`, #206 — since the in-place /// update a well-formed foreign URL would aim a content replace), so /// only Museion or the writer's own hand writes one. ponytail: /// host-allowlist stays the upgrade if another way in ever appears. 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 } /// The remembered post URL read from frontmatter — the ONE read the /// scan and the send share, gated like the decode: a hand-written /// broken value is no memory at all (an imported one never arrives — /// the boundary drops the key). static func rememberedURL(_ matter: [String: String]) -> String? { guard let raw = matter["micropub_url"], trustworthyURL(raw) else { return nil } return raw } /// #206: the short date the library row and the publish sheet both /// show (`Dec 4, 2026`) — one format, so the two can't drift. static func shortDate(_ date: Date) -> String { FixCardStore.formatted(date, "MMM d, yyyy") } /// Internal for MicropubMedia's media steps (#34) — the one failure /// decode this client speaks; extensions share it rather than fork it. /// A 5xx is Micro.blog's side (their nginx front with the app not /// answering behind it, or a rate limit) and arrives as an HTML page, /// never Micropub JSON — so the fallback names the outage instead of /// a bare `HTTP 503` (2026-12-04: a 503 in the sheet while the /// endpoint answered its usual 400 to a tokenless probe minutes later). static func decodeFailure(status: Int, body: Data) -> Outcome { let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:] let described = (root["error_description"] as? String) ?? (root["error"] as? String) if status == 401 || status == 403 { return .authFailed(described ?? "HTTP \(status)") } let fallback = (500 ... 599).contains(status) ? "unavailable on their side — retry in a few minutes (status.micro.blog)" : "HTTP \(status)" return .requestFailed(status: status, detail: described ?? fallback) } } /// 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) / #206 Micropub draft → publish extension PostsModel { /// The OPEN saved library piece as the micropub pair (id, Home) — /// the identity guard both publish steps share. brief-28: the open /// session must target THIS library's selected piece; the wire and /// every stamp below act on the piece actually sent (Home, ID), /// never the current Home's same-slug file. Nil = nothing to send. private var openMicropubPiece: (id: String, home: URL)? { guard let session, let id = session.postID, let home = watchedHome, id == selectedPostID, session.targets(postID: id, home: home), draft == nil, externalSession == nil, outlineGuardPieceID == nil else { return nil } return (id, home) } /// Step 1 of the two-step publish: send the OPEN piece to Micro.blog /// (name = Title, markdown content — 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. /// #206: a piece that remembers no post is CREATED as a draft /// (h=entry, post-status draft) and remembers its URL /// (`micropub_url` stamp); a piece that remembers one UPDATES that /// post in place — same URL, no second post — so a draft refreshes /// for review and a published piece edits live. A stamp failure /// never un-sends the draft. /// #179: outside the write rail by design — publish is not a library /// verb, and a stamp failure must never un-send the draft. func micropubSend( token: String, transport: Micropub.Transport = Micropub.urlSessionTransport, ) async -> Micropub.Outcome { guard let piece = openMicropubPiece else { return .refused("Open a saved post to publish.") } guard flushOrAbort(piece.id) else { return .refused(lastError ?? "Couldn't save the piece before sending.") } // Disk is the truth post-flush — ONE read serves the wire fields: // Title (heading markers stripped — it publishes as the entry's // name), the frontmatter-stripped body (the stamp is // bookkeeping, never prose; the body itself is never stripped, // GLOSSARY), and the remembered URL. No scan dependency: the // list can lag the open piece. guard let dir = PostStore.folder(of: piece.id, home: piece.home), let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8) else { return .refused("Couldn't read the piece before sending.") } let body = PostFrontmatter.split(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 title = Post.title(of: raw) // #206: the piece remembers its post → update THAT post in // place (the remembered URL never moves; nothing new to stamp). // A 404 means the post is gone on Micro.blog — the piece forgets // it rather than fail forever against a dead URL. if let remembered = Micropub.rememberedURL(PostFrontmatter.parse(raw)) { let outcome = await Micropub.update(url: remembered, title: title, body: wireBody, token: token, transport: transport) if case .requestFailed(404, _) = outcome { return micropubPostGone(id: piece.id, home: piece.home) } return outcome } let outcome = await Micropub.sendDraft( title: title, body: wireBody, token: token, transport: transport, ) if case let .drafted(url, _) = outcome { // Remember the draft's URL for the publish step and every // later in-place update. 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 (it // would create a second draft then). Kept quiet: the same // disk accepted the flush moments before. try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)]) } return outcome } /// Step 2: flip the remembered draft to published. #206: the model /// owns it — the sheet used to call the client directly, so nothing /// remembered a publish. Success is the piece's publish record: /// `micropub_published` stamped now (first publish wins — a later /// in-place update of the live post never moves it) and /// `micropub_url` healed in the same write should the send's stamp /// have failed. A stamp failure never un-publishes. No flush: no /// content travels, and the editor never writes frontmatter. The URL /// is trust-gated HERE — it lands in frontmatter (the heal), and a /// caller's value is external until proven. func micropubPublish( url: String, token: String, transport: Micropub.Transport = Micropub.urlSessionTransport, ) async -> Micropub.Outcome { guard let piece = openMicropubPiece else { return .refused("Open a saved post to publish.") } guard Micropub.trustworthyURL(url) else { return .refused("That post address isn't a clean https URL — nothing was sent or remembered.") } let outcome = await Micropub.publish(url: url, token: token, transport: transport) switch outcome { case .published: try? PostStore.stampMicropub(piece.id, home: piece.home, [ ("micropub_url", url), ("micropub_published", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)), ]) case .requestFailed(404, _): return micropubPostGone(id: piece.id, home: piece.home) default: break } return outcome } /// #206: Micro.blog answered 404 — the post is gone there, so the /// piece is no longer on Micro.blog: it forgets both stamps and the /// writer hears why (the next send is a fresh draft). A forget that /// cannot land refuses instead — never a "cleared" the disk /// contradicts: the link is still on the piece, so the sheet stays /// on it and says what to do by hand. private func micropubPostGone(id: String, home: URL) -> Micropub.Outcome { do { try PostStore.forgetMicropub(id: id, home: home) } catch { return .refused( "Micro.blog no longer has this post — it was deleted there — but its link couldn't be cleared from this piece " + "(\(error.localizedDescription)). Delete the `micropub_url` line from its frontmatter, then send it as a draft.", ) } return .forgotten("Micro.blog no longer has this post — it was deleted there. Its link is cleared; send it as a draft again.") } /// #34 (S6.2): the illustration rail of `micropubSend`. 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. 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)) } return await uploadRemembered(payloads, dir: dir, body: body, token: token, transport: transport) } /// One asset about to travel: its ref destination (the rewrite's /// map key), its wire content type, its bytes. private struct Payload { let destination: String let mimeType: String let data: Data } /// #206: the piece's upload memo answers first — an image whose /// bytes uploaded before rides that URL again (Micro.blog keeps /// every copy, and their listing carries no hash to match against, /// so the memory is local). Only what the memo lacks touches the /// wire: q=config, then one upload per pending payload, each /// remembered as it lands. private func uploadRemembered( _ payloads: [Payload], dir: URL, body: String, token: String, transport: Micropub.Transport, ) async -> IllustrationRail { var memo = Micropub.readUploadMemo(in: dir) let remembered = uploadedDestinations(payloads, memo: memo) let pending = payloads.filter { remembered[$0.destination] == nil } guard !pending.isEmpty else { return .ready(Micropub.rewritingIllustrations(body, uploaded: remembered)) } let mediaEndpoint: String switch await Micropub.mediaEndpoint(token: token, transport: transport) { case let .url(named): mediaEndpoint = named case let .failed(outcome): return .blocked(outcome) } // The `where` skips a later payload with the same bytes as one // uploaded earlier in this batch. for payload in pending where memo[Micropub.uploadKey(payload.data)] == nil { 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): // Remembered as it lands: a later failure in the batch // keeps the earlier uploads (a retry never repeats them). memo[Micropub.uploadKey(payload.data)] = url Micropub.writeUploadMemo(memo, in: dir) case let .failed(failure): return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece } } // Every payload is memoized now — the earlier uploads and this batch's. return .ready(Micropub.rewritingIllustrations(body, uploaded: uploadedDestinations(payloads, memo: memo))) } /// The rewrite's map: each payload's ref destination → its upload URL. private func uploadedDestinations(_ payloads: [Payload], memo: [String: String]) -> [String: String] { var uploaded: [String: String] = [:] for payload in payloads { if let url = memo[Micropub.uploadKey(payload.data)] { uploaded[payload.destination] = url } } return uploaded } }