@senseihq/emaki-posting 0.1.1 → 0.1.3

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/dist/access.js CHANGED
@@ -15,8 +15,10 @@ export const paths = { admin: '/admin', api: '/api/admin' };
15
15
  export function configurePaths(p) { Object.assign(paths, p); }
16
16
  export const isAdminPath = (path) => path === paths.admin || path.startsWith(paths.admin + '/') || path.startsWith(paths.api + '/');
17
17
  export const accessConfigured = (c) => Boolean(c.teamDomain && c.aud);
18
+ /** A host without its scheme or trailing slash, so a team domain and an issuer compare however they are written. */
19
+ const bare = (host) => host.replace(/^https?:\/\//, '').replace(/\/$/, '');
18
20
  async function keys(teamDomain, fetchFn, now) {
19
- const url = `https://${teamDomain.replace(/^https?:\/\//, '').replace(/\/$/, '')}/cdn-cgi/access/certs`;
21
+ const url = `https://${bare(teamDomain)}/cdn-cgi/access/certs`;
20
22
  if (certs && certs.url === url && now - certs.at < 3_600_000)
21
23
  return certs.keys;
22
24
  const r = await fetchFn(url);
@@ -25,6 +27,43 @@ async function keys(teamDomain, fetchFn, now) {
25
27
  certs = { url, keys: (await r.json()).keys, at: now };
26
28
  return certs.keys;
27
29
  }
30
+ /** Why a token is refused before anyone is looked up, in the order they are checked; the first that holds refuses. */
31
+ const REFUSALS = [
32
+ // not RS256
33
+ (t) => t.head.alg !== 'RS256',
34
+ // not for this app's audience
35
+ (t, k) => !(Array.isArray(t.claims.aud) ? t.claims.aud : [t.claims.aud]).some((a) => list(k.c.aud).includes(String(a).toLowerCase())),
36
+ // no expiry, or expired
37
+ (t, k) => typeof t.claims.exp !== 'number' || t.claims.exp * 1000 < k.now,
38
+ // issued by another team
39
+ (t, k) => Boolean(t.claims.iss) && bare(String(t.claims.iss)) !== bare(k.c.teamDomain),
40
+ ];
41
+ /** The service-token lists, in the order a client id is looked up in them. */
42
+ const MACHINES = [['stager', 'stagers'], ['poster', 'posters']];
43
+ /** Who the claims name: a listed person by email, else (only without an email) a listed machine by client id. */
44
+ function named(claims, c) {
45
+ const email = String(claims.email ?? '').toLowerCase();
46
+ if (email)
47
+ return list(c.emails).includes(email) ? { role: 'admin', id: email } : null;
48
+ const cn = String(claims.common_name ?? '').toLowerCase();
49
+ const machine = cn ? MACHINES.find(([, ids]) => list(c[ids]).includes(cn)) : undefined;
50
+ return machine ? { role: machine[0], id: cn } : null;
51
+ }
52
+ /** Whether the token is signed by the team key it names. */
53
+ async function signed(t, k) {
54
+ const jwk = (await keys(k.c.teamDomain, k.fetchFn, k.now)).find((x) => x.kid === t.head.kid);
55
+ if (!jwk)
56
+ return false;
57
+ const key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']);
58
+ return crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, b64(t.s), new TextEncoder().encode(`${t.h}.${t.p}`));
59
+ }
60
+ /** The caller a token names, once its claims hold and its signature checks out. Throws on a badly encoded token. */
61
+ async function callerOfToken(h, p, s, k) {
62
+ const t = { h, p, s, head: part(h), claims: part(p) };
63
+ const caller = REFUSALS.some((refuse) => refuse(t, k)) ? null : named(t.claims, k.c);
64
+ // The keys are fetched only for a token that names someone.
65
+ return caller && (await signed(t, k)) ? caller : null;
66
+ }
28
67
  /** The caller behind a valid Access token for this app, or null. */
29
68
  export async function verifyCaller(token, c, fetchFn = fetch, now = Date.now()) {
30
69
  if (!token || !accessConfigured(c))
@@ -32,54 +71,28 @@ export async function verifyCaller(token, c, fetchFn = fetch, now = Date.now())
32
71
  const [h, p, s] = token.split('.');
33
72
  if (!h || !p || !s)
34
73
  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
- }
74
+ return callerOfToken(h, p, s, { c, fetchFn, now }).catch(() => null);
68
75
  }
76
+ /** The endpoints each machine may use, as 'METHOD path' under the API prefix; a path ending in '/' is a prefix. */
77
+ const GRANTS = {
78
+ // The producing machine: upload media, stage posts, report what is produced, read and answer motion requests.
79
+ stager: ['PUT media/', 'POST stage', 'POST production', 'GET requests', 'POST requests'],
80
+ // The CI poster: read the approved queue and the posting order, download media, report outcomes.
81
+ poster: ['GET queue', 'POST posted', 'GET media/', 'GET schedule'],
82
+ };
83
+ const covers = (grant, method, sub) => {
84
+ const [m, path] = grant.split(' ');
85
+ return m === method && (path.endsWith('/') ? sub.startsWith(path) : sub === path);
86
+ };
69
87
  /** Which roles may use a path (and method). People: everything. Machines: only their own endpoints. */
70
88
  export function allowed(role, path, method) {
71
89
  if (role === 'admin')
72
90
  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;
91
+ const prefix = `${paths.api}/`;
92
+ if (!Object.hasOwn(GRANTS, role) || !path.startsWith(prefix))
93
+ return false;
94
+ const sub = path.slice(prefix.length);
95
+ return GRANTS[role].some((g) => covers(g, method, sub));
83
96
  }
84
97
  /** for tests: forget the cached keys */
85
98
  export function resetAccessCache() { certs = null; }
package/dist/api.d.ts CHANGED
@@ -1,6 +1,9 @@
1
- import { type Channel, type Production, type StagedPost } from './rules.js';
1
+ import { type Channel } from './rules.js';
2
2
  import type { Caller } from './access.js';
3
3
  import type { MediaStore, PostingStore } from './store.js';
4
+ import { HttpError } from './desk/http.js';
5
+ import * as page from './desk/page.js';
6
+ export { HttpError };
4
7
  /** One piece the desk knows about: its slug, its date as built, and (optionally) its kind. */
5
8
  export interface Piece {
6
9
  slug: string;
@@ -26,131 +29,10 @@ export interface DeskOptions {
26
29
  /** Channels expected for a piece (default: Shorts go everywhere; wide films skip the carousel). */
27
30
  channelsFor?: (p: Piece) => Channel[];
28
31
  }
29
- export declare class HttpError extends Error {
30
- status: number;
31
- constructor(status: number, message: string);
32
- }
33
32
  export declare function createDesk(o: DeskOptions): {
34
33
  api: (request: Request, caller: Caller, sub: string) => Promise<Response>;
35
34
  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
- };
35
+ desk: page.DeskActions;
154
36
  queue: (origin: string) => Promise<{
155
37
  paused: boolean;
156
38
  today: string;
@@ -158,7 +40,7 @@ export declare function createDesk(o: DeskOptions): {
158
40
  slug: string;
159
41
  channel: "youtube" | "instagram_reel" | "instagram_carousel" | "x";
160
42
  content_sha: string;
161
- post: StagedPost;
43
+ post: import("./rules.js").StagedPost;
162
44
  article: string;
163
45
  video: string;
164
46
  media: {
package/dist/api.js CHANGED
@@ -1,229 +1,62 @@
1
1
  // The desk's HTTP API as plain Web Request → Response, so it runs in any server that speaks fetch (SvelteKit, a
2
2
  // Cloudflare Worker, Hono, Next.js route handlers, Bun, Deno). Machines use it: the producing machine stages posts and
3
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;
4
+ // the `desk` actions below from its own form handlers. The handlers live in ./desk/machine.ts and ./desk/page.ts.
5
+ import { CHANNELS } from './rules.js';
6
+ import { HttpError, json, refusal } from './desk/http.js';
7
+ import * as machine from './desk/machine.js';
8
+ import * as page from './desk/page.js';
9
+ export { HttpError };
10
+ const answer = async (data) => json(await data);
11
+ // The body is parsed only once the route is known, so an unknown route never reads it.
12
+ const body = (request) => request.json();
13
+ const ROUTES = [
14
+ { method: 'GET', path: 'queue', handle: (d, r) => answer(machine.queue(d, new URL(r.url).origin)) },
15
+ { method: 'POST', path: 'posted', handle: async (d, r, c) => answer(machine.posted(d, c, await body(r))) },
16
+ { method: 'POST', path: 'stage', handle: async (d, r, c) => answer(machine.stage(d, c, await body(r))) },
17
+ { method: 'POST', path: 'production', handle: async (d, r) => answer(machine.production(d, await body(r))) },
18
+ { method: 'GET', path: 'schedule', handle: (d) => answer(machine.schedule(d)) },
19
+ { method: 'GET', path: 'requests', handle: (d) => answer(machine.openRequests(d)) },
20
+ { method: 'POST', path: 'requests', handle: async (d, r, c) => answer(machine.answerRequest(d, c, await body(r))) },
21
+ { method: 'GET', path: 'media/', handle: (d, _r, _c, key) => machine.getMedia(d, key) },
22
+ { method: 'PUT', path: 'media/', handle: (d, r, c, key) => answer(machine.putMedia(d, c, key, r)) },
23
+ ];
24
+ const isPrefix = (route) => route.path.endsWith('/');
25
+ const matches = (route, method, sub) => route.method === method && (isPrefix(route) ? sub.startsWith(route.path) : sub === route.path);
26
+ const restOf = (route, sub) => (isPrefix(route) ? sub.slice(route.path.length) : '');
27
+ /** The API under the admin prefix: `sub` is the path after it ('queue', 'media/<slug>/<file>', ...). */
28
+ async function api(d, request, caller, sub) {
29
+ const route = ROUTES.find((r) => matches(r, request.method, sub));
30
+ try {
31
+ return route ? await route.handle(d, request, caller, restOf(route, sub)) : refusal(404, 'Not found');
32
+ }
33
+ catch (e) {
34
+ if (e instanceof HttpError)
35
+ return refusal(e.status, e.message);
36
+ throw e;
13
37
  }
14
38
  }
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); };
39
+ const defaultChannels = (p) => (p.video === 'short' ? [...CHANNELS] : ['youtube', 'instagram_reel', 'x']);
17
40
  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
- }
41
+ const d = {
42
+ o, store: o.store, media: o.media, expected: o.channelsFor ?? defaultChannels,
43
+ slugs: async () => new Set((await o.pieces()).map((p) => p.slug)),
44
+ };
181
45
  /** What a person does on the desk page. Each returns { ok } or { error } with a status. */
182
46
  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' }; },
47
+ plan: () => page.plan(d),
48
+ approve: (who, slug, items) => page.approve(d, who, slug, items),
49
+ revoke: (who, slug, channel) => page.revoke(d, who, slug, channel),
50
+ makeNext: (who, slug) => page.makeNext(d, who, slug),
51
+ request: (who, slug, kind, body) => page.request(d, who, slug, kind, body),
52
+ reply: (who, id, body, status) => page.reply(d, who, id, body, status),
53
+ pause: (who) => page.pause(d, who),
54
+ resume: (who) => page.resume(d, who),
55
+ };
56
+ return {
57
+ api: (request, caller, sub) => api(d, request, caller, sub),
58
+ signedMedia: (key, url) => machine.signedMedia(d, key, url),
59
+ desk,
60
+ queue: (origin) => machine.queue(d, origin),
227
61
  };
228
- return { api, signedMedia, desk, queue };
229
62
  }
@@ -0,0 +1,24 @@
1
+ import type { DeskOptions, Piece } from '../api.js';
2
+ import type { Channel, RequestRow } from '../rules.js';
3
+ import type { MediaStore, PostingStore } from '../store.js';
4
+ export interface DeskContext {
5
+ o: DeskOptions;
6
+ store: PostingStore;
7
+ media: MediaStore;
8
+ /** The channels a piece is expected to go out on. */
9
+ expected: (p: Piece) => Channel[];
10
+ /** The slugs of the pieces in the built site. */
11
+ slugs: () => Promise<Set<string>>;
12
+ }
13
+ /** The top-level requests that pass `keep`, each with its replies as `thread`. */
14
+ export declare const threaded: (requests: RequestRow[], keep: (r: RequestRow) => boolean) => {
15
+ thread: RequestRow[];
16
+ id: number;
17
+ slug: string;
18
+ kind: string;
19
+ body: string;
20
+ author: string;
21
+ at: string;
22
+ status: string;
23
+ parent: number | null;
24
+ }[];
@@ -0,0 +1,2 @@
1
+ /** The top-level requests that pass `keep`, each with its replies as `thread`. */
2
+ export const threaded = (requests, keep) => requests.filter((r) => !r.parent && keep(r)).map((r) => ({ ...r, thread: requests.filter((x) => x.parent === r.id) }));
@@ -0,0 +1,8 @@
1
+ export declare class HttpError extends Error {
2
+ status: number;
3
+ constructor(status: number, message: string);
4
+ }
5
+ export declare const json: (data: unknown, status?: number) => Response;
6
+ export declare const fail: (status: number, reason: string) => never;
7
+ /** The JSON body every API refusal has. */
8
+ export declare const refusal: (status: number, reason: string) => Response;
@@ -0,0 +1,12 @@
1
+ // Responses and errors shared by the desk's handlers.
2
+ export class HttpError extends Error {
3
+ status;
4
+ constructor(status, message) {
5
+ super(message);
6
+ this.status = status;
7
+ }
8
+ }
9
+ export const json = (data, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } });
10
+ export const fail = (status, reason) => { throw new HttpError(status, reason); };
11
+ /** The JSON body every API refusal has. */
12
+ export const refusal = (status, reason) => json({ ok: false, reason }, status);