@artifactshare/cli 0.11.1 → 0.11.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/CHANGELOG.md +9 -0
- package/README.md +14 -2
- package/dist/index.js +622 -101
- package/package.json +1 -1
- package/skills/artifactshare/SKILL.md +13 -5
- package/skills/artifactshare/artifactshare.mdc +6 -3
package/dist/index.js
CHANGED
|
@@ -5,10 +5,10 @@ import { createReadStream, realpathSync } from "node:fs";
|
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
7
|
import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
8
|
+
import { arch, homedir, platform } from "node:os";
|
|
8
9
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
9
10
|
import { createHash, randomUUID } from "node:crypto";
|
|
10
11
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
11
|
-
import { arch, homedir, platform } from "node:os";
|
|
12
12
|
import { Blob } from "node:buffer";
|
|
13
13
|
//#region src/constants.ts
|
|
14
14
|
const DEFAULT_BASE_URL = "https://artifactshare.com";
|
|
@@ -178,7 +178,10 @@ function mapApiError(status, body, options = {}) {
|
|
|
178
178
|
if (!options.authenticated) return authRequiredError(options.baseUrl ?? "https://artifactshare.com");
|
|
179
179
|
const source = options.credentialSource;
|
|
180
180
|
const profile = options.profile;
|
|
181
|
-
if (typeof profile === "string" && profile.length > 0 && isProfileCredentialSource(source) && options.profileCredentialKind !== "api_token")
|
|
181
|
+
if (typeof profile === "string" && profile.length > 0 && isProfileCredentialSource(source) && options.profileCredentialKind !== "api_token") {
|
|
182
|
+
if (options.botProfile) return botReauthRequiredError(profile);
|
|
183
|
+
return profileReauthRequiredError(options.baseUrl ?? "https://artifactshare.com", source, profile);
|
|
184
|
+
}
|
|
182
185
|
return tokenInvalidError();
|
|
183
186
|
}
|
|
184
187
|
if (apiCode === "upload-not-allowed") return cliError({
|
|
@@ -219,15 +222,20 @@ function mapApiError(status, body, options = {}) {
|
|
|
219
222
|
requiresHuman: true,
|
|
220
223
|
recovery: { kind: "ask_human" }
|
|
221
224
|
});
|
|
222
|
-
if (apiCode === "quota-exceeded")
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
225
|
+
if (apiCode === "quota-exceeded") {
|
|
226
|
+
const apiDetails = typeof body?.error === "object" && isRecord(body.error.details) ? body.error.details : void 0;
|
|
227
|
+
const upgradeRequest = isRecord(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
|
|
228
|
+
return cliError({
|
|
229
|
+
code: "storage_limit_exceeded",
|
|
230
|
+
message: "Storage quota is exceeded.",
|
|
231
|
+
why: "The workspace does not have enough remaining storage for this upload.",
|
|
232
|
+
hint: "Reduce the artifact size or ask an administrator to increase storage.",
|
|
233
|
+
agentRecoverable: false,
|
|
234
|
+
requiresHuman: true,
|
|
235
|
+
recovery: { kind: "ask_human" },
|
|
236
|
+
...upgradeRequest ? { details: { upgrade_request: upgradeRequest } } : {}
|
|
237
|
+
});
|
|
238
|
+
}
|
|
231
239
|
if (apiCode !== null && ["too-large", "file-too-large"].includes(apiCode)) return cliError({
|
|
232
240
|
code: "file_too_large",
|
|
233
241
|
message: apiMessage ?? "The upload is too large.",
|
|
@@ -366,15 +374,20 @@ function mapApiError(status, body, options = {}) {
|
|
|
366
374
|
...currentVersionId ? { details: { current_version_id: currentVersionId } } : {}
|
|
367
375
|
});
|
|
368
376
|
}
|
|
369
|
-
if (apiCode === "project-limit-reached")
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
377
|
+
if (apiCode === "project-limit-reached") {
|
|
378
|
+
const apiDetails = typeof body?.error === "object" && isRecord(body.error.details) ? body.error.details : void 0;
|
|
379
|
+
const upgradeRequest = isRecord(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
|
|
380
|
+
return cliError({
|
|
381
|
+
code: "project_limit_reached",
|
|
382
|
+
message: apiMessage ?? "You've reached your plan's project limit. Upgrade your plan or archive existing projects.",
|
|
383
|
+
why: "The workspace already has the maximum number of active projects allowed by its plan.",
|
|
384
|
+
hint: "Archive an existing project, upgrade the workspace plan, or choose a different project.",
|
|
385
|
+
agentRecoverable: false,
|
|
386
|
+
requiresHuman: true,
|
|
387
|
+
recovery: { kind: "change_input" },
|
|
388
|
+
...upgradeRequest ? { details: { upgrade_request: upgradeRequest } } : {}
|
|
389
|
+
});
|
|
390
|
+
}
|
|
378
391
|
if (apiCode === "forbidden" || status === 403) return cliError({
|
|
379
392
|
code: "forbidden",
|
|
380
393
|
message: apiMessage ?? "You do not have permission to do that.",
|
|
@@ -542,6 +555,7 @@ function authRecoveryDetails(baseUrl, loginCommand = `${CLI_INVOCATION} login --
|
|
|
542
555
|
token_url: tokensUrl(baseUrl),
|
|
543
556
|
env_var: TOKEN_ENV_VAR,
|
|
544
557
|
login_command: loginCommand,
|
|
558
|
+
agent_login_command: `${loginCommand} --preset agent`,
|
|
545
559
|
token_option: TOKEN_OPTION
|
|
546
560
|
};
|
|
547
561
|
}
|
|
@@ -551,20 +565,47 @@ function authRequiredError(baseUrl) {
|
|
|
551
565
|
code: "auth_required",
|
|
552
566
|
message: "Login is required.",
|
|
553
567
|
why: `No ${TOKEN_ENV_VAR} or ${TOKEN_OPTION} value was provided.`,
|
|
554
|
-
hint: `
|
|
568
|
+
hint: `With a user present, run ${CLI_INVOCATION} login --profile default; for an agent, add --preset agent. In unattended CI or scripts without browser approval, issue a token at ${url}, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.`,
|
|
555
569
|
agentRecoverable: false,
|
|
556
570
|
requiresHuman: true,
|
|
557
571
|
recovery: { kind: "ask_human" },
|
|
558
572
|
details: authRecoveryDetails(baseUrl)
|
|
559
573
|
});
|
|
560
574
|
}
|
|
575
|
+
function botReauthRequiredError(profile) {
|
|
576
|
+
return cliError({
|
|
577
|
+
code: "auth_required",
|
|
578
|
+
message: "The bot credential is no longer valid.",
|
|
579
|
+
why: `The saved bot credential for profile "${profile}" is expired, was superseded by a reissue, or the bot was stopped.`,
|
|
580
|
+
hint: `If a workspace administrator already reissued the bot token, import it: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --force. Otherwise ask a workspace administrator to reissue the bot token.`,
|
|
581
|
+
agentRecoverable: false,
|
|
582
|
+
requiresHuman: true,
|
|
583
|
+
recovery: { kind: "ask_human" },
|
|
584
|
+
details: {
|
|
585
|
+
profile,
|
|
586
|
+
reauth_reason: "bot_credential_invalid"
|
|
587
|
+
}
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
function botTokenInvalidError(profile) {
|
|
591
|
+
return cliError({
|
|
592
|
+
code: "bot_token_invalid",
|
|
593
|
+
message: "The bot token was rejected.",
|
|
594
|
+
why: "The token is revoked (a newer reissue supersedes it), expired, or the bot was stopped.",
|
|
595
|
+
hint: "Ask a workspace administrator to reissue the bot token, then import the newly displayed token.",
|
|
596
|
+
agentRecoverable: false,
|
|
597
|
+
requiresHuman: true,
|
|
598
|
+
recovery: { kind: "ask_human" },
|
|
599
|
+
details: { profile }
|
|
600
|
+
});
|
|
601
|
+
}
|
|
561
602
|
function profileReauthRequiredError(baseUrl, source, profile) {
|
|
562
603
|
const loginCommand = `${CLI_INVOCATION} login --profile ${profile}`;
|
|
563
604
|
return cliError({
|
|
564
605
|
code: "auth_required",
|
|
565
606
|
message: "Login is required.",
|
|
566
607
|
why: `The saved credential for profile "${profile}" is invalid or expired.`,
|
|
567
|
-
hint: `
|
|
608
|
+
hint: `With a user present, run ${loginCommand}; for an agent, add --preset agent. In unattended CI or scripts without browser approval, issue a token at ${tokensUrl(baseUrl)}, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.`,
|
|
568
609
|
agentRecoverable: false,
|
|
569
610
|
requiresHuman: true,
|
|
570
611
|
recovery: { kind: "ask_human" },
|
|
@@ -676,16 +717,38 @@ function profileNotFoundError(profile) {
|
|
|
676
717
|
details: { profile }
|
|
677
718
|
});
|
|
678
719
|
}
|
|
679
|
-
function tokenStoreUnavailableError(profile) {
|
|
720
|
+
function tokenStoreUnavailableError(profile, cause = "credential_store_unavailable_or_failed", platform = process.platform) {
|
|
721
|
+
const hint = cause === "config_write_failed" ? "Check that the resolved configuration directory is private and writable, then retry." : cause === "store_operation_failed" ? "Retry the credential operation. If it continues to fail, check access to the configured credential store and configuration directory." : platform === "win32" ? "Windows requires Credential Manager for saved profiles. Check that Windows PowerShell 5.1 and Credential Manager are available, then retry." : `Configure an OS credential store, or rerun login with --allow-plaintext-token-store only if this machine is trusted.`;
|
|
722
|
+
const retryable = cause === "store_operation_failed" || cause === "config_write_failed";
|
|
680
723
|
return cliError({
|
|
681
724
|
code: "token_store_unavailable",
|
|
682
725
|
message: "No safe token store is available.",
|
|
683
|
-
why: "Artifact Share could not
|
|
684
|
-
hint
|
|
685
|
-
agentRecoverable:
|
|
686
|
-
requiresHuman:
|
|
687
|
-
recovery: { kind: "ask_human" },
|
|
688
|
-
|
|
726
|
+
why: "Artifact Share could not use an OS credential store for this environment.",
|
|
727
|
+
hint,
|
|
728
|
+
agentRecoverable: retryable,
|
|
729
|
+
requiresHuman: !retryable,
|
|
730
|
+
recovery: retryable ? { kind: "retry_later" } : { kind: "ask_human" },
|
|
731
|
+
details: {
|
|
732
|
+
cause,
|
|
733
|
+
platform,
|
|
734
|
+
...profile ? { profile } : {}
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
function configHomeUnavailableError(profile) {
|
|
739
|
+
return cliError({
|
|
740
|
+
code: "config_home_unavailable",
|
|
741
|
+
message: "The user configuration directory could not be resolved.",
|
|
742
|
+
why: "Artifact Share could not resolve a home directory for profile configuration or the plaintext token fallback.",
|
|
743
|
+
hint: "Set ARTIFACTSHARE_CONFIG_HOME to a private directory owned by the current user, then retry.",
|
|
744
|
+
agentRecoverable: true,
|
|
745
|
+
requiresHuman: false,
|
|
746
|
+
recovery: { kind: "change_input" },
|
|
747
|
+
details: {
|
|
748
|
+
cause: "config_home_unresolved",
|
|
749
|
+
platform: process.platform,
|
|
750
|
+
...profile ? { profile } : {}
|
|
751
|
+
}
|
|
689
752
|
});
|
|
690
753
|
}
|
|
691
754
|
function skillUpdateConflictError(path) {
|
|
@@ -1078,7 +1141,11 @@ function writeFailure(command, error, mode, exitCode) {
|
|
|
1078
1141
|
error
|
|
1079
1142
|
};
|
|
1080
1143
|
if (mode.json) process.stderr.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
1081
|
-
else
|
|
1144
|
+
else {
|
|
1145
|
+
const upgradeRequest = isRecord(error.details?.upgrade_request) ? error.details.upgrade_request : null;
|
|
1146
|
+
const upgradeHint = upgradeRequest?.kind === "contact" && typeof upgradeRequest.request_message === "string" ? upgradeRequest.request_message : upgradeRequest?.kind === "billing" && typeof upgradeRequest.upgrade_url === "string" ? upgradeRequest.upgrade_url : upgradeRequest?.kind === "support" && typeof upgradeRequest.support_url === "string" ? upgradeRequest.support_url : null;
|
|
1147
|
+
process.stderr.write(`Error: ${error.message}\nWhy: ${error.why}\nHint: ${error.hint}${upgradeHint ? `\n${upgradeHint}` : ""}\n`);
|
|
1148
|
+
}
|
|
1082
1149
|
process.exitCode = exitCode;
|
|
1083
1150
|
}
|
|
1084
1151
|
function writeText(text) {
|
|
@@ -1100,7 +1167,9 @@ function humanSuccess(command, data) {
|
|
|
1100
1167
|
`Visibility: ${fields.visibility}`,
|
|
1101
1168
|
""
|
|
1102
1169
|
].join("\n");
|
|
1103
|
-
|
|
1170
|
+
const warnings = shareWarnings(data);
|
|
1171
|
+
const withWarnings = warnings.length ? `${output}${warnings.map((message) => `Warning: ${message}`).join("\n")}\n` : output;
|
|
1172
|
+
return suffix ? `${withWarnings}${suffix}` : withWarnings;
|
|
1104
1173
|
}
|
|
1105
1174
|
if (command === "doctor") return doctorHumanOutput(data);
|
|
1106
1175
|
if (command === "open") return openHumanOutput(data);
|
|
@@ -1110,6 +1179,10 @@ function humanSuccess(command, data) {
|
|
|
1110
1179
|
const output = `${JSON.stringify(data, null, 2)}\n`;
|
|
1111
1180
|
return suffix ? `${output}${suffix}` : output;
|
|
1112
1181
|
}
|
|
1182
|
+
function shareWarnings(data) {
|
|
1183
|
+
if (!isRecord(data) || !Array.isArray(data.warnings)) return [];
|
|
1184
|
+
return data.warnings.flatMap((warning) => isRecord(warning) && warning.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [warning.message] : []);
|
|
1185
|
+
}
|
|
1113
1186
|
function skillAutoUpdateHumanOutput(data) {
|
|
1114
1187
|
if (!isRecord(data)) return "";
|
|
1115
1188
|
const skills = data.skills;
|
|
@@ -1722,9 +1795,16 @@ async function readProfileToken(profile, options) {
|
|
|
1722
1795
|
if (plaintext.reason === "legacy") return plaintext;
|
|
1723
1796
|
return {
|
|
1724
1797
|
ok: false,
|
|
1725
|
-
reason: native || options.allowPlaintextTokenStore ? "missing" : "unavailable"
|
|
1798
|
+
reason: native || options.allowPlaintextTokenStore && plaintextStoreWritable() ? "missing" : "unavailable"
|
|
1726
1799
|
};
|
|
1727
1800
|
}
|
|
1801
|
+
async function probeTokenStoreWritable(profile, options, { ignoreExistingEntry = false, platform = process.platform } = {}) {
|
|
1802
|
+
if (await nativeStore()) return true;
|
|
1803
|
+
if (options.allowPlaintextTokenStore) return plaintextStoreWritable(platform);
|
|
1804
|
+
if (ignoreExistingEntry) return false;
|
|
1805
|
+
if (!plaintextFallbackSupported(platform)) return false;
|
|
1806
|
+
return await readPlaintextToken(accountName(profile, baseUrlOf(options))) !== null;
|
|
1807
|
+
}
|
|
1728
1808
|
async function saveProfileSessionCredential(profile, credential, options) {
|
|
1729
1809
|
return await saveProfileCredential(profile, credential, options);
|
|
1730
1810
|
}
|
|
@@ -1735,10 +1815,13 @@ async function saveProfileCredential(profile, credential, options) {
|
|
|
1735
1815
|
const account = accountName(profile, baseUrlOf(options));
|
|
1736
1816
|
const value = JSON.stringify(credential);
|
|
1737
1817
|
const native = await nativeStore();
|
|
1738
|
-
if (native && await native.write(account, value))
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1818
|
+
if (native && await native.write(account, value)) {
|
|
1819
|
+
if (process.platform === "win32") await deletePlaintextTokenAccount(account).catch(() => false);
|
|
1820
|
+
return {
|
|
1821
|
+
ok: true,
|
|
1822
|
+
store: native.kind
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1742
1825
|
const hasPlaintextEntry = await readPlaintextToken(account) !== null;
|
|
1743
1826
|
if ((options.allowPlaintextTokenStore || hasPlaintextEntry) && await writePlaintextToken(account, value)) return {
|
|
1744
1827
|
ok: true,
|
|
@@ -1848,18 +1931,19 @@ function accountName(profile, baseUrl) {
|
|
|
1848
1931
|
let nativeStorePromise;
|
|
1849
1932
|
function nativeStore() {
|
|
1850
1933
|
if (process.env.ARTIFACTSHARE_DISABLE_NATIVE_TOKEN_STORE === "1") return Promise.resolve(null);
|
|
1851
|
-
return nativeStorePromise ??= detectNativeStore();
|
|
1934
|
+
return nativeStorePromise ??= detectNativeStore(process.platform);
|
|
1852
1935
|
}
|
|
1853
|
-
async function detectNativeStore() {
|
|
1854
|
-
if (
|
|
1855
|
-
if (
|
|
1936
|
+
async function detectNativeStore(platform, run = spawnFile) {
|
|
1937
|
+
if (platform === "darwin") return macosKeychain(run);
|
|
1938
|
+
if (platform === "linux") return await linuxSecretService(run);
|
|
1939
|
+
if (platform === "win32") return await windowsCredentialManager(run);
|
|
1856
1940
|
return null;
|
|
1857
1941
|
}
|
|
1858
|
-
function macosKeychain() {
|
|
1942
|
+
function macosKeychain(run) {
|
|
1859
1943
|
return {
|
|
1860
1944
|
kind: "macos_keychain",
|
|
1861
1945
|
read: async (account) => {
|
|
1862
|
-
const result = await
|
|
1946
|
+
const result = await run("security", [
|
|
1863
1947
|
"find-generic-password",
|
|
1864
1948
|
"-s",
|
|
1865
1949
|
SERVICE,
|
|
@@ -1870,7 +1954,7 @@ function macosKeychain() {
|
|
|
1870
1954
|
return result.status === 0 ? result.stdout.trim() || null : null;
|
|
1871
1955
|
},
|
|
1872
1956
|
write: async (account, token) => {
|
|
1873
|
-
return (await
|
|
1957
|
+
return (await run("security", ["-i"], `${[
|
|
1874
1958
|
"add-generic-password",
|
|
1875
1959
|
"-U",
|
|
1876
1960
|
"-s",
|
|
@@ -1882,7 +1966,7 @@ function macosKeychain() {
|
|
|
1882
1966
|
].join(" ")}\n`)).status === 0;
|
|
1883
1967
|
},
|
|
1884
1968
|
delete: async (account) => {
|
|
1885
|
-
return (await
|
|
1969
|
+
return (await run("security", [
|
|
1886
1970
|
"delete-generic-password",
|
|
1887
1971
|
"-s",
|
|
1888
1972
|
SERVICE,
|
|
@@ -1895,12 +1979,12 @@ function macosKeychain() {
|
|
|
1895
1979
|
function securityQuote(value) {
|
|
1896
1980
|
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
1897
1981
|
}
|
|
1898
|
-
async function linuxSecretService() {
|
|
1899
|
-
if ((await
|
|
1982
|
+
async function linuxSecretService(run) {
|
|
1983
|
+
if ((await run("secret-tool", ["--version"])).status !== 0) return null;
|
|
1900
1984
|
return {
|
|
1901
1985
|
kind: "linux_secret_service",
|
|
1902
1986
|
read: async (account) => {
|
|
1903
|
-
const result = await
|
|
1987
|
+
const result = await run("secret-tool", [
|
|
1904
1988
|
"lookup",
|
|
1905
1989
|
"service",
|
|
1906
1990
|
SERVICE,
|
|
@@ -1910,7 +1994,7 @@ async function linuxSecretService() {
|
|
|
1910
1994
|
return result.status === 0 ? result.stdout.trim() || null : null;
|
|
1911
1995
|
},
|
|
1912
1996
|
write: async (account, token) => {
|
|
1913
|
-
return (await
|
|
1997
|
+
return (await run("secret-tool", [
|
|
1914
1998
|
"store",
|
|
1915
1999
|
"--label",
|
|
1916
2000
|
`Artifact Share ${account}`,
|
|
@@ -1921,7 +2005,7 @@ async function linuxSecretService() {
|
|
|
1921
2005
|
], token)).status === 0;
|
|
1922
2006
|
},
|
|
1923
2007
|
delete: async (account) => {
|
|
1924
|
-
return (await
|
|
2008
|
+
return (await run("secret-tool", [
|
|
1925
2009
|
"clear",
|
|
1926
2010
|
"service",
|
|
1927
2011
|
SERVICE,
|
|
@@ -1931,6 +2015,274 @@ async function linuxSecretService() {
|
|
|
1931
2015
|
}
|
|
1932
2016
|
};
|
|
1933
2017
|
}
|
|
2018
|
+
const WINDOWS_CREDENTIAL_SCRIPT = String.raw`
|
|
2019
|
+
$ErrorActionPreference = 'Stop'
|
|
2020
|
+
Add-Type -TypeDefinition @'
|
|
2021
|
+
using System;
|
|
2022
|
+
using System.ComponentModel;
|
|
2023
|
+
using System.Runtime.InteropServices;
|
|
2024
|
+
|
|
2025
|
+
public static class ArtifactShareCredentialManager {
|
|
2026
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
2027
|
+
private struct Credential {
|
|
2028
|
+
public UInt32 Flags;
|
|
2029
|
+
public UInt32 Type;
|
|
2030
|
+
public string TargetName;
|
|
2031
|
+
public string Comment;
|
|
2032
|
+
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
|
2033
|
+
public UInt32 CredentialBlobSize;
|
|
2034
|
+
public IntPtr CredentialBlob;
|
|
2035
|
+
public UInt32 Persist;
|
|
2036
|
+
public UInt32 AttributeCount;
|
|
2037
|
+
public IntPtr Attributes;
|
|
2038
|
+
public string TargetAlias;
|
|
2039
|
+
public string UserName;
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
[DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
2043
|
+
private static extern bool CredRead(string target, UInt32 type, UInt32 flags, out IntPtr credential);
|
|
2044
|
+
|
|
2045
|
+
[DllImport("advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
2046
|
+
private static extern bool CredWrite(ref Credential credential, UInt32 flags);
|
|
2047
|
+
|
|
2048
|
+
[DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
2049
|
+
private static extern bool CredDelete(string target, UInt32 type, UInt32 flags);
|
|
2050
|
+
|
|
2051
|
+
[DllImport("advapi32.dll", EntryPoint = "CredFree")]
|
|
2052
|
+
private static extern void CredFree(IntPtr credential);
|
|
2053
|
+
|
|
2054
|
+
private const UInt32 Generic = 1;
|
|
2055
|
+
private const UInt32 PersistLocalMachine = 2;
|
|
2056
|
+
private const int ErrorNotFound = 1168;
|
|
2057
|
+
|
|
2058
|
+
public static bool Probe() { return true; }
|
|
2059
|
+
|
|
2060
|
+
public static byte[] Read(string target) {
|
|
2061
|
+
IntPtr pointer;
|
|
2062
|
+
if (!CredRead(target, Generic, 0, out pointer)) {
|
|
2063
|
+
int error = Marshal.GetLastWin32Error();
|
|
2064
|
+
if (error == ErrorNotFound) return null;
|
|
2065
|
+
throw new Win32Exception(error);
|
|
2066
|
+
}
|
|
2067
|
+
try {
|
|
2068
|
+
Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
|
|
2069
|
+
byte[] value = new byte[credential.CredentialBlobSize];
|
|
2070
|
+
if (value.Length > 0) Marshal.Copy(credential.CredentialBlob, value, 0, value.Length);
|
|
2071
|
+
return value;
|
|
2072
|
+
} finally {
|
|
2073
|
+
CredFree(pointer);
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
public static void Write(string target, byte[] value) {
|
|
2078
|
+
IntPtr blob = Marshal.AllocHGlobal(value.Length);
|
|
2079
|
+
try {
|
|
2080
|
+
if (value.Length > 0) Marshal.Copy(value, 0, blob, value.Length);
|
|
2081
|
+
Credential credential = new Credential {
|
|
2082
|
+
Type = Generic,
|
|
2083
|
+
TargetName = target,
|
|
2084
|
+
CredentialBlobSize = (UInt32)value.Length,
|
|
2085
|
+
CredentialBlob = blob,
|
|
2086
|
+
Persist = PersistLocalMachine,
|
|
2087
|
+
UserName = Environment.UserName
|
|
2088
|
+
};
|
|
2089
|
+
if (!CredWrite(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
2090
|
+
} finally {
|
|
2091
|
+
Marshal.FreeHGlobal(blob);
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
public static void Delete(string target) {
|
|
2096
|
+
if (!CredDelete(target, Generic, 0)) {
|
|
2097
|
+
int error = Marshal.GetLastWin32Error();
|
|
2098
|
+
if (error != ErrorNotFound) throw new Win32Exception(error);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
'@
|
|
2103
|
+
|
|
2104
|
+
$requestJson = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()))
|
|
2105
|
+
$request = $requestJson | ConvertFrom-Json
|
|
2106
|
+
$target = 'artifactshare-cli:' + [string]$request.account
|
|
2107
|
+
$chunkSize = 2400
|
|
2108
|
+
$chunkMarker = 'artifactshare-chunks-v1:'
|
|
2109
|
+
$deletingMarker = 'artifactshare-chunks-deleting-v1:'
|
|
2110
|
+
$cleanupMarker = 'artifactshare-chunks-cleanup-v1:'
|
|
2111
|
+
|
|
2112
|
+
function Get-ChunkManifest([byte[]]$bytes, [string]$marker = $chunkMarker) {
|
|
2113
|
+
if ($null -eq $bytes) { return $null }
|
|
2114
|
+
$text = [Text.Encoding]::UTF8.GetString($bytes)
|
|
2115
|
+
if (-not $text.StartsWith($marker)) { return $null }
|
|
2116
|
+
$parts = $text.Substring($marker.Length).Split(':')
|
|
2117
|
+
$count = 0
|
|
2118
|
+
if ($parts.Length -ne 2 -or -not [int]::TryParse($parts[1], [ref]$count) -or $count -lt 1) {
|
|
2119
|
+
throw 'Invalid chunked credential manifest.'
|
|
2120
|
+
}
|
|
2121
|
+
return [PSCustomObject]@{ Version = $parts[0]; Count = $count }
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
function Get-CleanupManifest([byte[]]$bytes) {
|
|
2125
|
+
if ($null -eq $bytes) { return $null }
|
|
2126
|
+
$text = [Text.Encoding]::UTF8.GetString($bytes)
|
|
2127
|
+
if (-not $text.StartsWith($cleanupMarker)) { return $null }
|
|
2128
|
+
$parts = $text.Substring($cleanupMarker.Length).Split(':')
|
|
2129
|
+
$activeCount = 0
|
|
2130
|
+
$staleCount = 0
|
|
2131
|
+
if (
|
|
2132
|
+
$parts.Length -ne 4 -or
|
|
2133
|
+
-not [int]::TryParse($parts[1], [ref]$activeCount) -or
|
|
2134
|
+
-not [int]::TryParse($parts[3], [ref]$staleCount) -or
|
|
2135
|
+
$activeCount -lt 1 -or
|
|
2136
|
+
$staleCount -lt 1
|
|
2137
|
+
) {
|
|
2138
|
+
throw 'Invalid credential cleanup manifest.'
|
|
2139
|
+
}
|
|
2140
|
+
return [PSCustomObject]@{
|
|
2141
|
+
Active = [PSCustomObject]@{ Version = $parts[0]; Count = $activeCount }
|
|
2142
|
+
Stale = [PSCustomObject]@{ Version = $parts[2]; Count = $staleCount }
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
function Remove-CredentialChunks($manifest) {
|
|
2147
|
+
if ($null -eq $manifest) { return }
|
|
2148
|
+
for ($index = 0; $index -lt $manifest.Count; $index++) {
|
|
2149
|
+
[ArtifactShareCredentialManager]::Delete(($target + ':chunk:' + $manifest.Version + ':' + $index))
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
switch ([string]$request.operation) {
|
|
2154
|
+
'probe' { [void][ArtifactShareCredentialManager]::Probe() }
|
|
2155
|
+
'read' {
|
|
2156
|
+
$bytes = [ArtifactShareCredentialManager]::Read($target)
|
|
2157
|
+
$deletingManifest = Get-ChunkManifest $bytes $deletingMarker
|
|
2158
|
+
if ($null -ne $deletingManifest) { break }
|
|
2159
|
+
$cleanupManifest = Get-CleanupManifest($bytes)
|
|
2160
|
+
$manifest = if ($null -ne $cleanupManifest) {
|
|
2161
|
+
$cleanupManifest.Active
|
|
2162
|
+
} else {
|
|
2163
|
+
Get-ChunkManifest($bytes)
|
|
2164
|
+
}
|
|
2165
|
+
if ($null -ne $manifest) {
|
|
2166
|
+
$stream = New-Object IO.MemoryStream
|
|
2167
|
+
try {
|
|
2168
|
+
for ($index = 0; $index -lt $manifest.Count; $index++) {
|
|
2169
|
+
$chunkTarget = $target + ':chunk:' + $manifest.Version + ':' + $index
|
|
2170
|
+
$chunk = [ArtifactShareCredentialManager]::Read($chunkTarget)
|
|
2171
|
+
if ($null -eq $chunk) { throw 'Credential chunk is missing.' }
|
|
2172
|
+
$stream.Write($chunk, 0, $chunk.Length)
|
|
2173
|
+
}
|
|
2174
|
+
$bytes = $stream.ToArray()
|
|
2175
|
+
} finally {
|
|
2176
|
+
$stream.Dispose()
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
if ($null -ne $bytes) { [Console]::Out.Write([Convert]::ToBase64String($bytes)) }
|
|
2180
|
+
}
|
|
2181
|
+
'write' {
|
|
2182
|
+
$oldBytes = [ArtifactShareCredentialManager]::Read($target)
|
|
2183
|
+
$pendingCleanup = Get-CleanupManifest($oldBytes)
|
|
2184
|
+
if ($null -ne $pendingCleanup) {
|
|
2185
|
+
Remove-CredentialChunks($pendingCleanup.Stale)
|
|
2186
|
+
$oldManifest = $pendingCleanup.Active
|
|
2187
|
+
$oldBytes = [Text.Encoding]::UTF8.GetBytes(($chunkMarker + $oldManifest.Version + ':' + $oldManifest.Count))
|
|
2188
|
+
[ArtifactShareCredentialManager]::Write($target, $oldBytes)
|
|
2189
|
+
} else {
|
|
2190
|
+
$oldManifest = Get-ChunkManifest($oldBytes)
|
|
2191
|
+
}
|
|
2192
|
+
if ($null -eq $oldManifest) {
|
|
2193
|
+
$oldManifest = Get-ChunkManifest $oldBytes $deletingMarker
|
|
2194
|
+
if ($null -ne $oldManifest) {
|
|
2195
|
+
Remove-CredentialChunks($oldManifest)
|
|
2196
|
+
$oldManifest = $null
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes([string]$request.value)
|
|
2200
|
+
if ($bytes.Length -le $chunkSize -and $null -eq $oldManifest) {
|
|
2201
|
+
[ArtifactShareCredentialManager]::Write($target, $bytes)
|
|
2202
|
+
} else {
|
|
2203
|
+
$version = [Guid]::NewGuid().ToString('N')
|
|
2204
|
+
$count = [int][Math]::Ceiling($bytes.Length / $chunkSize)
|
|
2205
|
+
$written = 0
|
|
2206
|
+
try {
|
|
2207
|
+
for ($index = 0; $index -lt $count; $index++) {
|
|
2208
|
+
$offset = [int]($index * $chunkSize)
|
|
2209
|
+
$length = [int][Math]::Min($chunkSize, $bytes.Length - $offset)
|
|
2210
|
+
$chunk = New-Object byte[] $length
|
|
2211
|
+
[Array]::Copy($bytes, $offset, $chunk, 0, $length)
|
|
2212
|
+
$chunkTarget = $target + ':chunk:' + $version + ':' + $index
|
|
2213
|
+
[ArtifactShareCredentialManager]::Write($chunkTarget, $chunk)
|
|
2214
|
+
$written++
|
|
2215
|
+
}
|
|
2216
|
+
$manifestBytes = [Text.Encoding]::UTF8.GetBytes(($chunkMarker + $version + ':' + $count))
|
|
2217
|
+
if ($null -ne $oldManifest) {
|
|
2218
|
+
$cleanupBytes = [Text.Encoding]::UTF8.GetBytes(
|
|
2219
|
+
($cleanupMarker + $version + ':' + $count + ':' + $oldManifest.Version + ':' + $oldManifest.Count)
|
|
2220
|
+
)
|
|
2221
|
+
[ArtifactShareCredentialManager]::Write($target, $cleanupBytes)
|
|
2222
|
+
$written = 0
|
|
2223
|
+
Remove-CredentialChunks($oldManifest)
|
|
2224
|
+
}
|
|
2225
|
+
[ArtifactShareCredentialManager]::Write($target, $manifestBytes)
|
|
2226
|
+
} catch {
|
|
2227
|
+
for ($index = 0; $index -lt $written; $index++) {
|
|
2228
|
+
[ArtifactShareCredentialManager]::Delete(($target + ':chunk:' + $version + ':' + $index))
|
|
2229
|
+
}
|
|
2230
|
+
throw
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
'delete' {
|
|
2235
|
+
$bytes = [ArtifactShareCredentialManager]::Read($target)
|
|
2236
|
+
$pendingCleanup = Get-CleanupManifest($bytes)
|
|
2237
|
+
if ($null -ne $pendingCleanup) {
|
|
2238
|
+
Remove-CredentialChunks($pendingCleanup.Stale)
|
|
2239
|
+
$manifest = $pendingCleanup.Active
|
|
2240
|
+
} else {
|
|
2241
|
+
$manifest = Get-ChunkManifest($bytes)
|
|
2242
|
+
}
|
|
2243
|
+
if ($null -eq $manifest) {
|
|
2244
|
+
$manifest = Get-ChunkManifest $bytes $deletingMarker
|
|
2245
|
+
}
|
|
2246
|
+
if ($null -ne $manifest) {
|
|
2247
|
+
$deletingBytes = [Text.Encoding]::UTF8.GetBytes(($deletingMarker + $manifest.Version + ':' + $manifest.Count))
|
|
2248
|
+
[ArtifactShareCredentialManager]::Write($target, $deletingBytes)
|
|
2249
|
+
Remove-CredentialChunks($manifest)
|
|
2250
|
+
}
|
|
2251
|
+
[ArtifactShareCredentialManager]::Delete($target)
|
|
2252
|
+
}
|
|
2253
|
+
default { throw 'Unknown credential operation.' }
|
|
2254
|
+
}
|
|
2255
|
+
`;
|
|
2256
|
+
const WINDOWS_CREDENTIAL_COMMAND = Buffer.from(WINDOWS_CREDENTIAL_SCRIPT, "utf16le").toString("base64");
|
|
2257
|
+
async function runWindowsCredentialOperation(run, operation, account = "", value) {
|
|
2258
|
+
return await run("powershell.exe", [
|
|
2259
|
+
"-NoProfile",
|
|
2260
|
+
"-NonInteractive",
|
|
2261
|
+
"-EncodedCommand",
|
|
2262
|
+
WINDOWS_CREDENTIAL_COMMAND
|
|
2263
|
+
], Buffer.from(JSON.stringify({
|
|
2264
|
+
operation,
|
|
2265
|
+
account,
|
|
2266
|
+
...value === void 0 ? {} : { value }
|
|
2267
|
+
}), "utf8").toString("base64"));
|
|
2268
|
+
}
|
|
2269
|
+
async function windowsCredentialManager(run) {
|
|
2270
|
+
if ((await runWindowsCredentialOperation(run, "probe")).status !== 0) return null;
|
|
2271
|
+
return {
|
|
2272
|
+
kind: "windows_credential_manager",
|
|
2273
|
+
read: async (account) => {
|
|
2274
|
+
const result = await runWindowsCredentialOperation(run, "read", account);
|
|
2275
|
+
if (result.status !== 0 || !result.stdout) return null;
|
|
2276
|
+
return Buffer.from(result.stdout, "base64").toString("utf8");
|
|
2277
|
+
},
|
|
2278
|
+
write: async (account, token) => {
|
|
2279
|
+
return (await runWindowsCredentialOperation(run, "write", account, token)).status === 0;
|
|
2280
|
+
},
|
|
2281
|
+
delete: async (account) => {
|
|
2282
|
+
return (await runWindowsCredentialOperation(run, "delete", account)).status === 0;
|
|
2283
|
+
}
|
|
2284
|
+
};
|
|
2285
|
+
}
|
|
1934
2286
|
async function deletePlaintextTokenAccount(account) {
|
|
1935
2287
|
const tokens = await readPlaintextTokens();
|
|
1936
2288
|
if (!tokens || !Object.hasOwn(tokens, account)) return false;
|
|
@@ -1954,6 +2306,7 @@ async function readPlaintextToken(account) {
|
|
|
1954
2306
|
async function writePlaintextToken(account, token) {
|
|
1955
2307
|
const home = configHome();
|
|
1956
2308
|
if (!home) return false;
|
|
2309
|
+
if (!plaintextFallbackSupported()) return false;
|
|
1957
2310
|
const tokens = await readPlaintextTokens() ?? {};
|
|
1958
2311
|
tokens[account] = token;
|
|
1959
2312
|
await mkdir(home, {
|
|
@@ -2049,15 +2402,42 @@ function isPendingDeviceAuth(value) {
|
|
|
2049
2402
|
if (!isRecord(value)) return false;
|
|
2050
2403
|
return typeof value.base_url === "string" && typeof value.profile === "string" && (value.preset === void 0 || value.preset === "unrestricted" || value.preset === "agent") && 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";
|
|
2051
2404
|
}
|
|
2052
|
-
function
|
|
2053
|
-
const override = nonEmpty(
|
|
2405
|
+
function resolveConfigHome(env, fallbackHome = homedir, platform = process.platform) {
|
|
2406
|
+
const override = nonEmpty(env.ARTIFACTSHARE_CONFIG_HOME);
|
|
2054
2407
|
if (override) return override;
|
|
2055
|
-
const xdgConfigHome = nonEmpty(
|
|
2408
|
+
const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
|
|
2056
2409
|
if (xdgConfigHome) return join(xdgConfigHome, "artifactshare");
|
|
2057
|
-
const home = nonEmpty(
|
|
2410
|
+
const home = platform === "win32" ? nonEmpty(env.USERPROFILE) ?? nonEmpty(env.HOME) : nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE);
|
|
2058
2411
|
if (home) return join(home, ".config/artifactshare");
|
|
2412
|
+
try {
|
|
2413
|
+
const detectedHome = nonEmpty(fallbackHome());
|
|
2414
|
+
if (detectedHome) return join(detectedHome, ".config/artifactshare");
|
|
2415
|
+
} catch {}
|
|
2059
2416
|
return null;
|
|
2060
2417
|
}
|
|
2418
|
+
function configHome() {
|
|
2419
|
+
return resolveConfigHome(process.env);
|
|
2420
|
+
}
|
|
2421
|
+
function plaintextFallbackSupported(platform = process.platform) {
|
|
2422
|
+
return platform !== "win32";
|
|
2423
|
+
}
|
|
2424
|
+
function plaintextStoreWritable(platform = process.platform) {
|
|
2425
|
+
if (!configHome()) return false;
|
|
2426
|
+
return plaintextFallbackSupported(platform);
|
|
2427
|
+
}
|
|
2428
|
+
async function tokenStoreDiagnostics() {
|
|
2429
|
+
const home = configHome();
|
|
2430
|
+
const native = await nativeStore();
|
|
2431
|
+
const plaintext = await readPlaintextTokens();
|
|
2432
|
+
const plaintextCredentials = plaintext ? Object.values(plaintext).filter((value) => typeof value === "string" && value.length > 0).length : 0;
|
|
2433
|
+
const plaintextProtection = home && process.platform !== "win32" ? "mode_0600" : "unavailable";
|
|
2434
|
+
return {
|
|
2435
|
+
config_home: home,
|
|
2436
|
+
native_store: native?.kind ?? "none",
|
|
2437
|
+
plaintext_credentials: plaintextCredentials,
|
|
2438
|
+
plaintext_protection: plaintextProtection
|
|
2439
|
+
};
|
|
2440
|
+
}
|
|
2061
2441
|
//#endregion
|
|
2062
2442
|
//#region src/credentials.ts
|
|
2063
2443
|
async function resolveCredential(options, projectInput = null) {
|
|
@@ -2120,6 +2500,7 @@ async function resolveProfileCredential(source, profile, options, globalConfig,
|
|
|
2120
2500
|
profile,
|
|
2121
2501
|
token: stored.token,
|
|
2122
2502
|
profileCredentialKind: stored.credential.kind,
|
|
2503
|
+
botProfile: globalConfig?.profiles?.[profile]?.kind === "bot",
|
|
2123
2504
|
...stored.credential.kind === "session" ? { refreshToken: stored.credential.refresh_token } : {}
|
|
2124
2505
|
};
|
|
2125
2506
|
return profileAuthRequired(source, profile, stored.reason, options, globalConfig, configPath, configKind);
|
|
@@ -2148,7 +2529,7 @@ async function profileAuthRequired(source, profile, reason, options, globalConfi
|
|
|
2148
2529
|
error: {
|
|
2149
2530
|
...error,
|
|
2150
2531
|
why,
|
|
2151
|
-
hint: `${switchHint} Or
|
|
2532
|
+
hint: `${switchHint} Or with a user present run ${CLI_INVOCATION} login --profile ${profile}; for an agent, add --preset agent. In unattended CI or scripts without browser approval, issue a token at ${url}, then set ${TOKEN_ENV_VAR}.`,
|
|
2152
2533
|
agent_recoverable: true,
|
|
2153
2534
|
requires_human: false,
|
|
2154
2535
|
recovery: {
|
|
@@ -2170,7 +2551,7 @@ async function profileAuthRequired(source, profile, reason, options, globalConfi
|
|
|
2170
2551
|
error: {
|
|
2171
2552
|
...error,
|
|
2172
2553
|
why,
|
|
2173
|
-
hint: `
|
|
2554
|
+
hint: `With a user present, run ${CLI_INVOCATION} login --profile ${profile}; for an agent, add --preset agent. In unattended CI or scripts without browser approval, issue a token at ${url}, then set ${TOKEN_ENV_VAR}.`,
|
|
2174
2555
|
details
|
|
2175
2556
|
}
|
|
2176
2557
|
};
|
|
@@ -2514,7 +2895,7 @@ async function writeProfileConfig(profile, options, tokenStore, whoami) {
|
|
|
2514
2895
|
profiles: {
|
|
2515
2896
|
...profiles,
|
|
2516
2897
|
[profile]: {
|
|
2517
|
-
...currentProfile,
|
|
2898
|
+
...currentProfile ? Object.fromEntries(Object.entries(currentProfile).filter(([key]) => key !== "kind")) : {},
|
|
2518
2899
|
base_url: baseUrlOf(options),
|
|
2519
2900
|
email: whoami.email ?? currentProfile?.email ?? null,
|
|
2520
2901
|
workspace_id: whoami.workspace_id,
|
|
@@ -2589,6 +2970,10 @@ async function canAttemptProfileTokenSave(profile, options) {
|
|
|
2589
2970
|
}
|
|
2590
2971
|
async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
|
|
2591
2972
|
if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
|
|
2973
|
+
const failedProfile = profileForAutoLogin(credential);
|
|
2974
|
+
if (failedProfile) {
|
|
2975
|
+
if ((await readGlobalConfig())?.profiles?.[failedProfile]?.kind === "bot") return writeFailure(command, botReauthRequiredError(failedProfile), mode, 1);
|
|
2976
|
+
}
|
|
2592
2977
|
if (mode.json && JSON_PENDING_AUTH_COMMANDS.has(command) && !isRetry) return handleJsonPendingAuth(command, credential, options, mode, rerun);
|
|
2593
2978
|
if (!isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
|
|
2594
2979
|
const performLogin = deps.performLogin ?? performDeviceLogin;
|
|
@@ -2639,6 +3024,10 @@ async function runAuthenticatedApi(credential, options, request) {
|
|
|
2639
3024
|
async function refreshStoredProfileSession(profile, refreshToken, options) {
|
|
2640
3025
|
const stored = await readProfileToken(profile, options);
|
|
2641
3026
|
if (!stored.ok || stored.credential.kind !== "session") return { ok: false };
|
|
3027
|
+
if (!await probeTokenStoreWritable(profile, options)) return {
|
|
3028
|
+
ok: false,
|
|
3029
|
+
error: tokenStoreUnavailableError(profile, "native_store_unavailable")
|
|
3030
|
+
};
|
|
2642
3031
|
const rotationRequestId = stored.credential.pending_rotation_id ?? randomUUID();
|
|
2643
3032
|
if (!stored.credential.pending_rotation_id) {
|
|
2644
3033
|
if (!(await saveProfileSessionCredential(profile, {
|
|
@@ -2646,7 +3035,7 @@ async function refreshStoredProfileSession(profile, refreshToken, options) {
|
|
|
2646
3035
|
pending_rotation_id: rotationRequestId
|
|
2647
3036
|
}, options)).ok) return {
|
|
2648
3037
|
ok: false,
|
|
2649
|
-
error: tokenStoreUnavailableError(profile)
|
|
3038
|
+
error: tokenStoreUnavailableError(profile, "store_operation_failed")
|
|
2650
3039
|
};
|
|
2651
3040
|
}
|
|
2652
3041
|
const request = await requestConfig(options);
|
|
@@ -2683,7 +3072,7 @@ async function refreshStoredProfileSession(profile, refreshToken, options) {
|
|
|
2683
3072
|
expires_at: body.expires_at
|
|
2684
3073
|
}, options)).ok) return {
|
|
2685
3074
|
ok: false,
|
|
2686
|
-
error: tokenStoreUnavailableError(profile)
|
|
3075
|
+
error: tokenStoreUnavailableError(profile, "store_operation_failed")
|
|
2687
3076
|
};
|
|
2688
3077
|
return {
|
|
2689
3078
|
ok: true,
|
|
@@ -2696,7 +3085,8 @@ async function handleJsonPendingAuth(command, credential, options, mode, rerun)
|
|
|
2696
3085
|
const baseUrl = baseUrlOf(options);
|
|
2697
3086
|
const request = await requestConfig(options);
|
|
2698
3087
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2699
|
-
if (!
|
|
3088
|
+
if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
|
|
3089
|
+
if (!await canAttemptProfileTokenSave(profile, options)) return writeFailure(command, tokenStoreUnavailableError(profile, "native_store_unavailable"), mode, 1);
|
|
2700
3090
|
const existing = await readPendingDeviceAuth(baseUrl, profile);
|
|
2701
3091
|
if (existing && !isPendingExpired(existing)) {
|
|
2702
3092
|
const exchange = await exchangeDeviceTokenOnce(options, existing.device_code, request.init);
|
|
@@ -2781,7 +3171,8 @@ async function fetchArtifact(parsed, target, credential) {
|
|
|
2781
3171
|
baseUrl: baseUrlOf(parsed.options),
|
|
2782
3172
|
credentialSource: credential.source,
|
|
2783
3173
|
profile: credential.profile,
|
|
2784
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
3174
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
3175
|
+
botProfile: credential.botProfile
|
|
2785
3176
|
}) };
|
|
2786
3177
|
if (!artifactGetSuccessFields(body)) return { error: serviceError("Artifact read succeeded but the response did not include source metadata.") };
|
|
2787
3178
|
return { data: body };
|
|
@@ -2816,7 +3207,8 @@ async function runArtifactsList(parsed, mode) {
|
|
|
2816
3207
|
baseUrl: baseUrlOf(parsed.options),
|
|
2817
3208
|
credentialSource: current.source,
|
|
2818
3209
|
profile: current.profile,
|
|
2819
|
-
profileCredentialKind: current.profileCredentialKind
|
|
3210
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
3211
|
+
botProfile: current.botProfile
|
|
2820
3212
|
}) };
|
|
2821
3213
|
return { data: body };
|
|
2822
3214
|
});
|
|
@@ -3328,7 +3720,8 @@ async function runCommentsList(parsed, mode) {
|
|
|
3328
3720
|
artifactTarget: true,
|
|
3329
3721
|
credentialSource: current.source,
|
|
3330
3722
|
profile: current.profile,
|
|
3331
|
-
profileCredentialKind: current.profileCredentialKind
|
|
3723
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
3724
|
+
botProfile: current.botProfile
|
|
3332
3725
|
});
|
|
3333
3726
|
return comments.error ? { error: comments.error } : { data: comments.body };
|
|
3334
3727
|
});
|
|
@@ -3370,7 +3763,8 @@ async function runCommentsPost(parsed, mode) {
|
|
|
3370
3763
|
artifactTarget: true,
|
|
3371
3764
|
credentialSource: current.source,
|
|
3372
3765
|
profile: current.profile,
|
|
3373
|
-
profileCredentialKind: current.profileCredentialKind
|
|
3766
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
3767
|
+
botProfile: current.botProfile
|
|
3374
3768
|
});
|
|
3375
3769
|
return posted.error ? { error: posted.error } : { data: posted.body };
|
|
3376
3770
|
});
|
|
@@ -3476,7 +3870,8 @@ async function postCommentAction(parsed, command, artifactId, payload, mode) {
|
|
|
3476
3870
|
artifactTarget: true,
|
|
3477
3871
|
credentialSource: current.source,
|
|
3478
3872
|
profile: current.profile,
|
|
3479
|
-
profileCredentialKind: current.profileCredentialKind
|
|
3873
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
3874
|
+
botProfile: current.botProfile
|
|
3480
3875
|
});
|
|
3481
3876
|
return action.error ? { error: action.error } : { data: action.body };
|
|
3482
3877
|
});
|
|
@@ -3511,7 +3906,8 @@ async function runDelete(parsed, mode) {
|
|
|
3511
3906
|
artifactTarget: true,
|
|
3512
3907
|
credentialSource: current.source,
|
|
3513
3908
|
profile: current.profile,
|
|
3514
|
-
profileCredentialKind: current.profileCredentialKind
|
|
3909
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
3910
|
+
botProfile: current.botProfile
|
|
3515
3911
|
});
|
|
3516
3912
|
return deleted.error ? { error: deleted.error } : { data: deleted.body };
|
|
3517
3913
|
});
|
|
@@ -3563,11 +3959,13 @@ async function runDoctor(parsed, mode) {
|
|
|
3563
3959
|
const data = {
|
|
3564
3960
|
next_command: null,
|
|
3565
3961
|
base_url: baseUrlOf(parsed.options),
|
|
3962
|
+
token_store: await tokenStoreDiagnostics(),
|
|
3566
3963
|
config: await configDiagnostics(project),
|
|
3567
3964
|
skills: await skillDiagnostics(),
|
|
3568
3965
|
auth: {
|
|
3569
3966
|
credential_source: credential.source,
|
|
3570
3967
|
...credential.profile ? { profile: credential.profile } : {},
|
|
3968
|
+
...credential.ok && credential.botProfile ? { profile_kind: "bot" } : {},
|
|
3571
3969
|
token_present: credential.ok,
|
|
3572
3970
|
ok: false
|
|
3573
3971
|
},
|
|
@@ -3609,7 +4007,8 @@ async function runDoctor(parsed, mode) {
|
|
|
3609
4007
|
baseUrl: baseUrlOf(parsed.options),
|
|
3610
4008
|
credentialSource: current.source,
|
|
3611
4009
|
profile: current.profile,
|
|
3612
|
-
profileCredentialKind: current.profileCredentialKind
|
|
4010
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
4011
|
+
botProfile: current.botProfile
|
|
3613
4012
|
}) };
|
|
3614
4013
|
return { data: {
|
|
3615
4014
|
kind: "body",
|
|
@@ -4001,7 +4400,8 @@ async function runDownload(parsed, mode, isRetry = false) {
|
|
|
4001
4400
|
baseUrl,
|
|
4002
4401
|
credentialSource: credential.source,
|
|
4003
4402
|
profile: credential.profile,
|
|
4004
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
4403
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
4404
|
+
botProfile: credential.botProfile
|
|
4005
4405
|
}), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
|
|
4006
4406
|
if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
|
|
4007
4407
|
const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
|
|
@@ -4021,7 +4421,8 @@ async function runDownload(parsed, mode, isRetry = false) {
|
|
|
4021
4421
|
baseUrl,
|
|
4022
4422
|
credentialSource: credential.source,
|
|
4023
4423
|
profile: credential.profile,
|
|
4024
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
4424
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
4425
|
+
botProfile: credential.botProfile
|
|
4025
4426
|
}), credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
|
|
4026
4427
|
const bytes = Buffer.from(await fileResponse.arrayBuffer());
|
|
4027
4428
|
const verified = verifyDownloadedBytes(file, bytes);
|
|
@@ -4086,7 +4487,8 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
|
|
|
4086
4487
|
artifactTarget: true,
|
|
4087
4488
|
credentialSource: credential.source,
|
|
4088
4489
|
profile: credential.profile,
|
|
4089
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
4490
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
4491
|
+
botProfile: credential.botProfile
|
|
4090
4492
|
}), credential, parsed.options, isRetry);
|
|
4091
4493
|
if (!refreshed.ok) return response;
|
|
4092
4494
|
credential = {
|
|
@@ -4114,7 +4516,8 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
|
|
|
4114
4516
|
artifactTarget: true,
|
|
4115
4517
|
credentialSource: credential.source,
|
|
4116
4518
|
profile: credential.profile,
|
|
4117
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
4519
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
4520
|
+
botProfile: credential.botProfile
|
|
4118
4521
|
}),
|
|
4119
4522
|
authFailure: response.status === 401
|
|
4120
4523
|
};
|
|
@@ -4284,7 +4687,8 @@ async function runEdit(parsed, mode) {
|
|
|
4284
4687
|
editSettings: true,
|
|
4285
4688
|
credentialSource: current.source,
|
|
4286
4689
|
profile: current.profile,
|
|
4287
|
-
profileCredentialKind: current.profileCredentialKind
|
|
4690
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
4691
|
+
botProfile: current.botProfile
|
|
4288
4692
|
});
|
|
4289
4693
|
return edited.error ? { error: edited.error } : { data: edited.body };
|
|
4290
4694
|
});
|
|
@@ -4494,7 +4898,7 @@ async function runInitConfig(parsed, mode, profile, projectId) {
|
|
|
4494
4898
|
if (parsed.options.dryRun === true) return writeFailure(command, validationError("--dry-run is only supported without --profile or --project-id.", "Run init --dry-run by itself to preview the skill install, or drop --dry-run to save the defaults."), mode, 1);
|
|
4495
4899
|
const resolved = await resolveProjectConfig();
|
|
4496
4900
|
if (profile) {
|
|
4497
|
-
if (!configHome()) return writeFailure(command,
|
|
4901
|
+
if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
|
|
4498
4902
|
const globalConfig = await readGlobalConfig();
|
|
4499
4903
|
if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
|
|
4500
4904
|
}
|
|
@@ -4545,7 +4949,7 @@ function optionsForProfileEntry(rawEntry, options) {
|
|
|
4545
4949
|
async function runLogout(parsed, mode) {
|
|
4546
4950
|
const command = "logout";
|
|
4547
4951
|
const explicitProfile = nonEmpty(parsed.options.profile);
|
|
4548
|
-
if (!configHome()) return writeFailure(command,
|
|
4952
|
+
if (!configHome()) return writeFailure(command, configHomeUnavailableError(explicitProfile), mode, 1);
|
|
4549
4953
|
const config = await readGlobalConfig() ?? {};
|
|
4550
4954
|
let profile;
|
|
4551
4955
|
if (explicitProfile) {
|
|
@@ -4572,7 +4976,7 @@ async function runLogout(parsed, mode) {
|
|
|
4572
4976
|
if (!revoked.response.ok && revoked.response.status !== 401) return writeFailure(command, mapApiError(revoked.response.status, revoked.body, { baseUrl: baseUrlOf(profileOptions) }), mode, 1);
|
|
4573
4977
|
}
|
|
4574
4978
|
const deleted = await deleteCredentialForProfileEntry(profile, rawEntry, parsed.options);
|
|
4575
|
-
if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
|
|
4979
|
+
if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(profile, "store_operation_failed"), mode, 1);
|
|
4576
4980
|
return writeSuccess(command, {
|
|
4577
4981
|
profile,
|
|
4578
4982
|
credential_removed: deleted.credential_removed,
|
|
@@ -4599,7 +5003,8 @@ async function runMove(parsed, mode) {
|
|
|
4599
5003
|
artifactTarget: true,
|
|
4600
5004
|
credentialSource: current.source,
|
|
4601
5005
|
profile: current.profile,
|
|
4602
|
-
profileCredentialKind: current.profileCredentialKind
|
|
5006
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
5007
|
+
botProfile: current.botProfile
|
|
4603
5008
|
});
|
|
4604
5009
|
return moved.error ? { error: moved.error } : { data: moved.body };
|
|
4605
5010
|
});
|
|
@@ -4658,7 +5063,7 @@ async function readStdinToken() {
|
|
|
4658
5063
|
}
|
|
4659
5064
|
async function runProfilesList(parsed, mode) {
|
|
4660
5065
|
const command = "profiles list";
|
|
4661
|
-
if (!configHome()) return writeFailure(command,
|
|
5066
|
+
if (!configHome()) return writeFailure(command, configHomeUnavailableError(), mode, 1);
|
|
4662
5067
|
const config = await readGlobalConfig() ?? {};
|
|
4663
5068
|
const defaultProfile = nonEmpty(config.default_profile) ?? null;
|
|
4664
5069
|
const profiles = await Promise.all(Object.entries(config.profiles ?? {}).map(async ([name, rawEntry]) => {
|
|
@@ -4675,7 +5080,8 @@ async function runProfilesList(parsed, mode) {
|
|
|
4675
5080
|
token_store: entry.token_store ?? null,
|
|
4676
5081
|
updated_at: nonEmpty(entry.updated_at) ?? null,
|
|
4677
5082
|
is_default: name === defaultProfile,
|
|
4678
|
-
token_present: stored.ok
|
|
5083
|
+
token_present: stored.ok,
|
|
5084
|
+
...entry.kind === "bot" ? { kind: "bot" } : {}
|
|
4679
5085
|
};
|
|
4680
5086
|
}));
|
|
4681
5087
|
writeSuccess(command, {
|
|
@@ -4688,7 +5094,7 @@ async function runProfilesUse(parsed, mode) {
|
|
|
4688
5094
|
const command = "profiles use";
|
|
4689
5095
|
const name = nonEmpty(parsed.positionals[0]);
|
|
4690
5096
|
if (!name) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles use <name>.`), mode, 1);
|
|
4691
|
-
if (!configHome()) return writeFailure(command,
|
|
5097
|
+
if (!configHome()) return writeFailure(command, configHomeUnavailableError(name), mode, 1);
|
|
4692
5098
|
const config = await readGlobalConfig() ?? {};
|
|
4693
5099
|
if (!Object.hasOwn(config.profiles ?? {}, name)) return writeFailure(command, profileNotFoundError(name), mode, 1);
|
|
4694
5100
|
const previous = nonEmpty(config.default_profile) ?? null;
|
|
@@ -4705,7 +5111,7 @@ async function runProfilesImportToken(parsed, mode) {
|
|
|
4705
5111
|
const command = "profiles import-token";
|
|
4706
5112
|
const profile = nonEmpty(parsed.options.profile);
|
|
4707
5113
|
if (!profile) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles import-token --profile <name>.`), mode, 1);
|
|
4708
|
-
if (!configHome()) return writeFailure(command,
|
|
5114
|
+
if (!configHome()) return writeFailure(command, configHomeUnavailableError(profile), mode, 1);
|
|
4709
5115
|
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);
|
|
4710
5116
|
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);
|
|
4711
5117
|
let token;
|
|
@@ -4715,6 +5121,7 @@ async function runProfilesImportToken(parsed, mode) {
|
|
|
4715
5121
|
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);
|
|
4716
5122
|
}
|
|
4717
5123
|
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);
|
|
5124
|
+
if (token.startsWith("asb_")) return await importBotTokenProfile(command, profile, token, parsed, mode);
|
|
4718
5125
|
const request = await requestConfig(parsed.options);
|
|
4719
5126
|
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
4720
5127
|
const stored = await verifyAndStoreApiTokenProfile(profile, token, parsed.options, request.init);
|
|
@@ -4731,12 +5138,12 @@ async function runProfilesDelete(parsed, mode) {
|
|
|
4731
5138
|
const command = "profiles delete";
|
|
4732
5139
|
const name = nonEmpty(parsed.positionals[0]);
|
|
4733
5140
|
if (!name) return writeFailure(command, validationError("A profile name is required.", `Run ${CLI_INVOCATION} profiles delete <name>.`), mode, 1);
|
|
4734
|
-
if (!configHome()) return writeFailure(command,
|
|
5141
|
+
if (!configHome()) return writeFailure(command, configHomeUnavailableError(name), mode, 1);
|
|
4735
5142
|
const config = await readGlobalConfig() ?? {};
|
|
4736
5143
|
if (!Object.hasOwn(config.profiles ?? {}, name)) return writeFailure(command, profileNotFoundError(name), mode, 1);
|
|
4737
5144
|
const rawEntry = config.profiles?.[name];
|
|
4738
5145
|
const deleted = await deleteCredentialForProfileEntry(name, rawEntry, parsed.options);
|
|
4739
|
-
if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(name), mode, 1);
|
|
5146
|
+
if (!deleted.ok) return writeFailure(command, tokenStoreUnavailableError(name, "store_operation_failed"), mode, 1);
|
|
4740
5147
|
const previousDefault = nonEmpty(config.default_profile) ?? null;
|
|
4741
5148
|
const { [name]: _removed, ...restProfiles } = config.profiles ?? {};
|
|
4742
5149
|
const defaultProfile = config.default_profile === name ? null : config.default_profile ?? null;
|
|
@@ -4754,6 +5161,94 @@ async function runProfilesDelete(parsed, mode) {
|
|
|
4754
5161
|
default_profile: defaultProfile
|
|
4755
5162
|
}, mode);
|
|
4756
5163
|
}
|
|
5164
|
+
async function importBotTokenProfile(command, profile, token, parsed, mode) {
|
|
5165
|
+
const config = await readGlobalConfig() ?? {};
|
|
5166
|
+
const entry = isRecord(config.profiles?.[profile]) ? config.profiles?.[profile] : void 0;
|
|
5167
|
+
if (entry && parsed.options.force !== true) {
|
|
5168
|
+
if ((await readProfileToken(profile, {
|
|
5169
|
+
...parsed.options,
|
|
5170
|
+
baseUrl: nonEmpty(entry.base_url) ?? baseUrlOf(parsed.options)
|
|
5171
|
+
})).ok) return writeFailure(command, validationError(`Profile "${profile}" already has a stored credential.`, `Re-run with --force to replace it: printf '%s' "$TOKEN" | ${CLI_INVOCATION} profiles import-token --profile ${profile} --force`), mode, 1);
|
|
5172
|
+
}
|
|
5173
|
+
const request = await requestConfig(parsed.options);
|
|
5174
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
5175
|
+
const forcedReplace = Boolean(entry && parsed.options.force === true);
|
|
5176
|
+
if (!await probeTokenStoreWritable(profile, parsed.options, { ignoreExistingEntry: forcedReplace })) return writeFailure(command, tokenStoreUnavailableError(profile, "native_store_unavailable"), mode, 1);
|
|
5177
|
+
if (forcedReplace && entry) {
|
|
5178
|
+
if (!(await deleteCredentialForProfileEntry(profile, entry, parsed.options)).ok) return writeFailure(command, validationError(`The existing credential for profile "${profile}" could not be removed, so the forced import was aborted before consuming the token.`, "Fix the credential store (or remove the credential with logout --profile), then re-run the import; the bot token is still unconsumed."), mode, 1);
|
|
5179
|
+
}
|
|
5180
|
+
let configWritable = false;
|
|
5181
|
+
try {
|
|
5182
|
+
configWritable = await writeGlobalConfig(config);
|
|
5183
|
+
} catch {
|
|
5184
|
+
configWritable = false;
|
|
5185
|
+
}
|
|
5186
|
+
if (!configWritable) return writeFailure(command, tokenStoreUnavailableError(profile, "config_write_failed"), mode, 1);
|
|
5187
|
+
const rotationRequestId = randomUUID();
|
|
5188
|
+
let result = await apiPostPublic("/api/cli/auth/refresh", {
|
|
5189
|
+
refresh_token: token,
|
|
5190
|
+
rotation_request_id: rotationRequestId
|
|
5191
|
+
}, parsed.options, request.init);
|
|
5192
|
+
for (let retry = 0; result.error && retry < 2; retry += 1) result = await apiPostPublic("/api/cli/auth/refresh", {
|
|
5193
|
+
refresh_token: token,
|
|
5194
|
+
rotation_request_id: rotationRequestId
|
|
5195
|
+
}, parsed.options, request.init);
|
|
5196
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
5197
|
+
const { response, body } = result;
|
|
5198
|
+
if (!response.ok) {
|
|
5199
|
+
if (response.status === 401) return writeFailure(command, botTokenInvalidError(profile), mode, 1);
|
|
5200
|
+
return writeFailure(command, mapApiError(response.status, body, { baseUrl: baseUrlOf(parsed.options) }), mode, 1);
|
|
5201
|
+
}
|
|
5202
|
+
if (typeof body?.access_token !== "string" || body.access_token.length === 0 || typeof body.expires_at !== "string" || typeof body.refresh_token !== "string" || !body.refresh_token || typeof body.refresh_token_expires_at !== "string") return writeFailure(command, validationError("The refresh response was invalid.", "Ask a workspace administrator to reissue the bot token, then retry with the new token.", "service_error"), mode, 1);
|
|
5203
|
+
const saved = await saveProfileSessionCredential(profile, {
|
|
5204
|
+
kind: "session",
|
|
5205
|
+
session_token: body.access_token,
|
|
5206
|
+
refresh_token: body.refresh_token,
|
|
5207
|
+
expires_at: body.expires_at
|
|
5208
|
+
}, parsed.options);
|
|
5209
|
+
if (!saved.ok) return writeFailure(command, validationError("The rotated bot credential could not be stored; the imported token is now consumed and lost.", "Fix the token store, ask a workspace administrator to reissue the bot token, and import the new token.", "token_store_unavailable"), mode, 1);
|
|
5210
|
+
const whoamiResult = await apiGet("/api/cli/whoami", body.access_token, parsed.options, request.init, {
|
|
5211
|
+
authenticated: true,
|
|
5212
|
+
baseUrl: baseUrlOf(parsed.options)
|
|
5213
|
+
});
|
|
5214
|
+
const whoami = whoamiResult.error ? null : whoamiProfile(whoamiResult.body);
|
|
5215
|
+
const latest = await readGlobalConfig() ?? {};
|
|
5216
|
+
const profiles = latest.profiles ?? {};
|
|
5217
|
+
let configSaved = false;
|
|
5218
|
+
try {
|
|
5219
|
+
configSaved = await writeGlobalConfig({
|
|
5220
|
+
...latest,
|
|
5221
|
+
default_profile: nonEmpty(latest.default_profile) ?? profile,
|
|
5222
|
+
profiles: {
|
|
5223
|
+
...profiles,
|
|
5224
|
+
[profile]: {
|
|
5225
|
+
...isRecord(profiles[profile]) ? profiles[profile] : {},
|
|
5226
|
+
kind: "bot",
|
|
5227
|
+
base_url: baseUrlOf(parsed.options),
|
|
5228
|
+
email: whoami?.email ?? null,
|
|
5229
|
+
workspace_id: whoami?.workspace_id ?? null,
|
|
5230
|
+
token_store: saved.store,
|
|
5231
|
+
preset: "agent",
|
|
5232
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
5233
|
+
}
|
|
5234
|
+
}
|
|
5235
|
+
});
|
|
5236
|
+
} catch {
|
|
5237
|
+
configSaved = false;
|
|
5238
|
+
}
|
|
5239
|
+
if (!configSaved) return writeFailure(command, validationError(`The rotated bot credential was stored, but the profile configuration for "${profile}" could not be written.`, "Without the config entry the profile loses its bot marker and later auth may attempt a human device login. Fix the config directory (disk space / permissions), then ask a workspace administrator to reissue the bot token and import it again.", "service_error"), mode, 1);
|
|
5240
|
+
return writeSuccess(command, {
|
|
5241
|
+
profile,
|
|
5242
|
+
token_store: saved.store,
|
|
5243
|
+
user: { email: whoami?.email ?? null },
|
|
5244
|
+
workspace: {
|
|
5245
|
+
id: whoami?.workspace_id ?? null,
|
|
5246
|
+
hosted_domain: whoami?.hosted_domain ?? null
|
|
5247
|
+
},
|
|
5248
|
+
base_url: baseUrlOf(parsed.options),
|
|
5249
|
+
kind: "bot"
|
|
5250
|
+
}, mode);
|
|
5251
|
+
}
|
|
4757
5252
|
//#endregion
|
|
4758
5253
|
//#region src/command-runners/projects.ts
|
|
4759
5254
|
async function fetchProjects(token, options, init, errorOptions = {}) {
|
|
@@ -4783,7 +5278,8 @@ async function runProjectsList(parsed, mode) {
|
|
|
4783
5278
|
const fetched = await fetchProjects(current.token, parsed.options, request.init, {
|
|
4784
5279
|
credentialSource: current.source,
|
|
4785
5280
|
profile: current.profile,
|
|
4786
|
-
profileCredentialKind: current.profileCredentialKind
|
|
5281
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
5282
|
+
botProfile: current.botProfile
|
|
4787
5283
|
});
|
|
4788
5284
|
return fetched.error ? { error: fetched.error } : { data: fetched.projects };
|
|
4789
5285
|
});
|
|
@@ -4820,7 +5316,8 @@ async function runProjectsCreate(parsed, mode) {
|
|
|
4820
5316
|
}, parsed.options, request.init, {
|
|
4821
5317
|
credentialSource: current.source,
|
|
4822
5318
|
profile: current.profile,
|
|
4823
|
-
profileCredentialKind: current.profileCredentialKind
|
|
5319
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
5320
|
+
botProfile: current.botProfile
|
|
4824
5321
|
});
|
|
4825
5322
|
return created.error ? { error: created.error } : { data: created.body };
|
|
4826
5323
|
});
|
|
@@ -4854,7 +5351,8 @@ async function runProjectsEdit(parsed, mode) {
|
|
|
4854
5351
|
projectTarget: true,
|
|
4855
5352
|
credentialSource: current.source,
|
|
4856
5353
|
profile: current.profile,
|
|
4857
|
-
profileCredentialKind: current.profileCredentialKind
|
|
5354
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
5355
|
+
botProfile: current.botProfile
|
|
4858
5356
|
});
|
|
4859
5357
|
return edited.error ? { error: edited.error } : { data: edited.body };
|
|
4860
5358
|
});
|
|
@@ -4966,7 +5464,8 @@ async function runShare(parsed, mode, isRetry = false) {
|
|
|
4966
5464
|
baseUrl,
|
|
4967
5465
|
credentialSource: credential.source,
|
|
4968
5466
|
profile: credential.profile,
|
|
4969
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
5467
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
5468
|
+
botProfile: credential.botProfile
|
|
4970
5469
|
});
|
|
4971
5470
|
if (resolved.error) return handleAuthenticatedCredentialFailure(command, resolved.error, credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
|
|
4972
5471
|
const { project: _project, ...rest } = parsed.options;
|
|
@@ -5009,14 +5508,21 @@ async function runShare(parsed, mode, isRetry = false) {
|
|
|
5009
5508
|
baseUrl,
|
|
5010
5509
|
credentialSource: credential.source,
|
|
5011
5510
|
profile: credential.profile,
|
|
5012
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
5511
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
5512
|
+
botProfile: credential.botProfile
|
|
5013
5513
|
}), credential, parsed.options, mode, () => runShare(parsed, mode, true), isRetry);
|
|
5014
5514
|
const id = body?.id ?? null;
|
|
5515
|
+
const url = body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null);
|
|
5516
|
+
const artifactKind = body?.artifactKind ?? upload.payload.kind;
|
|
5517
|
+
const warnings = Array.isArray(body?.warnings) ? body.warnings.flatMap((warning) => warning?.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [{
|
|
5518
|
+
code: "slack_reauthorization_required",
|
|
5519
|
+
message: warning.message
|
|
5520
|
+
}] : []) : [];
|
|
5015
5521
|
return writeSuccess(command, {
|
|
5016
5522
|
artifact: {
|
|
5017
5523
|
id,
|
|
5018
|
-
url
|
|
5019
|
-
kind:
|
|
5524
|
+
url,
|
|
5525
|
+
kind: artifactKind
|
|
5020
5526
|
},
|
|
5021
5527
|
version: { id: body?.versionId ?? null },
|
|
5022
5528
|
result: { created: body?.created ?? true },
|
|
@@ -5029,7 +5535,8 @@ async function runShare(parsed, mode, isRetry = false) {
|
|
|
5029
5535
|
visibility: body?.visibility ?? requestedVisibility,
|
|
5030
5536
|
grant_emails: grantEmails,
|
|
5031
5537
|
link_expires_at: body?.link_expires_at ?? null
|
|
5032
|
-
}
|
|
5538
|
+
},
|
|
5539
|
+
...warnings.length > 0 ? { warnings } : {}
|
|
5033
5540
|
}, mode);
|
|
5034
5541
|
}
|
|
5035
5542
|
async function resolveProjectIdByName(projectName, token, options, init, errorOptions) {
|
|
@@ -5071,7 +5578,8 @@ async function runResolve(parsed, mode) {
|
|
|
5071
5578
|
baseUrl: baseUrlOf(parsed.options),
|
|
5072
5579
|
credentialSource: current.source,
|
|
5073
5580
|
profile: current.profile,
|
|
5074
|
-
profileCredentialKind: current.profileCredentialKind
|
|
5581
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
5582
|
+
botProfile: current.botProfile
|
|
5075
5583
|
}) };
|
|
5076
5584
|
return { data: body };
|
|
5077
5585
|
});
|
|
@@ -5117,7 +5625,8 @@ async function runUpdate(parsed, mode, isRetry = false) {
|
|
|
5117
5625
|
baseUrl,
|
|
5118
5626
|
credentialSource: credential.source,
|
|
5119
5627
|
profile: credential.profile,
|
|
5120
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
5628
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
5629
|
+
botProfile: credential.botProfile
|
|
5121
5630
|
}), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
|
|
5122
5631
|
const id = body?.id ?? artifactId;
|
|
5123
5632
|
const result = {
|
|
@@ -5173,7 +5682,8 @@ async function runAppend(parsed, mode, isRetry = false) {
|
|
|
5173
5682
|
baseUrl: baseUrlOf(parsed.options),
|
|
5174
5683
|
credentialSource: credential.source,
|
|
5175
5684
|
profile: credential.profile,
|
|
5176
|
-
profileCredentialKind: credential.profileCredentialKind
|
|
5685
|
+
profileCredentialKind: credential.profileCredentialKind,
|
|
5686
|
+
botProfile: credential.botProfile
|
|
5177
5687
|
}), credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
|
|
5178
5688
|
const success = {
|
|
5179
5689
|
artifact: {
|
|
@@ -5199,7 +5709,8 @@ async function runWhoami(parsed, mode) {
|
|
|
5199
5709
|
const result = await apiGet("/api/cli/whoami", current.token, parsed.options, request.init, {
|
|
5200
5710
|
credentialSource: current.source,
|
|
5201
5711
|
profile: current.profile,
|
|
5202
|
-
profileCredentialKind: current.profileCredentialKind
|
|
5712
|
+
profileCredentialKind: current.profileCredentialKind,
|
|
5713
|
+
botProfile: current.botProfile
|
|
5203
5714
|
});
|
|
5204
5715
|
return result.error ? { error: result.error } : { data: result.body };
|
|
5205
5716
|
});
|
|
@@ -5713,7 +6224,7 @@ const commonArgs = {
|
|
|
5713
6224
|
allowPlaintextTokenStore: {
|
|
5714
6225
|
type: "boolean",
|
|
5715
6226
|
toKebab: true,
|
|
5716
|
-
description: "Allow a
|
|
6227
|
+
description: "Allow a plaintext token file (0600 on POSIX; unavailable on Windows)"
|
|
5717
6228
|
},
|
|
5718
6229
|
insecureLocalhost: {
|
|
5719
6230
|
type: "boolean",
|
|
@@ -5756,7 +6267,8 @@ npx --yes @artifactshare/cli doctor --json
|
|
|
5756
6267
|
|
|
5757
6268
|
Authentication:
|
|
5758
6269
|
Interactive terminal: run ${CLI_INVOCATION} login --profile default, then approve in your browser.
|
|
5759
|
-
|
|
6270
|
+
Agent with a user present: run ${CLI_INVOCATION} login --profile <name> --preset agent, then approve one project in your browser.
|
|
6271
|
+
Unattended CI or scripts: issue a token at ${DEFAULT_BASE_URL}/settings/tokens, then set ${TOKEN_ENV_VAR} or pass ${TOKEN_OPTION}.
|
|
5760
6272
|
|
|
5761
6273
|
Common failures:
|
|
5762
6274
|
auth_required Use ${TOKEN_ENV_VAR} or ${TOKEN_OPTION}; tokens are issued at ${DEFAULT_BASE_URL}/settings/tokens
|
|
@@ -5780,7 +6292,8 @@ const loginDefinition = define({
|
|
|
5780
6292
|
npx --yes @artifactshare/cli login --profile client-a --preset agent --json
|
|
5781
6293
|
|
|
5782
6294
|
login requires browser approval in an interactive terminal.
|
|
5783
|
-
For
|
|
6295
|
+
For an agent with a user present, use --preset agent and approve one project in the browser.
|
|
6296
|
+
For unattended CI or scripts without browser approval, 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.
|
|
5784
6297
|
|
|
5785
6298
|
Common failures:
|
|
5786
6299
|
auth_denied The browser approval was denied
|
|
@@ -6463,22 +6976,30 @@ Common failures:
|
|
|
6463
6976
|
});
|
|
6464
6977
|
const profilesImportTokenDefinition = define({
|
|
6465
6978
|
name: "import-token",
|
|
6466
|
-
description: "Read an API token from standard input and save it to a CLI profile.",
|
|
6979
|
+
description: "Read an API token or bot token from standard input and save it to a CLI profile.",
|
|
6467
6980
|
toKebab: true,
|
|
6468
6981
|
args: {
|
|
6469
6982
|
json: commonArgs.json,
|
|
6470
6983
|
baseUrl: commonArgs.baseUrl,
|
|
6471
6984
|
profile: commonArgs.profile,
|
|
6472
6985
|
allowPlaintextTokenStore: commonArgs.allowPlaintextTokenStore,
|
|
6473
|
-
insecureLocalhost: commonArgs.insecureLocalhost
|
|
6986
|
+
insecureLocalhost: commonArgs.insecureLocalhost,
|
|
6987
|
+
force: {
|
|
6988
|
+
type: "boolean",
|
|
6989
|
+
toKebab: true,
|
|
6990
|
+
description: "Replace an existing profile credential when importing a bot token (no-op for API tokens)"
|
|
6991
|
+
}
|
|
6474
6992
|
},
|
|
6475
6993
|
examples: `printf '%s' "$TOKEN" | npx --yes @artifactshare/cli profiles import-token --profile client-a --json
|
|
6476
6994
|
|
|
6477
|
-
Reads the token from standard input only. Use this in
|
|
6995
|
+
Reads the token from standard input only. Use this in unattended CI or scripts without browser approval after issuing a token at ${DEFAULT_BASE_URL}/settings/tokens.
|
|
6996
|
+
|
|
6997
|
+
Bot tokens (asb_ prefix, issued once by a workspace admin) are detected by prefix and imported as rotating refresh credentials; the first refresh consumes the displayed token, so the rotated credential is stored before success is reported. Importing a bot token over an existing profile credential requires --force (--force is a no-op for API tokens). A stored bot credential cannot be re-imported; recovery is an admin reissue.
|
|
6478
6998
|
|
|
6479
6999
|
Common failures:
|
|
6480
|
-
validation_failed Pass --profile and pipe a non-empty token on standard input
|
|
7000
|
+
validation_failed Pass --profile and pipe a non-empty token on standard input; bot-token overwrite needs --force
|
|
6481
7001
|
token_invalid The token is invalid or expired
|
|
7002
|
+
bot_token_invalid The bot token was revoked, superseded by a reissue, or the bot was stopped; ask an admin to reissue
|
|
6482
7003
|
auth_account_mismatch The token belongs to a different account than the saved profile email
|
|
6483
7004
|
token_store_unavailable Configure an OS credential store or use the explicit plaintext fallback`
|
|
6484
7005
|
});
|
|
@@ -6887,7 +7408,7 @@ const whoamiDefinition = define({
|
|
|
6887
7408
|
});
|
|
6888
7409
|
const doctorDefinition = define({
|
|
6889
7410
|
name: "doctor",
|
|
6890
|
-
description: "Check authentication, destination, network, and upload access.",
|
|
7411
|
+
description: "Check token storage, authentication, destination, network, and upload access.",
|
|
6891
7412
|
toKebab: true,
|
|
6892
7413
|
args: commonArgs
|
|
6893
7414
|
});
|