previewer-agency 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,7 +14,8 @@ npx previewer-agency push ./dist --client "Acme" --campaign "Spring sale"
14
14
  npx previewer-agency login
15
15
  ```
16
16
 
17
- Opens your browser. Check that the code matches the one in your terminal and approve. Your computer
17
+ Opens your browser. Type the code your terminal shows and approve (it is never in the link, so nobody
18
+ can send you a link that signs them in). You get an email about it. Your computer
18
19
  gets its own token: it can do what you can do in Previewer (owners and editors: upload, create
19
20
  campaigns, remove banners; viewers: look), stops working if your access ends, and shows under
20
21
  **API** in the admin, where an owner can revoke it. `previewer logout` revokes it yourself.
@@ -43,8 +44,10 @@ A file with the same name as a banner already in the campaign replaces it as a n
43
44
  campaign doesn't exist yet, `push` offers to create it (`--create` skips the question). Large files
44
45
  and big batches are split up for you.
45
46
 
46
- The first push saves the campaign in `.previewer.json` in the current folder (ids only, safe to
47
- commit). After that:
47
+ The first push saves the campaign in `.previewer.json` in the current folder (ids, names and the site
48
+ address; safe to commit, it never holds a token). A token is only ever sent to the site you chose
49
+ yourself: `PREVIEWER_TOKEN` goes to `--site`, `PREVIEWER_URL` or previewer.agency, never to a site a
50
+ `.previewer.json` names. Addresses other than `https://` are refused, except `http://localhost`. After that:
48
51
 
49
52
  ```bash
50
53
  npx previewer-agency push ./dist
@@ -80,7 +83,7 @@ PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
80
83
 
81
84
  `previewer mcp` runs Previewer as an MCP server, so an agent like Claude Code or Cursor can upload,
82
85
  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 approve the code in your browser.
86
+ computer isn't signed in yet, the agent starts the sign-in, and you type its code in your browser and approve.
84
87
 
85
88
  Claude Code:
86
89
 
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';
@@ -31,19 +31,29 @@ const fail = (message, hint) => {
31
31
  process.exit(1);
32
32
  };
33
33
 
34
+ // How this person runs us, so help and hints show a command that works when typed: through npx
35
+ // (no global install, so `previewer` itself isn't on their PATH) it's `npx previewer-agency`.
36
+ const RAN_VIA_NPX = process.env.npm_command === 'exec' || /[\\/]_npx[\\/]/.test(process.argv[1] || '');
37
+ const CMD = RAN_VIA_NPX ? 'npx previewer-agency' : 'previewer';
38
+
39
+ const COMMAND_HELP = [
40
+ ['login', 'Sign in (opens the browser to approve)'],
41
+ ['push [folder]', 'Upload a folder: ZIPs, banner folders, images, videos, backups'],
42
+ ['status', "Approvals and views of this folder's campaign"],
43
+ ['open', "Open the campaign's preview link"],
44
+ ['link', 'Choose which campaign this folder publishes to'],
45
+ ['campaigns', 'List campaigns'],
46
+ ['whoami', "Show who you're signed in as"],
47
+ ['logout', "Sign out (revokes this computer's token)"],
48
+ ['mcp', 'Run as an MCP server, for AI agents (Claude Code, Cursor, …)'],
49
+ ];
50
+ const commandWidth = Math.max(...COMMAND_HELP.map(([command]) => `${CMD} ${command}`.length)) + 3;
51
+
34
52
  const HELP = `${bold('previewer')} ${dim(VERSION)} — upload banners to Previewer and check on them
35
53
 
36
54
  ${bold('Usage')}
37
- previewer login Sign in (opens the browser to approve)
38
- previewer push [folder] Upload a folder: ZIPs, banner folders, images, videos, backups
39
- previewer status Approvals and views of this folder's campaign
40
- previewer open Open the campaign's preview link
41
- previewer link Choose which campaign this folder publishes to
42
- previewer campaigns List campaigns
43
- previewer whoami Show who you're signed in as
44
- previewer logout Sign out (revokes this computer's token)
45
- previewer mcp Run as an MCP server, for AI agents (Claude Code, Cursor, …)
46
-
55
+ ${COMMAND_HELP.map(([command, text]) => ` ${`${CMD} ${command}`.padEnd(commandWidth)}${text}`).join('\n')}
56
+ ${RAN_VIA_NPX ? `\n ${dim('Tip: npm install -g previewer-agency, then type just "previewer".')}\n` : ''}
47
57
  ${bold('Options')}
48
58
  --client <name|id> Client to publish to (push, link, campaigns)
49
59
  --campaign <name|id> Campaign to publish to (push, link, status, open)
@@ -55,21 +65,35 @@ ${bold('Options')}
55
65
 
56
66
  ${bold('In CI')}
57
67
  Set PREVIEWER_TOKEN (create one under API in the Previewer admin), then:
58
- previewer push dist --campaign 42
68
+ npx -y previewer-agency push dist --campaign 42
59
69
 
60
70
  ${bold('Folders')}
61
71
  *.zip and folders with an index.html are HTML5 banners. An image with the same name as a banner
62
72
  (300x250.zip + 300x250.jpg), or in a backups/ folder, is its backup image. Other images and videos
63
- are creatives. The first push saves the campaign to ${PROJECT_FILE}; after that, just run push.`;
73
+ are creatives. The first push saves the campaign to ${PROJECT_FILE}; after that, just run ${CMD} push.`;
64
74
 
65
75
  // --- small helpers -------------------------------------------------------------------------------
66
76
 
67
77
  // PREVIEWER_NO_BROWSER=1 (or no terminal, e.g. over SSH or in CI) prints the link instead. The MCP
68
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.
69
81
  const openInBrowser = (url, { always = false } = {}) => {
70
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
+ }
71
91
  const [command, args] =
72
- process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
92
+ process.platform === 'darwin'
93
+ ? ['open', [href]]
94
+ : process.platform === 'win32'
95
+ ? ['rundll32', ['url.dll,FileProtocolHandler', href]]
96
+ : ['xdg-open', [href]];
73
97
  try {
74
98
  spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => undefined).unref();
75
99
  return true;
@@ -141,19 +165,26 @@ const matchName = (items, wanted, key = 'name') => {
141
165
 
142
166
  const clientFor = async (options, project) => {
143
167
  const auth = await resolveAuth({ site: options.site, project });
144
- if (!auth.token) fail(`Not signed in to ${auth.site}.`, 'Run: previewer login');
168
+ if (!auth.token && auth.envTokenWithheld) {
169
+ fail(
170
+ `PREVIEWER_TOKEN was not sent to ${auth.site}, which comes from ${PROJECT_FILE}.`,
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
+ }
174
+ if (!auth.token) fail(`Not signed in to ${auth.site}.`, `Run: ${CMD} login`);
145
175
  return { client: new PreviewerClient({ baseUrl: auth.site, token: auth.token, userAgent: `previewer-cli/${VERSION}` }), auth };
146
176
  };
147
177
 
148
178
  const explain = (error) => {
149
- if (!(error instanceof PreviewerError)) throw error;
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));
150
181
  const hint =
151
182
  error.code === 'auth'
152
183
  ? process.env.PREVIEWER_TOKEN
153
184
  ? 'Check PREVIEWER_TOKEN.'
154
- : 'Run: previewer login'
185
+ : `Run: ${CMD} login`
155
186
  : error.code === 'forbidden'
156
- ? 'Your token can\'t do this. Ask an owner, or sign in again with previewer login.'
187
+ ? `Your token can't do this. Ask an owner, or sign in again with ${CMD} login.`
157
188
  : error.code === 'not_found'
158
189
  ? 'Check the id, or that your token can reach it.'
159
190
  : undefined;
@@ -167,10 +198,12 @@ async function login(options) {
167
198
  const { token, hash, hint } = newCliToken();
168
199
  const name = `${os.userInfo().username}@${os.hostname().replace(/\.local$/, '')}`;
169
200
  const started = await api.startLogin({ tokenHash: hash, tokenHint: hint, clientName: name });
170
- const url = `${site}${started.verifyPath}`;
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`;
171
204
 
172
- say('', `Your code: ${bold(started.userCode)}`, '', `Approve it in the browser: ${url}`);
173
- say(openInBrowser(url) ? dim('(Opened your browser. Check that it shows the same code.)') : dim('(Open that link in 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.)'));
174
207
  say(dim('Waiting for approval…'));
175
208
 
176
209
  const deadline = Date.parse(started.expiresAt);
@@ -179,14 +212,14 @@ async function login(options) {
179
212
  const status = await api.loginStatus(started.requestId, token);
180
213
  if (status === 'approved') {
181
214
  const me = await new PreviewerClient({ baseUrl: site, token }).me();
182
- await saveSiteLogin(site, { token, account: me.account });
215
+ await saveSiteLogin(site, { token, account: me.account }, { makeDefault: Boolean(options.site) });
183
216
  say(`${green('✔')} Signed in to ${bold(me.account?.name ?? site)} (${me.token.permission}).`);
184
217
  return;
185
218
  }
186
219
  if (status === 'denied') fail('The login was denied.');
187
220
  if (status === 'expired') break;
188
221
  }
189
- fail('The login expired before it was approved.', 'Run previewer login again.');
222
+ fail('The login expired before it was approved.', `Run ${CMD} login again.`);
190
223
  }
191
224
 
192
225
  async function logout(options) {
@@ -273,7 +306,7 @@ const pickCampaign = async (api, options, { allowCreate }) => {
273
306
  const rememberCampaign = async (site, campaign, project) => {
274
307
  if (project?.campaignId === campaign.id && project?.site === site) return;
275
308
  const file = await saveProject(process.cwd(), { site, campaignId: campaign.id, clientId: campaign.client.id, client: campaign.client.name, campaign: campaign.name });
276
- say(dim(`Saved to ${path.relative(process.cwd(), file) || file}: next time just run previewer push.`));
309
+ say(dim(`Saved to ${path.relative(process.cwd(), file) || file}: next time just run ${CMD} push.`));
277
310
  };
278
311
 
279
312
  async function link(options) {
@@ -409,14 +442,15 @@ const main = async () => {
409
442
  },
410
443
  });
411
444
  } catch (error) {
412
- fail(error.message, 'Run previewer help.');
445
+ // Node's parser adds advice about positional arguments that doesn't apply here.
446
+ fail(String(error.message).replace(/\. To specify a positional argument.*$/s, '.'), `Run ${CMD} help.`);
413
447
  }
414
448
  const { values, positionals } = parsed;
415
449
  if (values.version) return say(VERSION);
416
450
  const [command, ...rest] = positionals;
417
451
  if (!command || values.help || command === 'help') return say(HELP);
418
452
  const run = COMMANDS[command];
419
- if (!run) fail(`Unknown command "${command}".`, 'Run previewer help.');
453
+ if (!run) fail(`Unknown command "${command}".`, `Run ${CMD} help.`);
420
454
  try {
421
455
  await run(values, ...rest);
422
456
  } catch (error) {
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 only).
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,37 @@ export const saveConfig = async (config) => {
34
51
  await chmod(configPath(), 0o600).catch(() => undefined);
35
52
  };
36
53
 
37
- /** The site and token to use: flags, then environment, then the folder's link, then the saved default. */
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
+ const problem = siteProblem(site);
64
+ if (problem) throw new Error(problem);
41
65
  const envToken = String(process.env.PREVIEWER_TOKEN || '').trim();
66
+ const envSite = normalizeSite(siteFlag || process.env.PREVIEWER_URL || DEFAULT_SITE);
67
+ const useEnvToken = Boolean(envToken) && site === envSite;
42
68
  const saved = config.sites?.[site];
43
- return { site, token: envToken || saved?.token || '', fromEnv: Boolean(envToken), account: saved?.account ?? null, config };
69
+ return {
70
+ site,
71
+ token: (useEnvToken ? envToken : '') || saved?.token || '',
72
+ fromEnv: useEnvToken,
73
+ envTokenWithheld: Boolean(envToken) && !useEnvToken,
74
+ account: saved?.account ?? null,
75
+ config,
76
+ };
44
77
  };
45
78
 
46
- export const saveSiteLogin = async (site, { token, account }) => {
79
+ // `makeDefault` only when the person named the site themselves (`login --site`): a login started
80
+ // some other way (an AI agent, a folder's .previewer.json) must not move every later command to it.
81
+ export const saveSiteLogin = async (site, { token, account }, { makeDefault = false } = {}) => {
47
82
  const config = await loadConfig();
48
83
  config.sites = { ...(config.sites || {}), [site]: { token, account, savedAt: new Date().toISOString() } };
49
- config.defaultSite = site;
84
+ if (makeDefault) config.defaultSite = site;
50
85
  await saveConfig(config);
51
86
  };
52
87
 
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
 
@@ -84,6 +84,11 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
84
84
  const connect = async (folder) => {
85
85
  const project = await d.findProject(folderPath(folder));
86
86
  const auth = await d.resolveAuth({ project });
87
+ if (!auth.token && auth.envTokenWithheld) {
88
+ throw new ToolError(
89
+ `PREVIEWER_TOKEN is not sent to ${auth.site}, which comes from ${PROJECT_FILE}: it only goes to PREVIEWER_URL (default https://previewer.agency). Ask the user whether to trust that site.`,
90
+ );
91
+ }
87
92
  if (!auth.token) {
88
93
  const waiting = login?.status === 'pending' ? ` A sign-in is waiting for approval: code ${login.code} at ${login.url}.` : ' Call sign_in.';
89
94
  throw new ToolError(`Not signed in to ${auth.site}.${waiting}`);
@@ -128,17 +133,22 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
128
133
  return path.relative(cwd, file) || file;
129
134
  };
130
135
 
131
- const startLogin = async (site) => {
132
- const auth = await d.resolveAuth({ site });
136
+ // Signs in to the site the person set up (PREVIEWER_URL, else previewer.agency, else the saved
137
+ // default): never one an agent names, so a prompt-injected agent can't point the browser, and every
138
+ // later upload, at a look-alike site.
139
+ const startLogin = async () => {
140
+ const auth = await d.resolveAuth({});
133
141
  if (login?.status === 'pending' && login.site === auth.site && Date.now() < login.expires) return login;
134
142
  const api = d.makeClient({ baseUrl: auth.site, userAgent });
135
143
  const { token, hash, hint } = newCliToken();
136
144
  const started = await api.startLogin({ tokenHash: hash, tokenHint: hint, clientName: d.deviceName() });
145
+ if (!isApprovalPath(started.verifyPath)) throw new ToolError(`${auth.site} answered with an unexpected sign-in address.`);
137
146
  const current = {
138
147
  status: 'pending',
139
148
  site: auth.site,
140
149
  code: started.userCode,
141
- url: `${auth.site}${started.verifyPath}`,
150
+ // The code is typed into the page by the person, never carried in the link.
151
+ url: `${auth.site}/admin/cli-login`,
142
152
  expires: Date.parse(started.expiresAt),
143
153
  };
144
154
  login = current;
@@ -182,7 +192,7 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
182
192
  return {
183
193
  signedIn: false,
184
194
  signIn: login ? { status: login.status, code: login.code, url: login.url } : null,
185
- next: login?.status === 'pending' ? 'Ask the user to approve the code in their browser, then call whoami again.' : 'Call sign_in.',
195
+ 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
196
  };
187
197
  }
188
198
  throw error;
@@ -193,17 +203,17 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
193
203
  name: 'sign_in',
194
204
  title: 'Sign in to Previewer',
195
205
  description:
196
- 'Start signing this computer in to Previewer. Returns a code and a link (also opened in the browser when possible). Ask the user to open the link, check that it shows the same code, and approve; only a person signed in to Previewer can. Then call whoami. The request lasts 10 minutes.',
197
- inputSchema: object({ site: { type: 'string', description: 'Previewer address. Default https://previewer.agency.' } }),
206
+ '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.',
207
+ inputSchema: object(),
198
208
  annotations: { openWorldHint: false },
199
- run: async (args) => {
200
- const current = await startLogin(args.site);
209
+ run: async () => {
210
+ const current = await startLogin();
201
211
  return {
202
212
  status: 'waiting_for_approval',
203
213
  code: current.code,
204
214
  url: current.url,
205
215
  openedInBrowser: Boolean(current.opened),
206
- next: `Tell the user: open ${current.url}, check the code ${current.code}, and approve. Then call whoami.`,
216
+ next: `Tell the user: open ${current.url}, type the code ${current.code}, and approve. Then call whoami.`,
207
217
  };
208
218
  },
209
219
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "previewer-agency",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Upload HTML5 banners, images and videos to Previewer from any folder, CI job or AI agent (MCP), and check approvals.",
5
5
  "type": "module",
6
6
  "bin": {