CI / ci (push) Canceled after 0s
Two-step publish to Micro.blog over Micropub: Send as Draft (JSON h=entry create — name = the Title, markdown content verbatim, post-status draft), review via the preview link, then Publish (the action=update post-status flip). The piece remembers its draft URL as a frontmatter micropub_url stamp — in-place, body and foreign keys byte-identical — so a draft survives a reopen; Send Again re-drafts after edits. The app token lives in the Keychain (login keychain; entered once in the sheet, re-offered only on auth failure — ADR-0014's no-Keychain rule covers only provider keys hermes reads from .env). Frontmatter category: is permitted but never sent in v1 — pinned on the wire. The draft URL is trust-boundary data landing in frontmatter, so every URL passes a format gate (https + host, no line/control characters) at BOTH ends: the response decode (Location header → body url; the preview link is display-only, never the publish target) and Post.scan's read-back — imported frontmatter rides verbatim, and a newline--- rider would otherwise close the block and reparse as attacker markdown in the writer's piece. Twenty tests pin the wire contract, decode matrix, own-slot keychain round-trip, stamp/scan, and the model flow (flush-first, refusal guards, the category AC); all four audit guards are flip-verified. Full suite 529 passed / 0 failed. Live end-to-end on a real post (needs the owner's app token) remains open on the ticket.
284 lines
11 KiB
Swift
284 lines
11 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).
|
|
//
|
|
// 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). category: never sent in v1.
|
|
request.httpBody = try? JSONSerialization.data(withJSONObject: [
|
|
"type": ["h-entry"],
|
|
"properties": [
|
|
"name": [title],
|
|
"content": [body],
|
|
"post-status": ["draft"],
|
|
],
|
|
], 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.
|
|
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
|
|
}
|
|
|
|
private 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.
|
|
func micropubSendDraft(
|
|
home: URL,
|
|
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 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.")
|
|
}
|
|
let outcome = await Micropub.sendDraft(
|
|
title: Post.title(of: raw),
|
|
body: body,
|
|
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
|
|
}
|
|
}
|