@buildinternet/uploads 0.6.0 → 0.8.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.
@@ -1,15 +1,26 @@
1
+ import { hostname } from "node:os";
2
+ import { spawn } from "node:child_process";
1
3
  import { stdin, stdout } from "node:process";
2
4
  import { loadConfigFile, redactToken, resolveConfigPath, writeConfigKeys, workspaceFromToken, } from "../config.js";
3
- import { exchangeEnrollment, createUploadsClient } from "../client.js";
5
+ import { createUploadsClient, exchangeEnrollment, listMintWorkspaces, mintWorkspaceToken, requestDeviceCode, requestDeviceToken, } from "../client.js";
4
6
  import { flagBool, flagString, parseCommandArgs, UsageError } from "../cli-args.js";
7
+ import { parseScopes } from "./admin-enrollment.js";
5
8
  const HELP = `uploads login [options]
6
9
 
7
- Exchange a one-time enrollment code for workspace credentials, save them, and
8
- verify access. Ask your uploads.sh administrator for an enrollment code.
10
+ Sign in and save workspace credentials. With no flags, opens a browser to
11
+ authorize this device the recommended way to sign in. Pass an enrollment
12
+ code only if you were given one from before device login (fallback path).
9
13
 
10
14
  Options:
11
- --code <code> Code in argv (may be visible in shell history/process lists)
12
- --code-stdin Read one line from stdin
15
+ --workspace <name> Workspace to mint a token for (device flow; required if
16
+ your account can access more than one)
17
+ --scopes <list> Comma-separated scopes (default: files:read,files:write)
18
+ --label <text> Token label (default: this machine's hostname)
19
+ --auth-url <url> Auth base (default: https://auth.uploads.sh)
20
+ --no-open Don't try to open a browser automatically
21
+ --code <code> Fallback: use a pre-existing enrollment code instead of
22
+ device login (visible in shell history)
23
+ --code-stdin Fallback: read a pre-existing enrollment code from stdin
13
24
  --non-interactive Never prompt
14
25
  --api-url <url> API base (default: https://api.uploads.sh)
15
26
  --path <file> Config destination
@@ -17,10 +28,10 @@ Options:
17
28
  --no-check Skip doctor verification
18
29
 
19
30
  Examples:
20
- uploads login --code upe_…
21
- uploads login --code-stdin --non-interactive < code.txt
31
+ uploads login
32
+ uploads login --workspace acme
33
+ uploads login --code upe_… --force # fallback: pre-existing invite
22
34
  printf '%s' upe_… | uploads login --code-stdin --non-interactive
23
- uploads login --code upe_… --force --no-check
24
35
  `;
25
36
  export function validateEnrollmentCode(raw) {
26
37
  const code = raw.trim();
@@ -104,7 +115,143 @@ export async function resolveEnrollmentCode(parsed, io = {
104
115
  return validateEnrollmentCode(await io.readLine());
105
116
  return validateEnrollmentCode(await io.hiddenPrompt());
106
117
  }
107
- export async function runLogin(args, opts, help = false) {
118
+ /** True when the caller supplied an enrollment code (via flag, stdin, or env). */
119
+ function hasEnrollmentSource(parsed) {
120
+ return (Boolean(flagString(parsed.flags, "--code")) ||
121
+ flagBool(parsed.flags, "--code-stdin") ||
122
+ Boolean(process.env.UPLOADS_ENROLLMENT_CODE));
123
+ }
124
+ /**
125
+ * Auth worker base URL: explicit flag > UPLOADS_AUTH_URL > swap an `api.` host
126
+ * label for `auth.` > the production default. Local multi-worker dev (where
127
+ * auth runs on a different loopback port than the API) needs an explicit
128
+ * --auth-url / UPLOADS_AUTH_URL.
129
+ */
130
+ export function resolveAuthUrl(parsed, apiUrl) {
131
+ const explicit = flagString(parsed.flags, "--auth-url") ?? process.env.UPLOADS_AUTH_URL;
132
+ if (explicit)
133
+ return explicit.replace(/\/$/, "");
134
+ try {
135
+ const url = new URL(apiUrl);
136
+ if (url.hostname.startsWith("api.")) {
137
+ url.hostname = `auth.${url.hostname.slice(4)}`;
138
+ return url.origin;
139
+ }
140
+ }
141
+ catch {
142
+ // fall through to the default
143
+ }
144
+ return "https://auth.uploads.sh";
145
+ }
146
+ /** Best-effort browser open. The URL is always printed too, so failures are silent. */
147
+ function openUrl(url) {
148
+ try {
149
+ const isWin = process.platform === "win32";
150
+ const command = process.platform === "darwin" ? "open" : isWin ? "cmd" : "xdg-open";
151
+ const args = isWin ? ["/c", "start", "", url] : [url];
152
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
153
+ child.on("error", () => { });
154
+ child.unref();
155
+ }
156
+ catch {
157
+ // ignore — the URL is printed for manual navigation.
158
+ }
159
+ }
160
+ export const defaultDeviceIo = {
161
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
162
+ now: () => Date.now(),
163
+ openUrl,
164
+ write: (text) => {
165
+ process.stderr.write(text);
166
+ },
167
+ };
168
+ /**
169
+ * Browser device-authorization session only (no workspace token mint).
170
+ * Shared by `uploads login` and `uploads invite create`.
171
+ */
172
+ export async function obtainDeviceAccessToken(authUrl, opts = {}, io = defaultDeviceIo) {
173
+ const code = await requestDeviceCode(authUrl);
174
+ const verifyUrl = code.verification_uri_complete ?? code.verification_uri;
175
+ const prompt = opts.prompt ?? "To sign in, open:";
176
+ io.write(`${prompt}\n\n ${verifyUrl}\n\nand confirm this code:\n\n ${code.user_code}\n\n`);
177
+ if (!opts.noOpen)
178
+ io.openUrl(verifyUrl);
179
+ io.write("Waiting for approval…\n");
180
+ return pollForDeviceToken(authUrl, code, io);
181
+ }
182
+ /**
183
+ * Device-authorization login (RFC 8628): request a code, have the user approve
184
+ * it in a browser, poll for the session token, then mint a workspace token.
185
+ */
186
+ async function runDeviceLogin(parsed, opts, io) {
187
+ const scopes = parseScopes(flagString(parsed.flags, "--scopes"));
188
+ const label = flagString(parsed.flags, "--label") ?? safeHostname();
189
+ const requestedWorkspace = flagString(parsed.flags, "--workspace");
190
+ const accessToken = await obtainDeviceAccessToken(opts.authUrl, { noOpen: opts.noOpen }, io);
191
+ const workspace = await resolveMintWorkspace(opts.apiUrl, accessToken, requestedWorkspace);
192
+ const minted = await mintWorkspaceToken(opts.apiUrl, accessToken, { workspace, scopes, label });
193
+ return { workspace: minted.workspace, token: minted.token, apiUrl: opts.apiUrl };
194
+ }
195
+ function safeHostname() {
196
+ try {
197
+ return hostname() || "cli";
198
+ }
199
+ catch {
200
+ return "cli";
201
+ }
202
+ }
203
+ /** Poll device/token honoring interval / slow_down / pending until approved or expired. */
204
+ export async function pollForDeviceToken(authUrl, code, io) {
205
+ let intervalMs = Math.max(1, code.interval) * 1000;
206
+ const deadline = io.now() + Math.max(1, code.expires_in) * 1000;
207
+ while (io.now() < deadline) {
208
+ await io.sleep(intervalMs);
209
+ let result;
210
+ try {
211
+ result = await requestDeviceToken(authUrl, { deviceCode: code.device_code });
212
+ }
213
+ catch {
214
+ // A transient network blip mid-poll shouldn't abort a login the user may
215
+ // already have approved — keep polling until the device code's deadline.
216
+ continue;
217
+ }
218
+ switch (result.status) {
219
+ case "ok":
220
+ return result.accessToken;
221
+ case "pending":
222
+ continue;
223
+ case "slow_down":
224
+ // RFC 8628 §3.5: back off by 5s and keep polling.
225
+ intervalMs += 5000;
226
+ continue;
227
+ case "denied":
228
+ throw new UsageError("device authorization was denied");
229
+ case "expired":
230
+ throw new UsageError("the device code expired before it was approved");
231
+ default:
232
+ throw new UsageError(`device authorization failed: ${result.error}${result.description ? ` — ${result.description}` : ""}`);
233
+ }
234
+ }
235
+ throw new UsageError("timed out waiting for device authorization");
236
+ }
237
+ /**
238
+ * Pick the workspace to mint for. An explicit --workspace wins; otherwise, if
239
+ * the account can access exactly one workspace, use it — and if it can access
240
+ * several, require the flag rather than guessing.
241
+ */
242
+ async function resolveMintWorkspace(apiUrl, accessToken, requested) {
243
+ if (requested)
244
+ return requested;
245
+ const { workspaces } = await listMintWorkspaces(apiUrl, accessToken);
246
+ if (workspaces.length === 1)
247
+ return workspaces[0].workspace;
248
+ if (workspaces.length === 0) {
249
+ throw new UsageError("your account has no workspace access yet — ask an administrator for an invitation");
250
+ }
251
+ const names = workspaces.map((w) => w.workspace).join(", ");
252
+ throw new UsageError(`multiple workspaces available (${names}); pass --workspace <name>`);
253
+ }
254
+ export async function runLogin(args, opts, help = false, deviceIo = defaultDeviceIo) {
108
255
  const parsed = parseCommandArgs(args);
109
256
  if (help || parsed.help) {
110
257
  process.stderr.write(HELP);
@@ -118,11 +265,24 @@ export async function runLogin(args, opts, help = false) {
118
265
  throw new UsageError(`credentials already exist in ${path}; use --force to replace them`);
119
266
  if (process.env.UPLOADS_TOKEN && !force)
120
267
  throw new UsageError("UPLOADS_TOKEN is already set in the environment; unset it or use --force");
121
- const code = await resolveEnrollmentCode(parsed);
122
- const result = await exchangeEnrollment(apiUrl, code);
268
+ let result;
269
+ if (hasEnrollmentSource(parsed)) {
270
+ const code = await resolveEnrollmentCode(parsed);
271
+ result = await exchangeEnrollment(apiUrl, code);
272
+ }
273
+ else {
274
+ // The device flow is inherently interactive (browser approval, then a poll
275
+ // that runs to the device code's ~30-min deadline). Fail fast rather than
276
+ // hanging a non-interactive/CI invocation that has no code to fall back on.
277
+ if (flagBool(parsed.flags, "--non-interactive")) {
278
+ throw new UsageError("device login requires a browser; run interactively, or pass --code for the enrollment path");
279
+ }
280
+ const authUrl = resolveAuthUrl(parsed, apiUrl);
281
+ result = await runDeviceLogin(parsed, { apiUrl, authUrl, noOpen: flagBool(parsed.flags, "--no-open") }, deviceIo);
282
+ }
123
283
  const encoded = workspaceFromToken(result.token);
124
284
  if (!encoded || encoded !== result.workspace || /[\r\n]/.test(result.token))
125
- throw new UsageError("enrollment returned invalid credentials");
285
+ throw new UsageError("login returned invalid credentials");
126
286
  const savedApiUrl = result.apiUrl ?? apiUrl;
127
287
  const write = writeConfigKeys(path, {
128
288
  UPLOADS_API_URL: savedApiUrl,
@@ -64,8 +64,10 @@ function formatWizard(status) {
64
64
  lines.push("");
65
65
  if (!status.token) {
66
66
  lines.push("Step 1 — Sign in");
67
- lines.push(" Ask your uploads.sh administrator for a one-time enrollment code, then run:");
67
+ lines.push(" Run:");
68
68
  lines.push(" uploads login");
69
+ lines.push(" This opens a browser to authorize this device.");
70
+ lines.push(" Have a pre-existing enrollment code instead? uploads login --code upe_…");
69
71
  lines.push(" If you already have a bearer token:");
70
72
  lines.push(" uploads setup --token up_<workspace>_…");
71
73
  lines.push("");
@@ -207,7 +209,7 @@ export async function runSetup(args, opts, help = false) {
207
209
  process.stderr.write("hint: run uploads doctor to verify\n");
208
210
  }
209
211
  else {
210
- process.stderr.write("hint: run uploads login with an admin-provided enrollment code\n");
212
+ process.stderr.write("hint: run uploads login (or uploads login --code <code> if you have one)\n");
211
213
  }
212
214
  return doctorOk === false ? 1 : 0;
213
215
  }
@@ -13,6 +13,8 @@ export interface CliContext {
13
13
  quiet: boolean;
14
14
  envFile?: string;
15
15
  }
16
+ /** Read a local file (or `-` for stdin). Missing path → FILE_NOT_FOUND (exit 2). */
17
+ export declare function readFileArg(fileArg: string): Uint8Array;
16
18
  /**
17
19
  * Turns a pr/issue pair (+ optional repo) into a GhTarget; undefined when
18
20
  * neither is present. Shared by the CLI flags and the MCP tool arguments.
@@ -43,6 +45,8 @@ export declare function runAttach(ctx: CliContext, args: string[], help?: boolea
43
45
  export declare function runPut(ctx: CliContext, args: string[], help?: boolean, run?: CommandRunner): Promise<number>;
44
46
  export declare function runGallery(ctx: CliContext, args: string[], help?: boolean): Promise<number>;
45
47
  export declare function runList(ctx: CliContext, args: string[], help?: boolean, run?: CommandRunner): Promise<number>;
48
+ export declare function runFind(ctx: CliContext, args: string[], help?: boolean): Promise<number>;
49
+ export declare function runMeta(ctx: CliContext, args: string[], help?: boolean): Promise<number>;
46
50
  export declare function runDelete(ctx: CliContext, args: string[], help?: boolean): Promise<number>;
47
51
  export declare function runComment(ctx: CliContext, args: string[], help?: boolean, run?: CommandRunner): Promise<number>;
48
52
  export declare function runUsage(ctx: CliContext, args: string[], help?: boolean): Promise<number>;