inkwire-receiver-core 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Isaac Gounton
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.4
2
+ Name: inkwire-receiver-core
3
+ Version: 0.1.0
4
+ Summary: Shared Python core for building an Inkwire blog-post receiver.
5
+ Author: Isaac Gounton
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/etugrand/inkwire
8
+ Project-URL: Documentation, https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pydantic>=2.9
13
+ Requires-Dist: markdown>=3.7
14
+ Requires-Dist: nh3>=0.2.18
15
+ Requires-Dist: email-validator>=2.0
16
+ Provides-Extra: fastapi
17
+ Requires-Dist: fastapi>=0.115; extra == "fastapi"
18
+ Provides-Extra: dev
19
+ Requires-Dist: fastapi>=0.115; extra == "dev"
20
+ Requires-Dist: pytest>=8.3; extra == "dev"
21
+ Requires-Dist: httpx>=0.27; extra == "dev"
22
+ Requires-Dist: uvicorn>=0.30; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # inkwire-receiver-core
26
+
27
+ Shared Python core for building an [Inkwire](https://github.com/etugrand/inkwire)
28
+ receiver. It validates incoming posts, derives SEO metadata, safely renders
29
+ Markdown, resolves slugs, and upserts through a storage interface you provide.
30
+
31
+ ```bash
32
+ pip install "inkwire-receiver-core[fastapi]"
33
+ ```
34
+
35
+ ```python
36
+ from fastapi import FastAPI, Request
37
+ from fastapi.responses import JSONResponse
38
+ from inkwire_receiver import MemoryStore, handle_post
39
+
40
+ app = FastAPI()
41
+ store = MemoryStore() # Replace with your database-backed store.
42
+
43
+
44
+ @app.post("/api/posts")
45
+ async def create_post(request: Request):
46
+ try:
47
+ body = await request.json()
48
+ except Exception:
49
+ body = None
50
+
51
+ status, response, headers = await handle_post(
52
+ request.headers.get("authorization"),
53
+ body,
54
+ ["your-api-key"],
55
+ store,
56
+ )
57
+ return JSONResponse(status_code=status, content=response, headers=headers)
58
+ ```
59
+
60
+ `MemoryStore` is intended for local development and tests. Production sites
61
+ should provide an asynchronous store implementing `find_by_external_id`,
62
+ `find_by_slug`, and `upsert`. See the
63
+ [protocol specification](https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md)
64
+ for the complete wire and storage semantics.
@@ -0,0 +1,40 @@
1
+ # inkwire-receiver-core
2
+
3
+ Shared Python core for building an [Inkwire](https://github.com/etugrand/inkwire)
4
+ receiver. It validates incoming posts, derives SEO metadata, safely renders
5
+ Markdown, resolves slugs, and upserts through a storage interface you provide.
6
+
7
+ ```bash
8
+ pip install "inkwire-receiver-core[fastapi]"
9
+ ```
10
+
11
+ ```python
12
+ from fastapi import FastAPI, Request
13
+ from fastapi.responses import JSONResponse
14
+ from inkwire_receiver import MemoryStore, handle_post
15
+
16
+ app = FastAPI()
17
+ store = MemoryStore() # Replace with your database-backed store.
18
+
19
+
20
+ @app.post("/api/posts")
21
+ async def create_post(request: Request):
22
+ try:
23
+ body = await request.json()
24
+ except Exception:
25
+ body = None
26
+
27
+ status, response, headers = await handle_post(
28
+ request.headers.get("authorization"),
29
+ body,
30
+ ["your-api-key"],
31
+ store,
32
+ )
33
+ return JSONResponse(status_code=status, content=response, headers=headers)
34
+ ```
35
+
36
+ `MemoryStore` is intended for local development and tests. Production sites
37
+ should provide an asynchronous store implementing `find_by_external_id`,
38
+ `find_by_slug`, and `upsert`. See the
39
+ [protocol specification](https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md)
40
+ for the complete wire and storage semantics.
@@ -0,0 +1,4 @@
1
+ from .handle import handle_post
2
+ from .store import MemoryStore, PostStore, StoredPost, UpsertResult
3
+
4
+ __all__ = ["MemoryStore", "PostStore", "StoredPost", "UpsertResult", "handle_post"]
@@ -0,0 +1,8 @@
1
+ import hmac
2
+ from .errors import InkwireError
3
+ def authorize(auth_header: str | None, api_keys: list[str]) -> str:
4
+ token = auth_header[7:] if auth_header and auth_header.startswith("Bearer ") else ""
5
+ for k in api_keys:
6
+ if hmac.compare_digest(k, token):
7
+ return k
8
+ raise InkwireError("unauthorized", "missing or invalid API key")
@@ -0,0 +1,7 @@
1
+ HTTP = {"invalid_payload": 400, "unauthorized": 401, "conflict": 409, "rate_limited": 429, "internal": 500}
2
+ class InkwireError(Exception):
3
+ def __init__(self, code: str, message: str):
4
+ super().__init__(message)
5
+ self.code = code
6
+ self.message = message
7
+ self.http_status = HTTP[code]
@@ -0,0 +1,56 @@
1
+ from datetime import datetime, timezone
2
+ from pydantic import ValidationError
3
+ from .schema import PostInput
4
+ from .auth import authorize
5
+ from .render import render_markdown, slugify
6
+ from .errors import InkwireError
7
+ HEADERS = {"Inkwire-Version": "1"}
8
+
9
+ MAX_SLUG_LENGTH = 255
10
+
11
+ async def _dedupe_slug(store, key, base):
12
+ slug, n = base, 1
13
+ while await store.find_by_slug(key, slug):
14
+ n += 1
15
+ suffix = f"-{n}"
16
+ slug = base[:MAX_SLUG_LENGTH - len(suffix)] + suffix
17
+ return slug
18
+
19
+ async def handle_post(auth_header, raw_body, api_keys, store):
20
+ try:
21
+ key = authorize(auth_header, api_keys)
22
+ try:
23
+ p = PostInput(**(raw_body or {}))
24
+ p.validate_slug()
25
+ except (ValidationError, ValueError, TypeError) as e:
26
+ raise InkwireError("invalid_payload", str(e).splitlines()[0])
27
+ if p.slug:
28
+ owner = await store.find_by_slug(key, p.slug)
29
+ if owner and owner["external_id"] != p.external_id:
30
+ raise InkwireError("conflict", f"slug '{p.slug}' is taken")
31
+ slug = p.slug
32
+ else:
33
+ existing = await store.find_by_external_id(key, p.external_id)
34
+ slug = existing["slug"] if existing else await _dedupe_slug(store, key, slugify(p.title))
35
+ html = render_markdown(p.markdown)
36
+ seo = {
37
+ "title": p.seo.title if p.seo and p.seo.title is not None else p.title,
38
+ "description": p.seo.description if p.seo and p.seo.description is not None else (p.excerpt or p.title),
39
+ "image_url": p.seo.image_url if p.seo and p.seo.image_url is not None else p.cover_image_url,
40
+ "noindex": p.seo.noindex if p.seo else False,
41
+ }
42
+ result = await store.upsert(key, {
43
+ "external_id": p.external_id, "title": p.title, "html": html, "markdown": p.markdown,
44
+ "slug": slug,
45
+ "excerpt": p.excerpt, "tags": p.tags, "cover_image_url": p.cover_image_url,
46
+ "canonical_url": p.canonical_url, "seo": seo,
47
+ "author": p.author.model_dump() if p.author else None,
48
+ "status": p.status,
49
+ "published_at": p.published_at or datetime.now(timezone.utc).isoformat(),
50
+ })
51
+ return 200, {"id": result["id"], "external_id": p.external_id, "url": result["url"],
52
+ "slug": result["slug"], "status": p.status, "created": result["created"]}, HEADERS
53
+ except InkwireError as e:
54
+ return e.http_status, {"error": {"code": e.code, "message": e.message}}, HEADERS
55
+ except Exception:
56
+ return 500, {"error": {"code": "internal", "message": "unexpected error"}}, HEADERS
@@ -0,0 +1,22 @@
1
+ import re
2
+ import markdown as md
3
+ import nh3
4
+ # Canonical allowlist per SPEC.md "Content safety": sanitize-html's default
5
+ # allowedTags union {img, h1, h2} (h1/h2 already in the default set). Keep in
6
+ # sync with core-ts/src/render.ts.
7
+ ALLOWED_TAGS = {
8
+ "a","abbr","address","article","aside","b","bdi","bdo","blockquote","br",
9
+ "caption","cite","code","col","colgroup","data","dd","dfn","div","dl","dt",
10
+ "em","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header",
11
+ "hgroup","hr","i","img","kbd","li","main","mark","menu","nav","ol","p",
12
+ "pre","q","rb","rp","rt","rtc","ruby","s","samp","section","small","span",
13
+ "strong","sub","sup","table","tbody","td","tfoot","th","thead","time","tr",
14
+ "u","ul","var","wbr",
15
+ }
16
+ ALLOWED_ATTRS = {"a": {"href", "name", "rel"}, "img": {"src", "alt", "title"}}
17
+ def render_markdown(text: str) -> str:
18
+ raw = md.markdown(text, extensions=["extra"])
19
+ return nh3.clean(raw, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS, url_schemes={"http","https","mailto"}, link_rel=None)
20
+ def slugify(s: str) -> str:
21
+ out = re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")[:255]
22
+ return out or "post"
@@ -0,0 +1,89 @@
1
+ import re
2
+ from datetime import datetime
3
+ from typing import Annotated, Literal, Optional
4
+ from pydantic import BaseModel, Field, EmailStr, ValidationError, field_validator, AnyUrl, TypeAdapter, StrictBool
5
+ SLUG = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
6
+ HTTP_URL = re.compile(r"^https?://")
7
+ DATE_TIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
8
+ _URL_ADAPTER = TypeAdapter(AnyUrl)
9
+ class Author(BaseModel):
10
+ model_config = {"extra": "forbid"}
11
+ name: Optional[str] = None
12
+ email: Optional[EmailStr] = None
13
+ class Seo(BaseModel):
14
+ model_config = {"extra": "forbid"}
15
+ title: Optional[str] = Field(default=None, min_length=1, max_length=512)
16
+ description: Optional[str] = Field(default=None, min_length=1, max_length=1024)
17
+ image_url: Optional[str] = None
18
+ noindex: StrictBool = False
19
+
20
+ @field_validator("title", "description", "image_url", mode="before")
21
+ @classmethod
22
+ def reject_null_values(cls, v):
23
+ if v is None:
24
+ raise ValueError("SEO overrides cannot be null")
25
+ return v
26
+
27
+ @field_validator("image_url")
28
+ @classmethod
29
+ def check_image_url(cls, v):
30
+ if v is None:
31
+ return v
32
+ if not HTTP_URL.match(v):
33
+ raise ValueError("must be an http(s) URL")
34
+ try:
35
+ _URL_ADAPTER.validate_python(v)
36
+ except ValidationError:
37
+ raise ValueError("must be a valid URL")
38
+ return v
39
+ class PostInput(BaseModel):
40
+ model_config = {"extra": "forbid"}
41
+ external_id: str = Field(min_length=1, max_length=255)
42
+ title: str = Field(min_length=1, max_length=512)
43
+ markdown: str = Field(min_length=1)
44
+ slug: Optional[str] = Field(default=None, max_length=255)
45
+ excerpt: Optional[str] = Field(default=None, max_length=1024)
46
+ tags: Optional[list[Annotated[str, Field(max_length=64)]]] = Field(default=None, max_length=50)
47
+ cover_image_url: Optional[str] = None
48
+ canonical_url: Optional[str] = None
49
+ seo: Optional[Seo] = None
50
+ author: Optional[Author] = None
51
+ status: Literal["draft", "published"] = "draft"
52
+ published_at: Optional[str] = None
53
+
54
+ @field_validator("seo", mode="before")
55
+ @classmethod
56
+ def reject_null_seo(cls, v):
57
+ if v is None:
58
+ raise ValueError("seo must be an object")
59
+ return v
60
+
61
+ @field_validator("cover_image_url", "canonical_url")
62
+ @classmethod
63
+ def check_http_url(cls, v):
64
+ if v is None:
65
+ return v
66
+ if not HTTP_URL.match(v):
67
+ raise ValueError("must be an http(s) URL")
68
+ try:
69
+ _URL_ADAPTER.validate_python(v)
70
+ except ValidationError:
71
+ raise ValueError("must be a valid URL")
72
+ return v
73
+
74
+ @field_validator("published_at")
75
+ @classmethod
76
+ def check_published_at(cls, v):
77
+ if v is None:
78
+ return v
79
+ try:
80
+ datetime.fromisoformat(v.replace("Z", "+00:00"))
81
+ except ValueError:
82
+ raise ValueError("published_at must be an ISO 8601 date-time string")
83
+ if not DATE_TIME.match(v):
84
+ raise ValueError("published_at must be an RFC3339 date-time with a time component and Z/offset")
85
+ return v
86
+
87
+ def validate_slug(self):
88
+ if self.slug is not None and not SLUG.match(self.slug):
89
+ raise ValueError("slug must be kebab-case")
@@ -0,0 +1,25 @@
1
+ from typing import Protocol, Optional, TypedDict
2
+ class StoredPost(TypedDict):
3
+ id: str; slug: str; url: str; external_id: str
4
+ class UpsertResult(TypedDict):
5
+ id: str; url: str; slug: str; created: bool
6
+ class PostStore(Protocol):
7
+ async def find_by_external_id(self, key: str, external_id: str) -> Optional[StoredPost]: ...
8
+ async def find_by_slug(self, key: str, slug: str) -> Optional[StoredPost]: ...
9
+ async def upsert(self, key: str, post: dict) -> UpsertResult: ...
10
+ class MemoryStore:
11
+ def __init__(self): self._by_ext = {}; self._by_slug = {}; self._seq = 0
12
+ def _k(self, key, i): return f"{key}::{i}"
13
+ async def find_by_external_id(self, key, external_id):
14
+ return self._by_ext.get(self._k(key, external_id))
15
+ async def find_by_slug(self, key, slug):
16
+ return self._by_slug.get(self._k(key, slug))
17
+ async def upsert(self, key, post):
18
+ existing = self._by_ext.get(self._k(key, post["external_id"]))
19
+ if existing: pid = existing["id"]
20
+ else: self._seq += 1; pid = str(self._seq)
21
+ slug = post["slug"]; url = f"https://demo.local/blog/{slug}"
22
+ rec = {"id": pid, "slug": slug, "url": url, "external_id": post["external_id"]}
23
+ self._by_ext[self._k(key, post["external_id"])] = rec
24
+ self._by_slug[self._k(key, slug)] = rec
25
+ return {"id": pid, "url": url, "slug": slug, "created": existing is None}
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.4
2
+ Name: inkwire-receiver-core
3
+ Version: 0.1.0
4
+ Summary: Shared Python core for building an Inkwire blog-post receiver.
5
+ Author: Isaac Gounton
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/etugrand/inkwire
8
+ Project-URL: Documentation, https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pydantic>=2.9
13
+ Requires-Dist: markdown>=3.7
14
+ Requires-Dist: nh3>=0.2.18
15
+ Requires-Dist: email-validator>=2.0
16
+ Provides-Extra: fastapi
17
+ Requires-Dist: fastapi>=0.115; extra == "fastapi"
18
+ Provides-Extra: dev
19
+ Requires-Dist: fastapi>=0.115; extra == "dev"
20
+ Requires-Dist: pytest>=8.3; extra == "dev"
21
+ Requires-Dist: httpx>=0.27; extra == "dev"
22
+ Requires-Dist: uvicorn>=0.30; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # inkwire-receiver-core
26
+
27
+ Shared Python core for building an [Inkwire](https://github.com/etugrand/inkwire)
28
+ receiver. It validates incoming posts, derives SEO metadata, safely renders
29
+ Markdown, resolves slugs, and upserts through a storage interface you provide.
30
+
31
+ ```bash
32
+ pip install "inkwire-receiver-core[fastapi]"
33
+ ```
34
+
35
+ ```python
36
+ from fastapi import FastAPI, Request
37
+ from fastapi.responses import JSONResponse
38
+ from inkwire_receiver import MemoryStore, handle_post
39
+
40
+ app = FastAPI()
41
+ store = MemoryStore() # Replace with your database-backed store.
42
+
43
+
44
+ @app.post("/api/posts")
45
+ async def create_post(request: Request):
46
+ try:
47
+ body = await request.json()
48
+ except Exception:
49
+ body = None
50
+
51
+ status, response, headers = await handle_post(
52
+ request.headers.get("authorization"),
53
+ body,
54
+ ["your-api-key"],
55
+ store,
56
+ )
57
+ return JSONResponse(status_code=status, content=response, headers=headers)
58
+ ```
59
+
60
+ `MemoryStore` is intended for local development and tests. Production sites
61
+ should provide an asynchronous store implementing `find_by_external_id`,
62
+ `find_by_slug`, and `upsert`. See the
63
+ [protocol specification](https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md)
64
+ for the complete wire and storage semantics.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ inkwire_receiver/__init__.py
5
+ inkwire_receiver/auth.py
6
+ inkwire_receiver/errors.py
7
+ inkwire_receiver/handle.py
8
+ inkwire_receiver/render.py
9
+ inkwire_receiver/schema.py
10
+ inkwire_receiver/store.py
11
+ inkwire_receiver_core.egg-info/PKG-INFO
12
+ inkwire_receiver_core.egg-info/SOURCES.txt
13
+ inkwire_receiver_core.egg-info/dependency_links.txt
14
+ inkwire_receiver_core.egg-info/requires.txt
15
+ inkwire_receiver_core.egg-info/top_level.txt
16
+ tests/test_receiver.py
@@ -0,0 +1,13 @@
1
+ pydantic>=2.9
2
+ markdown>=3.7
3
+ nh3>=0.2.18
4
+ email-validator>=2.0
5
+
6
+ [dev]
7
+ fastapi>=0.115
8
+ pytest>=8.3
9
+ httpx>=0.27
10
+ uvicorn>=0.30
11
+
12
+ [fastapi]
13
+ fastapi>=0.115
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "inkwire-receiver-core"
3
+ version = "0.1.0"
4
+ description = "Shared Python core for building an Inkwire blog-post receiver."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ authors = [{ name = "Isaac Gounton" }]
8
+ requires-python = ">=3.11"
9
+ dependencies = ["pydantic>=2.9", "markdown>=3.7", "nh3>=0.2.18", "email-validator>=2.0"]
10
+
11
+ [project.urls]
12
+ Repository = "https://github.com/etugrand/inkwire"
13
+ Documentation = "https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md"
14
+
15
+ [project.optional-dependencies]
16
+ fastapi = ["fastapi>=0.115"]
17
+ dev = ["fastapi>=0.115", "pytest>=8.3", "httpx>=0.27", "uvicorn>=0.30"]
18
+
19
+ [build-system]
20
+ requires = ["setuptools>=77"]
21
+ build-backend = "setuptools.build_meta"
22
+
23
+ [tool.setuptools.packages.find]
24
+ include = ["inkwire_receiver*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,126 @@
1
+ from fastapi.testclient import TestClient
2
+ import os
3
+ os.environ["INKWIRE_API_KEYS"] = "secret-key"
4
+ from app import app
5
+ from inkwire_receiver.render import render_markdown
6
+ from inkwire_receiver.handle import handle_post
7
+ from inkwire_receiver.store import MemoryStore
8
+ import asyncio
9
+
10
+ client = TestClient(app)
11
+ AUTH = {"Authorization": "Bearer secret-key"}
12
+
13
+ def test_render_strips_script():
14
+ html = render_markdown("Hi\n\n<script>alert(1)</script>")
15
+ assert "<script>" not in html
16
+
17
+ def test_create_published():
18
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "a", "title": "T", "markdown": "# H", "status": "published"})
19
+ assert r.status_code == 200
20
+ assert r.headers["inkwire-version"] == "1"
21
+ assert r.json()["created"] is True and r.json()["status"] == "published"
22
+
23
+ def test_upsert():
24
+ client.post("/api/posts", headers=AUTH, json={"external_id": "b", "title": "One", "markdown": "x"})
25
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "b", "title": "Two", "markdown": "x"})
26
+ assert r.json()["created"] is False
27
+
28
+ def test_default_draft():
29
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "c", "title": "T", "markdown": "x"})
30
+ assert r.json()["status"] == "draft"
31
+
32
+ def test_missing_title_400():
33
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "d", "markdown": "x"})
34
+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_payload"
35
+
36
+ def test_bad_auth_401():
37
+ r = client.post("/api/posts", headers={"Authorization": "Bearer nope"}, json={"external_id": "e", "title": "T", "markdown": "x"})
38
+ assert r.status_code == 401 and r.json()["error"]["code"] == "unauthorized"
39
+
40
+ def test_slug_conflict_409():
41
+ client.post("/api/posts", headers=AUTH, json={"external_id": "owner", "title": "O", "markdown": "x", "slug": "taken"})
42
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "other", "title": "X", "markdown": "x", "slug": "taken"})
43
+ assert r.status_code == 409 and r.json()["error"]["code"] == "conflict"
44
+
45
+ def test_non_object_body_400():
46
+ r = client.post("/api/posts", headers=AUTH, json=[1, 2, 3])
47
+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_payload"
48
+
49
+ def test_too_many_tags_400():
50
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "f", "title": "T", "markdown": "x", "tags": [f"t{i}" for i in range(51)]})
51
+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_payload"
52
+
53
+ def test_tag_too_long_400():
54
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "g", "title": "T", "markdown": "x", "tags": ["x" * 65]})
55
+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_payload"
56
+
57
+ def test_bad_published_at_400():
58
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "h", "title": "T", "markdown": "x", "published_at": "not-a-date-at-all"})
59
+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_payload"
60
+
61
+ def test_author_extra_field_400():
62
+ r = client.post("/api/posts", headers=AUTH, json={"external_id": "i", "title": "T", "markdown": "x", "author": {"name": "A", "unexpected": "nope"}})
63
+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_payload"
64
+
65
+ def test_dedupe_slug_stays_within_length_cap():
66
+ long_title = "a" * 300
67
+ first = client.post("/api/posts", headers=AUTH, json={"external_id": "long-1", "title": long_title, "markdown": "x"})
68
+ second = client.post("/api/posts", headers=AUTH, json={"external_id": "long-2", "title": long_title, "markdown": "x"})
69
+ first_slug, second_slug = first.json()["slug"], second.json()["slug"]
70
+ assert len(first_slug) == 255
71
+ assert len(second_slug) <= 255
72
+ assert second_slug != first_slug
73
+
74
+ class CapturingStore(MemoryStore):
75
+ captured = None
76
+
77
+ async def upsert(self, key, post):
78
+ self.captured = post
79
+ return await super().upsert(key, post)
80
+
81
+ def test_derives_effective_seo_metadata():
82
+ store = CapturingStore()
83
+ status, _, _ = asyncio.run(handle_post("Bearer secret-key", {
84
+ "external_id": "seo-derived", "title": "Post title", "markdown": "x",
85
+ "excerpt": "Post excerpt", "cover_image_url": "https://images.test/cover.jpg",
86
+ }, ["secret-key"], store))
87
+ assert status == 200
88
+ assert store.captured["seo"] == {
89
+ "title": "Post title", "description": "Post excerpt",
90
+ "image_url": "https://images.test/cover.jpg", "noindex": False,
91
+ }
92
+
93
+ def test_applies_seo_overrides_independently():
94
+ store = CapturingStore()
95
+ status, _, _ = asyncio.run(handle_post("Bearer secret-key", {
96
+ "external_id": "seo-overrides", "title": "Post title", "markdown": "x",
97
+ "excerpt": "Post excerpt", "cover_image_url": "https://images.test/cover.jpg",
98
+ "seo": {"title": "Search title", "image_url": "https://images.test/social.jpg", "noindex": True},
99
+ }, ["secret-key"], store))
100
+ assert status == 200
101
+ assert store.captured["seo"] == {
102
+ "title": "Search title", "description": "Post excerpt",
103
+ "image_url": "https://images.test/social.jpg", "noindex": True,
104
+ }
105
+
106
+ def test_invalid_nested_seo_400():
107
+ unknown = client.post("/api/posts", headers=AUTH, json={
108
+ "external_id": "seo-invalid-1", "title": "T", "markdown": "x", "seo": {"keywords": ["x"]},
109
+ })
110
+ unsafe = client.post("/api/posts", headers=AUTH, json={
111
+ "external_id": "seo-invalid-2", "title": "T", "markdown": "x", "seo": {"image_url": "javascript:alert(1)"},
112
+ })
113
+ null = client.post("/api/posts", headers=AUTH, json={
114
+ "external_id": "seo-invalid-3", "title": "T", "markdown": "x", "seo": None,
115
+ })
116
+ nested_null = client.post("/api/posts", headers=AUTH, json={
117
+ "external_id": "seo-invalid-4", "title": "T", "markdown": "x", "seo": {"title": None},
118
+ })
119
+ coerced_bool = client.post("/api/posts", headers=AUTH, json={
120
+ "external_id": "seo-invalid-5", "title": "T", "markdown": "x", "seo": {"noindex": "false"},
121
+ })
122
+ assert unknown.status_code == 400
123
+ assert unsafe.status_code == 400
124
+ assert null.status_code == 400
125
+ assert nested_null.status_code == 400
126
+ assert coerced_bool.status_code == 400