@senseihq/emaki-posting 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +54 -2
- package/dist/access.d.ts +37 -0
- package/dist/access.js +100 -0
- package/dist/api.d.ts +172 -0
- package/dist/api.js +229 -0
- package/dist/cloudflare/index.d.ts +36 -0
- package/dist/cloudflare/index.js +90 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +7 -0
- package/dist/rules.d.ts +112 -0
- package/dist/rules.js +97 -0
- package/dist/store.d.ts +69 -0
- package/dist/store.js +72 -0
- package/dist/sveltekit/index.d.ts +33 -0
- package/dist/sveltekit/index.js +46 -0
- package/migrations/0001_posting.sql +53 -0
- package/migrations/0002_planning.sql +31 -0
- package/package.json +40 -4
- package/poster/post.py +245 -0
- package/poster/sync_schedule.py +24 -0
- package/poster/youtube.py +31 -0
- package/src/access.ts +97 -0
- package/src/api.ts +225 -0
- package/src/cloudflare/index.ts +103 -0
- package/src/index.ts +7 -0
- package/src/rules.ts +117 -0
- package/src/store.ts +98 -0
- package/src/sveltekit/index.ts +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SenecaGlobal
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,55 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @senseihq/emaki-posting
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The posting desk: the machine that renders a story **stages** each post (media + text per channel); a person
|
|
4
|
+
**approves** exactly what was staged; a CI job **posts** what is approved once the story's date comes. An approval
|
|
5
|
+
holds the fingerprint (sha256) of the post it was given for, so restaging anything voids it. Posting starts paused.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm i @senseihq/emaki-posting
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
| Export | What |
|
|
12
|
+
|---|---|
|
|
13
|
+
| `@senseihq/emaki-posting` | rules (`contentSha`, `channelState`, `due`, `makeNext`, `signMedia`, `checkSignature`, `validKey`), access (`verifyCaller`, `callerOf`, `allowed`, roles admin / stager / poster), `PostingStore` + `MediaStore` interfaces and `memoryStore()`, and `createDesk(options)` → `{ api, signedMedia, desk }` |
|
|
14
|
+
| `/cloudflare` | `d1Store(db)` and `r2Media(bucket)` |
|
|
15
|
+
| `/sveltekit` | `postingHandle({ env, dev })` (the guard hook), `apiRoutes(desk)`, `mediaRoute(desk)` |
|
|
16
|
+
| `/migrations/*` | D1 / SQLite schema: staged, approvals, posts, audit, settings, schedule, production, requests |
|
|
17
|
+
| `poster/` | `post.py` (YouTube, Instagram, X; dry-run by default) and `sync_schedule.py`, for CI |
|
|
18
|
+
|
|
19
|
+
`desk.api(request, caller, path)` is a Web `Request → Response` handler, so it mounts on any fetch-style server
|
|
20
|
+
(SvelteKit, Workers, Hono, Next.js route handlers, Bun, Deno). `desk.desk` holds what a person does on the desk page:
|
|
21
|
+
`plan()`, `approve`, `revoke`, `makeNext`, `request`, `reply`, `pause`, `resume`.
|
|
22
|
+
|
|
23
|
+
## SvelteKit on Cloudflare
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// src/lib/server/desk.ts
|
|
27
|
+
import { createDesk } from '@senseihq/emaki-posting';
|
|
28
|
+
import { d1Store, r2Media } from '@senseihq/emaki-posting/cloudflare';
|
|
29
|
+
export const desk = (e) => createDesk({
|
|
30
|
+
store: d1Store(e.platform.env.DB), media: r2Media(e.platform.env.MEDIA),
|
|
31
|
+
pieces: () => STORIES.map((s) => ({ slug: s.slug, date: s.publish_date, video: s.kind })),
|
|
32
|
+
today: () => today(SITE.timeZone), pieceUrl: (slug) => `${SITE.url}/stories/${slug}`,
|
|
33
|
+
mediaSecret: e.platform.env.MEDIA_URL_SECRET,
|
|
34
|
+
});
|
|
35
|
+
// src/hooks.server.ts
|
|
36
|
+
export const handle = postingHandle({ env: () => env, dev });
|
|
37
|
+
// src/routes/api/admin/[...path]/+server.ts
|
|
38
|
+
export const { GET, POST, PUT } = apiRoutes(desk);
|
|
39
|
+
// src/routes/m/[...key]/+server.ts
|
|
40
|
+
export const { GET } = mediaRoute(desk);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Setup:
|
|
44
|
+
|
|
45
|
+
1. `wrangler d1 create`, bind it as `DB`; apply `migrations/0001_posting.sql` and `0002_planning.sql`. Create a
|
|
46
|
+
private R2 bucket bound as `MEDIA`.
|
|
47
|
+
2. Put a Cloudflare Access application in front of `/admin` and `/api/admin`, allowing your people; create two
|
|
48
|
+
service tokens (stager, poster).
|
|
49
|
+
3. Secrets (never in files): `CF_ACCESS_TEAM_DOMAIN`, `CF_ACCESS_AUD`, `ADMIN_EMAILS`, `STAGER_CLIENT_IDS`,
|
|
50
|
+
`POSTER_CLIENT_IDS`, `MEDIA_URL_SECRET`.
|
|
51
|
+
4. CI (GitHub Actions in a protected environment): `ADMIN_ORIGIN`, `POSTER_CLIENT_ID/SECRET`, the platform keys,
|
|
52
|
+
`POST_MODE=dry-run` until you trust it; run `python3 node_modules/@senseihq/emaki-posting/poster/post.py`.
|
|
53
|
+
5. Test in dry-run: stage → approve → change the text (the approval lapses) → re-approve → dry-run post.
|
|
54
|
+
|
|
55
|
+
MIT © SenecaGlobal
|
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type Role = 'admin' | 'stager' | 'poster';
|
|
2
|
+
export interface Caller {
|
|
3
|
+
role: Role;
|
|
4
|
+
id: string;
|
|
5
|
+
}
|
|
6
|
+
export interface AccessConfig {
|
|
7
|
+
teamDomain?: string;
|
|
8
|
+
aud?: string;
|
|
9
|
+
emails?: string;
|
|
10
|
+
stagers?: string;
|
|
11
|
+
posters?: string;
|
|
12
|
+
}
|
|
13
|
+
/** Where the desk lives: the admin pages and the admin API. Change them with configurePaths() before handling requests. */
|
|
14
|
+
export declare const paths: {
|
|
15
|
+
admin: string;
|
|
16
|
+
api: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function configurePaths(p: Partial<typeof paths>): void;
|
|
19
|
+
export declare const isAdminPath: (path: string) => boolean;
|
|
20
|
+
export declare const accessConfigured: (c: AccessConfig) => boolean;
|
|
21
|
+
/** The caller behind a valid Access token for this app, or null. */
|
|
22
|
+
export declare function verifyCaller(token: string | null, c: AccessConfig, fetchFn?: typeof fetch, now?: number): Promise<Caller | null>;
|
|
23
|
+
/** Which roles may use a path (and method). People: everything. Machines: only their own endpoints. */
|
|
24
|
+
export declare function allowed(role: Role, path: string, method: string): boolean;
|
|
25
|
+
/** for tests: forget the cached keys */
|
|
26
|
+
export declare function resetAccessCache(): void;
|
|
27
|
+
/** Access settings from environment variables (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUD, ADMIN_EMAILS, STAGER_CLIENT_IDS,
|
|
28
|
+
* POSTER_CLIENT_IDS). */
|
|
29
|
+
export declare const accessFromEnv: (env: Record<string, string | undefined>) => AccessConfig;
|
|
30
|
+
/**
|
|
31
|
+
* The caller of an admin request, or null to refuse it. `dev` lets a local admin in only when Access is not set up
|
|
32
|
+
* (never pass true in production). Does not check the role against the path; use allowed() for that.
|
|
33
|
+
*/
|
|
34
|
+
export declare function callerOf(request: Request, config: AccessConfig, o?: {
|
|
35
|
+
dev?: boolean;
|
|
36
|
+
fetch?: typeof fetch;
|
|
37
|
+
}): Promise<Caller | null>;
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Who is calling the admin paths. Cloudflare Access sits in front of them (the Access application's policies decide
|
|
2
|
+
// who reaches the site at all); this checks again on the server, and fails closed:
|
|
3
|
+
// - a person: a valid Access token (Cf-Access-Jwt-Assertion) signed by the team's keys, for this app's audience,
|
|
4
|
+
// unexpired, naming an email in ADMIN_EMAILS;
|
|
5
|
+
// - a machine: the same token issued to an Access service token, whose client id is in STAGER_CLIENT_IDS (the Mac
|
|
6
|
+
// that uploads finished media and post text) or POSTER_CLIENT_IDS (the GitHub job that posts approved pieces).
|
|
7
|
+
// Without a team domain + audience the deployed site refuses everything here; only a dev server lets a local admin in.
|
|
8
|
+
// Any host whose identity proxy issues RS256 JWTs with a JWKS can reuse verifyCaller with its own certs URL.
|
|
9
|
+
let certs = null;
|
|
10
|
+
const b64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0));
|
|
11
|
+
const part = (s) => JSON.parse(new TextDecoder().decode(b64(s)));
|
|
12
|
+
const list = (raw) => (raw ?? '').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean);
|
|
13
|
+
/** Where the desk lives: the admin pages and the admin API. Change them with configurePaths() before handling requests. */
|
|
14
|
+
export const paths = { admin: '/admin', api: '/api/admin' };
|
|
15
|
+
export function configurePaths(p) { Object.assign(paths, p); }
|
|
16
|
+
export const isAdminPath = (path) => path === paths.admin || path.startsWith(paths.admin + '/') || path.startsWith(paths.api + '/');
|
|
17
|
+
export const accessConfigured = (c) => Boolean(c.teamDomain && c.aud);
|
|
18
|
+
async function keys(teamDomain, fetchFn, now) {
|
|
19
|
+
const url = `https://${teamDomain.replace(/^https?:\/\//, '').replace(/\/$/, '')}/cdn-cgi/access/certs`;
|
|
20
|
+
if (certs && certs.url === url && now - certs.at < 3_600_000)
|
|
21
|
+
return certs.keys;
|
|
22
|
+
const r = await fetchFn(url);
|
|
23
|
+
if (!r.ok)
|
|
24
|
+
throw new Error(`Access certs ${r.status}`);
|
|
25
|
+
certs = { url, keys: (await r.json()).keys, at: now };
|
|
26
|
+
return certs.keys;
|
|
27
|
+
}
|
|
28
|
+
/** The caller behind a valid Access token for this app, or null. */
|
|
29
|
+
export async function verifyCaller(token, c, fetchFn = fetch, now = Date.now()) {
|
|
30
|
+
if (!token || !accessConfigured(c))
|
|
31
|
+
return null;
|
|
32
|
+
const [h, p, s] = token.split('.');
|
|
33
|
+
if (!h || !p || !s)
|
|
34
|
+
return null;
|
|
35
|
+
try {
|
|
36
|
+
const head = part(h), claims = part(p);
|
|
37
|
+
if (head.alg !== 'RS256')
|
|
38
|
+
return null;
|
|
39
|
+
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
40
|
+
if (!aud.some((a) => list(c.aud).includes(String(a).toLowerCase())))
|
|
41
|
+
return null;
|
|
42
|
+
if (typeof claims.exp !== 'number' || claims.exp * 1000 < now)
|
|
43
|
+
return null;
|
|
44
|
+
const team = c.teamDomain.replace(/^https?:\/\//, '').replace(/\/$/, '');
|
|
45
|
+
if (claims.iss && String(claims.iss).replace(/^https?:\/\//, '').replace(/\/$/, '') !== team)
|
|
46
|
+
return null;
|
|
47
|
+
let caller = null;
|
|
48
|
+
const email = String(claims.email ?? '').toLowerCase();
|
|
49
|
+
const cn = String(claims.common_name ?? '').toLowerCase();
|
|
50
|
+
if (email && list(c.emails).includes(email))
|
|
51
|
+
caller = { role: 'admin', id: email };
|
|
52
|
+
else if (!email && cn && list(c.stagers).includes(cn))
|
|
53
|
+
caller = { role: 'stager', id: cn };
|
|
54
|
+
else if (!email && cn && list(c.posters).includes(cn))
|
|
55
|
+
caller = { role: 'poster', id: cn };
|
|
56
|
+
if (!caller)
|
|
57
|
+
return null;
|
|
58
|
+
const jwk = (await keys(c.teamDomain, fetchFn, now)).find((k) => k.kid === head.kid);
|
|
59
|
+
if (!jwk)
|
|
60
|
+
return null;
|
|
61
|
+
const key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']);
|
|
62
|
+
const ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, b64(s), new TextEncoder().encode(`${h}.${p}`));
|
|
63
|
+
return ok ? caller : null;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Which roles may use a path (and method). People: everything. Machines: only their own endpoints. */
|
|
70
|
+
export function allowed(role, path, method) {
|
|
71
|
+
if (role === 'admin')
|
|
72
|
+
return true;
|
|
73
|
+
const a = paths.api;
|
|
74
|
+
// The producing machine: upload media, stage posts, report what is produced, read and answer motion requests.
|
|
75
|
+
if (role === 'stager')
|
|
76
|
+
return (path.startsWith(`${a}/media/`) && method === 'PUT') || (path === `${a}/stage` && method === 'POST') ||
|
|
77
|
+
(path === `${a}/production` && method === 'POST') || (path === `${a}/requests` && (method === 'GET' || method === 'POST'));
|
|
78
|
+
// The CI poster: read the approved queue and the posting order, download media, report outcomes.
|
|
79
|
+
if (role === 'poster')
|
|
80
|
+
return (path === `${a}/queue` && method === 'GET') || (path === `${a}/posted` && method === 'POST') ||
|
|
81
|
+
(path.startsWith(`${a}/media/`) && method === 'GET') || (path === `${a}/schedule` && method === 'GET');
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
/** for tests: forget the cached keys */
|
|
85
|
+
export function resetAccessCache() { certs = null; }
|
|
86
|
+
/** Access settings from environment variables (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUD, ADMIN_EMAILS, STAGER_CLIENT_IDS,
|
|
87
|
+
* POSTER_CLIENT_IDS). */
|
|
88
|
+
export const accessFromEnv = (env) => ({
|
|
89
|
+
teamDomain: env.CF_ACCESS_TEAM_DOMAIN, aud: env.CF_ACCESS_AUD, emails: env.ADMIN_EMAILS,
|
|
90
|
+
stagers: env.STAGER_CLIENT_IDS, posters: env.POSTER_CLIENT_IDS,
|
|
91
|
+
});
|
|
92
|
+
/**
|
|
93
|
+
* The caller of an admin request, or null to refuse it. `dev` lets a local admin in only when Access is not set up
|
|
94
|
+
* (never pass true in production). Does not check the role against the path; use allowed() for that.
|
|
95
|
+
*/
|
|
96
|
+
export async function callerOf(request, config, o = {}) {
|
|
97
|
+
if (!accessConfigured(config))
|
|
98
|
+
return o.dev ? { role: 'admin', id: 'dev@localhost' } : null;
|
|
99
|
+
return verifyCaller(request.headers.get('cf-access-jwt-assertion'), config, o.fetch ?? fetch);
|
|
100
|
+
}
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { type Channel, type Production, type StagedPost } from './rules.js';
|
|
2
|
+
import type { Caller } from './access.js';
|
|
3
|
+
import type { MediaStore, PostingStore } from './store.js';
|
|
4
|
+
/** One piece the desk knows about: its slug, its date as built, and (optionally) its kind. */
|
|
5
|
+
export interface Piece {
|
|
6
|
+
slug: string;
|
|
7
|
+
date: string;
|
|
8
|
+
title?: string;
|
|
9
|
+
video?: 'short' | 'wide' | string;
|
|
10
|
+
}
|
|
11
|
+
export interface DeskOptions {
|
|
12
|
+
store: PostingStore;
|
|
13
|
+
media: MediaStore;
|
|
14
|
+
/** The pieces in the built site (index.json). */
|
|
15
|
+
pieces: () => Piece[] | Promise<Piece[]>;
|
|
16
|
+
/** Today in the site's time zone (YYYY-MM-DD). */
|
|
17
|
+
today: () => string;
|
|
18
|
+
/** The public link of a piece, for the posts. */
|
|
19
|
+
pieceUrl: (slug: string) => string;
|
|
20
|
+
/** Secret for the short-lived public media links (Instagram fetches media from a URL). Without it, no links. */
|
|
21
|
+
mediaSecret?: string;
|
|
22
|
+
/** Origin the signed media links point at (default: the request's). */
|
|
23
|
+
mediaOrigin?: string;
|
|
24
|
+
/** Path of the signed media route (default /m). */
|
|
25
|
+
mediaPath?: string;
|
|
26
|
+
/** Channels expected for a piece (default: Shorts go everywhere; wide films skip the carousel). */
|
|
27
|
+
channelsFor?: (p: Piece) => Channel[];
|
|
28
|
+
}
|
|
29
|
+
export declare class HttpError extends Error {
|
|
30
|
+
status: number;
|
|
31
|
+
constructor(status: number, message: string);
|
|
32
|
+
}
|
|
33
|
+
export declare function createDesk(o: DeskOptions): {
|
|
34
|
+
api: (request: Request, caller: Caller, sub: string) => Promise<Response>;
|
|
35
|
+
signedMedia: (key: string, url: URL) => Promise<Response>;
|
|
36
|
+
desk: {
|
|
37
|
+
plan: () => Promise<{
|
|
38
|
+
today: string;
|
|
39
|
+
paused: boolean;
|
|
40
|
+
plan: {
|
|
41
|
+
date: string;
|
|
42
|
+
built: string;
|
|
43
|
+
moved: boolean;
|
|
44
|
+
live: boolean;
|
|
45
|
+
channels: {
|
|
46
|
+
channel: "youtube" | "instagram_reel" | "instagram_carousel" | "x";
|
|
47
|
+
state: import("./rules.js").ChannelState;
|
|
48
|
+
staged: import("./rules.js").StagedRow | null;
|
|
49
|
+
url: string | null;
|
|
50
|
+
last: import("./rules.js").PostRow | null;
|
|
51
|
+
}[];
|
|
52
|
+
script: string | null;
|
|
53
|
+
status: Production;
|
|
54
|
+
reported: string | null;
|
|
55
|
+
requests: {
|
|
56
|
+
thread: import("./rules.js").RequestRow[];
|
|
57
|
+
id: number;
|
|
58
|
+
slug: string;
|
|
59
|
+
kind: string;
|
|
60
|
+
body: string;
|
|
61
|
+
author: string;
|
|
62
|
+
at: string;
|
|
63
|
+
status: string;
|
|
64
|
+
parent: number | null;
|
|
65
|
+
}[];
|
|
66
|
+
slug: string;
|
|
67
|
+
title?: string;
|
|
68
|
+
video?: "short" | "wide" | string;
|
|
69
|
+
}[];
|
|
70
|
+
next: {
|
|
71
|
+
date: string;
|
|
72
|
+
built: string;
|
|
73
|
+
moved: boolean;
|
|
74
|
+
live: boolean;
|
|
75
|
+
channels: {
|
|
76
|
+
channel: "youtube" | "instagram_reel" | "instagram_carousel" | "x";
|
|
77
|
+
state: import("./rules.js").ChannelState;
|
|
78
|
+
staged: import("./rules.js").StagedRow | null;
|
|
79
|
+
url: string | null;
|
|
80
|
+
last: import("./rules.js").PostRow | null;
|
|
81
|
+
}[];
|
|
82
|
+
script: string | null;
|
|
83
|
+
status: Production;
|
|
84
|
+
reported: string | null;
|
|
85
|
+
requests: {
|
|
86
|
+
thread: import("./rules.js").RequestRow[];
|
|
87
|
+
id: number;
|
|
88
|
+
slug: string;
|
|
89
|
+
kind: string;
|
|
90
|
+
body: string;
|
|
91
|
+
author: string;
|
|
92
|
+
at: string;
|
|
93
|
+
status: string;
|
|
94
|
+
parent: number | null;
|
|
95
|
+
}[];
|
|
96
|
+
slug: string;
|
|
97
|
+
title?: string;
|
|
98
|
+
video?: "short" | "wide" | string;
|
|
99
|
+
} | null;
|
|
100
|
+
audit: import("./rules.js").AuditRow[];
|
|
101
|
+
}>;
|
|
102
|
+
approve(who: string, slug: string, items: string[]): Promise<{
|
|
103
|
+
ok: string;
|
|
104
|
+
status?: undefined;
|
|
105
|
+
error?: undefined;
|
|
106
|
+
} | {
|
|
107
|
+
status: number;
|
|
108
|
+
error: string;
|
|
109
|
+
ok?: undefined;
|
|
110
|
+
}>;
|
|
111
|
+
revoke(who: string, slug: string, channel: string): Promise<{
|
|
112
|
+
status: number;
|
|
113
|
+
error: string;
|
|
114
|
+
ok?: undefined;
|
|
115
|
+
} | {
|
|
116
|
+
ok: string;
|
|
117
|
+
status?: undefined;
|
|
118
|
+
error?: undefined;
|
|
119
|
+
}>;
|
|
120
|
+
makeNext(who: string, slug: string): Promise<{
|
|
121
|
+
status: number;
|
|
122
|
+
error: string;
|
|
123
|
+
ok?: undefined;
|
|
124
|
+
} | {
|
|
125
|
+
ok: string;
|
|
126
|
+
status?: undefined;
|
|
127
|
+
error?: undefined;
|
|
128
|
+
}>;
|
|
129
|
+
request(who: string, slug: string, kind: string, body: string): Promise<{
|
|
130
|
+
status: number;
|
|
131
|
+
error: string;
|
|
132
|
+
ok?: undefined;
|
|
133
|
+
} | {
|
|
134
|
+
ok: string;
|
|
135
|
+
status?: undefined;
|
|
136
|
+
error?: undefined;
|
|
137
|
+
}>;
|
|
138
|
+
reply(who: string, id: number, body: string, status?: string): Promise<{
|
|
139
|
+
status: number;
|
|
140
|
+
error: string;
|
|
141
|
+
ok?: undefined;
|
|
142
|
+
} | {
|
|
143
|
+
ok: string;
|
|
144
|
+
status?: undefined;
|
|
145
|
+
error?: undefined;
|
|
146
|
+
}>;
|
|
147
|
+
pause(who: string): Promise<{
|
|
148
|
+
ok: string;
|
|
149
|
+
}>;
|
|
150
|
+
resume(who: string): Promise<{
|
|
151
|
+
ok: string;
|
|
152
|
+
}>;
|
|
153
|
+
};
|
|
154
|
+
queue: (origin: string) => Promise<{
|
|
155
|
+
paused: boolean;
|
|
156
|
+
today: string;
|
|
157
|
+
items: {
|
|
158
|
+
slug: string;
|
|
159
|
+
channel: "youtube" | "instagram_reel" | "instagram_carousel" | "x";
|
|
160
|
+
content_sha: string;
|
|
161
|
+
post: StagedPost;
|
|
162
|
+
article: string;
|
|
163
|
+
video: string;
|
|
164
|
+
media: {
|
|
165
|
+
url: string | null;
|
|
166
|
+
key: string;
|
|
167
|
+
sha256: string;
|
|
168
|
+
type: string;
|
|
169
|
+
}[];
|
|
170
|
+
}[];
|
|
171
|
+
}>;
|
|
172
|
+
};
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
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 } from './rules.js';
|
|
6
|
+
const TYPES = { mp4: 'video/mp4', jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', srt: 'text/plain; charset=utf-8', vtt: 'text/vtt' };
|
|
7
|
+
const MAX = 95 * 1024 * 1024; // under the Workers request-body limit
|
|
8
|
+
export class HttpError extends Error {
|
|
9
|
+
status;
|
|
10
|
+
constructor(status, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const json = (data, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
|
|
16
|
+
const fail = (status, reason) => { throw new HttpError(status, reason); };
|
|
17
|
+
export function createDesk(o) {
|
|
18
|
+
const { store, media } = o;
|
|
19
|
+
const expected = o.channelsFor ?? ((p) => (p.video === 'short' ? [...CHANNELS] : ['youtube', 'instagram_reel', 'x']));
|
|
20
|
+
const slugs = async () => new Set((await o.pieces()).map((p) => p.slug));
|
|
21
|
+
/** The API under the admin prefix: `sub` is the path after it ('queue', 'media/<slug>/<file>', ...). */
|
|
22
|
+
async function api(request, caller, sub) {
|
|
23
|
+
try {
|
|
24
|
+
const m = request.method;
|
|
25
|
+
if (sub === 'queue' && m === 'GET')
|
|
26
|
+
return json(await queue(new URL(request.url).origin));
|
|
27
|
+
if (sub === 'posted' && m === 'POST')
|
|
28
|
+
return json(await posted(caller, await request.json()));
|
|
29
|
+
if (sub === 'stage' && m === 'POST')
|
|
30
|
+
return json(await stage(caller, await request.json()));
|
|
31
|
+
if (sub === 'production' && m === 'POST')
|
|
32
|
+
return json(await production(await request.json()));
|
|
33
|
+
if (sub === 'schedule' && m === 'GET')
|
|
34
|
+
return json(await schedule());
|
|
35
|
+
if (sub === 'requests' && m === 'GET')
|
|
36
|
+
return json(await openRequests());
|
|
37
|
+
if (sub === 'requests' && m === 'POST')
|
|
38
|
+
return json(await answerRequest(caller, await request.json()));
|
|
39
|
+
if (sub.startsWith('media/')) {
|
|
40
|
+
const key = sub.slice(6);
|
|
41
|
+
if (m === 'GET')
|
|
42
|
+
return await getMedia(key);
|
|
43
|
+
if (m === 'PUT')
|
|
44
|
+
return json(await putMedia(caller, key, request));
|
|
45
|
+
}
|
|
46
|
+
return json({ ok: false, reason: 'Not found' }, 404);
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
if (e instanceof HttpError)
|
|
50
|
+
return json({ ok: false, reason: e.message }, e.status);
|
|
51
|
+
throw e;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** What is approved and due now, with short-lived media links. Empty while posting is paused. */
|
|
55
|
+
async function queue(origin) {
|
|
56
|
+
const all = await store.readAll(), t = o.today();
|
|
57
|
+
const planned = new Map(all.schedule.map((s) => [s.slug, s.publish_date]));
|
|
58
|
+
const pieces = await o.pieces();
|
|
59
|
+
const rows = pieces.map((a) => ({
|
|
60
|
+
slug: a.slug, date: a.date, planned: planned.get(a.slug),
|
|
61
|
+
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),
|
|
62
|
+
}));
|
|
63
|
+
const base = o.mediaOrigin || origin;
|
|
64
|
+
return {
|
|
65
|
+
paused: all.paused, today: t,
|
|
66
|
+
items: await Promise.all(due(rows, t, all.paused).map(async (s) => ({
|
|
67
|
+
slug: s.slug, channel: s.channel, content_sha: s.content_sha, post: s.post, article: o.pieceUrl(s.slug),
|
|
68
|
+
video: pieces.find((a) => a.slug === s.slug)?.video ?? 'short',
|
|
69
|
+
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 }))),
|
|
70
|
+
}))),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
async function posted(caller, b) {
|
|
74
|
+
if (!b.slug || !isChannel(b.channel) || !b.content_sha || !['posted', 'dry-run', 'failed'].includes(b.status))
|
|
75
|
+
fail(400, 'slug, channel, content_sha and status are required');
|
|
76
|
+
await store.recordPost(caller.id, { slug: b.slug, channel: b.channel, content_sha: b.content_sha, status: b.status, url: b.url, external_id: b.external_id, detail: b.detail?.slice(0, 2000), run: b.run });
|
|
77
|
+
return { ok: true };
|
|
78
|
+
}
|
|
79
|
+
/** The post for one piece and channel, as it will go out. Every media file must already be uploaded, same sha256. */
|
|
80
|
+
async function stage(caller, b) {
|
|
81
|
+
if (!(await slugs()).has(b.slug))
|
|
82
|
+
fail(400, `No piece "${b.slug}" in the index`);
|
|
83
|
+
if (!isChannel(b.channel) || !b.post || !Array.isArray(b.post.media))
|
|
84
|
+
fail(400, 'channel and post.media are required');
|
|
85
|
+
for (const x of b.post.media) {
|
|
86
|
+
if (!validKey(x.key) || !x.key.startsWith(`${b.slug}/`))
|
|
87
|
+
fail(400, `Bad media key ${x.key}`);
|
|
88
|
+
const head = await media.head(x.key);
|
|
89
|
+
if (!head || head.sha256 !== x.sha256)
|
|
90
|
+
fail(400, `${x.key} is not uploaded with that sha256`);
|
|
91
|
+
}
|
|
92
|
+
return { ok: true, content_sha: await store.stage(caller.id, b.slug, b.channel, b.post) };
|
|
93
|
+
}
|
|
94
|
+
async function production(b) {
|
|
95
|
+
const known = await slugs();
|
|
96
|
+
let saved = 0;
|
|
97
|
+
for (const it of b.items ?? []) {
|
|
98
|
+
if (!known.has(it.slug))
|
|
99
|
+
continue;
|
|
100
|
+
await store.saveProduction(it.slug, (it.script ?? '').slice(0, 60000) || null, it.status ?? {});
|
|
101
|
+
saved++;
|
|
102
|
+
}
|
|
103
|
+
return { ok: true, saved };
|
|
104
|
+
}
|
|
105
|
+
/** Dates set on the desk that differ from the build: the schedule job writes them into index.json. */
|
|
106
|
+
async function schedule() {
|
|
107
|
+
const built = new Map((await o.pieces()).map((a) => [a.slug, a.date]));
|
|
108
|
+
return { changes: (await store.readSchedule()).filter((s) => built.has(s.slug) && built.get(s.slug) !== s.publish_date) };
|
|
109
|
+
}
|
|
110
|
+
async function openRequests() {
|
|
111
|
+
const all = await store.readRequests();
|
|
112
|
+
return { requests: all.filter((r) => !r.parent && r.status !== 'done').map((r) => ({ ...r, thread: all.filter((x) => x.parent === r.id) })) };
|
|
113
|
+
}
|
|
114
|
+
async function answerRequest(caller, b) {
|
|
115
|
+
const parent = (await store.readRequests()).find((r) => r.id === Number(b.id) && !r.parent);
|
|
116
|
+
if (!parent)
|
|
117
|
+
fail(404, 'No such request');
|
|
118
|
+
if (b.reply)
|
|
119
|
+
await store.addRequest(caller.id, parent.slug, 'note', b.reply, parent.id);
|
|
120
|
+
if (b.status && ['open', 'working', 'done'].includes(b.status))
|
|
121
|
+
await store.setRequestStatus(caller.id, parent.id, b.status);
|
|
122
|
+
return { ok: true };
|
|
123
|
+
}
|
|
124
|
+
async function getMedia(key) {
|
|
125
|
+
if (!validKey(key))
|
|
126
|
+
fail(400, 'Bad key');
|
|
127
|
+
const obj = await media.get(key);
|
|
128
|
+
if (!obj)
|
|
129
|
+
fail(404, 'Not found');
|
|
130
|
+
return new Response(obj.body, { headers: { 'content-type': obj.contentType ?? 'application/octet-stream', 'content-length': String(obj.size), 'x-content-sha256': obj.sha256 ?? '' } });
|
|
131
|
+
}
|
|
132
|
+
async function putMedia(caller, key, request) {
|
|
133
|
+
if (!validKey(key))
|
|
134
|
+
fail(400, 'Bad key: <slug>/<file>, lower-case');
|
|
135
|
+
const want = (request.headers.get('x-content-sha256') ?? '').toLowerCase();
|
|
136
|
+
const body = await request.arrayBuffer();
|
|
137
|
+
if (body.byteLength > MAX)
|
|
138
|
+
fail(413, 'Too large');
|
|
139
|
+
const got = await sha256(body);
|
|
140
|
+
if (!want || got !== want)
|
|
141
|
+
fail(400, `sha256 mismatch (got ${got})`);
|
|
142
|
+
await media.put(key, body, { contentType: TYPES[key.split('.').pop() ?? ''] ?? 'application/octet-stream', sha256: got });
|
|
143
|
+
await store.audit(caller.id, 'upload', key.split('/')[0], null, `${key} ${got.slice(0, 12)}`);
|
|
144
|
+
return { ok: true, key, sha256: got, bytes: body.byteLength };
|
|
145
|
+
}
|
|
146
|
+
/** /m/<key>?exp=…&sig=…: one media file, public only with a valid, unexpired signature. The bucket stays private. */
|
|
147
|
+
async function signedMedia(key, url) {
|
|
148
|
+
const notFound = new Response('Not found', { status: 404 });
|
|
149
|
+
if (!o.mediaSecret || !validKey(key))
|
|
150
|
+
return notFound;
|
|
151
|
+
if (!(await checkSignature(key, url.searchParams.get('exp') ?? '', url.searchParams.get('sig') ?? '', o.mediaSecret)))
|
|
152
|
+
return notFound;
|
|
153
|
+
const obj = await media.get(key);
|
|
154
|
+
if (!obj)
|
|
155
|
+
return notFound;
|
|
156
|
+
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' } });
|
|
157
|
+
}
|
|
158
|
+
/** The desk page's data: every piece in date order with each channel's state, production and requests. */
|
|
159
|
+
async function plan() {
|
|
160
|
+
const t = o.today(), all = await store.readAll(), prod = await store.readProduction(), requests = await store.readRequests();
|
|
161
|
+
const pieces = await o.pieces(), dates = effectiveDates(pieces, all.schedule);
|
|
162
|
+
const rows = pieces.map((a) => {
|
|
163
|
+
const date = dates.get(a.slug);
|
|
164
|
+
const channels = expected(a).map((c) => {
|
|
165
|
+
const staged = all.staged.find((s) => s.slug === a.slug && s.channel === c);
|
|
166
|
+
const posts = all.posts.filter((p) => p.slug === a.slug && p.channel === c);
|
|
167
|
+
return {
|
|
168
|
+
channel: c, state: channelState(staged, all.approvals.filter((x) => x.slug === a.slug && x.channel === c), posts),
|
|
169
|
+
staged: staged ?? null, url: posts.filter((p) => p.status === 'posted').at(-1)?.url ?? null, last: posts.at(-1) ?? null,
|
|
170
|
+
};
|
|
171
|
+
});
|
|
172
|
+
const p = prod.find((x) => x.slug === a.slug);
|
|
173
|
+
return {
|
|
174
|
+
...a, date, built: a.date, moved: date !== a.date, live: a.date <= t, channels,
|
|
175
|
+
script: p?.script ?? null, status: p?.status ?? {}, reported: p?.updated_at ?? null,
|
|
176
|
+
requests: requests.filter((r) => r.slug === a.slug && !r.parent).map((r) => ({ ...r, thread: requests.filter((x) => x.parent === r.id) })),
|
|
177
|
+
};
|
|
178
|
+
}).sort((x, y) => x.date.localeCompare(y.date) || x.slug.localeCompare(y.slug));
|
|
179
|
+
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() };
|
|
180
|
+
}
|
|
181
|
+
/** What a person does on the desk page. Each returns { ok } or { error } with a status. */
|
|
182
|
+
const desk = {
|
|
183
|
+
plan,
|
|
184
|
+
async approve(who, slug, items) {
|
|
185
|
+
let n = 0;
|
|
186
|
+
for (const item of items) {
|
|
187
|
+
const [c, sha] = item.split(':');
|
|
188
|
+
if (isChannel(c) && (await store.approve(who, slug, c, sha)))
|
|
189
|
+
n++;
|
|
190
|
+
}
|
|
191
|
+
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.` };
|
|
192
|
+
},
|
|
193
|
+
async revoke(who, slug, channel) {
|
|
194
|
+
if (!isChannel(channel))
|
|
195
|
+
return { status: 400, error: 'Bad channel' };
|
|
196
|
+
await store.revoke(who, slug, channel);
|
|
197
|
+
return { ok: 'Approval withdrawn' };
|
|
198
|
+
},
|
|
199
|
+
async makeNext(who, slug) {
|
|
200
|
+
const all = await store.readAll();
|
|
201
|
+
const moved = makeNext(effectiveDates(await o.pieces(), all.schedule), slug, o.today());
|
|
202
|
+
if (!moved.size)
|
|
203
|
+
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, slug, kind, body) {
|
|
208
|
+
if (!(await slugs()).has(slug))
|
|
209
|
+
return { status: 400, error: 'No such piece' };
|
|
210
|
+
if (!body.trim() && kind !== 'generate')
|
|
211
|
+
return { status: 400, error: 'Say what to change' };
|
|
212
|
+
await store.addRequest(who, slug, ['generate', 'edit', 'note'].includes(kind) ? kind : 'edit', body.trim() || 'Generate the motion for this piece from its script.');
|
|
213
|
+
return { ok: 'Sent. Replies appear in the thread.' };
|
|
214
|
+
},
|
|
215
|
+
async reply(who, id, body, status) {
|
|
216
|
+
const parent = (await store.readRequests()).find((r) => r.id === id && !r.parent);
|
|
217
|
+
if (!parent)
|
|
218
|
+
return { status: 404, error: 'No such request' };
|
|
219
|
+
if (body.trim())
|
|
220
|
+
await store.addRequest(who, parent.slug, 'note', body.trim(), id);
|
|
221
|
+
if (status)
|
|
222
|
+
await store.setRequestStatus(who, id, status);
|
|
223
|
+
return { ok: 'Saved' };
|
|
224
|
+
},
|
|
225
|
+
async pause(who) { await store.setPaused(who, true); return { ok: 'Posting paused' }; },
|
|
226
|
+
async resume(who) { await store.setPaused(who, false); return { ok: 'Posting resumed' }; },
|
|
227
|
+
};
|
|
228
|
+
return { api, signedMedia, desk, queue };
|
|
229
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { MediaStore, PostingStore } from '../store.js';
|
|
2
|
+
export interface D1Stmt {
|
|
3
|
+
bind(...v: unknown[]): D1Stmt;
|
|
4
|
+
all<T = Record<string, unknown>>(): Promise<{
|
|
5
|
+
results: T[];
|
|
6
|
+
}>;
|
|
7
|
+
first<T = Record<string, unknown>>(): Promise<T | null>;
|
|
8
|
+
run(): Promise<unknown>;
|
|
9
|
+
}
|
|
10
|
+
export interface D1 {
|
|
11
|
+
prepare(sql: string): D1Stmt;
|
|
12
|
+
batch(s: D1Stmt[]): Promise<unknown>;
|
|
13
|
+
}
|
|
14
|
+
export interface R2Object {
|
|
15
|
+
body: ReadableStream;
|
|
16
|
+
size: number;
|
|
17
|
+
httpMetadata?: {
|
|
18
|
+
contentType?: string;
|
|
19
|
+
};
|
|
20
|
+
customMetadata?: Record<string, string>;
|
|
21
|
+
}
|
|
22
|
+
export interface R2 {
|
|
23
|
+
get(key: string): Promise<R2Object | null>;
|
|
24
|
+
head(key: string): Promise<{
|
|
25
|
+
size: number;
|
|
26
|
+
customMetadata?: Record<string, string>;
|
|
27
|
+
} | null>;
|
|
28
|
+
put(key: string, body: ReadableStream | ArrayBuffer, o?: {
|
|
29
|
+
httpMetadata?: {
|
|
30
|
+
contentType?: string;
|
|
31
|
+
};
|
|
32
|
+
customMetadata?: Record<string, string>;
|
|
33
|
+
}): Promise<unknown>;
|
|
34
|
+
}
|
|
35
|
+
export declare function d1Store(db: D1): PostingStore;
|
|
36
|
+
export declare function r2Media(bucket: R2): MediaStore;
|