previewer-agency 0.2.2 → 0.3.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/README.md +33 -5
- package/bin/previewer.mjs +60 -14
- package/lib/api.mjs +4 -1
- package/lib/config.mjs +43 -5
- package/lib/files.mjs +6 -0
- package/lib/mcp.mjs +28 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,20 +1,46 @@
|
|
|
1
1
|
# previewer
|
|
2
2
|
|
|
3
3
|
Upload HTML5 banners, images and videos to [Previewer](https://previewer.agency) from any folder,
|
|
4
|
-
whatever tool built them, and check on approvals.
|
|
4
|
+
whatever tool built them, and check on approvals.
|
|
5
5
|
|
|
6
6
|
```bash
|
|
7
7
|
npx previewer-agency login
|
|
8
8
|
npx previewer-agency push ./dist --client "Acme" --campaign "Spring sale"
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
Needs [Node.js](https://nodejs.org) 20.11 or newer; check with `node --version`.
|
|
14
|
+
|
|
15
|
+
**Without installing**, put `npx previewer-agency` in front of each command, as in the examples on this
|
|
16
|
+
page. npx fetches the latest version the first time.
|
|
17
|
+
|
|
18
|
+
**On your computer**, for the shorter `previewer` command (run it again later to update):
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install -g previewer-agency
|
|
22
|
+
previewer --version
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Every example then works with `previewer` instead of `npx previewer-agency`, for example
|
|
26
|
+
`previewer push ./dist`.
|
|
27
|
+
|
|
28
|
+
**In a project**, so everyone on it uses the same version:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npm install --save-dev previewer-agency
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Then add a script to `package.json`, `"preview": "previewer push dist"`, and run `npm run preview`.
|
|
35
|
+
|
|
11
36
|
## Sign in
|
|
12
37
|
|
|
13
38
|
```bash
|
|
14
39
|
npx previewer-agency login
|
|
15
40
|
```
|
|
16
41
|
|
|
17
|
-
Opens your browser.
|
|
42
|
+
Opens your browser. Type the code your terminal shows and approve (it is never in the link, so nobody
|
|
43
|
+
can send you a link that signs them in). You get an email about it. Your computer
|
|
18
44
|
gets its own token: it can do what you can do in Previewer (owners and editors: upload, create
|
|
19
45
|
campaigns, remove banners; viewers: look), stops working if your access ends, and shows under
|
|
20
46
|
**API** in the admin, where an owner can revoke it. `previewer logout` revokes it yourself.
|
|
@@ -43,8 +69,10 @@ A file with the same name as a banner already in the campaign replaces it as a n
|
|
|
43
69
|
campaign doesn't exist yet, `push` offers to create it (`--create` skips the question). Large files
|
|
44
70
|
and big batches are split up for you.
|
|
45
71
|
|
|
46
|
-
The first push saves the campaign in `.previewer.json` in the current folder (ids
|
|
47
|
-
commit).
|
|
72
|
+
The first push saves the campaign in `.previewer.json` in the current folder (ids, names and the site
|
|
73
|
+
address; safe to commit, it never holds a token). A token is only ever sent to the site you chose
|
|
74
|
+
yourself: `PREVIEWER_TOKEN` goes to `--site`, `PREVIEWER_URL` or previewer.agency, never to a site a
|
|
75
|
+
`.previewer.json` names. Addresses other than `https://` are refused, except `http://localhost`. After that:
|
|
48
76
|
|
|
49
77
|
```bash
|
|
50
78
|
npx previewer-agency push ./dist
|
|
@@ -80,7 +108,7 @@ PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
|
|
|
80
108
|
|
|
81
109
|
`previewer mcp` runs Previewer as an MCP server, so an agent like Claude Code or Cursor can upload,
|
|
82
110
|
check approvals and set up a project for you. It uses the same sign-in as the command line; if this
|
|
83
|
-
computer isn't signed in yet, the agent starts the sign-in and you
|
|
111
|
+
computer isn't signed in yet, the agent starts the sign-in, and you type its code in your browser and approve.
|
|
84
112
|
|
|
85
113
|
Claude Code:
|
|
86
114
|
|
package/bin/previewer.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import os from 'node:os';
|
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { createInterface } from 'node:readline/promises';
|
|
10
10
|
import { parseArgs } from 'node:util';
|
|
11
|
-
import { PreviewerClient, PreviewerError, newCliToken } from '../lib/api.mjs';
|
|
11
|
+
import { PreviewerClient, PreviewerError, isApprovalPath, newCliToken } from '../lib/api.mjs';
|
|
12
12
|
import { collectUploads } from '../lib/files.mjs';
|
|
13
13
|
import { createMcpServer, runStdio } from '../lib/mcp.mjs';
|
|
14
14
|
import { selectMenu } from '../lib/menu.mjs';
|
|
@@ -76,10 +76,24 @@ ${bold('Folders')}
|
|
|
76
76
|
|
|
77
77
|
// PREVIEWER_NO_BROWSER=1 (or no terminal, e.g. over SSH or in CI) prints the link instead. The MCP
|
|
78
78
|
// server has no terminal but does have a person at the computer, so it passes `always`.
|
|
79
|
+
// The URL often comes from the server (a sign-in path, a preview link), so only a well-formed http(s)
|
|
80
|
+
// URL is opened, and on Windows not through `cmd`, which would read & or | in it as commands.
|
|
79
81
|
const openInBrowser = (url, { always = false } = {}) => {
|
|
80
82
|
if (process.env.PREVIEWER_NO_BROWSER || (!interactive && !always)) return false;
|
|
83
|
+
let href;
|
|
84
|
+
try {
|
|
85
|
+
const parsed = new URL(url);
|
|
86
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;
|
|
87
|
+
href = parsed.href;
|
|
88
|
+
} catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
81
91
|
const [command, args] =
|
|
82
|
-
process.platform === 'darwin'
|
|
92
|
+
process.platform === 'darwin'
|
|
93
|
+
? ['open', [href]]
|
|
94
|
+
: process.platform === 'win32'
|
|
95
|
+
? ['rundll32', ['url.dll,FileProtocolHandler', href]]
|
|
96
|
+
: ['xdg-open', [href]];
|
|
83
97
|
try {
|
|
84
98
|
spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => undefined).unref();
|
|
85
99
|
return true;
|
|
@@ -151,12 +165,19 @@ const matchName = (items, wanted, key = 'name') => {
|
|
|
151
165
|
|
|
152
166
|
const clientFor = async (options, project) => {
|
|
153
167
|
const auth = await resolveAuth({ site: options.site, project });
|
|
168
|
+
if (!auth.token && auth.envTokenWithheld) {
|
|
169
|
+
fail(
|
|
170
|
+
`PREVIEWER_TOKEN was not sent to ${auth.site}, which comes from ${auth.siteFrom === 'project' ? PROJECT_FILE : 'your saved sign-in'}.`,
|
|
171
|
+
`The token only goes to the site set with --site or PREVIEWER_URL (default ${DEFAULT_SITE}). If you trust ${auth.site}, set PREVIEWER_URL to it.`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
154
174
|
if (!auth.token) fail(`Not signed in to ${auth.site}.`, `Run: ${CMD} login`);
|
|
155
175
|
return { client: new PreviewerClient({ baseUrl: auth.site, token: auth.token, userAgent: `previewer-cli/${VERSION}` }), auth };
|
|
156
176
|
};
|
|
157
177
|
|
|
158
178
|
const explain = (error) => {
|
|
159
|
-
|
|
179
|
+
// Anything else (an unreadable config, a refused site) is still a plain message, not a stack trace.
|
|
180
|
+
if (!(error instanceof PreviewerError)) fail(error instanceof Error ? error.message : String(error));
|
|
160
181
|
const hint =
|
|
161
182
|
error.code === 'auth'
|
|
162
183
|
? process.env.PREVIEWER_TOKEN
|
|
@@ -177,26 +198,35 @@ async function login(options) {
|
|
|
177
198
|
const { token, hash, hint } = newCliToken();
|
|
178
199
|
const name = `${os.userInfo().username}@${os.hostname().replace(/\.local$/, '')}`;
|
|
179
200
|
const started = await api.startLogin({ tokenHash: hash, tokenHint: hint, clientName: name });
|
|
180
|
-
|
|
201
|
+
if (!isApprovalPath(started.verifyPath)) fail(`${site} answered with an unexpected sign-in address.`, 'Check --site and PREVIEWER_URL.');
|
|
202
|
+
// The code is typed into the page, not carried in the link: a link someone sends you can't sign them in.
|
|
203
|
+
const url = `${site}/admin/cli-login`;
|
|
181
204
|
|
|
182
|
-
say('', `Your code: ${bold(started.userCode)}`, '', `
|
|
183
|
-
say(openInBrowser(url) ? dim('(Opened your browser.
|
|
205
|
+
say('', `Your code: ${bold(started.userCode)}`, '', `Enter it in the browser: ${url}`);
|
|
206
|
+
say(openInBrowser(url) ? dim('(Opened your browser.)') : dim('(Open that address in your browser.)'));
|
|
184
207
|
say(dim('Waiting for approval…'));
|
|
185
208
|
|
|
186
209
|
const deadline = Date.parse(started.expiresAt);
|
|
187
210
|
while (Date.now() < deadline) {
|
|
188
211
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
|
189
|
-
|
|
212
|
+
// A dropped connection while waiting isn't the end of the sign-in: keep asking until it expires.
|
|
213
|
+
let status;
|
|
214
|
+
try {
|
|
215
|
+
status = await api.loginStatus(started.requestId, token);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (error instanceof PreviewerError && error.code === 'network') continue;
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
190
220
|
if (status === 'approved') {
|
|
191
221
|
const me = await new PreviewerClient({ baseUrl: site, token }).me();
|
|
192
|
-
await saveSiteLogin(site, { token, account: me.account });
|
|
222
|
+
await saveSiteLogin(site, { token, account: me.account }, { makeDefault: Boolean(options.site) });
|
|
193
223
|
say(`${green('✔')} Signed in to ${bold(me.account?.name ?? site)} (${me.token.permission}).`);
|
|
194
224
|
return;
|
|
195
225
|
}
|
|
196
|
-
if (status === 'denied') fail('The
|
|
226
|
+
if (status === 'denied') fail('The sign-in was denied.');
|
|
197
227
|
if (status === 'expired') break;
|
|
198
228
|
}
|
|
199
|
-
fail('The
|
|
229
|
+
fail('The sign-in expired before it was approved.', `Run ${CMD} login again.`);
|
|
200
230
|
}
|
|
201
231
|
|
|
202
232
|
async function logout(options) {
|
|
@@ -301,7 +331,9 @@ async function listCampaigns(options) {
|
|
|
301
331
|
if (options.json) return say(JSON.stringify(campaigns, null, 2));
|
|
302
332
|
if (campaigns.length === 0) return say('No campaigns.');
|
|
303
333
|
for (const campaign of campaigns) {
|
|
304
|
-
|
|
334
|
+
// Out of what the client can approve (not links or banners hidden from the preview); an older
|
|
335
|
+
// server without that count falls back to all banners.
|
|
336
|
+
const approvals = campaign.approvedCount === null ? '' : ` · ${campaign.approvedCount}/${campaign.reviewableCount ?? campaign.bannerCount} approved`;
|
|
305
337
|
say(`${dim(String(campaign.id).padStart(5))} ${bold(campaign.name)} ${dim(`— ${campaign.client.name}`)}`, ` ${campaign.bannerCount} banners${approvals} · ${campaign.previewUrl}`);
|
|
306
338
|
}
|
|
307
339
|
}
|
|
@@ -329,6 +361,14 @@ async function push(options, folder = '.') {
|
|
|
329
361
|
if (options['dry-run']) {
|
|
330
362
|
say(`${bold('Would upload')} ${summary} (${kb(total)}):`);
|
|
331
363
|
for (const item of items) say(` ${dim(item.type.padEnd(6))} ${item.source}${item.source !== item.name ? dim(` → ${item.name}`) : ''} ${dim(kb(item.size))}`);
|
|
364
|
+
// Uploads nothing, but does say now what the real push would stop on: a client that isn't there.
|
|
365
|
+
if (options.client) {
|
|
366
|
+
const auth = await resolveAuth({ site: options.site, project: await findProject(process.cwd()) });
|
|
367
|
+
if (!auth.token) return say('', dim(`Not signed in to ${auth.site}, so the client and campaign weren't checked.`));
|
|
368
|
+
const clients = await new PreviewerClient({ baseUrl: auth.site, token: auth.token, userAgent: `previewer-cli/${VERSION}` }).clients();
|
|
369
|
+
const known = /^\d+$/.test(String(options.client)) ? clients.some((client) => client.id === Number(options.client)) : matchName(clients, options.client).length > 0;
|
|
370
|
+
if (!known) say('', `${yellow('!')} No client "${options.client}" yet. Create it in the Previewer admin first; the campaign is created for you.`);
|
|
371
|
+
}
|
|
332
372
|
return;
|
|
333
373
|
}
|
|
334
374
|
|
|
@@ -361,7 +401,8 @@ async function status(options) {
|
|
|
361
401
|
const { campaign } = await resolveCampaign(api, options, project);
|
|
362
402
|
if (options.json) return say(JSON.stringify(campaign, null, 2));
|
|
363
403
|
|
|
364
|
-
|
|
404
|
+
// What the client can approve: no links, nothing hidden from the preview.
|
|
405
|
+
const reviewable = campaign.banners.filter((banner) => banner.kind !== 'external' && !banner.hidden);
|
|
365
406
|
const approved = reviewable.filter((banner) => banner.status === 'approved').length;
|
|
366
407
|
say(
|
|
367
408
|
`${bold(`${campaign.client.name} → ${campaign.name}`)}`,
|
|
@@ -376,7 +417,11 @@ async function status(options) {
|
|
|
376
417
|
const width = Math.max(10, ...campaign.banners.map((banner) => banner.label.length));
|
|
377
418
|
for (const banner of campaign.banners) {
|
|
378
419
|
const approvedNow = banner.status === 'approved';
|
|
379
|
-
const state =
|
|
420
|
+
const state = banner.hidden
|
|
421
|
+
? dim('hidden'.padEnd(9))
|
|
422
|
+
: !campaign.approvalsRequired
|
|
423
|
+
? ''.padEnd(9)
|
|
424
|
+
: (approvedNow ? green : yellow)((approvedNow ? 'approved' : 'in review').padEnd(9));
|
|
380
425
|
const backup = banner.kind !== 'html' ? ''.padEnd(9) : banner.hasBackup ? dim('backup ✓'.padEnd(9)) : yellow('no backup');
|
|
381
426
|
say(` ${banner.label.padEnd(width)} ${dim(`${banner.width}×${banner.height}`.padEnd(9))} ${state} ${backup} ${dim(ago(banner.updatedAt) ?? '')}`);
|
|
382
427
|
}
|
|
@@ -419,7 +464,8 @@ const main = async () => {
|
|
|
419
464
|
},
|
|
420
465
|
});
|
|
421
466
|
} catch (error) {
|
|
422
|
-
|
|
467
|
+
// Node's parser adds advice about positional arguments that doesn't apply here.
|
|
468
|
+
fail(String(error.message).replace(/\. To specify a positional argument.*$/s, '.'), `Run ${CMD} help.`);
|
|
423
469
|
}
|
|
424
470
|
const { values, positionals } = parsed;
|
|
425
471
|
if (values.version) return say(VERSION);
|
package/lib/api.mjs
CHANGED
|
@@ -13,6 +13,10 @@ export class PreviewerError extends Error {
|
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
// Where a server may send the browser to approve `previewer login`: only the admin's own approval
|
|
17
|
+
// page. Anything else (another host, a path with shell characters) is refused before it is opened.
|
|
18
|
+
export const isApprovalPath = (value) => typeof value === 'string' && /^\/admin\/cli-login(\?code=[A-Z0-9-]{9})?$/.test(value);
|
|
19
|
+
|
|
16
20
|
// Vercel caps one request body at 4.5 MB. Small files go in batches under 4 MB; anything over
|
|
17
21
|
// 3.5 MB is uploaded straight to storage first (upload-urls) and then registered.
|
|
18
22
|
const MAX_BATCH_BYTES = 4 * 1024 * 1024;
|
|
@@ -227,7 +231,6 @@ async function putToStorage(config, target, buffer, contentType) {
|
|
|
227
231
|
headers: {
|
|
228
232
|
apikey: config.supabaseAnonKey,
|
|
229
233
|
Authorization: `Bearer ${config.supabaseAnonKey}`,
|
|
230
|
-
'x-upsert': 'true',
|
|
231
234
|
'content-type': contentType || 'application/octet-stream',
|
|
232
235
|
},
|
|
233
236
|
body: buffer,
|
package/lib/config.mjs
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
// Where the CLI keeps things:
|
|
2
2
|
// - Sign-in per site: ~/.config/previewer/config.json (%APPDATA%\previewer on Windows), readable
|
|
3
3
|
// only by you (600). PREVIEWER_TOKEN / PREVIEWER_URL override it, for CI.
|
|
4
|
-
// - Which campaign a folder publishes to: .previewer.json in that folder (safe to commit: ids
|
|
4
|
+
// - Which campaign a folder publishes to: .previewer.json in that folder (safe to commit: ids and,
|
|
5
|
+
// when it isn't the default, the site address; never a token). A token is only ever sent to a
|
|
6
|
+
// site you chose yourself: PREVIEWER_TOKEN goes to --site, PREVIEWER_URL or previewer.agency, never
|
|
7
|
+
// to a site named in a .previewer.json, which anyone with commit access can edit.
|
|
5
8
|
|
|
6
9
|
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
7
10
|
import os from 'node:os';
|
|
@@ -12,6 +15,20 @@ export const PROJECT_FILE = '.previewer.json';
|
|
|
12
15
|
|
|
13
16
|
export const normalizeSite = (value) => String(value || '').trim().replace(/\/+$/, '');
|
|
14
17
|
|
|
18
|
+
// A token travels in a header, so only over https; plain http is for a local dev server.
|
|
19
|
+
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
20
|
+
export const siteProblem = (site) => {
|
|
21
|
+
let url;
|
|
22
|
+
try {
|
|
23
|
+
url = new URL(site);
|
|
24
|
+
} catch {
|
|
25
|
+
return `"${site}" is not a web address.`;
|
|
26
|
+
}
|
|
27
|
+
if (url.protocol === 'https:') return null;
|
|
28
|
+
if (url.protocol === 'http:' && (LOCAL_HOSTS.has(url.hostname) || url.hostname.endsWith('.localhost'))) return null;
|
|
29
|
+
return `"${site}" isn't https. Previewer only sends your token over https (plain http only for localhost).`;
|
|
30
|
+
};
|
|
31
|
+
|
|
15
32
|
const configDir = () =>
|
|
16
33
|
process.platform === 'win32'
|
|
17
34
|
? path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'previewer')
|
|
@@ -34,19 +51,40 @@ export const saveConfig = async (config) => {
|
|
|
34
51
|
await chmod(configPath(), 0o600).catch(() => undefined);
|
|
35
52
|
};
|
|
36
53
|
|
|
37
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* The site and token to use: flags, then environment, then the folder's link, then the saved default.
|
|
56
|
+
* PREVIEWER_TOKEN is sent only to the site you named yourself (--site, else PREVIEWER_URL, else
|
|
57
|
+
* previewer.agency); for any other site only a token saved by `previewer login` to that very site is
|
|
58
|
+
* used. `envTokenWithheld` is set when PREVIEWER_TOKEN was there but not sent, to explain why.
|
|
59
|
+
*/
|
|
38
60
|
export const resolveAuth = async ({ site: siteFlag, project } = {}) => {
|
|
39
61
|
const config = await loadConfig();
|
|
40
62
|
const site = normalizeSite(siteFlag || process.env.PREVIEWER_URL || project?.site || config.defaultSite || DEFAULT_SITE);
|
|
63
|
+
// Where that site came from, for messages that have to say so.
|
|
64
|
+
const siteFrom = siteFlag ? 'flag' : process.env.PREVIEWER_URL ? 'env' : project?.site ? 'project' : config.defaultSite ? 'saved' : 'default';
|
|
65
|
+
const problem = siteProblem(site);
|
|
66
|
+
if (problem) throw new Error(problem);
|
|
41
67
|
const envToken = String(process.env.PREVIEWER_TOKEN || '').trim();
|
|
68
|
+
const envSite = normalizeSite(siteFlag || process.env.PREVIEWER_URL || DEFAULT_SITE);
|
|
69
|
+
const useEnvToken = Boolean(envToken) && site === envSite;
|
|
42
70
|
const saved = config.sites?.[site];
|
|
43
|
-
return {
|
|
71
|
+
return {
|
|
72
|
+
site,
|
|
73
|
+
siteFrom,
|
|
74
|
+
token: (useEnvToken ? envToken : '') || saved?.token || '',
|
|
75
|
+
fromEnv: useEnvToken,
|
|
76
|
+
envTokenWithheld: Boolean(envToken) && !useEnvToken,
|
|
77
|
+
account: saved?.account ?? null,
|
|
78
|
+
config,
|
|
79
|
+
};
|
|
44
80
|
};
|
|
45
81
|
|
|
46
|
-
|
|
82
|
+
// `makeDefault` only when the person named the site themselves (`login --site`): a login started
|
|
83
|
+
// some other way (an AI agent, a folder's .previewer.json) must not move every later command to it.
|
|
84
|
+
export const saveSiteLogin = async (site, { token, account }, { makeDefault = false } = {}) => {
|
|
47
85
|
const config = await loadConfig();
|
|
48
86
|
config.sites = { ...(config.sites || {}), [site]: { token, account, savedAt: new Date().toISOString() } };
|
|
49
|
-
config.defaultSite = site;
|
|
87
|
+
if (makeDefault) config.defaultSite = site;
|
|
50
88
|
await saveConfig(config);
|
|
51
89
|
};
|
|
52
90
|
|
package/lib/files.mjs
CHANGED
|
@@ -244,6 +244,12 @@ export const collectUploads = async (dir) => {
|
|
|
244
244
|
skipped.push({ name: image.name, reason: 'backup images must be JPG, PNG or WebP' });
|
|
245
245
|
continue;
|
|
246
246
|
}
|
|
247
|
+
// Its banner has no size in the file name (the size is only in the ad.size tag), so there is no
|
|
248
|
+
// id to hang the backup on, and the server would refuse the whole backup batch over it.
|
|
249
|
+
if (pair && !pair.id && !sizeFromName(image.name)) {
|
|
250
|
+
skipped.push({ name: image.name, reason: `backup for ${baseName(image.name)}.zip, which has no size in its name: rename both, e.g. ${baseName(image.name)}-300x250` });
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
247
253
|
// Named after its banner's id when known, so it lands on exactly that banner.
|
|
248
254
|
const name = pair?.id ? `${pair.id}${ext}` : image.name;
|
|
249
255
|
items.push({ type: 'backup', name, size: info.size, path: image.full, mimeType: MIME[ext], source: path.relative(dir, image.full) });
|
package/lib/mcp.mjs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import os from 'node:os';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { createInterface } from 'node:readline';
|
|
10
|
-
import { PreviewerClient, PreviewerError, newCliToken } from './api.mjs';
|
|
10
|
+
import { PreviewerClient, PreviewerError, isApprovalPath, newCliToken } from './api.mjs';
|
|
11
11
|
import { collectUploads } from './files.mjs';
|
|
12
12
|
import { PROJECT_FILE, findProject, resolveAuth, saveProject, saveSiteLogin } from './config.mjs';
|
|
13
13
|
|
|
@@ -56,6 +56,7 @@ const campaignSummary = (campaign) => ({
|
|
|
56
56
|
client: campaign.client,
|
|
57
57
|
previewUrl: campaign.previewUrl,
|
|
58
58
|
bannerCount: campaign.bannerCount,
|
|
59
|
+
reviewableCount: campaign.reviewableCount ?? null,
|
|
59
60
|
approvedCount: campaign.approvedCount,
|
|
60
61
|
});
|
|
61
62
|
|
|
@@ -84,7 +85,19 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
84
85
|
const connect = async (folder) => {
|
|
85
86
|
const project = await d.findProject(folderPath(folder));
|
|
86
87
|
const auth = await d.resolveAuth({ project });
|
|
88
|
+
if (!auth.token && auth.envTokenWithheld) {
|
|
89
|
+
throw new ToolError(
|
|
90
|
+
`PREVIEWER_TOKEN is not sent to ${auth.site}, which comes from ${auth.siteFrom === 'project' ? PROJECT_FILE : 'the saved sign-in'}: it only goes to PREVIEWER_URL (default https://previewer.agency). Ask the user whether to trust that site.`,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
87
93
|
if (!auth.token) {
|
|
94
|
+
// sign_in only ever signs in to the site the person set up, so for a folder that points
|
|
95
|
+
// somewhere else it would never help: the person has to sign in there themselves.
|
|
96
|
+
if (auth.siteFrom === 'project') {
|
|
97
|
+
throw new ToolError(
|
|
98
|
+
`Not signed in to ${auth.site}, the site this folder's ${PROJECT_FILE} names. sign_in can't sign in there. Ask the user whether they trust that site, and if so to run: previewer login --site ${auth.site}`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
88
101
|
const waiting = login?.status === 'pending' ? ` A sign-in is waiting for approval: code ${login.code} at ${login.url}.` : ' Call sign_in.';
|
|
89
102
|
throw new ToolError(`Not signed in to ${auth.site}.${waiting}`);
|
|
90
103
|
}
|
|
@@ -128,17 +141,22 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
128
141
|
return path.relative(cwd, file) || file;
|
|
129
142
|
};
|
|
130
143
|
|
|
131
|
-
|
|
132
|
-
|
|
144
|
+
// Signs in to the site the person set up (PREVIEWER_URL, else previewer.agency, else the saved
|
|
145
|
+
// default): never one an agent names, so a prompt-injected agent can't point the browser, and every
|
|
146
|
+
// later upload, at a look-alike site.
|
|
147
|
+
const startLogin = async () => {
|
|
148
|
+
const auth = await d.resolveAuth({});
|
|
133
149
|
if (login?.status === 'pending' && login.site === auth.site && Date.now() < login.expires) return login;
|
|
134
150
|
const api = d.makeClient({ baseUrl: auth.site, userAgent });
|
|
135
151
|
const { token, hash, hint } = newCliToken();
|
|
136
152
|
const started = await api.startLogin({ tokenHash: hash, tokenHint: hint, clientName: d.deviceName() });
|
|
153
|
+
if (!isApprovalPath(started.verifyPath)) throw new ToolError(`${auth.site} answered with an unexpected sign-in address.`);
|
|
137
154
|
const current = {
|
|
138
155
|
status: 'pending',
|
|
139
156
|
site: auth.site,
|
|
140
157
|
code: started.userCode,
|
|
141
|
-
|
|
158
|
+
// The code is typed into the page by the person, never carried in the link.
|
|
159
|
+
url: `${auth.site}/admin/cli-login`,
|
|
142
160
|
expires: Date.parse(started.expiresAt),
|
|
143
161
|
};
|
|
144
162
|
login = current;
|
|
@@ -182,7 +200,7 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
182
200
|
return {
|
|
183
201
|
signedIn: false,
|
|
184
202
|
signIn: login ? { status: login.status, code: login.code, url: login.url } : null,
|
|
185
|
-
next: login?.status === 'pending' ? 'Ask the user to
|
|
203
|
+
next: login?.status === 'pending' ? 'Ask the user to type the code on the Previewer page in their browser and approve, then call whoami again.' : 'Call sign_in.',
|
|
186
204
|
};
|
|
187
205
|
}
|
|
188
206
|
throw error;
|
|
@@ -193,17 +211,17 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
193
211
|
name: 'sign_in',
|
|
194
212
|
title: 'Sign in to Previewer',
|
|
195
213
|
description:
|
|
196
|
-
'Start signing this computer in to Previewer. Returns a code and a
|
|
197
|
-
inputSchema: object(
|
|
214
|
+
'Start signing this computer in to Previewer (https://previewer.agency, or the PREVIEWER_URL the user set). Returns a code and a page (also opened in the browser when possible). Ask the user to type the code on that page and approve; only a person signed in to Previewer can. Then call whoami. The request lasts 10 minutes.',
|
|
215
|
+
inputSchema: object(),
|
|
198
216
|
annotations: { openWorldHint: false },
|
|
199
|
-
run: async (
|
|
200
|
-
const current = await startLogin(
|
|
217
|
+
run: async () => {
|
|
218
|
+
const current = await startLogin();
|
|
201
219
|
return {
|
|
202
220
|
status: 'waiting_for_approval',
|
|
203
221
|
code: current.code,
|
|
204
222
|
url: current.url,
|
|
205
223
|
openedInBrowser: Boolean(current.opened),
|
|
206
|
-
next: `Tell the user: open ${current.url},
|
|
224
|
+
next: `Tell the user: open ${current.url}, type the code ${current.code}, and approve. Then call whoami.`,
|
|
207
225
|
};
|
|
208
226
|
},
|
|
209
227
|
},
|
package/package.json
CHANGED