previewer-agency 0.2.2 → 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';
@@ -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' ? ['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]];
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 ${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
+ }
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
- 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));
160
181
  const hint =
161
182
  error.code === 'auth'
162
183
  ? process.env.PREVIEWER_TOKEN
@@ -177,10 +198,12 @@ 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
- 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`;
181
204
 
182
- say('', `Your code: ${bold(started.userCode)}`, '', `Approve it in the browser: ${url}`);
183
- 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.)'));
184
207
  say(dim('Waiting for approval…'));
185
208
 
186
209
  const deadline = Date.parse(started.expiresAt);
@@ -189,7 +212,7 @@ async function login(options) {
189
212
  const status = await api.loginStatus(started.requestId, token);
190
213
  if (status === 'approved') {
191
214
  const me = await new PreviewerClient({ baseUrl: site, token }).me();
192
- await saveSiteLogin(site, { token, account: me.account });
215
+ await saveSiteLogin(site, { token, account: me.account }, { makeDefault: Boolean(options.site) });
193
216
  say(`${green('✔')} Signed in to ${bold(me.account?.name ?? site)} (${me.token.permission}).`);
194
217
  return;
195
218
  }
@@ -419,7 +442,8 @@ const main = async () => {
419
442
  },
420
443
  });
421
444
  } catch (error) {
422
- fail(error.message, `Run ${CMD} 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.`);
423
447
  }
424
448
  const { values, positionals } = parsed;
425
449
  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 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.2",
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": {