inkwire-receiver-core 0.1.0
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.
- package/README.md +25 -0
- package/dist/__tests__/handle.test.d.ts +1 -0
- package/dist/__tests__/handle.test.js +44 -0
- package/dist/__tests__/render.test.d.ts +1 -0
- package/dist/__tests__/render.test.js +17 -0
- package/dist/auth.d.ts +1 -0
- package/dist/auth.js +13 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +11 -0
- package/dist/handle.d.ts +12 -0
- package/dist/handle.js +49 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/render.d.ts +2 -0
- package/dist/render.js +15 -0
- package/dist/schema.d.ts +54 -0
- package/dist/schema.js +15 -0
- package/dist/store.d.ts +47 -0
- package/dist/store.js +18 -0
- package/package.json +12 -0
package/README.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# inkwire-receiver-core
|
|
2
|
+
|
|
3
|
+
Shared TypeScript core for building an [Inkwire](https://github.com/etugrand/inkwire) receiver: validate the incoming payload against the frozen schema, render+sanitize markdown to HTML, and upsert by `external_id` against a `PostStore` you provide.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { handlePost, MemoryStore } from "inkwire-receiver-core";
|
|
7
|
+
|
|
8
|
+
const store = new MemoryStore(); // or your own PostStore-backed implementation
|
|
9
|
+
const { status, body, headers } = await handlePost({
|
|
10
|
+
authHeader: req.headers.get("authorization"),
|
|
11
|
+
rawBody: await req.json(),
|
|
12
|
+
apiKeys: ["your-api-key"],
|
|
13
|
+
store,
|
|
14
|
+
});
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
This package is the shared logic behind the [Express](https://github.com/etugrand/inkwire/tree/master/inkwire/receivers/node-express) and [Next.js](https://github.com/etugrand/inkwire/tree/master/inkwire/receivers/nextjs) reference receivers — see either for a full adapter example, and the [protocol spec](https://github.com/etugrand/inkwire/blob/master/inkwire/SPEC.md) for the wire contract `handlePost` implements.
|
|
18
|
+
|
|
19
|
+
## Exports
|
|
20
|
+
|
|
21
|
+
- `handlePost(input)` — the whole request lifecycle: auth, validation, slugging, sanitization, store upsert.
|
|
22
|
+
- `type PostStore` — the interface your storage backend must implement (`findByExternalId`, `findBySlug`, `upsert`).
|
|
23
|
+
- `MemoryStore` — an in-memory `PostStore` for local dev/testing.
|
|
24
|
+
- `renderMarkdown`, `slugify` — the sanitization and slug-generation helpers `handlePost` uses internally.
|
|
25
|
+
- `InkwireError` — typed error class mapping to the protocol's error codes.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { it, expect, beforeEach } from "vitest";
|
|
2
|
+
import { handlePost } from "../handle";
|
|
3
|
+
import { MemoryStore } from "../store";
|
|
4
|
+
let store;
|
|
5
|
+
const keys = ["secret-key"];
|
|
6
|
+
const auth = "Bearer secret-key";
|
|
7
|
+
beforeEach(() => { store = new MemoryStore(); });
|
|
8
|
+
it("creates a published post", async () => {
|
|
9
|
+
const r = await handlePost({ authHeader: auth, apiKeys: keys, store,
|
|
10
|
+
rawBody: { external_id: "a", title: "T", markdown: "# H", status: "published" } });
|
|
11
|
+
expect(r.status).toBe(200);
|
|
12
|
+
expect(r.body).toMatchObject({ created: true, status: "published" });
|
|
13
|
+
expect(r.headers["Inkwire-Version"]).toBe("1");
|
|
14
|
+
});
|
|
15
|
+
it("upserts on external_id", async () => {
|
|
16
|
+
const base = { external_id: "a", markdown: "x" };
|
|
17
|
+
await handlePost({ authHeader: auth, apiKeys: keys, store, rawBody: { ...base, title: "One" } });
|
|
18
|
+
const r = await handlePost({ authHeader: auth, apiKeys: keys, store, rawBody: { ...base, title: "Two" } });
|
|
19
|
+
expect(r.body).toMatchObject({ created: false });
|
|
20
|
+
});
|
|
21
|
+
it("defaults status to draft", async () => {
|
|
22
|
+
const r = await handlePost({ authHeader: auth, apiKeys: keys, store,
|
|
23
|
+
rawBody: { external_id: "b", title: "T", markdown: "x" } });
|
|
24
|
+
expect(r.body).toMatchObject({ status: "draft" });
|
|
25
|
+
});
|
|
26
|
+
it("rejects missing title with 400 invalid_payload", async () => {
|
|
27
|
+
const r = await handlePost({ authHeader: auth, apiKeys: keys, store, rawBody: { external_id: "c", markdown: "x" } });
|
|
28
|
+
expect(r.status).toBe(400);
|
|
29
|
+
expect(r.body.error.code).toBe("invalid_payload");
|
|
30
|
+
});
|
|
31
|
+
it("rejects bad auth with 401", async () => {
|
|
32
|
+
const r = await handlePost({ authHeader: "Bearer nope", apiKeys: keys, store,
|
|
33
|
+
rawBody: { external_id: "d", title: "T", markdown: "x" } });
|
|
34
|
+
expect(r.status).toBe(401);
|
|
35
|
+
expect(r.body.error.code).toBe("unauthorized");
|
|
36
|
+
});
|
|
37
|
+
it("409 on explicit slug owned by a different external_id", async () => {
|
|
38
|
+
await handlePost({ authHeader: auth, apiKeys: keys, store,
|
|
39
|
+
rawBody: { external_id: "owner", title: "O", markdown: "x", slug: "taken" } });
|
|
40
|
+
const r = await handlePost({ authHeader: auth, apiKeys: keys, store,
|
|
41
|
+
rawBody: { external_id: "other", title: "X", markdown: "x", slug: "taken" } });
|
|
42
|
+
expect(r.status).toBe(409);
|
|
43
|
+
expect(r.body.error.code).toBe("conflict");
|
|
44
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { renderMarkdown } from "../render";
|
|
3
|
+
describe("renderMarkdown", () => {
|
|
4
|
+
it("renders markdown to html", () => {
|
|
5
|
+
expect(renderMarkdown("# Hi")).toContain("<h1>Hi</h1>");
|
|
6
|
+
});
|
|
7
|
+
it("strips script tags and their contents", () => {
|
|
8
|
+
const html = renderMarkdown("Hi\n\n<script>alert(1)</script>");
|
|
9
|
+
expect(html).not.toContain("<script>");
|
|
10
|
+
expect(html).not.toContain("alert(1)");
|
|
11
|
+
});
|
|
12
|
+
it("strips event handlers and javascript: urls", () => {
|
|
13
|
+
const html = renderMarkdown('<a href="javascript:alert(1)" onclick="x()">z</a>');
|
|
14
|
+
expect(html).not.toContain("onclick");
|
|
15
|
+
expect(html).not.toContain("javascript:");
|
|
16
|
+
});
|
|
17
|
+
});
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function authorize(authHeader: string | undefined, apiKeys: string[]): string;
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { InkwireError } from "./errors";
|
|
3
|
+
function eq(a, b) {
|
|
4
|
+
const ab = Buffer.from(a), bb = Buffer.from(b);
|
|
5
|
+
return ab.length === bb.length && timingSafeEqual(ab, bb);
|
|
6
|
+
}
|
|
7
|
+
export function authorize(authHeader, apiKeys) {
|
|
8
|
+
const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
|
|
9
|
+
const match = apiKeys.find((k) => eq(k, token));
|
|
10
|
+
if (!match)
|
|
11
|
+
throw new InkwireError("unauthorized", "missing or invalid API key");
|
|
12
|
+
return match;
|
|
13
|
+
}
|
package/dist/errors.d.ts
ADDED
package/dist/errors.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const HTTP = {
|
|
2
|
+
invalid_payload: 400, unauthorized: 401, conflict: 409, rate_limited: 429, internal: 500,
|
|
3
|
+
};
|
|
4
|
+
export class InkwireError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
get httpStatus() { return HTTP[this.code]; }
|
|
11
|
+
}
|
package/dist/handle.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { PostStore } from "./store";
|
|
2
|
+
export type { PostStore } from "./store";
|
|
3
|
+
export declare function handlePost(input: {
|
|
4
|
+
authHeader?: string;
|
|
5
|
+
rawBody: unknown;
|
|
6
|
+
apiKeys: string[];
|
|
7
|
+
store: PostStore;
|
|
8
|
+
}): Promise<{
|
|
9
|
+
status: number;
|
|
10
|
+
body: object;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
}>;
|
package/dist/handle.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { PostInput } from "./schema";
|
|
2
|
+
import { authorize } from "./auth";
|
|
3
|
+
import { renderMarkdown, slugify } from "./render";
|
|
4
|
+
import { InkwireError } from "./errors";
|
|
5
|
+
const HEADERS = { "Inkwire-Version": "1", "content-type": "application/json" };
|
|
6
|
+
export async function handlePost(input) {
|
|
7
|
+
try {
|
|
8
|
+
const key = authorize(input.authHeader, input.apiKeys);
|
|
9
|
+
const parsed = PostInput.safeParse(input.rawBody);
|
|
10
|
+
if (!parsed.success) {
|
|
11
|
+
const first = parsed.error.issues[0];
|
|
12
|
+
throw new InkwireError("invalid_payload", `${first.path.join(".") || "body"}: ${first.message}`);
|
|
13
|
+
}
|
|
14
|
+
const p = parsed.data;
|
|
15
|
+
// Slug resolution + explicit-collision guard.
|
|
16
|
+
let slug;
|
|
17
|
+
if (p.slug) {
|
|
18
|
+
const owner = await input.store.findBySlug(key, p.slug);
|
|
19
|
+
if (owner && owner.external_id !== p.external_id)
|
|
20
|
+
throw new InkwireError("conflict", `slug '${p.slug}' is taken`);
|
|
21
|
+
slug = p.slug;
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
const existing = await input.store.findByExternalId(key, p.external_id);
|
|
25
|
+
slug = existing?.slug ?? await dedupeSlug(input.store, key, slugify(p.title));
|
|
26
|
+
}
|
|
27
|
+
const html = renderMarkdown(p.markdown);
|
|
28
|
+
const result = await input.store.upsert(key, {
|
|
29
|
+
external_id: p.external_id, title: p.title, html, markdown: p.markdown, slug,
|
|
30
|
+
excerpt: p.excerpt, tags: p.tags, cover_image_url: p.cover_image_url,
|
|
31
|
+
canonical_url: p.canonical_url, author: p.author, status: p.status,
|
|
32
|
+
published_at: p.published_at ?? new Date().toISOString(),
|
|
33
|
+
});
|
|
34
|
+
return { status: 200, headers: HEADERS, body: {
|
|
35
|
+
id: result.id, external_id: p.external_id, url: result.url,
|
|
36
|
+
slug: result.slug, status: p.status, created: result.created,
|
|
37
|
+
} };
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
const e = err instanceof InkwireError ? err : new InkwireError("internal", "unexpected error");
|
|
41
|
+
return { status: e.httpStatus, headers: HEADERS, body: { error: { code: e.code, message: e.message } } };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function dedupeSlug(store, key, base) {
|
|
45
|
+
let slug = base, n = 1;
|
|
46
|
+
while (await store.findBySlug(key, slug))
|
|
47
|
+
slug = `${base}-${++n}`;
|
|
48
|
+
return slug;
|
|
49
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/render.d.ts
ADDED
package/dist/render.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import MarkdownIt from "markdown-it";
|
|
2
|
+
import sanitizeHtml from "sanitize-html";
|
|
3
|
+
const md = new MarkdownIt({ html: true, linkify: true });
|
|
4
|
+
export function renderMarkdown(markdown) {
|
|
5
|
+
const raw = md.render(markdown);
|
|
6
|
+
return sanitizeHtml(raw, {
|
|
7
|
+
allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img", "h1", "h2"]),
|
|
8
|
+
allowedAttributes: { a: ["href", "name", "rel"], img: ["src", "alt", "title"] },
|
|
9
|
+
allowedSchemes: ["http", "https", "mailto"],
|
|
10
|
+
disallowedTagsMode: "discard",
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
export function slugify(s) {
|
|
14
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 255) || "post";
|
|
15
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const PostInput: z.ZodObject<{
|
|
3
|
+
external_id: z.ZodString;
|
|
4
|
+
title: z.ZodString;
|
|
5
|
+
markdown: z.ZodString;
|
|
6
|
+
slug: z.ZodOptional<z.ZodString>;
|
|
7
|
+
excerpt: z.ZodOptional<z.ZodString>;
|
|
8
|
+
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
9
|
+
cover_image_url: z.ZodOptional<z.ZodEffects<z.ZodString, string, string>>;
|
|
10
|
+
canonical_url: z.ZodOptional<z.ZodEffects<z.ZodString, string, string>>;
|
|
11
|
+
author: z.ZodOptional<z.ZodObject<{
|
|
12
|
+
name: z.ZodOptional<z.ZodString>;
|
|
13
|
+
email: z.ZodOptional<z.ZodString>;
|
|
14
|
+
}, "strict", z.ZodTypeAny, {
|
|
15
|
+
name?: string | undefined;
|
|
16
|
+
email?: string | undefined;
|
|
17
|
+
}, {
|
|
18
|
+
name?: string | undefined;
|
|
19
|
+
email?: string | undefined;
|
|
20
|
+
}>>;
|
|
21
|
+
status: z.ZodDefault<z.ZodEnum<["draft", "published"]>>;
|
|
22
|
+
published_at: z.ZodOptional<z.ZodString>;
|
|
23
|
+
}, "strict", z.ZodTypeAny, {
|
|
24
|
+
external_id: string;
|
|
25
|
+
title: string;
|
|
26
|
+
markdown: string;
|
|
27
|
+
status: "draft" | "published";
|
|
28
|
+
slug?: string | undefined;
|
|
29
|
+
excerpt?: string | undefined;
|
|
30
|
+
tags?: string[] | undefined;
|
|
31
|
+
cover_image_url?: string | undefined;
|
|
32
|
+
canonical_url?: string | undefined;
|
|
33
|
+
author?: {
|
|
34
|
+
name?: string | undefined;
|
|
35
|
+
email?: string | undefined;
|
|
36
|
+
} | undefined;
|
|
37
|
+
published_at?: string | undefined;
|
|
38
|
+
}, {
|
|
39
|
+
external_id: string;
|
|
40
|
+
title: string;
|
|
41
|
+
markdown: string;
|
|
42
|
+
slug?: string | undefined;
|
|
43
|
+
excerpt?: string | undefined;
|
|
44
|
+
status?: "draft" | "published" | undefined;
|
|
45
|
+
tags?: string[] | undefined;
|
|
46
|
+
cover_image_url?: string | undefined;
|
|
47
|
+
canonical_url?: string | undefined;
|
|
48
|
+
author?: {
|
|
49
|
+
name?: string | undefined;
|
|
50
|
+
email?: string | undefined;
|
|
51
|
+
} | undefined;
|
|
52
|
+
published_at?: string | undefined;
|
|
53
|
+
}>;
|
|
54
|
+
export type PostInput = z.infer<typeof PostInput>;
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const httpUrl = z.string().url().refine((u) => /^https?:\/\//i.test(u), { message: "must be an http(s) URL" });
|
|
3
|
+
export const PostInput = z.object({
|
|
4
|
+
external_id: z.string().min(1).max(255),
|
|
5
|
+
title: z.string().min(1).max(512),
|
|
6
|
+
markdown: z.string().min(1),
|
|
7
|
+
slug: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(255).optional(),
|
|
8
|
+
excerpt: z.string().max(1024).optional(),
|
|
9
|
+
tags: z.array(z.string().max(64)).max(50).optional(),
|
|
10
|
+
cover_image_url: httpUrl.optional(),
|
|
11
|
+
canonical_url: httpUrl.optional(),
|
|
12
|
+
author: z.object({ name: z.string().optional(), email: z.string().email().optional() }).strict().optional(),
|
|
13
|
+
status: z.enum(["draft", "published"]).default("draft"),
|
|
14
|
+
published_at: z.string().datetime({ offset: true }).optional(),
|
|
15
|
+
}).strict();
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export interface StoredPost {
|
|
2
|
+
id: string;
|
|
3
|
+
slug: string;
|
|
4
|
+
url: string;
|
|
5
|
+
external_id: string;
|
|
6
|
+
}
|
|
7
|
+
export interface UpsertInput {
|
|
8
|
+
external_id: string;
|
|
9
|
+
title: string;
|
|
10
|
+
html: string;
|
|
11
|
+
markdown: string;
|
|
12
|
+
slug: string;
|
|
13
|
+
excerpt?: string;
|
|
14
|
+
tags?: string[];
|
|
15
|
+
cover_image_url?: string;
|
|
16
|
+
canonical_url?: string;
|
|
17
|
+
author?: {
|
|
18
|
+
name?: string;
|
|
19
|
+
email?: string;
|
|
20
|
+
};
|
|
21
|
+
status: "draft" | "published";
|
|
22
|
+
published_at: string;
|
|
23
|
+
}
|
|
24
|
+
export interface PostStore {
|
|
25
|
+
findByExternalId(key: string, externalId: string): Promise<StoredPost | null>;
|
|
26
|
+
findBySlug(key: string, slug: string): Promise<StoredPost | null>;
|
|
27
|
+
upsert(key: string, post: UpsertInput): Promise<{
|
|
28
|
+
id: string;
|
|
29
|
+
url: string;
|
|
30
|
+
slug: string;
|
|
31
|
+
created: boolean;
|
|
32
|
+
}>;
|
|
33
|
+
}
|
|
34
|
+
export declare class MemoryStore implements PostStore {
|
|
35
|
+
private byExt;
|
|
36
|
+
private bySlug;
|
|
37
|
+
private seq;
|
|
38
|
+
private k;
|
|
39
|
+
findByExternalId(key: string, externalId: string): Promise<StoredPost | null>;
|
|
40
|
+
findBySlug(key: string, slug: string): Promise<StoredPost | null>;
|
|
41
|
+
upsert(key: string, post: UpsertInput): Promise<{
|
|
42
|
+
id: string;
|
|
43
|
+
url: string;
|
|
44
|
+
slug: string;
|
|
45
|
+
created: boolean;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export class MemoryStore {
|
|
2
|
+
byExt = new Map();
|
|
3
|
+
bySlug = new Map();
|
|
4
|
+
seq = 0;
|
|
5
|
+
k(key, id) { return `${key}::${id}`; }
|
|
6
|
+
async findByExternalId(key, externalId) { return this.byExt.get(this.k(key, externalId)) ?? null; }
|
|
7
|
+
async findBySlug(key, slug) { return this.bySlug.get(this.k(key, slug)) ?? null; }
|
|
8
|
+
async upsert(key, post) {
|
|
9
|
+
const existing = this.byExt.get(this.k(key, post.external_id));
|
|
10
|
+
const id = existing?.id ?? String(++this.seq);
|
|
11
|
+
const slug = post.slug;
|
|
12
|
+
const url = `https://demo.local/blog/${slug}`;
|
|
13
|
+
const rec = { id, slug, url, external_id: post.external_id };
|
|
14
|
+
this.byExt.set(this.k(key, post.external_id), rec);
|
|
15
|
+
this.bySlug.set(this.k(key, slug), rec);
|
|
16
|
+
return { id, url, slug, created: !existing };
|
|
17
|
+
}
|
|
18
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "inkwire-receiver-core", "version": "0.1.0", "type": "module",
|
|
3
|
+
"description": "Shared TS core (validate, render, sanitize, upsert) for building an Inkwire receiver.",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": { "type": "git", "url": "git+https://github.com/etugrand/inkwire.git", "directory": "inkwire/receivers/core-ts" },
|
|
6
|
+
"main": "dist/index.js", "types": "dist/index.d.ts",
|
|
7
|
+
"files": ["dist"],
|
|
8
|
+
"scripts": { "build": "tsc", "test": "vitest run" },
|
|
9
|
+
"dependencies": { "zod": "^3.23.8", "markdown-it": "^14.1.0", "sanitize-html": "^2.13.1" },
|
|
10
|
+
"devDependencies": { "vitest": "^2.1.0", "typescript": "^5.5.0",
|
|
11
|
+
"@types/markdown-it": "^14.1.2", "@types/sanitize-html": "^2.13.0", "@types/node": "^22.5.0" }
|
|
12
|
+
}
|