@artifactshare/cli 0.1.2 → 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/README.md CHANGED
@@ -24,8 +24,8 @@ npx --yes @artifactshare/cli update <share-url> ./dist
24
24
  ## Authentication
25
25
 
26
26
  - **Interactive**: run `npx --yes @artifactshare/cli login`, or just run any command — unauthenticated `publish` / `update` / `download` start the sign-in for you (the CLI prints a link and code to open in your browser).
27
- - **CI / non-interactive**: set `ARTIFACTSHARE_TOKEN` (or pass `--token`). Without a token, non-interactive runs fail with `error.code: "auth_required"` instead of hanging.
28
- - Multiple accounts: keep one local profile per account (`profiles list` / `profiles use <name>`), no re-linking required.
27
+ - **CI / non-interactive**: issue a token at `https://artifactshare.com/settings/tokens`, then set `ARTIFACTSHARE_TOKEN` (or pass `--token`). Without a token, non-interactive runs fail with `error.code: "auth_required"` instead of hanging.
28
+ - Multiple accounts: keep one local profile per account (`profiles list` / `profiles use <name>`). In non-interactive agents, pipe an issued token into `profiles import-token --profile <name> --json` to create a saved profile without browser login.
29
29
 
30
30
  ## Commands
31
31
 
@@ -41,7 +41,7 @@ npx --yes @artifactshare/cli update <share-url> ./dist
41
41
  | `request-access` | Join the waitlist when publishing is not enabled yet |
42
42
  | `login` / `whoami` | Sign in and check who you are |
43
43
  | `doctor` | Diagnose auth, destination, network, and upload readiness — tells you the next command to run |
44
- | `profiles list / use` | Switch between local account profiles |
44
+ | `profiles list / use / import-token` | Switch between local account profiles and import an issued token from stdin |
45
45
  | `init` | Save a default project for the current directory |
46
46
  | `skills install / list / update / remove` | Install the bundled usage guide into your AI agent's skills |
47
47
 
package/dist/index.js CHANGED
@@ -7,8 +7,12 @@ import { createReadStream } from "node:fs";
7
7
  import { createHash } from "node:crypto";
8
8
  import { setTimeout } from "node:timers/promises";
9
9
  import { homedir } from "node:os";
10
+ //#region src/constants.ts
11
+ const DEFAULT_BASE_URL = "https://artifactshare.com";
10
12
  const DEVICE_CLIENT_ID = "artifactshare-cli";
11
13
  const CLI_INVOCATION = "npx --yes @artifactshare/cli";
14
+ const TOKEN_ENV_VAR = "ARTIFACTSHARE_TOKEN";
15
+ const TOKEN_OPTION = "--token";
12
16
  const IGNORED_FILENAMES = new Set([
13
17
  ".DS_Store",
14
18
  "Thumbs.db",
@@ -69,7 +73,11 @@ const COMMAND_NAMES = new Set([
69
73
  const SUBCOMMANDS = {
70
74
  artifacts: ["get"],
71
75
  comments: ["list", "post"],
72
- profiles: ["list", "use"],
76
+ profiles: [
77
+ "list",
78
+ "use",
79
+ "import-token"
80
+ ],
73
81
  projects: ["list"],
74
82
  skills: [
75
83
  "install",
@@ -79,6 +87,7 @@ const SUBCOMMANDS = {
79
87
  ]
80
88
  };
81
89
  const UPDATE_OPTION_KEYS = new Set([
90
+ "allowPlaintextTokenStore",
82
91
  "baseUrl",
83
92
  "help",
84
93
  "insecureLocalhost",
@@ -341,15 +350,55 @@ function serviceError(message) {
341
350
  function tokensUrl(baseUrl) {
342
351
  return `${baseUrl.replace(/\/$/, "")}/settings/tokens`;
343
352
  }
353
+ function authRecoveryDetails(baseUrl, loginCommand = `${CLI_INVOCATION} login --profile default`) {
354
+ return {
355
+ token_url: tokensUrl(baseUrl),
356
+ env_var: TOKEN_ENV_VAR,
357
+ login_command: loginCommand,
358
+ token_option: TOKEN_OPTION
359
+ };
360
+ }
344
361
  function authRequiredError(baseUrl) {
362
+ const url = tokensUrl(baseUrl);
345
363
  return cliError({
346
364
  code: "auth_required",
347
365
  message: "Login is required.",
348
- why: "No ARTIFACTSHARE_TOKEN or --token value was provided.",
349
- hint: `Run ${CLI_INVOCATION} login --profile default, or set ARTIFACTSHARE_TOKEN. You can issue a token at ${tokensUrl(baseUrl)}.`,
366
+ why: `No ${TOKEN_ENV_VAR} or ${TOKEN_OPTION} value was provided.`,
367
+ hint: `In an interactive terminal, run ${CLI_INVOCATION} login --profile default. In agents or CI, issue a token at ${url}, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.`,
350
368
  agentRecoverable: false,
351
369
  requiresHuman: true,
352
- recovery: { kind: "ask_human" }
370
+ recovery: { kind: "ask_human" },
371
+ details: authRecoveryDetails(baseUrl)
372
+ });
373
+ }
374
+ function deviceAuthErrorDetails(pending) {
375
+ const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
376
+ return {
377
+ profile: pending.profile,
378
+ verification_uri: pending.verification_uri,
379
+ verification_uri_complete: pending.verification_uri_complete,
380
+ user_code: pending.user_code,
381
+ expires_at: pending.expires_at,
382
+ interval_seconds: pending.interval_seconds,
383
+ instruction: `Open ${openUrl} and enter code ${pending.user_code} to sign in.`,
384
+ retry_hint: "After approval in the browser, rerun the same command to continue."
385
+ };
386
+ }
387
+ function authRequiredWithDeviceAuthError(baseUrl, pending) {
388
+ const device = deviceAuthErrorDetails(pending);
389
+ const openUrl = pending.verification_uri_complete ?? pending.verification_uri;
390
+ return cliError({
391
+ code: "auth_required",
392
+ message: "Login is required.",
393
+ why: `No ${TOKEN_ENV_VAR} or ${TOKEN_OPTION} value was provided.`,
394
+ hint: `Open ${openUrl} and enter code ${pending.user_code}. ${device.retry_hint}`,
395
+ agentRecoverable: false,
396
+ requiresHuman: true,
397
+ recovery: { kind: "ask_human" },
398
+ details: {
399
+ ...authRecoveryDetails(baseUrl, `${CLI_INVOCATION} login --profile ${pending.profile}`),
400
+ ...device
401
+ }
353
402
  });
354
403
  }
355
404
  function tokenInvalidError() {
@@ -357,7 +406,7 @@ function tokenInvalidError() {
357
406
  code: "token_invalid",
358
407
  message: "The bearer token is invalid or expired.",
359
408
  why: "Artifact Share rejected the Authorization bearer token.",
360
- hint: "Refresh ARTIFACTSHARE_TOKEN or sign in again, then retry.",
409
+ hint: `Refresh ${TOKEN_ENV_VAR} or sign in again, then retry.`,
361
410
  agentRecoverable: false,
362
411
  requiresHuman: true,
363
412
  recovery: { kind: "ask_human" }
@@ -396,9 +445,9 @@ function authExpiredError(profile) {
396
445
  function authAccountMismatchError(profile, expectedEmail, actualEmail) {
397
446
  return cliError({
398
447
  code: "auth_account_mismatch",
399
- message: "Login used a different account than this profile expects.",
400
- why: `Profile "${profile}" is already associated with ${expectedEmail}, but the browser approved ${actualEmail}.`,
401
- hint: "Choose the expected Google account in the browser, or use another --profile name.",
448
+ message: "The credential uses a different account than this profile expects.",
449
+ why: `Profile "${profile}" is already associated with ${expectedEmail}, but the credential identifies ${actualEmail ?? "an unknown account"}.`,
450
+ hint: "Use a credential for the expected account, or use another --profile name.",
402
451
  agentRecoverable: false,
403
452
  requiresHuman: true,
404
453
  recovery: { kind: "ask_human" },
@@ -1200,6 +1249,75 @@ async function readPlaintextTokens() {
1200
1249
  function plaintextTokensPath(home) {
1201
1250
  return join(home, "tokens.json");
1202
1251
  }
1252
+ function pendingDeviceAuthPath(home) {
1253
+ return join(home, "pending-device-auth.json");
1254
+ }
1255
+ function pendingDeviceAuthKey(baseUrl, profile) {
1256
+ return `${baseUrl}:${profile}`;
1257
+ }
1258
+ async function readPendingDeviceAuth(baseUrl, profile) {
1259
+ const home = configHome();
1260
+ if (!home) return null;
1261
+ const raw = await readFile(pendingDeviceAuthPath(home), "utf8").catch(() => null);
1262
+ if (!raw) return null;
1263
+ try {
1264
+ const parsed = JSON.parse(raw);
1265
+ if (!isRecord(parsed)) return null;
1266
+ const entry = parsed[pendingDeviceAuthKey(baseUrl, profile)];
1267
+ return isPendingDeviceAuth(entry) ? entry : null;
1268
+ } catch {
1269
+ return null;
1270
+ }
1271
+ }
1272
+ async function writePendingDeviceAuth(pending) {
1273
+ const home = configHome();
1274
+ if (!home) return false;
1275
+ const path = pendingDeviceAuthPath(home);
1276
+ const existing = await readFile(path, "utf8").then((raw) => {
1277
+ try {
1278
+ const parsed = JSON.parse(raw);
1279
+ return isRecord(parsed) ? parsed : {};
1280
+ } catch {
1281
+ return {};
1282
+ }
1283
+ }).catch(() => ({}));
1284
+ const key = pendingDeviceAuthKey(pending.base_url, pending.profile);
1285
+ await mkdir(home, {
1286
+ recursive: true,
1287
+ mode: 448
1288
+ });
1289
+ await writeFile(path, `${JSON.stringify({
1290
+ ...existing,
1291
+ [key]: pending
1292
+ }, null, 2)}\n`, { mode: 384 });
1293
+ await chmod(path, 384);
1294
+ return true;
1295
+ }
1296
+ async function clearPendingDeviceAuth(baseUrl, profile) {
1297
+ const home = configHome();
1298
+ if (!home) return;
1299
+ const path = pendingDeviceAuthPath(home);
1300
+ const raw = await readFile(path, "utf8").catch(() => null);
1301
+ if (!raw) return;
1302
+ try {
1303
+ const parsed = JSON.parse(raw);
1304
+ if (!isRecord(parsed)) return;
1305
+ const key = pendingDeviceAuthKey(baseUrl, profile);
1306
+ if (!Object.hasOwn(parsed, key)) return;
1307
+ const { [key]: _removed, ...rest } = parsed;
1308
+ if (Object.keys(rest).length === 0) {
1309
+ await writeFile(path, "{}\n", { mode: 384 });
1310
+ return;
1311
+ }
1312
+ await writeFile(path, `${JSON.stringify(rest, null, 2)}\n`, { mode: 384 });
1313
+ } catch {
1314
+ return;
1315
+ }
1316
+ }
1317
+ function isPendingDeviceAuth(value) {
1318
+ if (!isRecord(value)) return false;
1319
+ return typeof value.base_url === "string" && typeof value.profile === "string" && typeof value.device_code === "string" && typeof value.verification_uri === "string" && (typeof value.verification_uri_complete === "string" || value.verification_uri_complete === null) && typeof value.user_code === "string" && typeof value.expires_at === "string" && typeof value.interval_seconds === "number" && typeof value.created_at === "string";
1320
+ }
1203
1321
  function configHome() {
1204
1322
  const override = nonEmpty(process.env.ARTIFACTSHARE_CONFIG_HOME);
1205
1323
  if (override) return override;
@@ -1280,6 +1398,7 @@ async function profileAuthRequired(source, profile, reason, options, globalConfi
1280
1398
  const why = reason === "unavailable" ? `No safe token store is available for profile "${profile}".` : `No saved credential was found for profile "${profile}".`;
1281
1399
  const alternative = await findAlternativeProfileWithToken(globalConfig, options, profile);
1282
1400
  const details = {
1401
+ ...authRecoveryDetails(baseUrl, `${CLI_INVOCATION} login --profile ${profile}`),
1283
1402
  credential_source: source,
1284
1403
  profile
1285
1404
  };
@@ -1296,7 +1415,7 @@ async function profileAuthRequired(source, profile, reason, options, globalConfi
1296
1415
  error: {
1297
1416
  ...error,
1298
1417
  why,
1299
- hint: `${switchHint} Or run ${CLI_INVOCATION} login --profile ${profile}, or set ARTIFACTSHARE_TOKEN. You can issue a token at ${url}.`,
1418
+ hint: `${switchHint} Or in an interactive terminal run ${CLI_INVOCATION} login --profile ${profile}. In agents or CI, issue a token at ${url}, then set ${TOKEN_ENV_VAR}.`,
1300
1419
  agent_recoverable: true,
1301
1420
  requires_human: false,
1302
1421
  recovery: {
@@ -1318,7 +1437,7 @@ async function profileAuthRequired(source, profile, reason, options, globalConfi
1318
1437
  error: {
1319
1438
  ...error,
1320
1439
  why,
1321
- hint: `Run ${CLI_INVOCATION} login --profile ${profile}, or set ARTIFACTSHARE_TOKEN. You can issue a token at ${url}.`,
1440
+ hint: `In an interactive terminal, run ${CLI_INVOCATION} login --profile ${profile}. In agents or CI, issue a token at ${url}, then set ${TOKEN_ENV_VAR}.`,
1322
1441
  details
1323
1442
  }
1324
1443
  };
@@ -1488,11 +1607,21 @@ function resolveDoctorNextCommand(data) {
1488
1607
  }
1489
1608
  return null;
1490
1609
  }
1610
+ function authRecovery(data, nextCommand) {
1611
+ const loginCommand = nextCommand?.startsWith(LOGIN_COMMAND) === true ? nextCommand : data.auth.profile ? `${LOGIN_COMMAND} --profile ${data.auth.profile}` : LOGIN_COMMAND;
1612
+ return authRecoveryDetails(data.base_url, loginCommand);
1613
+ }
1491
1614
  function doctorDataWithNextCommand(data) {
1492
- return {
1615
+ const nextCommand = resolveDoctorNextCommand(data);
1616
+ const next = {
1493
1617
  ...data,
1494
- next_command: resolveDoctorNextCommand(data)
1618
+ next_command: nextCommand
1495
1619
  };
1620
+ if (next.auth.code === "auth_required") next.auth = {
1621
+ ...next.auth,
1622
+ recovery: authRecovery(next, nextCommand)
1623
+ };
1624
+ return next;
1496
1625
  }
1497
1626
  async function runDoctor(parsed, mode) {
1498
1627
  const command = "doctor";
@@ -1812,35 +1941,19 @@ async function performDeviceLogin(profile, options, mode) {
1812
1941
  error: token.error
1813
1942
  };
1814
1943
  const sessionExpiresAt = token.expires_in === void 0 ? null : new Date(Date.now() + token.expires_in * 1e3).toISOString();
1815
- const config = await readGlobalConfig() ?? {};
1816
- const whoamiResult = await apiGet("/api/cli/whoami", token.access_token, options, request.init);
1817
- if (whoamiResult.error) return {
1818
- ok: false,
1819
- error: whoamiResult.error
1820
- };
1821
- const whoami = whoamiProfile(whoamiResult.body);
1822
- const expectedEmail = config.profiles?.[profile]?.email;
1823
- if (expectedEmail && whoami.email && expectedEmail !== whoami.email) return {
1944
+ const stored = await verifyAndStoreProfileToken(profile, token.access_token, options, request.init);
1945
+ if (!stored.ok) return {
1824
1946
  ok: false,
1825
- error: authAccountMismatchError(profile, expectedEmail, whoami.email)
1947
+ error: stored.error
1826
1948
  };
1827
- const saved = await saveProfileToken(profile, token.access_token, options);
1828
- if (!saved.ok) return {
1829
- ok: false,
1830
- error: tokenStoreUnavailableError(profile)
1831
- };
1832
- await writeProfileConfig(profile, options, saved.store, whoami);
1833
1949
  const effective = await resolveEffectiveDefaultProfile(await resolveProjectConfig());
1834
1950
  const data = {
1835
1951
  profile,
1836
1952
  status: "completed",
1837
1953
  credential_source: "profile",
1838
- token_store: saved.store,
1839
- user: { email: whoami.email },
1840
- workspace: {
1841
- id: whoami.workspace_id,
1842
- hosted_domain: whoami.hosted_domain
1843
- },
1954
+ token_store: stored.data.token_store,
1955
+ user: stored.data.user,
1956
+ workspace: stored.data.workspace,
1844
1957
  verification_uri: code.verification_uri,
1845
1958
  verification_uri_complete: code.verification_uri_complete ?? null,
1846
1959
  user_code: code.user_code,
@@ -1877,6 +1990,44 @@ async function requestDeviceCode(options, init) {
1877
1990
  if (!isDeviceCodeResponse(body)) return { error: validationError("Device login response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
1878
1991
  return body;
1879
1992
  }
1993
+ async function exchangeDeviceTokenOnce(options, deviceCode, init) {
1994
+ const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
1995
+ method: "POST",
1996
+ headers: { "content-type": "application/json" },
1997
+ body: JSON.stringify({
1998
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1999
+ device_code: deviceCode,
2000
+ client_id: DEVICE_CLIENT_ID
2001
+ }),
2002
+ ...init
2003
+ }).catch((error) => ({ networkError: error }));
2004
+ if ("networkError" in response) return { error: networkError(response.networkError) };
2005
+ const body = await readJson(response);
2006
+ if (response.ok && isDeviceTokenResponse(body)) return {
2007
+ status: "success",
2008
+ token: body
2009
+ };
2010
+ const authError = deviceTokenError(body);
2011
+ if (authError === "authorization_pending") return { status: "pending" };
2012
+ if (authError === "slow_down") return { status: "slow_down" };
2013
+ if (authError === "access_denied") return { status: "denied" };
2014
+ if (authError === "expired_token") return { status: "expired" };
2015
+ if (response.status === 429 || response.status >= 500) return { status: "retry_later" };
2016
+ return { error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) }) };
2017
+ }
2018
+ function pendingDeviceAuthFromCode(profile, options, code) {
2019
+ return {
2020
+ base_url: baseUrlOf(options),
2021
+ profile,
2022
+ device_code: code.device_code,
2023
+ verification_uri: code.verification_uri,
2024
+ verification_uri_complete: code.verification_uri_complete ?? null,
2025
+ user_code: code.user_code,
2026
+ expires_at: new Date(Date.now() + code.expires_in * 1e3).toISOString(),
2027
+ interval_seconds: code.interval,
2028
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
2029
+ };
2030
+ }
1880
2031
  async function pollForToken(options, code, init, profile, deadline) {
1881
2032
  let intervalMs = Math.max(code.interval, 1) * 1e3;
1882
2033
  let networkFailures = 0;
@@ -1912,17 +2063,52 @@ async function pollForToken(options, code, init, profile, deadline) {
1912
2063
  }
1913
2064
  return { error: authExpiredError(profile) };
1914
2065
  }
2066
+ async function verifyAndStoreProfileToken(profile, token, options, init) {
2067
+ const config = await readGlobalConfig() ?? {};
2068
+ const whoamiResult = await apiGet("/api/cli/whoami", token, options, init);
2069
+ if (whoamiResult.error) return {
2070
+ ok: false,
2071
+ error: whoamiResult.error
2072
+ };
2073
+ const whoami = whoamiProfile(whoamiResult.body);
2074
+ const profiles = config.profiles ?? {};
2075
+ const expectedEmail = nonEmpty((Object.hasOwn(profiles, profile) ? profiles[profile] : void 0)?.email);
2076
+ if (expectedEmail && whoami.email !== expectedEmail) return {
2077
+ ok: false,
2078
+ error: authAccountMismatchError(profile, expectedEmail, whoami.email)
2079
+ };
2080
+ const saved = await saveProfileToken(profile, token, options);
2081
+ if (!saved.ok) return {
2082
+ ok: false,
2083
+ error: tokenStoreUnavailableError(profile)
2084
+ };
2085
+ await writeProfileConfig(profile, options, saved.store, whoami);
2086
+ return {
2087
+ ok: true,
2088
+ data: {
2089
+ profile,
2090
+ token_store: saved.store,
2091
+ user: { email: whoami.email },
2092
+ workspace: {
2093
+ id: whoami.workspace_id,
2094
+ hosted_domain: whoami.hosted_domain
2095
+ }
2096
+ }
2097
+ };
2098
+ }
1915
2099
  async function writeProfileConfig(profile, options, tokenStore, whoami) {
1916
2100
  const config = await readGlobalConfig() ?? {};
2101
+ const profiles = config.profiles ?? {};
2102
+ const currentProfile = Object.hasOwn(profiles, profile) ? profiles[profile] : void 0;
1917
2103
  await writeGlobalConfig({
1918
2104
  ...config,
1919
2105
  default_profile: nonEmpty(config.default_profile) ?? profile,
1920
2106
  profiles: {
1921
- ...config.profiles,
2107
+ ...profiles,
1922
2108
  [profile]: {
1923
- ...config.profiles?.[profile],
2109
+ ...currentProfile,
1924
2110
  base_url: baseUrlOf(options),
1925
- email: whoami.email,
2111
+ email: whoami.email ?? currentProfile?.email ?? null,
1926
2112
  workspace_id: whoami.workspace_id,
1927
2113
  token_store: tokenStore,
1928
2114
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
@@ -1954,14 +2140,25 @@ function whoamiProfile(body) {
1954
2140
  }
1955
2141
  //#endregion
1956
2142
  //#region src/command-runners/auto-login.ts
2143
+ const JSON_PENDING_AUTH_COMMANDS = new Set(["publish", "update"]);
1957
2144
  function isInteractiveTerminal(mode) {
1958
2145
  return !mode.json && process.stdin.isTTY === true;
1959
2146
  }
1960
2147
  function profileForAutoLogin(credential) {
1961
2148
  return credential.source === "none" ? "default" : credential.profile ?? "default";
1962
2149
  }
2150
+ function isPendingExpired(pending) {
2151
+ const expiresAt = Date.parse(pending.expires_at);
2152
+ return Number.isNaN(expiresAt) || expiresAt <= Date.now();
2153
+ }
2154
+ async function canAttemptProfileTokenSave(profile, options) {
2155
+ const stored = await readProfileToken(profile, options);
2156
+ return stored.ok || stored.reason !== "unavailable";
2157
+ }
1963
2158
  async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
1964
- if (credential.error.code !== "auth_required" || !isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
2159
+ if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
2160
+ if (mode.json && JSON_PENDING_AUTH_COMMANDS.has(command) && !isRetry) return handleJsonPendingAuth(command, credential, options, mode, rerun);
2161
+ if (!isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
1965
2162
  const performLogin = deps.performLogin ?? performDeviceLogin;
1966
2163
  const profile = profileForAutoLogin(credential);
1967
2164
  writeText("Not signed in. Starting device login to continue...\n");
@@ -1969,6 +2166,39 @@ async function handleCredentialFailure(command, credential, options, mode, rerun
1969
2166
  if (!loginResult.ok) return writeFailure(command, loginResult.error, mode, 1);
1970
2167
  return rerun();
1971
2168
  }
2169
+ async function handleJsonPendingAuth(command, credential, options, mode, rerun) {
2170
+ const profile = profileForAutoLogin(credential);
2171
+ const baseUrl = baseUrlOf(options);
2172
+ const request = await requestConfig(options);
2173
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2174
+ if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
2175
+ const existing = await readPendingDeviceAuth(baseUrl, profile);
2176
+ if (existing && !isPendingExpired(existing)) {
2177
+ const exchange = await exchangeDeviceTokenOnce(options, existing.device_code, request.init);
2178
+ if ("error" in exchange) {
2179
+ if (exchange.error.code !== "network_failed") await clearPendingDeviceAuth(baseUrl, profile);
2180
+ return writeFailure(command, exchange.error, mode, 1);
2181
+ }
2182
+ if (exchange.status === "success") {
2183
+ const stored = await verifyAndStoreProfileToken(profile, exchange.token.access_token, options, request.init);
2184
+ if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
2185
+ await clearPendingDeviceAuth(baseUrl, profile);
2186
+ return rerun();
2187
+ }
2188
+ if (exchange.status === "denied") {
2189
+ await clearPendingDeviceAuth(baseUrl, profile);
2190
+ return writeFailure(command, authDeniedError(profile), mode, 1);
2191
+ }
2192
+ if (exchange.status === "expired") await clearPendingDeviceAuth(baseUrl, profile);
2193
+ else if (exchange.status === "retry_later") return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
2194
+ else return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, existing), mode, 1);
2195
+ } else if (existing) await clearPendingDeviceAuth(baseUrl, profile);
2196
+ const code = await requestDeviceCode(options, request.init);
2197
+ if ("error" in code) return writeFailure(command, credential.error, mode, 1);
2198
+ const pending = pendingDeviceAuthFromCode(profile, options, code);
2199
+ if (!await writePendingDeviceAuth(pending)) return writeFailure(command, credential.error, mode, 1);
2200
+ return writeFailure(command, authRequiredWithDeviceAuthError(baseUrl, pending), mode, 1);
2201
+ }
1972
2202
  //#endregion
1973
2203
  //#region src/command-runners/download.ts
1974
2204
  async function runDownload(parsed, mode, isRetry = false) {
@@ -2150,6 +2380,12 @@ function initData(written, config, resolved) {
2150
2380
  }
2151
2381
  //#endregion
2152
2382
  //#region src/command-runners/profiles.ts
2383
+ async function readStdinToken() {
2384
+ if (process.stdin.isTTY === true) return "";
2385
+ const chunks = [];
2386
+ for await (const chunk of process.stdin) chunks.push(chunk);
2387
+ return Buffer.concat(chunks).toString("utf8").trim();
2388
+ }
2153
2389
  async function runProfilesList(parsed, mode) {
2154
2390
  const command = "profiles list";
2155
2391
  if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
@@ -2195,6 +2431,32 @@ async function runProfilesUse(parsed, mode) {
2195
2431
  previous_default: previous
2196
2432
  }, mode);
2197
2433
  }
2434
+ async function runProfilesImportToken(parsed, mode) {
2435
+ const command = "profiles import-token";
2436
+ const profile = nonEmpty(parsed.options.profile);
2437
+ if (!profile) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles import-token --profile <name>.`), mode, 1);
2438
+ if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
2439
+ if (nonEmpty(parsed.options.token)) return writeFailure(command, validationError("Do not pass API tokens with --token to import-token.", "Pipe the token on standard input so it does not appear in process arguments."), mode, 1);
2440
+ if (parsed.positionals.length > 0) return writeFailure(command, validationError("Do not pass API tokens as positional arguments.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`), mode, 1);
2441
+ let token;
2442
+ try {
2443
+ token = await readStdinToken();
2444
+ } catch {
2445
+ return writeFailure(command, validationError("The token could not be read from standard input.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`, "service_error"), mode, 1);
2446
+ }
2447
+ if (!token) return writeFailure(command, validationError("A token is required on standard input.", `Pipe a token: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --json`), mode, 1);
2448
+ const request = await requestConfig(parsed.options);
2449
+ if (request.error) return writeFailure(command, request.error, mode, 1);
2450
+ const stored = await verifyAndStoreProfileToken(profile, token, parsed.options, request.init);
2451
+ if (!stored.ok) return writeFailure(command, stored.error, mode, 1);
2452
+ return writeSuccess(command, {
2453
+ profile,
2454
+ token_store: stored.data.token_store,
2455
+ user: stored.data.user,
2456
+ workspace: stored.data.workspace,
2457
+ base_url: baseUrlOf(parsed.options)
2458
+ }, mode);
2459
+ }
2198
2460
  //#endregion
2199
2461
  //#region src/command-runners/projects.ts
2200
2462
  async function fetchProjects(token, options, init) {
@@ -2755,6 +3017,11 @@ async function profilesUseRunner(ctx) {
2755
3017
  const parsed = parsedArgsFromContext("profiles use", ctx);
2756
3018
  return await runProfilesUse(parsed, outputMode(parsed.options));
2757
3019
  }
3020
+ async function profilesImportTokenRunner(ctx) {
3021
+ const parsed = parsedArgsFromContext("profiles import-token", ctx);
3022
+ if (hasOptionToken(ctx, "token")) parsed.options.token = "<redacted>";
3023
+ return await runProfilesImportToken(parsed, outputMode(parsed.options));
3024
+ }
2758
3025
  async function projectsListRunner(ctx) {
2759
3026
  const parsed = parsedArgsFromContext("projects list", ctx);
2760
3027
  return await runProjectsList(parsed, outputMode(parsed.options));
@@ -2789,6 +3056,13 @@ function parentCommandRunner(command) {
2789
3056
  writeFailure(command, validationError("A subcommand is required.", `Run ${CLI_INVOCATION} ${command} <${(SUBCOMMANDS[command] ?? []).join(" | ")}>.`), outputMode(parsed.options), 1);
2790
3057
  };
2791
3058
  }
3059
+ function hasOptionToken(ctx, name) {
3060
+ for (const token of ctx.tokens) {
3061
+ if (token.kind !== "option") continue;
3062
+ if ((token.name ?? token.rawName?.replace(/^--?/, "")) === name) return true;
3063
+ }
3064
+ return false;
3065
+ }
2792
3066
  //#endregion
2793
3067
  //#region src/index.ts
2794
3068
  async function main(rawArgv) {
@@ -2859,7 +3133,7 @@ const commonArgs = {
2859
3133
  token: {
2860
3134
  type: "string",
2861
3135
  toKebab: true,
2862
- description: "Bearer token (default: ARTIFACTSHARE_TOKEN)"
3136
+ description: `Bearer token (default: ${TOKEN_ENV_VAR})`
2863
3137
  },
2864
3138
  profile: {
2865
3139
  type: "string",
@@ -2901,8 +3175,12 @@ npx --yes @artifactshare/cli request-access --json
2901
3175
  npx --yes @artifactshare/cli whoami --json
2902
3176
  npx --yes @artifactshare/cli doctor --json
2903
3177
 
3178
+ Authentication:
3179
+ Interactive terminal: run ${CLI_INVOCATION} login --profile default, then approve in your browser.
3180
+ Agents or CI: issue a token at ${DEFAULT_BASE_URL}/settings/tokens, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.
3181
+
2904
3182
  Common failures:
2905
- auth_required Set ARTIFACTSHARE_TOKEN or pass --token
3183
+ auth_required Use ${TOKEN_ENV_VAR} or ${TOKEN_OPTION}; tokens are issued at ${DEFAULT_BASE_URL}/settings/tokens
2906
3184
  destination_required Add --project-id, configure .artifactshare/config.json, or pass --home
2907
3185
  target_not_found Use an artifact ID, share URL, or sandbox URL
2908
3186
  upload_not_allowed Upload access is limited; run request-access to join the waitlist`,
@@ -2910,12 +3188,15 @@ Common failures:
2910
3188
  });
2911
3189
  const loginDefinition = define({
2912
3190
  name: "login",
2913
- description: "Sign in with device authorization and save a CLI profile.",
3191
+ description: "Sign in with browser device authorization and save a CLI profile.",
2914
3192
  toKebab: true,
2915
3193
  args: commonArgs,
2916
3194
  examples: `npx --yes @artifactshare/cli login --profile default
2917
3195
  npx --yes @artifactshare/cli login --profile client-a --json
2918
3196
 
3197
+ login requires browser approval in an interactive terminal.
3198
+ For agents or CI, issue a token at ${DEFAULT_BASE_URL}/settings/tokens, then pass it to normal commands with ${TOKEN_ENV_VAR} or ${TOKEN_OPTION}; do not pass the token to login.
3199
+
2919
3200
  Common failures:
2920
3201
  auth_denied The browser approval was denied
2921
3202
  auth_expired The device code expired before approval
@@ -3214,6 +3495,27 @@ const profilesUseDefinition = define({
3214
3495
  Common failures:
3215
3496
  profile_not_found Run profiles list to see saved profiles, or login --profile <name>`
3216
3497
  });
3498
+ const profilesImportTokenDefinition = define({
3499
+ name: "import-token",
3500
+ description: "Read an API token from standard input and save it to a CLI profile.",
3501
+ toKebab: true,
3502
+ args: {
3503
+ json: commonArgs.json,
3504
+ baseUrl: commonArgs.baseUrl,
3505
+ profile: commonArgs.profile,
3506
+ allowPlaintextTokenStore: commonArgs.allowPlaintextTokenStore,
3507
+ insecureLocalhost: commonArgs.insecureLocalhost
3508
+ },
3509
+ examples: `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile client-a --json
3510
+
3511
+ Reads the token from standard input only. Use this in agents or CI after issuing a token at ${DEFAULT_BASE_URL}/settings/tokens.
3512
+
3513
+ Common failures:
3514
+ validation_failed Pass --profile and pipe a non-empty token on standard input
3515
+ token_invalid The token is invalid or expired
3516
+ auth_account_mismatch The token belongs to a different account than the saved profile email
3517
+ token_store_unavailable Configure an OS credential store or use the explicit plaintext fallback`
3518
+ });
3217
3519
  const profilesDefinition = define({
3218
3520
  name: "profiles",
3219
3521
  description: "Manage saved CLI profiles.",
@@ -3221,10 +3523,12 @@ const profilesDefinition = define({
3221
3523
  args: commonArgs,
3222
3524
  subCommands: {
3223
3525
  list: lazyCommand(profilesListDefinition, profilesListRunner),
3224
- use: lazyCommand(profilesUseDefinition, profilesUseRunner)
3526
+ use: lazyCommand(profilesUseDefinition, profilesUseRunner),
3527
+ "import-token": lazyCommand(profilesImportTokenDefinition, profilesImportTokenRunner)
3225
3528
  },
3226
3529
  examples: `npx --yes @artifactshare/cli profiles list --json
3227
- npx --yes @artifactshare/cli profiles use client-a --json`,
3530
+ npx --yes @artifactshare/cli profiles use client-a --json
3531
+ printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile client-a --json`,
3228
3532
  run: parentCommandRunner("profiles")
3229
3533
  });
3230
3534
  const projectsDefinition = define({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@artifactshare/cli",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Publish and update Artifact Share artifacts from terminals, AI agents, and CI.",
5
5
  "homepage": "https://artifactshare.com/connect",
6
6
  "license": "Apache-2.0",
@@ -4,7 +4,7 @@ description: Publish, update, and read back shared artifacts with the Artifact S
4
4
  ---
5
5
 
6
6
  <!-- artifactshare-skill
7
- version: 3
7
+ version: 5
8
8
  managed: true
9
9
  -->
10
10
 
@@ -28,8 +28,16 @@ paths like `/Users/.../report.html` from the user's filesystem.
28
28
 
29
29
  ## Authentication
30
30
 
31
- - Use `ARTIFACTSHARE_TOKEN`, `--token`, or a saved profile (`--profile`).
32
- - `login --profile <name>` prints a sign-in URL and code (device flow); only suggest it in interactive sessions.
31
+ - In non-interactive environments (agents, CI, scripts), ask the user to issue
32
+ an API token at `https://artifactshare.com/settings/tokens`, then use
33
+ `ARTIFACTSHARE_TOKEN` or `--token` for normal commands.
34
+ - `login --profile <name>` prints a sign-in URL and code (device flow); only
35
+ suggest it in interactive sessions. Do not pass API tokens to `login`.
36
+ - To keep using an issued token as a named profile without TTY or browser
37
+ login, pipe it on standard input:
38
+ `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile <name> --json`.
39
+ Use `--allow-plaintext-token-store` only on a trusted machine without a native token store.
40
+ - Saved profiles (`--profile`) are created by `login` or `profiles import-token`.
33
41
  - Check the current state with `whoami --json`, or `doctor --json` for authentication, destination, network, and upload access at once.
34
42
 
35
43
  ## Choosing the destination
@@ -4,7 +4,7 @@ alwaysApply: false
4
4
  ---
5
5
 
6
6
  <!-- artifactshare-skill
7
- version: 3
7
+ version: 5
8
8
  managed: true
9
9
  -->
10
10
 
@@ -20,6 +20,9 @@ Markdown source strings; they cannot read paths like `/Users/.../report.html`
20
20
  from the user's filesystem.
21
21
 
22
22
  - Always pass `--json`; on failure read `error.code`, `error.hint`, and `error.recovery`.
23
+ - In agents, CI, or scripts, ask the user to issue an API token at `https://artifactshare.com/settings/tokens`, then run normal commands with `ARTIFACTSHARE_TOKEN` or `--token`; do not pass API tokens to `login`.
24
+ - To save that token as a named profile without TTY or browser login, pipe it on standard input: `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile <name> --json`. Add `--allow-plaintext-token-store` only on a trusted machine without a native token store.
25
+ - Use `login --profile <name>` only in an interactive terminal where the user can approve the browser device flow.
23
26
  - Pick the destination with `projects list --json`, `init --project-id <id>`, or `--project-id`.
24
27
  - Publish with `publish <path> --json`; add a version with `update <artifact-id-or-url> <path> --json`.
25
28
  - Resolve titles, project names, and URLs to IDs with `resolve <value> --json` before writing.