inkwire-receiver-core 0.1.0__py3-none-any.whl

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,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,12 @@
1
+ inkwire_receiver/__init__.py,sha256=DjuAX-u6WnUAH_Xw9041g_8ly8YuP5nG6-O9U4PS0wQ,185
2
+ inkwire_receiver/auth.py,sha256=AIUNAuS2rlFZa84SY1mpTulwx4OiwUW231HDnoPX7Qs,357
3
+ inkwire_receiver/errors.py,sha256=VWdyIYF23czqaOZR7pAwOvCzcTQbQaxFC1ug37bCfXU,316
4
+ inkwire_receiver/handle.py,sha256=F_7TBJAowzPEt75JPZvUFqfXW_ZDcL1yJYa6emCAcEQ,2652
5
+ inkwire_receiver/render.py,sha256=a2vp2tj30pGNpvQRiT75VjB-xxqtER5X9IVtMnzcXUs,1161
6
+ inkwire_receiver/schema.py,sha256=BFinqJHn77TlFpBFW8u2W6H2E8UgG3vV6tobagrH-D0,3338
7
+ inkwire_receiver/store.py,sha256=7fxszhykdUxZKvYejZJdP8swROhz-N53e7MuJCdt98w,1396
8
+ inkwire_receiver_core-0.1.0.dist-info/licenses/LICENSE,sha256=TyRJbYVXTzP0x9go0Flgvy_CWRL4Kyd0_m3QmtkcpMU,1070
9
+ inkwire_receiver_core-0.1.0.dist-info/METADATA,sha256=yyvYnF1owekK5NXOxRa8-yCs_3aPciPAjMrC0jJxD7U,2104
10
+ inkwire_receiver_core-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
11
+ inkwire_receiver_core-0.1.0.dist-info/top_level.txt,sha256=qW-w3MlCG_qPiofaz-jTQ2PB7njevCvfO8IFoboCVSo,17
12
+ inkwire_receiver_core-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ inkwire_receiver