@senseihq/emaki-posting 0.0.0-stage → 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/src/api.ts ADDED
@@ -0,0 +1,225 @@
1
+ // The desk's HTTP API as plain Web Request → Response, so it runs in any server that speaks fetch (SvelteKit, a
2
+ // Cloudflare Worker, Hono, Next.js route handlers, Bun, Deno). Machines use it: the producing machine stages posts and
3
+ // uploads media; the CI poster reads the approved queue and reports outcomes. People use the desk page, which calls
4
+ // the `desk` actions below from its own form handlers.
5
+ import { channelState, CHANNELS, checkSignature, due, effectiveDates, isChannel, makeNext, sha256, signMedia, validKey, type Channel, type Production, type StagedPost } from './rules.js';
6
+ import type { Caller } from './access.js';
7
+ import type { MediaStore, PostingStore } from './store.js';
8
+
9
+ /** One piece the desk knows about: its slug, its date as built, and (optionally) its kind. */
10
+ export interface Piece { slug: string; date: string; title?: string; video?: 'short' | 'wide' | string }
11
+
12
+ export interface DeskOptions {
13
+ store: PostingStore;
14
+ media: MediaStore;
15
+ /** The pieces in the built site (index.json). */
16
+ pieces: () => Piece[] | Promise<Piece[]>;
17
+ /** Today in the site's time zone (YYYY-MM-DD). */
18
+ today: () => string;
19
+ /** The public link of a piece, for the posts. */
20
+ pieceUrl: (slug: string) => string;
21
+ /** Secret for the short-lived public media links (Instagram fetches media from a URL). Without it, no links. */
22
+ mediaSecret?: string;
23
+ /** Origin the signed media links point at (default: the request's). */
24
+ mediaOrigin?: string;
25
+ /** Path of the signed media route (default /m). */
26
+ mediaPath?: string;
27
+ /** Channels expected for a piece (default: Shorts go everywhere; wide films skip the carousel). */
28
+ channelsFor?: (p: Piece) => Channel[];
29
+ }
30
+
31
+ const TYPES: Record<string, string> = { mp4: 'video/mp4', jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', srt: 'text/plain; charset=utf-8', vtt: 'text/vtt' };
32
+ const MAX = 95 * 1024 * 1024; // under the Workers request-body limit
33
+
34
+ export class HttpError extends Error { constructor(public status: number, message: string) { super(message); } }
35
+ const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
36
+ const fail = (status: number, reason: string): never => { throw new HttpError(status, reason); };
37
+
38
+ export function createDesk(o: DeskOptions) {
39
+ const { store, media } = o;
40
+ const expected = o.channelsFor ?? ((p: Piece) => (p.video === 'short' ? [...CHANNELS] : (['youtube', 'instagram_reel', 'x'] as Channel[])));
41
+ const slugs = async () => new Set((await o.pieces()).map((p) => p.slug));
42
+
43
+ /** The API under the admin prefix: `sub` is the path after it ('queue', 'media/<slug>/<file>', ...). */
44
+ async function api(request: Request, caller: Caller, sub: string): Promise<Response> {
45
+ try {
46
+ const m = request.method;
47
+ if (sub === 'queue' && m === 'GET') return json(await queue(new URL(request.url).origin));
48
+ if (sub === 'posted' && m === 'POST') return json(await posted(caller, await request.json()));
49
+ if (sub === 'stage' && m === 'POST') return json(await stage(caller, await request.json()));
50
+ if (sub === 'production' && m === 'POST') return json(await production(await request.json()));
51
+ if (sub === 'schedule' && m === 'GET') return json(await schedule());
52
+ if (sub === 'requests' && m === 'GET') return json(await openRequests());
53
+ if (sub === 'requests' && m === 'POST') return json(await answerRequest(caller, await request.json()));
54
+ if (sub.startsWith('media/')) {
55
+ const key = sub.slice(6);
56
+ if (m === 'GET') return await getMedia(key);
57
+ if (m === 'PUT') return json(await putMedia(caller, key, request));
58
+ }
59
+ return json({ ok: false, reason: 'Not found' }, 404);
60
+ } catch (e) {
61
+ if (e instanceof HttpError) return json({ ok: false, reason: e.message }, e.status);
62
+ throw e;
63
+ }
64
+ }
65
+
66
+ /** What is approved and due now, with short-lived media links. Empty while posting is paused. */
67
+ async function queue(origin: string) {
68
+ const all = await store.readAll(), t = o.today();
69
+ const planned = new Map(all.schedule.map((s) => [s.slug, s.publish_date]));
70
+ const pieces = await o.pieces();
71
+ const rows = pieces.map((a) => ({
72
+ slug: a.slug, date: a.date, planned: planned.get(a.slug),
73
+ staged: all.staged.filter((s) => s.slug === a.slug), approvals: all.approvals.filter((x) => x.slug === a.slug), posts: all.posts.filter((p) => p.slug === a.slug),
74
+ }));
75
+ const base = o.mediaOrigin || origin;
76
+ return {
77
+ paused: all.paused, today: t,
78
+ items: await Promise.all(due(rows, t, all.paused).map(async (s) => ({
79
+ slug: s.slug, channel: s.channel, content_sha: s.content_sha, post: s.post, article: o.pieceUrl(s.slug),
80
+ video: pieces.find((a) => a.slug === s.slug)?.video ?? 'short',
81
+ media: await Promise.all(s.post.media.map(async (x) => ({ ...x, url: o.mediaSecret ? await signMedia(x.key, o.mediaSecret, base, 3600, Date.now(), o.mediaPath ?? '/m') : null }))),
82
+ }))),
83
+ };
84
+ }
85
+
86
+ async function posted(caller: Caller, b: Record<string, string>) {
87
+ if (!b.slug || !isChannel(b.channel) || !b.content_sha || !['posted', 'dry-run', 'failed'].includes(b.status)) fail(400, 'slug, channel, content_sha and status are required');
88
+ await store.recordPost(caller.id, { slug: b.slug, channel: b.channel as Channel, content_sha: b.content_sha, status: b.status as 'posted', url: b.url, external_id: b.external_id, detail: b.detail?.slice(0, 2000), run: b.run });
89
+ return { ok: true };
90
+ }
91
+
92
+ /** The post for one piece and channel, as it will go out. Every media file must already be uploaded, same sha256. */
93
+ async function stage(caller: Caller, b: { slug: string; channel: string; post: StagedPost }) {
94
+ if (!(await slugs()).has(b.slug)) fail(400, `No piece "${b.slug}" in the index`);
95
+ if (!isChannel(b.channel) || !b.post || !Array.isArray(b.post.media)) fail(400, 'channel and post.media are required');
96
+ for (const x of b.post.media) {
97
+ if (!validKey(x.key) || !x.key.startsWith(`${b.slug}/`)) fail(400, `Bad media key ${x.key}`);
98
+ const head = await media.head(x.key);
99
+ if (!head || head.sha256 !== x.sha256) fail(400, `${x.key} is not uploaded with that sha256`);
100
+ }
101
+ return { ok: true, content_sha: await store.stage(caller.id, b.slug, b.channel as Channel, b.post) };
102
+ }
103
+
104
+ async function production(b: { items: { slug: string; script?: string; status: Production }[] }) {
105
+ const known = await slugs();
106
+ let saved = 0;
107
+ for (const it of b.items ?? []) {
108
+ if (!known.has(it.slug)) continue;
109
+ await store.saveProduction(it.slug, (it.script ?? '').slice(0, 60000) || null, it.status ?? {});
110
+ saved++;
111
+ }
112
+ return { ok: true, saved };
113
+ }
114
+
115
+ /** Dates set on the desk that differ from the build: the schedule job writes them into index.json. */
116
+ async function schedule() {
117
+ const built = new Map((await o.pieces()).map((a) => [a.slug, a.date]));
118
+ return { changes: (await store.readSchedule()).filter((s) => built.has(s.slug) && built.get(s.slug) !== s.publish_date) };
119
+ }
120
+
121
+ async function openRequests() {
122
+ const all = await store.readRequests();
123
+ return { requests: all.filter((r) => !r.parent && r.status !== 'done').map((r) => ({ ...r, thread: all.filter((x) => x.parent === r.id) })) };
124
+ }
125
+
126
+ async function answerRequest(caller: Caller, b: { id: number; reply?: string; status?: string }) {
127
+ const parent = (await store.readRequests()).find((r) => r.id === Number(b.id) && !r.parent);
128
+ if (!parent) fail(404, 'No such request');
129
+ if (b.reply) await store.addRequest(caller.id, parent!.slug, 'note', b.reply, parent!.id);
130
+ if (b.status && ['open', 'working', 'done'].includes(b.status)) await store.setRequestStatus(caller.id, parent!.id, b.status);
131
+ return { ok: true };
132
+ }
133
+
134
+ async function getMedia(key: string) {
135
+ if (!validKey(key)) fail(400, 'Bad key');
136
+ const obj = await media.get(key);
137
+ if (!obj) fail(404, 'Not found');
138
+ return new Response(obj!.body, { headers: { 'content-type': obj!.contentType ?? 'application/octet-stream', 'content-length': String(obj!.size), 'x-content-sha256': obj!.sha256 ?? '' } });
139
+ }
140
+
141
+ async function putMedia(caller: Caller, key: string, request: Request) {
142
+ if (!validKey(key)) fail(400, 'Bad key: <slug>/<file>, lower-case');
143
+ const want = (request.headers.get('x-content-sha256') ?? '').toLowerCase();
144
+ const body = await request.arrayBuffer();
145
+ if (body.byteLength > MAX) fail(413, 'Too large');
146
+ const got = await sha256(body);
147
+ if (!want || got !== want) fail(400, `sha256 mismatch (got ${got})`);
148
+ await media.put(key, body, { contentType: TYPES[key.split('.').pop() ?? ''] ?? 'application/octet-stream', sha256: got });
149
+ await store.audit(caller.id, 'upload', key.split('/')[0], null, `${key} ${got.slice(0, 12)}`);
150
+ return { ok: true, key, sha256: got, bytes: body.byteLength };
151
+ }
152
+
153
+ /** /m/<key>?exp=…&sig=…: one media file, public only with a valid, unexpired signature. The bucket stays private. */
154
+ async function signedMedia(key: string, url: URL): Promise<Response> {
155
+ const notFound = new Response('Not found', { status: 404 });
156
+ if (!o.mediaSecret || !validKey(key)) return notFound;
157
+ if (!(await checkSignature(key, url.searchParams.get('exp') ?? '', url.searchParams.get('sig') ?? '', o.mediaSecret))) return notFound;
158
+ const obj = await media.get(key);
159
+ if (!obj) return notFound;
160
+ return new Response(obj.body, { headers: { 'content-type': obj.contentType ?? 'application/octet-stream', 'content-length': String(obj.size), 'cache-control': 'private, no-store', 'x-robots-tag': 'noindex' } });
161
+ }
162
+
163
+ /** The desk page's data: every piece in date order with each channel's state, production and requests. */
164
+ async function plan() {
165
+ const t = o.today(), all = await store.readAll(), prod = await store.readProduction(), requests = await store.readRequests();
166
+ const pieces = await o.pieces(), dates = effectiveDates(pieces, all.schedule);
167
+ const rows = pieces.map((a) => {
168
+ const date = dates.get(a.slug)!;
169
+ const channels = expected(a).map((c) => {
170
+ const staged = all.staged.find((s) => s.slug === a.slug && s.channel === c);
171
+ const posts = all.posts.filter((p) => p.slug === a.slug && p.channel === c);
172
+ return {
173
+ channel: c, state: channelState(staged, all.approvals.filter((x) => x.slug === a.slug && x.channel === c), posts),
174
+ staged: staged ?? null, url: posts.filter((p) => p.status === 'posted').at(-1)?.url ?? null, last: posts.at(-1) ?? null,
175
+ };
176
+ });
177
+ const p = prod.find((x) => x.slug === a.slug);
178
+ return {
179
+ ...a, date, built: a.date, moved: date !== a.date, live: a.date <= t, channels,
180
+ script: p?.script ?? null, status: p?.status ?? {}, reported: p?.updated_at ?? null,
181
+ requests: requests.filter((r) => r.slug === a.slug && !r.parent).map((r) => ({ ...r, thread: requests.filter((x) => x.parent === r.id) })),
182
+ };
183
+ }).sort((x, y) => x.date.localeCompare(y.date) || x.slug.localeCompare(y.slug));
184
+ return { today: t, paused: all.paused, plan: rows, next: rows.find((r) => r.date >= t && r.channels.some((c) => c.state !== 'posted')) ?? null, audit: await store.recentAudit() };
185
+ }
186
+
187
+ /** What a person does on the desk page. Each returns { ok } or { error } with a status. */
188
+ const desk = {
189
+ plan,
190
+ async approve(who: string, slug: string, items: string[]) {
191
+ let n = 0;
192
+ for (const item of items) { const [c, sha] = item.split(':'); if (isChannel(c) && (await store.approve(who, slug, c, sha))) n++; }
193
+ return n === items.length ? { ok: `Approved ${n}` } : { status: 409, error: `Approved ${n} of ${items.length}: the rest changed since this page loaded. Reload and check again.` };
194
+ },
195
+ async revoke(who: string, slug: string, channel: string) {
196
+ if (!isChannel(channel)) return { status: 400, error: 'Bad channel' };
197
+ await store.revoke(who, slug, channel);
198
+ return { ok: 'Approval withdrawn' };
199
+ },
200
+ async makeNext(who: string, slug: string) {
201
+ const all = await store.readAll();
202
+ const moved = makeNext(effectiveDates(await o.pieces(), all.schedule), slug, o.today());
203
+ if (!moved.size) return { status: 400, error: 'That piece is already next, or already published.' };
204
+ await store.setDates(who, moved, `make next: ${slug}`);
205
+ return { ok: `Moved ${slug} to ${moved.get(slug)}; ${moved.size - 1} other piece(s) moved down one slot.` };
206
+ },
207
+ async request(who: string, slug: string, kind: string, body: string) {
208
+ if (!(await slugs()).has(slug)) return { status: 400, error: 'No such piece' };
209
+ if (!body.trim() && kind !== 'generate') return { status: 400, error: 'Say what to change' };
210
+ await store.addRequest(who, slug, ['generate', 'edit', 'note'].includes(kind) ? kind : 'edit', body.trim() || 'Generate the motion for this piece from its script.');
211
+ return { ok: 'Sent. Replies appear in the thread.' };
212
+ },
213
+ async reply(who: string, id: number, body: string, status?: string) {
214
+ const parent = (await store.readRequests()).find((r) => r.id === id && !r.parent);
215
+ if (!parent) return { status: 404, error: 'No such request' };
216
+ if (body.trim()) await store.addRequest(who, parent.slug, 'note', body.trim(), id);
217
+ if (status) await store.setRequestStatus(who, id, status);
218
+ return { ok: 'Saved' };
219
+ },
220
+ async pause(who: string) { await store.setPaused(who, true); return { ok: 'Posting paused' }; },
221
+ async resume(who: string) { await store.setPaused(who, false); return { ok: 'Posting resumed' }; },
222
+ };
223
+
224
+ return { api, signedMedia, desk, queue };
225
+ }
@@ -0,0 +1,103 @@
1
+ // The desk on Cloudflare: rows in D1 (migrations/ in this package), media in a private R2 bucket. The binding
2
+ // shapes are declared here, so this needs no Cloudflare types package.
3
+ import { contentSha, type ApprovalRow, type AuditRow, type PostRow, type Production, type RequestRow, type StagedRow } from '../rules.js';
4
+ import type { MediaStore, PostingStore } from '../store.js';
5
+
6
+ export interface D1Stmt { bind(...v: unknown[]): D1Stmt; all<T = Record<string, unknown>>(): Promise<{ results: T[] }>; first<T = Record<string, unknown>>(): Promise<T | null>; run(): Promise<unknown> }
7
+ export interface D1 { prepare(sql: string): D1Stmt; batch(s: D1Stmt[]): Promise<unknown> }
8
+ export interface R2Object { body: ReadableStream; size: number; httpMetadata?: { contentType?: string }; customMetadata?: Record<string, string> }
9
+ export interface R2 {
10
+ get(key: string): Promise<R2Object | null>;
11
+ head(key: string): Promise<{ size: number; customMetadata?: Record<string, string> } | null>;
12
+ put(key: string, body: ReadableStream | ArrayBuffer, o?: { httpMetadata?: { contentType?: string }; customMetadata?: Record<string, string> }): Promise<unknown>;
13
+ }
14
+
15
+ const nowIso = () => new Date().toISOString();
16
+ const parse = (r: Record<string, unknown>): StagedRow => ({ ...(r as unknown as StagedRow), post: JSON.parse(String(r.post)) });
17
+
18
+ export function d1Store(db: D1): PostingStore {
19
+ const audit: PostingStore['audit'] = async (actor, action, slug, channel, detail) => {
20
+ await db.prepare('INSERT INTO audit (at, actor, action, slug, channel, detail) VALUES (?, ?, ?, ?, ?, ?)').bind(nowIso(), actor, action, slug ?? null, channel ?? null, detail ?? null).run();
21
+ };
22
+ const readRequests: PostingStore['readRequests'] = (openOnly = false) =>
23
+ db.prepare(`SELECT * FROM requests ${openOnly ? "WHERE parent IS NULL AND status != 'done'" : ''} ORDER BY id`).all<RequestRow>().then((r) => r.results);
24
+ return {
25
+ audit,
26
+ async readAll() {
27
+ const [staged, approvals, posts, settings, schedule] = await Promise.all([
28
+ db.prepare('SELECT * FROM staged').all(),
29
+ db.prepare('SELECT * FROM approvals ORDER BY id').all<ApprovalRow>(),
30
+ db.prepare('SELECT * FROM posts ORDER BY id').all<PostRow>(),
31
+ db.prepare('SELECT key, value FROM settings').all<{ key: string; value: string }>(),
32
+ db.prepare('SELECT slug, publish_date FROM schedule').all<{ slug: string; publish_date: string }>(),
33
+ ]);
34
+ return {
35
+ staged: staged.results.map(parse), approvals: approvals.results, posts: posts.results,
36
+ paused: (settings.results.find((s) => s.key === 'paused')?.value ?? '1') !== '0',
37
+ schedule: schedule.results,
38
+ };
39
+ },
40
+ recentAudit: (n = 40) => db.prepare('SELECT * FROM audit ORDER BY id DESC LIMIT ?').bind(n).all<AuditRow>().then((r) => r.results),
41
+ async stage(actor, slug, channel, post) {
42
+ const sha = await contentSha(channel, post);
43
+ await db.prepare('INSERT INTO staged (slug, channel, post, content_sha, staged_by, staged_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (slug, channel) DO UPDATE SET post = excluded.post, content_sha = excluded.content_sha, staged_by = excluded.staged_by, staged_at = excluded.staged_at')
44
+ .bind(slug, channel, JSON.stringify(post), sha, actor, nowIso()).run();
45
+ await audit(actor, 'stage', slug, channel, sha.slice(0, 12));
46
+ return sha;
47
+ },
48
+ async approve(actor, slug, channel, seen) {
49
+ const row = await db.prepare('SELECT content_sha FROM staged WHERE slug = ? AND channel = ?').bind(slug, channel).first<{ content_sha: string }>();
50
+ if (!row || row.content_sha !== seen) return false;
51
+ await db.prepare('INSERT INTO approvals (slug, channel, content_sha, approved_by, approved_at) VALUES (?, ?, ?, ?, ?)').bind(slug, channel, row.content_sha, actor, nowIso()).run();
52
+ await audit(actor, 'approve', slug, channel, row.content_sha.slice(0, 12));
53
+ return true;
54
+ },
55
+ async revoke(actor, slug, channel) {
56
+ await db.prepare('UPDATE approvals SET revoked_at = ? WHERE slug = ? AND channel = ? AND revoked_at IS NULL').bind(nowIso(), slug, channel).run();
57
+ await audit(actor, 'revoke', slug, channel);
58
+ },
59
+ async setPaused(actor, paused) {
60
+ await db.prepare("INSERT INTO settings (key, value) VALUES ('paused', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").bind(paused ? '1' : '0').run();
61
+ await audit(actor, paused ? 'pause' : 'resume');
62
+ },
63
+ async recordPost(actor, p) {
64
+ await db.prepare('INSERT INTO posts (slug, channel, content_sha, status, url, external_id, detail, run, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
65
+ .bind(p.slug, p.channel, p.content_sha, p.status, p.url ?? null, p.external_id ?? null, p.detail ?? null, p.run ?? null, nowIso()).run();
66
+ await audit(actor, p.status, p.slug, p.channel, p.url ?? p.detail);
67
+ },
68
+ readSchedule: () => db.prepare('SELECT slug, publish_date FROM schedule').all<{ slug: string; publish_date: string }>().then((r) => r.results),
69
+ async setDates(actor, moved, why) {
70
+ if (!moved.size) return;
71
+ const now = nowIso();
72
+ await db.batch([...moved].map(([slug, d]) => db.prepare('INSERT INTO schedule (slug, publish_date, set_by, set_at) VALUES (?, ?, ?, ?) ON CONFLICT (slug) DO UPDATE SET publish_date = excluded.publish_date, set_by = excluded.set_by, set_at = excluded.set_at').bind(slug, d, actor, now)));
73
+ await audit(actor, 'reorder', null, null, `${why}: ${[...moved].map(([s, d]) => `${s}→${d}`).join(', ')}`.slice(0, 1900));
74
+ },
75
+ readProduction: () =>
76
+ db.prepare('SELECT slug, script, status, updated_at FROM production').all<{ slug: string; script: string | null; status: string; updated_at: string }>()
77
+ .then((r) => r.results.map((x) => ({ ...x, status: JSON.parse(x.status) as Production }))),
78
+ async saveProduction(slug, script, status) {
79
+ await db.prepare('INSERT INTO production (slug, script, status, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (slug) DO UPDATE SET script = excluded.script, status = excluded.status, updated_at = excluded.updated_at')
80
+ .bind(slug, script, JSON.stringify(status), nowIso()).run();
81
+ },
82
+ readRequests,
83
+ async addRequest(actor, slug, kind, body, parent = null) {
84
+ await db.prepare('INSERT INTO requests (slug, kind, body, author, at, parent) VALUES (?, ?, ?, ?, ?, ?)').bind(slug, kind, body.slice(0, 4000), actor, nowIso(), parent).run();
85
+ await audit(actor, parent ? 'reply' : `request:${kind}`, slug, null, body.slice(0, 200));
86
+ },
87
+ async setRequestStatus(actor, id, status) {
88
+ await db.prepare('UPDATE requests SET status = ? WHERE id = ?').bind(status, id).run();
89
+ await audit(actor, `request:${status}`, null, null, `#${id}`);
90
+ },
91
+ };
92
+ }
93
+
94
+ export function r2Media(bucket: R2): MediaStore {
95
+ return {
96
+ async get(key) {
97
+ const o = await bucket.get(key);
98
+ return o ? { body: o.body, size: o.size, contentType: o.httpMetadata?.contentType, sha256: o.customMetadata?.sha256 } : null;
99
+ },
100
+ async head(key) { const h = await bucket.head(key); return h ? { size: h.size, sha256: h.customMetadata?.sha256 } : null; },
101
+ async put(key, body, o) { await bucket.put(key, body, { httpMetadata: { contentType: o.contentType }, customMetadata: { sha256: o.sha256 } }); },
102
+ };
103
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ // @senseihq/emaki-posting: the posting desk. Pieces are staged by the machine that renders them, approved by a person
2
+ // for exactly the content staged, and posted by a CI job when their date comes. Framework-free core; adapters in
3
+ // ./cloudflare (D1 + R2) and ./sveltekit (hook + routes).
4
+ export * from './rules.js';
5
+ export * from './access.js';
6
+ export * from './store.js';
7
+ export { createDesk, HttpError, type DeskOptions, type Piece } from './api.js';
package/src/rules.ts ADDED
@@ -0,0 +1,117 @@
1
+ // The posting desk's rules: what is staged, what an approval covers, what may go out and when. Plain functions over
2
+ // plain rows, no storage and no framework (tested in spec/rules.spec.ts). Stores live in ./store.ts and ./cloudflare.
3
+
4
+ export const CHANNELS = ['youtube', 'instagram_reel', 'instagram_carousel', 'x'] as const;
5
+ export type Channel = (typeof CHANNELS)[number];
6
+ export const CHANNEL_NAMES: Record<Channel, string> = { youtube: 'YouTube', instagram_reel: 'Instagram Reel', instagram_carousel: 'Instagram carousel', x: 'X' };
7
+ export const isChannel = (c: string): c is Channel => (CHANNELS as readonly string[]).includes(c);
8
+
9
+ export interface MediaRef { key: string; sha256: string; type: string }
10
+ export interface StagedPost {
11
+ title?: string; description?: string; tags?: string[]; // youtube
12
+ caption?: string; // instagram
13
+ text?: string; thread?: string[]; // x
14
+ short?: boolean; // youtube: a Short (9:16) or a regular video
15
+ media: MediaRef[];
16
+ }
17
+ export interface StagedRow { slug: string; channel: Channel; post: StagedPost; content_sha: string; staged_by: string; staged_at: string }
18
+ export interface ApprovalRow { id: number; slug: string; channel: Channel; content_sha: string; approved_by: string; approved_at: string; revoked_at: string | null }
19
+ export interface PostRow { id: number; slug: string; channel: Channel; content_sha: string; status: 'posted' | 'dry-run' | 'failed'; url: string | null; external_id: string | null; detail: string | null; run: string | null; at: string }
20
+
21
+ const enc = new TextEncoder();
22
+ export async function sha256(data: string | ArrayBuffer): Promise<string> {
23
+ const buf = await crypto.subtle.digest('SHA-256', typeof data === 'string' ? enc.encode(data) : data);
24
+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
25
+ }
26
+ /** JSON with sorted keys, so the same post always fingerprints the same. */
27
+ export function canonical(v: unknown): string {
28
+ if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
29
+ if (v && typeof v === 'object') return `{${Object.keys(v as object).sort().map((k) => `${JSON.stringify(k)}:${canonical((v as Record<string, unknown>)[k])}`).join(',')}}`;
30
+ return JSON.stringify(v ?? null);
31
+ }
32
+ /** The fingerprint an approval is given for: the channel and everything that goes out on it, media by sha256. */
33
+ export const contentSha = (channel: Channel, post: StagedPost) => sha256(canonical({ channel, post }));
34
+
35
+ // ── Rules ────────────────────────────────────────────────────────────────────────────────────────────────
36
+
37
+ export type ChannelState = 'not-staged' | 'awaiting' | 'changed' | 'approved' | 'posted' | 'failed';
38
+ /** Where one article's channel stands. An approval counts only for the exact content now staged. */
39
+ export function channelState(staged: StagedRow | undefined, approvals: ApprovalRow[], posts: PostRow[]): ChannelState {
40
+ if (posts.some((p) => p.status === 'posted')) return 'posted';
41
+ if (!staged) return 'not-staged';
42
+ const live = approvals.filter((a) => !a.revoked_at);
43
+ if (live.some((a) => a.content_sha === staged.content_sha)) {
44
+ const last = posts.filter((p) => p.content_sha === staged.content_sha).at(-1);
45
+ return last?.status === 'failed' ? 'failed' : 'approved';
46
+ }
47
+ return live.length ? 'changed' : 'awaiting';
48
+ }
49
+
50
+ /** What the poster may post now: approved for the staged content, not yet posted, article date reached, not paused. */
51
+ export function due(
52
+ rows: { slug: string; date: string; planned?: string; staged: StagedRow[]; approvals: ApprovalRow[]; posts: PostRow[] }[],
53
+ today: string, paused: boolean,
54
+ ): StagedRow[] {
55
+ if (paused) return [];
56
+ const out: StagedRow[] = [];
57
+ for (const r of rows) {
58
+ // `date` is the article's date as built (it is live on the site); `planned` is the date set in /admin. Both must
59
+ // have come, so nothing is posted for an article the site has not published yet.
60
+ if (r.date > today || (r.planned ?? r.date) > today) continue;
61
+ for (const s of r.staged) {
62
+ const state = channelState(s, r.approvals.filter((a) => a.channel === s.channel), r.posts.filter((p) => p.channel === s.channel));
63
+ if (state === 'approved') out.push(s);
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /** A short-lived, signed public URL for one media file (Instagram fetches media from a URL). */
70
+ export async function signMedia(key: string, secret: string, origin: string, ttl = 3600, now = Date.now(), path = '/m') {
71
+ const exp = Math.floor(now / 1000) + ttl;
72
+ const sig = await hmac(secret, `${key}:${exp}`);
73
+ return `${origin}${path}/${key.split('/').map(encodeURIComponent).join('/')}?exp=${exp}&sig=${sig}`;
74
+ }
75
+ export async function checkSignature(key: string, exp: string, sig: string, secret: string, now = Date.now()) {
76
+ if (!secret || !/^\d+$/.test(exp) || Number(exp) * 1000 < now) return false;
77
+ const want = await hmac(secret, `${key}:${exp}`);
78
+ if (want.length !== sig.length) return false;
79
+ let d = 0; for (let i = 0; i < want.length; i++) d |= want.charCodeAt(i) ^ sig.charCodeAt(i);
80
+ return d === 0;
81
+ }
82
+ async function hmac(secret: string, msg: string) {
83
+ const k = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
84
+ const s = await crypto.subtle.sign('HMAC', k, enc.encode(msg));
85
+ return [...new Uint8Array(s)].map((b) => b.toString(16).padStart(2, '0')).join('');
86
+ }
87
+
88
+ /** Media keys: <slug>/<file>, lower-case, no path tricks. */
89
+ export const validKey = (k: string) => /^[a-z0-9-]+\/[a-z0-9._-]+$/.test(k) && !k.includes('..');
90
+
91
+ // ── Planning ────────────────────────────────────────────────────────────────────────────────────────────
92
+
93
+ /** Each article's publish date as set in /admin, else as built from index.json. */
94
+ export function effectiveDates(articles: { slug: string; date: string }[], overrides: { slug: string; publish_date: string }[]) {
95
+ const o = new Map(overrides.map((r) => [r.slug, r.publish_date]));
96
+ return new Map(articles.map((a) => [a.slug, o.get(a.slug) ?? a.date]));
97
+ }
98
+
99
+ /**
100
+ * "Make next": `slug` takes the first upcoming publishing slot and every other upcoming article moves down one slot.
101
+ * The slots (dates) stay where they are; only which article sits in each changes. Upcoming = dated after today.
102
+ * Returns the new date of every article that moves.
103
+ */
104
+ export function makeNext(dates: Map<string, string>, slug: string, today: string): Map<string, string> {
105
+ const upcoming = [...dates].filter(([, d]) => d > today).sort((a, b) => a[1].localeCompare(b[1]) || a[0].localeCompare(b[0]));
106
+ if (!upcoming.some(([s]) => s === slug)) return new Map();
107
+ const slots = upcoming.map(([, d]) => d);
108
+ const order = [slug, ...upcoming.map(([s]) => s).filter((s) => s !== slug)];
109
+ const moved = new Map<string, string>();
110
+ order.forEach((s, i) => { if (dates.get(s) !== slots[i]) moved.set(s, slots[i]); });
111
+ return moved;
112
+ }
113
+
114
+ export interface Production { motion?: boolean; film?: boolean; takes?: number; takesNeeded?: number; render?: boolean; short?: boolean; carousel?: number }
115
+
116
+ export interface RequestRow { id: number; slug: string; kind: string; body: string; author: string; at: string; status: string; parent: number | null }
117
+ export interface AuditRow { id: number; at: string; actor: string; action: string; slug: string | null; channel: string | null; detail: string | null }
package/src/store.ts ADDED
@@ -0,0 +1,98 @@
1
+ // Where the desk keeps its rows. The rules (./rules.ts) never touch storage; the API (./api.ts) talks to a
2
+ // PostingStore and a MediaStore. ./cloudflare has D1 + R2; memoryStore() is for tests, demos and local dev; any other
3
+ // database (Postgres, SQLite, KV) only needs these methods.
4
+ import { contentSha, type ApprovalRow, type AuditRow, type Channel, type PostRow, type Production, type RequestRow, type StagedPost, type StagedRow } from './rules.js';
5
+
6
+ export interface DeskState {
7
+ staged: StagedRow[]; approvals: ApprovalRow[]; posts: PostRow[]; paused: boolean;
8
+ schedule: { slug: string; publish_date: string }[];
9
+ }
10
+
11
+ export interface PostingStore {
12
+ readAll(): Promise<DeskState>;
13
+ recentAudit(n?: number): Promise<AuditRow[]>;
14
+ audit(actor: string, action: string, slug?: string | null, channel?: string | null, detail?: string): Promise<void>;
15
+ /** Stores the post as it will go out; returns its fingerprint (restaging changes it, so old approvals lapse). */
16
+ stage(actor: string, slug: string, channel: Channel, post: StagedPost): Promise<string>;
17
+ /** Approves only the content the approver saw: false if it was restaged since. */
18
+ approve(actor: string, slug: string, channel: Channel, contentShaSeen: string): Promise<boolean>;
19
+ revoke(actor: string, slug: string, channel: Channel): Promise<void>;
20
+ setPaused(actor: string, paused: boolean): Promise<void>;
21
+ recordPost(actor: string, p: { slug: string; channel: Channel; content_sha: string; status: PostRow['status']; url?: string; external_id?: string; detail?: string; run?: string }): Promise<void>;
22
+ readSchedule(): Promise<{ slug: string; publish_date: string }[]>;
23
+ setDates(actor: string, moved: Map<string, string>, why: string): Promise<void>;
24
+ readProduction(): Promise<{ slug: string; script: string | null; status: Production; updated_at: string }[]>;
25
+ saveProduction(slug: string, script: string | null, status: Production): Promise<void>;
26
+ readRequests(openOnly?: boolean): Promise<RequestRow[]>;
27
+ addRequest(actor: string, slug: string, kind: string, body: string, parent?: number | null): Promise<void>;
28
+ setRequestStatus(actor: string, id: number, status: string): Promise<void>;
29
+ }
30
+
31
+ /** Media files (rendered video, cover images, captions), kept private and addressed as <slug>/<file>. */
32
+ export interface MediaObject { body: ReadableStream | ArrayBuffer; size: number; contentType?: string; sha256?: string }
33
+ export interface MediaStore {
34
+ get(key: string): Promise<MediaObject | null>;
35
+ head(key: string): Promise<{ size: number; sha256?: string } | null>;
36
+ put(key: string, body: ArrayBuffer, o: { contentType: string; sha256: string }): Promise<void>;
37
+ }
38
+
39
+ const now = () => new Date().toISOString();
40
+
41
+ /** Everything in memory. Starts paused, like the real one. */
42
+ export function memoryStore(): PostingStore & { media: MediaStore } {
43
+ const s: DeskState = { staged: [], approvals: [], posts: [], paused: true, schedule: [] };
44
+ const log: AuditRow[] = [], production = new Map<string, { slug: string; script: string | null; status: Production; updated_at: string }>();
45
+ const requests: RequestRow[] = [], files = new Map<string, { bytes: ArrayBuffer; contentType: string; sha256: string }>();
46
+ let id = 0;
47
+ const store: PostingStore & { media: MediaStore } = {
48
+ async readAll() { return structuredClone(s); },
49
+ async recentAudit(n = 40) { return log.slice(-n).reverse(); },
50
+ async audit(actor, action, slug = null, channel = null, detail) { log.push({ id: ++id, at: now(), actor, action, slug, channel, detail: detail ?? null }); },
51
+ async stage(actor, slug, channel, post) {
52
+ const sha = await contentSha(channel, post);
53
+ s.staged = s.staged.filter((r) => !(r.slug === slug && r.channel === channel));
54
+ s.staged.push({ slug, channel, post: structuredClone(post), content_sha: sha, staged_by: actor, staged_at: now() });
55
+ await store.audit(actor, 'stage', slug, channel, sha.slice(0, 12));
56
+ return sha;
57
+ },
58
+ async approve(actor, slug, channel, seen) {
59
+ const row = s.staged.find((r) => r.slug === slug && r.channel === channel);
60
+ if (!row || row.content_sha !== seen) return false;
61
+ s.approvals.push({ id: ++id, slug, channel, content_sha: seen, approved_by: actor, approved_at: now(), revoked_at: null });
62
+ await store.audit(actor, 'approve', slug, channel, seen.slice(0, 12));
63
+ return true;
64
+ },
65
+ async revoke(actor, slug, channel) {
66
+ for (const a of s.approvals) if (a.slug === slug && a.channel === channel && !a.revoked_at) a.revoked_at = now();
67
+ await store.audit(actor, 'revoke', slug, channel);
68
+ },
69
+ async setPaused(actor, paused) { s.paused = paused; await store.audit(actor, paused ? 'pause' : 'resume'); },
70
+ async recordPost(actor, p) {
71
+ s.posts.push({ id: ++id, slug: p.slug, channel: p.channel, content_sha: p.content_sha, status: p.status, url: p.url ?? null, external_id: p.external_id ?? null, detail: p.detail ?? null, run: p.run ?? null, at: now() });
72
+ await store.audit(actor, p.status, p.slug, p.channel, p.url ?? p.detail);
73
+ },
74
+ async readSchedule() { return structuredClone(s.schedule); },
75
+ async setDates(actor, moved, why) {
76
+ if (!moved.size) return;
77
+ for (const [slug, d] of moved) { s.schedule = s.schedule.filter((x) => x.slug !== slug); s.schedule.push({ slug, publish_date: d }); }
78
+ await store.audit(actor, 'reorder', null, null, `${why}: ${[...moved].map(([x, d]) => `${x}→${d}`).join(', ')}`);
79
+ },
80
+ async readProduction() { return [...production.values()]; },
81
+ async saveProduction(slug, script, status) { production.set(slug, { slug, script, status, updated_at: now() }); },
82
+ async readRequests(openOnly = false) { return requests.filter((r) => !openOnly || (!r.parent && r.status !== 'done')); },
83
+ async addRequest(actor, slug, kind, body, parent = null) {
84
+ requests.push({ id: ++id, slug, kind, body: body.slice(0, 4000), author: actor, at: now(), status: 'open', parent });
85
+ await store.audit(actor, parent ? 'reply' : `request:${kind}`, slug, null, body.slice(0, 200));
86
+ },
87
+ async setRequestStatus(actor, rid, status) {
88
+ const r = requests.find((x) => x.id === rid); if (r) r.status = status;
89
+ await store.audit(actor, `request:${status}`, null, null, `#${rid}`);
90
+ },
91
+ media: {
92
+ async get(key) { const f = files.get(key); return f ? { body: f.bytes, size: f.bytes.byteLength, contentType: f.contentType, sha256: f.sha256 } : null; },
93
+ async head(key) { const f = files.get(key); return f ? { size: f.bytes.byteLength, sha256: f.sha256 } : null; },
94
+ async put(key, bytes, o) { files.set(key, { bytes, ...o }); },
95
+ },
96
+ };
97
+ return store;
98
+ }
@@ -0,0 +1,59 @@
1
+ // SvelteKit glue: a hook that guards the admin paths with Cloudflare Access and the role rules, and route handlers
2
+ // for the API and the signed media links. Typed structurally, so this does not import @sveltejs/kit.
3
+ //
4
+ // // src/hooks.server.ts
5
+ // import { postingHandle } from '@senseihq/emaki-posting/sveltekit';
6
+ // import { env } from '$env/dynamic/private'; import { dev } from '$app/environment';
7
+ // export const handle = postingHandle({ env: () => env, dev });
8
+ //
9
+ // // src/routes/api/admin/[...path]/+server.ts // src/routes/m/[...key]/+server.ts
10
+ // export const { GET, POST, PUT } = apiRoutes(desk); export const { GET } = mediaRoute(desk);
11
+ // (desk = (event) => createDesk({ store: d1Store(event.platform.env.DB), media: r2Media(event.platform.env.MEDIA), ... }))
12
+ import { accessFromEnv, allowed, callerOf, isAdminPath, paths, type Caller } from '../access.js';
13
+ import type { createDesk } from '../api.js';
14
+
15
+ type Desk = ReturnType<typeof createDesk>;
16
+ interface Event { request: Request; url: URL; params: Record<string, string | undefined>; locals: Record<string, unknown>; platform?: unknown }
17
+ type Resolve = (event: never) => Response | Promise<Response>;
18
+
19
+ export interface HandleOptions {
20
+ /** Private env (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUD, ADMIN_EMAILS, STAGER_CLIENT_IDS, POSTER_CLIENT_IDS). */
21
+ env: () => Record<string, string | undefined>;
22
+ /** Let a local admin in when Access is not configured (pass SvelteKit's `dev`). */
23
+ dev?: boolean;
24
+ }
25
+
26
+ /** Guards the admin pages and API: a valid Access token whose role may use the path, else 403. Sets locals.caller. */
27
+ export function postingHandle(o: HandleOptions) {
28
+ return async ({ event, resolve }: { event: Event; resolve: Resolve }) => {
29
+ const path = event.url.pathname;
30
+ if (!isAdminPath(path)) return resolve(event as never);
31
+ const caller = await callerOf(event.request, accessFromEnv(o.env()), { dev: o.dev });
32
+ if (!caller || !allowed(caller.role, path, event.request.method)) {
33
+ return path.startsWith(paths.api + '/')
34
+ ? new Response(JSON.stringify({ ok: false, reason: 'Not allowed' }), { status: 403, headers: { 'content-type': 'application/json' } })
35
+ : new Response('Not allowed', { status: 403 });
36
+ }
37
+ event.locals.caller = caller;
38
+ const res = await resolve(event as never);
39
+ res.headers.set('cache-control', 'no-store');
40
+ res.headers.set('x-robots-tag', 'noindex');
41
+ return res;
42
+ };
43
+ }
44
+
45
+ /** GET/POST/PUT for src/routes/<api>/[...path]/+server.ts. `desk` builds the desk for this request (bindings live on
46
+ * event.platform). */
47
+ export function apiRoutes(desk: (event: Event) => Desk | Promise<Desk>) {
48
+ const h = async (event: Event) => {
49
+ const caller = event.locals.caller as Caller | undefined;
50
+ if (!caller) return new Response('Not allowed', { status: 403 });
51
+ return (await desk(event)).api(event.request, caller, event.params.path ?? '');
52
+ };
53
+ return { GET: h, POST: h, PUT: h };
54
+ }
55
+
56
+ /** GET for src/routes/m/[...key]/+server.ts: the signed, short-lived public media links. */
57
+ export function mediaRoute(desk: (event: Event) => Desk | Promise<Desk>) {
58
+ return { GET: async (event: Event) => (await desk(event)).signedMedia(event.params.key ?? '', event.url) };
59
+ }