@knowttl/artium-axi 0.0.34 → 0.0.35

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
@@ -76,7 +76,7 @@ Write capabilities below require administrator opt-in.
76
76
  | Group | Purpose | Access | Reference |
77
77
  | --- | --- | --- | --- |
78
78
  | BeyondTrust PM Cloud | Endpoint Privilege Management reads, selected writes, deletes and four downloads | Managed credentials; exact operation grants; separate delete toggle | [Credentials](docs/tool-credentials.md#beyondtrust-pm-cloud) |
79
- | Discovery and sessions | Identity, login, tools, doctor, update and setup | Client/session operations | [Commands](docs/commands.md) |
79
+ | Discovery and sessions | Identity, login, tools, doctor, update, setup and delegated token management | Client/session operations; see delegated boundaries for rollout | [Commands](docs/commands.md), [delegated boundaries](docs/safety.md#delegated-sessions) |
80
80
  | Falcon | Endpoint investigations, search lifecycle, MalQuery and restricted RTR | Exact administrator grants; native RTR profile opt-in and confirmation | [Capabilities](docs/safety.md#write-gates-by-tool) |
81
81
  | Kubernetes | Cluster resources, logs and passive authorization reviews | Bounded reads, native prepare/preview/confirm mutations, caller-owned workspaces, explicitly granted byte sessions and port forwarding, protected service-account token delivery | [Capabilities](docs/safety.md#kubernetes-reads) |
82
82
  | SSH | Granted hosts, authentication checks, confirmed commands and reusable transports | Dedicated host bindings and caller grants; writes default off | [Capabilities](docs/safety.md#ssh-reads) |
@@ -43,7 +43,7 @@ var init_package = __esm({
43
43
  "package.json"() {
44
44
  package_default = {
45
45
  name: "artium-axi",
46
- version: "0.0.34",
46
+ version: "0.0.35",
47
47
  private: true,
48
48
  license: "MIT",
49
49
  type: "module",
@@ -21852,12 +21852,164 @@ var init_zod = __esm({
21852
21852
  }
21853
21853
  });
21854
21854
 
21855
+ // src/shared/errors.ts
21856
+ function errorResponse(error62, requestId) {
21857
+ return { error: {
21858
+ code: error62.code,
21859
+ source: error62.source,
21860
+ message: error62.message,
21861
+ next: error62.next,
21862
+ requestId: error62.requestId ?? requestId,
21863
+ ...error62.recovery ? { recovery: error62.recovery } : {}
21864
+ } };
21865
+ }
21866
+ var cliOutdatedDownloadNext, definitions, usageErrors, errors, ArtiumError;
21867
+ var init_errors3 = __esm({
21868
+ "src/shared/errors.ts"() {
21869
+ "use strict";
21870
+ cliOutdatedDownloadNext = "Download the current CLI from /cli/artium-axi.mjs on this server, verify it with the SHA-256 checksum at /cli/artium-axi.mjs.sha256, and install it as artium-axi.";
21871
+ definitions = {
21872
+ CONNECTION_BUSY: { status: 409, message: "An SSH command is already active on this connection.", next: "Inspect its execution before submitting another command, or explicitly open another connection." },
21873
+ CONNECTION_CLOSED: { status: 409, message: "The selected SSH connection is closed or expired.", next: "Inspect remote state before explicitly opening another connection; no reconnection or command replay occurred." },
21874
+ STORE_SCHEMA_INVALID: { status: 503, message: "The store schema is unsupported by this image.", next: "Use the matching image, or restore the pre-upgrade backup into a new volume with its matching image and key." },
21875
+ BACKUP_FAILED: { status: 500, message: "Database backup did not complete.", next: "Check the source store and a writable backup directory; choose a new output file." },
21876
+ RESTORE_FAILED: { status: 500, message: "Database restore did not complete.", next: "Stop the destination server and use an empty new data volume, an intact backup and its matching master key." },
21877
+ CLI_OUTDATED: { status: 426, message: "The CLI version is too old for this server.", next: cliOutdatedDownloadNext },
21878
+ CERTIFICATE_INVALID: { status: 503, message: "The server certificate could not be verified.", next: "Check certificate trust or set ARTIUM_AXI_CA_FILE to the trusted CA file." },
21879
+ ADMIN_REQUIRED: { status: 403, message: "Administrator capability is required.", next: "Ask an administrator to perform this operation." },
21880
+ REVISION_CONFLICT: { status: 409, message: "The record changed since it was read.", next: "Read the current record revision and retry your edit." },
21881
+ LAST_ADMINISTRATOR: { status: 409, message: "The last enabled administrator must remain enabled.", next: "Enable another administrator before changing this account." },
21882
+ USERNAME_INVALID: { status: 400, message: "The local username is invalid.", next: "Supply a nonempty username without whitespace or control characters." },
21883
+ PASSWORD_FILE_INVALID: { status: 400, message: "The password file is missing or unreadable.", next: "Supply a readable UTF-8 password file containing the exact password, without an added newline." },
21884
+ BOOTSTRAP_INCONSISTENT: { status: 503, message: "The store contains data without a bootstrap marker.", next: "Stop the server and restore a consistent bootstrapped store and matching master key." },
21885
+ RECOVERY_FAILED: { status: 500, message: "Administrator recovery did not complete.", next: "Use an existing local username in a bootstrapped store, check the matching master key and inspect local storage." },
21886
+ PASSWORD_INVALID: { status: 400, message: "The password must be non-empty and at most 512 UTF-8 bytes.", next: "Enter a password of at most 512 UTF-8 bytes." },
21887
+ SIGN_IN_FAILED: { status: 401, message: "The username or password is incorrect.", next: "Check your username and password." },
21888
+ SSO_STATE_INVALID: { status: 400, message: "The SSO sign-in request expired or was already used.", next: "Start a new sign-in from this browser." },
21889
+ SSO_TOKEN_INVALID: { status: 401, message: "The identity provider response could not be verified.", next: "Start a new sign-in or ask an administrator to check provider settings." },
21890
+ SSO_NOT_INVITED: { status: 403, message: "This identity is not linked to an artium account.", next: "Ask an administrator for an invitation and open its link to sign in." },
21891
+ SSO_INVITE_INVALID: { status: 403, message: "This invitation cannot be claimed by this identity.", next: "Use the expected sign-in username or ask an administrator for a new invitation link." },
21892
+ SSO_PROVIDER_ERROR: { status: 503, message: "SSO sign-in is unavailable.", next: "Ask an administrator to check the provider configuration or try again later." },
21893
+ DEVICE_CODE_INVALID: { status: 400, message: "The device code is invalid or was already used.", next: "Run artium-axi login --sso to start a new request." },
21894
+ DEVICE_CODE_EXPIRED: { status: 400, message: "The device request expired.", next: "Run artium-axi login --sso to start a new request." },
21895
+ DEVICE_DENIED: { status: 403, message: "The device request was denied.", next: "Start a new sign-in only if you requested it." },
21896
+ DEVICE_POLL_LIMITED: { status: 429, message: "The device request was polled too quickly.", next: "Wait for the requested polling interval before polling again." },
21897
+ AUTH_RATE_LIMITED: { status: 429, message: "The authentication attempt limit was reached.", next: "Wait 15 minutes before trying again." },
21898
+ ACCOUNT_LOCKED: { status: 429, message: "The account is temporarily locked.", next: "Wait 15 minutes or ask an administrator to unlock the account." },
21899
+ REAUTH_REQUIRED: { status: 401, message: "Recent identity confirmation is required.", next: "In the browser, confirm at /reauth using Microsoft for SSO or your local password. Local CLI users confirm their password through /v1/auth/reauth." },
21900
+ CSRF_INVALID: { status: 403, message: "The form token or request origin is invalid.", next: "Reload the form on this server and submit it again." },
21901
+ AUTH_BUSY: { status: 429, message: "The concurrent password hashing limit was reached.", next: "Wait for an active authentication request to finish." },
21902
+ MAINTENANCE_BUSY: { status: 503, message: "The store is held by another server or maintenance process.", next: "Stop the server and wait for maintenance to finish before retrying." },
21903
+ MAINTENANCE_UNAVAILABLE: { status: 503, message: "The store maintenance lock is unavailable.", next: "Check data-volume capacity and permissions." },
21904
+ ROTATION_FAILED: { status: 500, message: "Master key rotation did not complete.", next: "Keep both keys. Inspect the durable key_rotations receipt and restart with its latest new_key_id, or the old key if no rotation committed." },
21905
+ CLIENT_CONFIG_INVALID: { status: 400, message: "The CLI server configuration is invalid.", next: "Set ARTIUM_AXI_URL to an HTTPS URL; optionally set ARTIUM_AXI_CA_FILE." },
21906
+ SESSION_STORAGE_UNAVAILABLE: { status: 500, message: "Secure CLI session storage is unavailable.", next: "Check your configuration folder permissions and capacity, then sign in again." },
21907
+ SESSION_SERVER_MISMATCH: { status: 400, message: "The stored session belongs to a different server.", next: "Restore ARTIUM_AXI_URL or use artium-axi logout before signing in to the new server." },
21908
+ SESSION_BUSY: { status: 503, message: "Another CLI process holds the session lock.", next: "Wait for the other CLI process. If all CLI processes exited, remove the session.lock directory in your artium-axi configuration folder." },
21909
+ SESSION_CHANGED: { status: 409, message: "The signed-in user changed during this operation.", next: "Check the signed-in identity before starting a new operation." },
21910
+ PASSWORD_CHANGE_REQUIRED: { status: 409, message: "Change your temporary password before using tools.", next: "Run artium-axi passwd --password-stdin." },
21911
+ SERVER_UNAVAILABLE: { status: 503, message: "The CLI could not receive a server response.", next: "Check the server address and certificate trust; confirm the previous call outcome before retrying." },
21912
+ INVALID_RESPONSE: { status: 500, message: "The server returned an invalid response.", next: "Check the server URL and API version." },
21913
+ KEY_LEVEL_RESTRICTED: { status: 403, message: "HTTP 403: restricted key cannot download.", next: "Request vetted-account download access. Administrator write settings cannot grant upstream entitlement. No other key or route was tried." },
21914
+ PERMISSION_DENIED: { status: 403, message: "HTTP 403: download denied; key level unknown.", next: "Check upstream entitlement and request account vetting where required. Administrator write settings cannot grant upstream entitlement. No other key or route was tried." },
21915
+ ARTIFACT_SAVE_FAILED: { status: 400, message: "The archive was not verified and saved.", next: "Check the dedicated private destination directory. Start a fresh preview and confirmation; interrupted transfers cannot be retried." },
21916
+ DEV_AUTH_INVALID: { status: 503, message: "Development authentication settings are unsupported.", next: "Remove ARTIUM_AXI_DEV and ARTIUM_AXI_DEV_TOKEN_FILE and use local sign-in." },
21917
+ PROXY_HEADERS_UNTRUSTED: { status: 400, message: "Forwarding headers came from an untrusted address.", next: "Connect through the configured trusted proxy or remove forwarding headers." },
21918
+ NOT_FOUND: { status: 404, message: "The endpoint does not exist.", next: "Use a supported API endpoint and tool name." },
21919
+ AUDIT_UNAVAILABLE: { status: 503, message: "The audit event could not be stored.", next: "Ask the administrator to check audit storage capacity and availability." },
21920
+ TOKEN_INVALID: { status: 401, message: "The token is invalid or revoked.", next: "Sign in again to obtain a valid token." },
21921
+ DELEGATED_SCOPE_DENIED: { status: 403, message: "This operation is unavailable to delegated sessions.", next: "Use an authorized session for this operation." },
21922
+ TOKEN_EXPIRED: { status: 401, message: "The token has expired.", next: "Sign in again." },
21923
+ USER_DISABLED: { status: 403, message: "The user is disabled.", next: "Ask the administrator to enable the user." },
21924
+ TOOL_DISABLED: { status: 403, message: "The tool is disabled.", next: "Ask the administrator to enable the tool." },
21925
+ TOOL_NOT_GRANTED: { status: 403, message: "The user has no role granting this tool.", next: "Ask the administrator to assign a role granting the tool." },
21926
+ MASTER_KEY_INVALID: { status: 503, message: "The master key is missing or invalid.", next: "Supply a 32-byte master key file or a base64 master key." },
21927
+ CREDENTIAL_INVALID: { status: 503, message: "The stored credential is invalid.", next: "Ask an administrator to check the named field, matching master key and credential JSON, then save and test again." },
21928
+ CREDENTIAL_EXPIRED: { status: 503, message: "The GitHub credential expired or was revoked.", next: "Ask an administrator to reconnect at /admin/tools/gh-axi. Tokens are never refreshed automatically." },
21929
+ FLAG_BLOCKED: { status: 400, message: "The arguments override the managed tool boundary.", next: "Remove destination, tenant, credential or local configuration overrides." },
21930
+ CREDENTIAL_NOT_CONFIGURED: { status: 503, message: "No credential is configured for the tool.", next: "Ask an administrator to save a credential and run Test connection." },
21931
+ UPSTREAM_AUTH_FAILED: { status: 503, message: "The upstream service rejected the credential.", next: "Ask an administrator to check the provider code, identity, secret expiry and permissions, then test again." },
21932
+ UPSTREAM_NETWORK_FAILED: { status: 503, message: "The upstream service could not be reached.", next: "Ask an administrator to check DNS, routing, firewall rules and the diagnostic host and stage." },
21933
+ UPSTREAM_TLS_FAILED: { status: 503, message: "The upstream certificate could not be verified.", next: "Ask an administrator to check the host, certificate chain and trusted CA configuration." },
21934
+ UPSTREAM_RESPONSE_INVALID: { status: 503, message: "The upstream service returned a response the tool could not accept.", next: "Ask an administrator to inspect the diagnostic message and hint, check the service endpoint and API compatibility, then test again." },
21935
+ TOOL_REJECTED_INPUT: { status: 503, message: "The tool rejected its configuration or arguments.", next: "Ask an administrator to correct the field or combination named by the tool and test again." },
21936
+ TOOL_FAILED: { status: 503, message: "The tool exited unsuccessfully.", next: "Ask an administrator to inspect the diagnostic message and hint from Test connection." },
21937
+ INVALID_INPUT: { status: 400, message: "The request input is invalid.", next: "Check the request fields and content type." },
21938
+ UNSUPPORTED_INPUT: { status: 400, message: "The input file is not a matching upload.", next: "Upload the file using a reviewed input-file flag." },
21939
+ SECRET_IN_OUTPUT: { status: 500, message: "A known secret was detected in tool output.", next: "Check upstream output redaction before retrying." },
21940
+ SPAWN_FAILED: { status: 500, message: "The upstream tool could not be started.", next: "Check the configured executable and environment." },
21941
+ PROCESS_SIGNAL: { status: 500, message: "The upstream tool ended on a signal.", next: "Check the tool status before retrying." },
21942
+ TIMEOUT: { status: 504, message: "The upstream tool exceeded its timeout.", next: "Check the tool status before retrying." },
21943
+ UNKNOWN_OUTCOME: { status: 504, message: "The write may have changed state before the tool stopped.", next: "Check current state before trying again." },
21944
+ CANCELLED: { status: 500, message: "The call was cancelled.", next: "Check the tool status before retrying." },
21945
+ OUTPUT_LIMIT: { status: 500, message: "The upstream tool exceeded the output limit.", next: "Use a command that produces less output." },
21946
+ TOO_MANY_CALLS: { status: 429, message: "The concurrent call limit was reached.", next: "Wait for an active call to finish." },
21947
+ RUNNER_CLOSED: { status: 503, message: "The runner is shutting down.", next: "Wait for the server to become available." },
21948
+ TEMP_UNAVAILABLE: { status: 503, message: "The private call inputs could not be created.", next: "Check temporary storage capacity and permissions." },
21949
+ INTERNAL_ERROR: { status: 500, message: "The server could not complete the request.", next: "Contact the administrator with the request ID." }
21950
+ };
21951
+ usageErrors = ["INVALID_INPUT", "UNSUPPORTED_INPUT", "FLAG_BLOCKED", "CLIENT_CONFIG_INVALID"];
21952
+ errors = Object.fromEntries(Object.entries(definitions).map(([code, definition]) => [code, { ...definition, source: "artium-axi", exitCode: usageErrors.includes(code) ? 2 : 1 }]));
21953
+ ArtiumError = class extends Error {
21954
+ constructor(code, message = errors[code].message, next = errors[code].next, requestId) {
21955
+ super(message);
21956
+ this.code = code;
21957
+ this.requestId = requestId;
21958
+ this.source = errors[code].source;
21959
+ this.next = next;
21960
+ }
21961
+ code;
21962
+ requestId;
21963
+ recovery;
21964
+ diagnostic;
21965
+ source;
21966
+ next;
21967
+ };
21968
+ }
21969
+ });
21970
+
21855
21971
  // src/shared/kubernetes.ts
21856
- var kubernetesHostedCommands, kubernetesSessionKind, kubernetesSessionPolicy, kubernetesWorkspacePath, kubernetesFile, kubernetesSessionView, kubernetesWorkspaceManifest, kubernetesSessionStart;
21972
+ function kubernetesHostedArguments(rest, group, action) {
21973
+ const separator = rest.indexOf("--"), controls = separator === -1 ? rest : rest.slice(0, separator);
21974
+ const native = separator === -1 ? [] : rest.slice(separator + 1);
21975
+ const flags = /* @__PURE__ */ new Map(), positionals = [];
21976
+ const booleans = ["--json", "--help", "--wait", "--ready", "--confirm"];
21977
+ const values = ["--workspace", "--stdin-file", "--input-workspace", "--input-path", "--timeout", "--output-limit", "--digest", "--after", "--output"];
21978
+ for (let index = 0; index < controls.length; index++) {
21979
+ const word = controls[index];
21980
+ if (booleans.includes(word)) {
21981
+ if (flags.has(word)) throw new ArtiumError("INVALID_INPUT");
21982
+ flags.set(word, "true");
21983
+ } else if (values.includes(word)) {
21984
+ if (flags.has(word) || controls[index + 1] === void 0 || controls[index + 1].startsWith("--")) throw new ArtiumError("INVALID_INPUT");
21985
+ flags.set(word, controls[++index]);
21986
+ } else if (word.startsWith("-")) throw new ArtiumError("INVALID_INPUT");
21987
+ else positionals.push(word);
21988
+ }
21989
+ const help = action === "--help" || flags.has("--help") || action === void 0;
21990
+ const allowed = {
21991
+ "workspace create": [],
21992
+ "workspace show": [],
21993
+ "workspace delete": [],
21994
+ "workspace download": ["--output"],
21995
+ "session list": [],
21996
+ "session start": values.filter((flag) => !["--digest", "--after", "--output"].includes(flag)),
21997
+ "session show": ["--wait", "--ready"],
21998
+ "session output": ["--after", "--wait"],
21999
+ "session confirm": ["--digest"],
22000
+ "session cancel": ["--confirm"],
22001
+ "session artifact": ["--output"]
22002
+ };
22003
+ const route = `${group} ${action}`;
22004
+ if (!help && (!allowed[route] || [...flags.keys()].some((flag) => flag !== "--json" && !allowed[route].includes(flag)) || route !== "session start" && separator !== -1 || flags.has("--wait") && flags.has("--ready"))) throw new ArtiumError("INVALID_INPUT");
22005
+ return { flags, positionals, native, help, route };
22006
+ }
22007
+ var kubernetesHostedCommands, kubernetesHostedRoutes, kubernetesSessionKind, kubernetesSessionPolicy, kubernetesWorkspacePath, kubernetesFile, kubernetesSessionView, kubernetesWorkspaceManifest, kubernetesSessionStart;
21857
22008
  var init_kubernetes = __esm({
21858
22009
  "src/shared/kubernetes.ts"() {
21859
22010
  "use strict";
21860
22011
  init_zod();
22012
+ init_errors3();
21861
22013
  kubernetesHostedCommands = [
21862
22014
  "workspace create <directory>",
21863
22015
  "workspace show <id>",
@@ -21873,6 +22025,10 @@ var init_kubernetes = __esm({
21873
22025
  "tunnel <session-id> --port <remote-port> [--port <remote-port>]",
21874
22026
  "credential <result-id> --credential-fd <private-pipe-fd>"
21875
22027
  ];
22028
+ kubernetesHostedRoutes = kubernetesHostedCommands.map((usage) => {
22029
+ const command = usage.split(" ").slice(0, /^(tunnel|credential) /.test(usage) ? 1 : 2).join(" ");
22030
+ return { command, effect: ["workspace show", "workspace download", "session list", "session show", "session output", "session artifact"].includes(command) ? "read" : "write" };
22031
+ });
21876
22032
  kubernetesSessionKind = external_exports.enum(["watch", "logs", "exec", "attach", "apply", "create", "cp", "port-forward"]);
21877
22033
  kubernetesSessionPolicy = external_exports.strictObject({
21878
22034
  grants: external_exports.record(external_exports.string().min(1).max(128), external_exports.array(kubernetesSessionKind).max(8)),
@@ -25905,121 +26061,6 @@ var init_gitea_writes = __esm({
25905
26061
  }
25906
26062
  });
25907
26063
 
25908
- // src/shared/errors.ts
25909
- function errorResponse(error62, requestId) {
25910
- return { error: {
25911
- code: error62.code,
25912
- source: error62.source,
25913
- message: error62.message,
25914
- next: error62.next,
25915
- requestId: error62.requestId ?? requestId,
25916
- ...error62.recovery ? { recovery: error62.recovery } : {}
25917
- } };
25918
- }
25919
- var cliOutdatedDownloadNext, definitions, usageErrors, errors, ArtiumError;
25920
- var init_errors3 = __esm({
25921
- "src/shared/errors.ts"() {
25922
- "use strict";
25923
- cliOutdatedDownloadNext = "Download the current CLI from /cli/artium-axi.mjs on this server, verify it with the SHA-256 checksum at /cli/artium-axi.mjs.sha256, and install it as artium-axi.";
25924
- definitions = {
25925
- CONNECTION_BUSY: { status: 409, message: "An SSH command is already active on this connection.", next: "Inspect its execution before submitting another command, or explicitly open another connection." },
25926
- CONNECTION_CLOSED: { status: 409, message: "The selected SSH connection is closed or expired.", next: "Inspect remote state before explicitly opening another connection; no reconnection or command replay occurred." },
25927
- STORE_SCHEMA_INVALID: { status: 503, message: "The store schema is unsupported by this image.", next: "Use the matching image, or restore the pre-upgrade backup into a new volume with its matching image and key." },
25928
- BACKUP_FAILED: { status: 500, message: "Database backup did not complete.", next: "Check the source store and a writable backup directory; choose a new output file." },
25929
- RESTORE_FAILED: { status: 500, message: "Database restore did not complete.", next: "Stop the destination server and use an empty new data volume, an intact backup and its matching master key." },
25930
- CLI_OUTDATED: { status: 426, message: "The CLI version is too old for this server.", next: cliOutdatedDownloadNext },
25931
- CERTIFICATE_INVALID: { status: 503, message: "The server certificate could not be verified.", next: "Check certificate trust or set ARTIUM_AXI_CA_FILE to the trusted CA file." },
25932
- ADMIN_REQUIRED: { status: 403, message: "Administrator capability is required.", next: "Ask an administrator to perform this operation." },
25933
- REVISION_CONFLICT: { status: 409, message: "The record changed since it was read.", next: "Read the current record revision and retry your edit." },
25934
- LAST_ADMINISTRATOR: { status: 409, message: "The last enabled administrator must remain enabled.", next: "Enable another administrator before changing this account." },
25935
- USERNAME_INVALID: { status: 400, message: "The local username is invalid.", next: "Supply a nonempty username without whitespace or control characters." },
25936
- PASSWORD_FILE_INVALID: { status: 400, message: "The password file is missing or unreadable.", next: "Supply a readable UTF-8 password file containing the exact password, without an added newline." },
25937
- BOOTSTRAP_INCONSISTENT: { status: 503, message: "The store contains data without a bootstrap marker.", next: "Stop the server and restore a consistent bootstrapped store and matching master key." },
25938
- RECOVERY_FAILED: { status: 500, message: "Administrator recovery did not complete.", next: "Use an existing local username in a bootstrapped store, check the matching master key and inspect local storage." },
25939
- PASSWORD_INVALID: { status: 400, message: "The password must be non-empty and at most 512 UTF-8 bytes.", next: "Enter a password of at most 512 UTF-8 bytes." },
25940
- SIGN_IN_FAILED: { status: 401, message: "The username or password is incorrect.", next: "Check your username and password." },
25941
- SSO_STATE_INVALID: { status: 400, message: "The SSO sign-in request expired or was already used.", next: "Start a new sign-in from this browser." },
25942
- SSO_TOKEN_INVALID: { status: 401, message: "The identity provider response could not be verified.", next: "Start a new sign-in or ask an administrator to check provider settings." },
25943
- SSO_NOT_INVITED: { status: 403, message: "This identity is not linked to an artium account.", next: "Ask an administrator for an invitation and open its link to sign in." },
25944
- SSO_INVITE_INVALID: { status: 403, message: "This invitation cannot be claimed by this identity.", next: "Use the expected sign-in username or ask an administrator for a new invitation link." },
25945
- SSO_PROVIDER_ERROR: { status: 503, message: "SSO sign-in is unavailable.", next: "Ask an administrator to check the provider configuration or try again later." },
25946
- DEVICE_CODE_INVALID: { status: 400, message: "The device code is invalid or was already used.", next: "Run artium-axi login --sso to start a new request." },
25947
- DEVICE_CODE_EXPIRED: { status: 400, message: "The device request expired.", next: "Run artium-axi login --sso to start a new request." },
25948
- DEVICE_DENIED: { status: 403, message: "The device request was denied.", next: "Start a new sign-in only if you requested it." },
25949
- DEVICE_POLL_LIMITED: { status: 429, message: "The device request was polled too quickly.", next: "Wait for the requested polling interval before polling again." },
25950
- AUTH_RATE_LIMITED: { status: 429, message: "The authentication attempt limit was reached.", next: "Wait 15 minutes before trying again." },
25951
- ACCOUNT_LOCKED: { status: 429, message: "The account is temporarily locked.", next: "Wait 15 minutes or ask an administrator to unlock the account." },
25952
- REAUTH_REQUIRED: { status: 401, message: "Recent identity confirmation is required.", next: "In the browser, confirm at /reauth using Microsoft for SSO or your local password. Local CLI users confirm their password through /v1/auth/reauth." },
25953
- CSRF_INVALID: { status: 403, message: "The form token or request origin is invalid.", next: "Reload the form on this server and submit it again." },
25954
- AUTH_BUSY: { status: 429, message: "The concurrent password hashing limit was reached.", next: "Wait for an active authentication request to finish." },
25955
- MAINTENANCE_BUSY: { status: 503, message: "The store is held by another server or maintenance process.", next: "Stop the server and wait for maintenance to finish before retrying." },
25956
- MAINTENANCE_UNAVAILABLE: { status: 503, message: "The store maintenance lock is unavailable.", next: "Check data-volume capacity and permissions." },
25957
- ROTATION_FAILED: { status: 500, message: "Master key rotation did not complete.", next: "Keep both keys. Inspect the durable key_rotations receipt and restart with its latest new_key_id, or the old key if no rotation committed." },
25958
- CLIENT_CONFIG_INVALID: { status: 400, message: "The CLI server configuration is invalid.", next: "Set ARTIUM_AXI_URL to an HTTPS URL; optionally set ARTIUM_AXI_CA_FILE." },
25959
- SESSION_STORAGE_UNAVAILABLE: { status: 500, message: "Secure CLI session storage is unavailable.", next: "Check your configuration folder permissions and capacity, then sign in again." },
25960
- SESSION_SERVER_MISMATCH: { status: 400, message: "The stored session belongs to a different server.", next: "Restore ARTIUM_AXI_URL or use artium-axi logout before signing in to the new server." },
25961
- SESSION_BUSY: { status: 503, message: "Another CLI process holds the session lock.", next: "Wait for the other CLI process. If all CLI processes exited, remove the session.lock directory in your artium-axi configuration folder." },
25962
- SESSION_CHANGED: { status: 409, message: "The signed-in user changed during this operation.", next: "Check the signed-in identity before starting a new operation." },
25963
- PASSWORD_CHANGE_REQUIRED: { status: 409, message: "Change your temporary password before using tools.", next: "Run artium-axi passwd --password-stdin." },
25964
- SERVER_UNAVAILABLE: { status: 503, message: "The CLI could not receive a server response.", next: "Check the server address and certificate trust; confirm the previous call outcome before retrying." },
25965
- INVALID_RESPONSE: { status: 500, message: "The server returned an invalid response.", next: "Check the server URL and API version." },
25966
- KEY_LEVEL_RESTRICTED: { status: 403, message: "HTTP 403: restricted key cannot download.", next: "Request vetted-account download access. Administrator write settings cannot grant upstream entitlement. No other key or route was tried." },
25967
- PERMISSION_DENIED: { status: 403, message: "HTTP 403: download denied; key level unknown.", next: "Check upstream entitlement and request account vetting where required. Administrator write settings cannot grant upstream entitlement. No other key or route was tried." },
25968
- ARTIFACT_SAVE_FAILED: { status: 400, message: "The archive was not verified and saved.", next: "Check the dedicated private destination directory. Start a fresh preview and confirmation; interrupted transfers cannot be retried." },
25969
- DEV_AUTH_INVALID: { status: 503, message: "Development authentication settings are unsupported.", next: "Remove ARTIUM_AXI_DEV and ARTIUM_AXI_DEV_TOKEN_FILE and use local sign-in." },
25970
- PROXY_HEADERS_UNTRUSTED: { status: 400, message: "Forwarding headers came from an untrusted address.", next: "Connect through the configured trusted proxy or remove forwarding headers." },
25971
- NOT_FOUND: { status: 404, message: "The endpoint does not exist.", next: "Use a supported API endpoint and tool name." },
25972
- AUDIT_UNAVAILABLE: { status: 503, message: "The audit event could not be stored.", next: "Ask the administrator to check audit storage capacity and availability." },
25973
- TOKEN_INVALID: { status: 401, message: "The token is invalid or revoked.", next: "Sign in again to obtain a valid token." },
25974
- TOKEN_EXPIRED: { status: 401, message: "The token has expired.", next: "Sign in again." },
25975
- USER_DISABLED: { status: 403, message: "The user is disabled.", next: "Ask the administrator to enable the user." },
25976
- TOOL_DISABLED: { status: 403, message: "The tool is disabled.", next: "Ask the administrator to enable the tool." },
25977
- TOOL_NOT_GRANTED: { status: 403, message: "The user has no role granting this tool.", next: "Ask the administrator to assign a role granting the tool." },
25978
- MASTER_KEY_INVALID: { status: 503, message: "The master key is missing or invalid.", next: "Supply a 32-byte master key file or a base64 master key." },
25979
- CREDENTIAL_INVALID: { status: 503, message: "The stored credential is invalid.", next: "Ask an administrator to check the named field, matching master key and credential JSON, then save and test again." },
25980
- CREDENTIAL_EXPIRED: { status: 503, message: "The GitHub credential expired or was revoked.", next: "Ask an administrator to reconnect at /admin/tools/gh-axi. Tokens are never refreshed automatically." },
25981
- FLAG_BLOCKED: { status: 400, message: "The arguments override the managed tool boundary.", next: "Remove destination, tenant, credential or local configuration overrides." },
25982
- CREDENTIAL_NOT_CONFIGURED: { status: 503, message: "No credential is configured for the tool.", next: "Ask an administrator to save a credential and run Test connection." },
25983
- UPSTREAM_AUTH_FAILED: { status: 503, message: "The upstream service rejected the credential.", next: "Ask an administrator to check the provider code, identity, secret expiry and permissions, then test again." },
25984
- UPSTREAM_NETWORK_FAILED: { status: 503, message: "The upstream service could not be reached.", next: "Ask an administrator to check DNS, routing, firewall rules and the diagnostic host and stage." },
25985
- UPSTREAM_TLS_FAILED: { status: 503, message: "The upstream certificate could not be verified.", next: "Ask an administrator to check the host, certificate chain and trusted CA configuration." },
25986
- UPSTREAM_RESPONSE_INVALID: { status: 503, message: "The upstream service returned a response the tool could not accept.", next: "Ask an administrator to inspect the diagnostic message and hint, check the service endpoint and API compatibility, then test again." },
25987
- TOOL_REJECTED_INPUT: { status: 503, message: "The tool rejected its configuration or arguments.", next: "Ask an administrator to correct the field or combination named by the tool and test again." },
25988
- TOOL_FAILED: { status: 503, message: "The tool exited unsuccessfully.", next: "Ask an administrator to inspect the diagnostic message and hint from Test connection." },
25989
- INVALID_INPUT: { status: 400, message: "The request input is invalid.", next: "Check the request fields and content type." },
25990
- UNSUPPORTED_INPUT: { status: 400, message: "The input file is not a matching upload.", next: "Upload the file using a reviewed input-file flag." },
25991
- SECRET_IN_OUTPUT: { status: 500, message: "A known secret was detected in tool output.", next: "Check upstream output redaction before retrying." },
25992
- SPAWN_FAILED: { status: 500, message: "The upstream tool could not be started.", next: "Check the configured executable and environment." },
25993
- PROCESS_SIGNAL: { status: 500, message: "The upstream tool ended on a signal.", next: "Check the tool status before retrying." },
25994
- TIMEOUT: { status: 504, message: "The upstream tool exceeded its timeout.", next: "Check the tool status before retrying." },
25995
- UNKNOWN_OUTCOME: { status: 504, message: "The write may have changed state before the tool stopped.", next: "Check current state before trying again." },
25996
- CANCELLED: { status: 500, message: "The call was cancelled.", next: "Check the tool status before retrying." },
25997
- OUTPUT_LIMIT: { status: 500, message: "The upstream tool exceeded the output limit.", next: "Use a command that produces less output." },
25998
- TOO_MANY_CALLS: { status: 429, message: "The concurrent call limit was reached.", next: "Wait for an active call to finish." },
25999
- RUNNER_CLOSED: { status: 503, message: "The runner is shutting down.", next: "Wait for the server to become available." },
26000
- TEMP_UNAVAILABLE: { status: 503, message: "The private call inputs could not be created.", next: "Check temporary storage capacity and permissions." },
26001
- INTERNAL_ERROR: { status: 500, message: "The server could not complete the request.", next: "Contact the administrator with the request ID." }
26002
- };
26003
- usageErrors = ["INVALID_INPUT", "UNSUPPORTED_INPUT", "FLAG_BLOCKED", "CLIENT_CONFIG_INVALID"];
26004
- errors = Object.fromEntries(Object.entries(definitions).map(([code, definition]) => [code, { ...definition, source: "artium-axi", exitCode: usageErrors.includes(code) ? 2 : 1 }]));
26005
- ArtiumError = class extends Error {
26006
- constructor(code, message = errors[code].message, next = errors[code].next, requestId) {
26007
- super(message);
26008
- this.code = code;
26009
- this.requestId = requestId;
26010
- this.source = errors[code].source;
26011
- this.next = next;
26012
- }
26013
- code;
26014
- requestId;
26015
- recovery;
26016
- diagnostic;
26017
- source;
26018
- next;
26019
- };
26020
- }
26021
- });
26022
-
26023
26064
  // src/shared/mutation-outcome.ts
26024
26065
  var mutationReceiptSchema, completedMutationSchema;
26025
26066
  var init_mutation_outcome = __esm({
@@ -45955,7 +45996,7 @@ function transferRoutesFor(tool) {
45955
45996
  function decodedFileBytes(value) {
45956
45997
  return value.length / 4 * 3 - (value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0);
45957
45998
  }
45958
- var inputLimits, transferLimits, transferWarning, sha256Schema, sampleSha256Schema, reportIdSchema, transferOwnerIdSchema, mailSelectorSchema, transferSelectionSchema, transferPrepareSchema, transferIdSchema, transferScopeSchema, transferPreviewSchema, transferExecuteSchema, transferRetrieveSchema, transferOutcomeSchema, transferSaveOutcomeSchema, transferArchiveSchema, transferReceiptSchema, transferEvidenceSchema, transferStatusSchema, transferRoutes, transferAuditSchema, byteLength, passwordSchema, passwordChangeSchema, loginSchema, refreshSchema, reauthSchema, reauthResponseSchema, loginResponseSchema, deviceUserCodeSchema, devicePollSchema, deviceStartResponseSchema, devicePollResponseSchema, ssoReauthSchema, ssoReauthResponseSchema, meResponseSchema, accountId, toolSchema, skillsResponseSchema, adminUserSchema, adminPageQuerySchema, adminUsersQuerySchema, adminUsersResponseSchema, adminUserDetailSchema, adminUserCreateSchema, adminUserPatchSchema, adminUserUnlockSchema, adminUserResetSchema, adminUserParamsSchema, userSessionsSchema, sessionParamsSchema, emptyInputSchema, revokedSchema, adminUserRoutes, text, auditCursorSchema, auditFiltersSchema, orderedAuditRange, adminAuditQuerySchema, adminAuditExportRoute, adminAuditRecordSchema, adminAuditRoute, falconRtrSettingsSchema, ghWriteOperations, falconWriteOperations, unifiWriteOperations, proxmoxWriteOperations, technitiumWriteOperations, nativeSettingsSchemas, diagnosticSchema, healthSchema, toolWriteStateSchema, writeAccessInputSchema, adminToolSchema, adminCredentialSchema, adminToolParamsSchema, certificateDetailsSchema, certificateInspectionSchema, trustedCredentialCertificateSchema, adminCertificateRoutes, githubConnectionInput, githubDeviceRoutes, adminToolRoutes, oidcIssuerSchema, providerSettings, entraSettings, oidcSettings, providerSettingsSchema, providerFields, adminProviderSchema, adminProviderCredentialSchema, adminProviderRoutes, roleRuleSettingsSchema, adminRoleRuleSchema, adminRoleRuleRoutes, invitationLifetimeSchema, adminInvitationSchema, invitationLinkSchema, adminInvitationRoutes, adminRoleSchema, adminRolesResponseSchema, adminRoleRoutes, toolsResponseSchema, inputFileSchema, runInputSchema, runRequestSchema, counts, runSuccessSchema, errorResponseSchema, runResponseSchema;
45999
+ var inputLimits, transferLimits, transferWarning, sha256Schema, sampleSha256Schema, reportIdSchema, transferOwnerIdSchema, mailSelectorSchema, transferSelectionSchema, transferPrepareSchema, transferIdSchema, transferScopeSchema, transferPreviewSchema, transferExecuteSchema, transferRetrieveSchema, transferOutcomeSchema, transferSaveOutcomeSchema, transferArchiveSchema, transferReceiptSchema, transferEvidenceSchema, transferStatusSchema, transferRoutes, transferAuditSchema, byteLength, passwordSchema, passwordChangeSchema, loginSchema, refreshSchema, reauthSchema, reauthResponseSchema, loginResponseSchema, deviceUserCodeSchema, devicePollSchema, deviceStartResponseSchema, devicePollResponseSchema, ssoReauthSchema, ssoReauthResponseSchema, accountId, toolSchema, delegationScopeSchema, meResponseSchema, createDelegationSchema, delegatedExchangeSchema, createdDelegationSchema, skillsResponseSchema, adminUserSchema, adminPageQuerySchema, adminUsersQuerySchema, adminUsersResponseSchema, adminUserDetailSchema, adminUserCreateSchema, adminUserPatchSchema, adminUserUnlockSchema, adminUserResetSchema, adminUserParamsSchema, userSessionsSchema, sessionParamsSchema, emptyInputSchema, revokedSchema, adminUserRoutes, text, auditCursorSchema, auditFiltersSchema, orderedAuditRange, adminAuditQuerySchema, adminAuditExportRoute, adminAuditRecordSchema, adminAuditRoute, falconRtrSettingsSchema, ghWriteOperations, falconWriteOperations, unifiWriteOperations, proxmoxWriteOperations, technitiumWriteOperations, nativeSettingsSchemas, diagnosticSchema, healthSchema, toolWriteStateSchema, writeAccessInputSchema, adminToolSchema, adminCredentialSchema, adminToolParamsSchema, certificateDetailsSchema, certificateInspectionSchema, trustedCredentialCertificateSchema, adminCertificateRoutes, githubConnectionInput, githubDeviceRoutes, adminToolRoutes, oidcIssuerSchema, providerSettings, entraSettings, oidcSettings, providerSettingsSchema, providerFields, adminProviderSchema, adminProviderCredentialSchema, adminProviderRoutes, roleRuleSettingsSchema, adminRoleRuleSchema, adminRoleRuleRoutes, invitationLifetimeSchema, adminInvitationSchema, invitationLinkSchema, adminInvitationRoutes, adminRoleSchema, adminRolesResponseSchema, adminRoleRoutes, toolsResponseSchema, inputFileSchema, runInputSchema, runRequestSchema, counts, runSuccessSchema, errorResponseSchema, runResponseSchema;
45959
46000
  var init_api2 = __esm({
45960
46001
  "src/shared/api.ts"() {
45961
46002
  "use strict";
@@ -46135,16 +46176,37 @@ var init_api2 = __esm({
46135
46176
  external_exports.strictObject({ status: external_exports.literal("pending") }),
46136
46177
  reauthResponseSchema
46137
46178
  ]);
46138
- meResponseSchema = external_exports.strictObject({
46139
- username: external_exports.string(),
46140
- displayName: external_exports.string(),
46141
- administrator: external_exports.boolean(),
46142
- roles: external_exports.array(external_exports.string()),
46143
- accessExpiresAt: external_exports.number().int(),
46144
- sessionExpiresAt: external_exports.number().int()
46145
- });
46146
46179
  accountId = external_exports.string().min(1);
46147
46180
  toolSchema = external_exports.enum(["falcon-axi", "vectra-axi", "az-axi", "mg-axi", "ldap-axi", "ado-axi", "awx-axi", "tenable-axi", "hybrid-axi", "checkpoint-axi", "beyondtrust-axi", "gh-axi", "unifi-axi", "proxmox-axi", "technitium-axi", "gitea-axi", "kubernetes-axi", "ssh-axi"]);
46181
+ delegationScopeSchema = external_exports.strictObject({
46182
+ tools: external_exports.array(external_exports.strictObject({ tool: toolSchema, commands: external_exports.array(external_exports.string().min(1).max(200)).min(1).max(100).optional() })).min(1).max(36)
46183
+ });
46184
+ meResponseSchema = external_exports.union([
46185
+ external_exports.strictObject({
46186
+ username: external_exports.string(),
46187
+ displayName: external_exports.string(),
46188
+ administrator: external_exports.boolean(),
46189
+ roles: external_exports.array(external_exports.string()),
46190
+ accessExpiresAt: external_exports.number().int(),
46191
+ sessionExpiresAt: external_exports.number().int()
46192
+ }),
46193
+ external_exports.strictObject({
46194
+ username: external_exports.string(),
46195
+ displayName: external_exports.string(),
46196
+ delegation: external_exports.strictObject({ label: external_exports.string(), expiresAt: external_exports.number().int(), scope: delegationScopeSchema.extend({ tools: external_exports.array(delegationScopeSchema.shape.tools.element.extend({ commands: external_exports.array(external_exports.string()) })).max(36) }) }),
46197
+ accessExpiresAt: external_exports.number().int(),
46198
+ sessionExpiresAt: external_exports.number().int()
46199
+ })
46200
+ ]);
46201
+ createDelegationSchema = external_exports.strictObject({
46202
+ label: external_exports.string().trim().min(1).max(100),
46203
+ scope: delegationScopeSchema,
46204
+ readOnly: external_exports.boolean(),
46205
+ reusable: external_exports.boolean(),
46206
+ expiresAt: external_exports.number().int().positive()
46207
+ });
46208
+ delegatedExchangeSchema = external_exports.strictObject({ token: external_exports.string().regex(/^artd_[A-Za-z0-9_-]{43}$/) });
46209
+ createdDelegationSchema = external_exports.strictObject({ id: external_exports.uuid(), token: external_exports.string().regex(/^artd_[A-Za-z0-9_-]{43}$/), expiresAt: external_exports.number().int() });
46148
46210
  skillsResponseSchema = external_exports.strictObject({ skills: external_exports.array(external_exports.strictObject({
46149
46211
  name: toolSchema,
46150
46212
  content: external_exports.string().min(1)
@@ -46310,6 +46372,7 @@ var init_api2 = __esm({
46310
46372
  return [ceiling, time3, id].every(Number.isSafeInteger) && ceiling > 0 && id > 0 && id <= ceiling && time3 <= 864e13;
46311
46373
  });
46312
46374
  auditFiltersSchema = external_exports.strictObject({
46375
+ delegationId: external_exports.string().min(1).max(100).optional(),
46313
46376
  requestId: external_exports.string().min(1).max(100).optional(),
46314
46377
  failed: external_exports.enum(["0", "1"]).optional(),
46315
46378
  user: external_exports.string().min(1).max(256).optional(),
@@ -46338,6 +46401,7 @@ var init_api2 = __esm({
46338
46401
  occurred_at: external_exports.number().int(),
46339
46402
  event: external_exports.string(),
46340
46403
  user_id: external_exports.string().nullable(),
46404
+ delegation_id: external_exports.string().nullable(),
46341
46405
  tool: toolSchema.nullable(),
46342
46406
  arguments: external_exports.string().nullable(),
46343
46407
  request_id: external_exports.string(),
@@ -46993,7 +47057,8 @@ var init_api2 = __esm({
46993
47057
  version: external_exports.string(),
46994
47058
  readOnly: external_exports.boolean().default(true),
46995
47059
  status: external_exports.enum(["unconfigured", "unknown", "checking", "ok", "error", "disabled"]),
46996
- errorCode: healthSchema.shape.errorCode.optional()
47060
+ errorCode: healthSchema.shape.errorCode.optional(),
47061
+ commands: external_exports.array(external_exports.string()).optional()
46997
47062
  }))
46998
47063
  });
46999
47064
  inputFileSchema = external_exports.strictObject({
@@ -47072,6 +47137,23 @@ function restrictWindowsAcl(path, directory) {
47072
47137
  env: { ...process.env, ARTIUM_AXI_SESSION_ACL_PATH: path, ARTIUM_AXI_SESSION_ACL_KIND: directory ? "directory" : "file" }
47073
47138
  });
47074
47139
  }
47140
+ function readStoredSession(file2 = sessionPath(), platform = process.platform, acl = restrictWindowsAcl) {
47141
+ try {
47142
+ if (!existsSync(file2)) return void 0;
47143
+ if (platform === "win32") acl(file2, false);
47144
+ const stat = statSync(file2);
47145
+ if (!stat.isFile() || platform !== "win32" && ((stat.mode & 511) !== 384 || (statSync(dirname(file2)).mode & 511) !== 448)) throw new Error();
47146
+ const { serverUrl, loginGeneration, delegated, ...tokens } = JSON.parse(readFileSync(file2, "utf8"));
47147
+ return { serverUrl: external_exports.string().parse(serverUrl), session: {
47148
+ ...loginResponseSchema.parse(tokens),
47149
+ loginGeneration: external_exports.uuid().parse(loginGeneration),
47150
+ ...delegated === void 0 ? {} : { delegated: external_exports.boolean().parse(delegated) }
47151
+ } };
47152
+ } catch (error62) {
47153
+ if (error62 instanceof ArtiumError) throw error62;
47154
+ throw new ArtiumError("SESSION_STORAGE_UNAVAILABLE");
47155
+ }
47156
+ }
47075
47157
  var SessionStore;
47076
47158
  var init_session = __esm({
47077
47159
  "src/cli/session.ts"() {
@@ -47102,24 +47184,20 @@ var init_session = __esm({
47102
47184
  }
47103
47185
  }
47104
47186
  read() {
47105
- try {
47106
- if (!existsSync(this.file)) return void 0;
47107
- if (this.platform === "win32") this.acl(this.file, false);
47108
- const stat = statSync(this.file);
47109
- if (!stat.isFile() || this.platform !== "win32" && ((stat.mode & 511) !== 384 || (statSync(this.directory).mode & 511) !== 448)) throw new Error();
47110
- const { serverUrl, loginGeneration, ...tokens } = JSON.parse(readFileSync(this.file, "utf8"));
47111
- if (serverUrl !== this.serverUrl) throw new ArtiumError("SESSION_SERVER_MISMATCH");
47112
- return { ...loginResponseSchema.parse(tokens), loginGeneration: external_exports.uuid().parse(loginGeneration) };
47113
- } catch (error62) {
47114
- if (error62 instanceof ArtiumError) throw error62;
47115
- throw new ArtiumError("SESSION_STORAGE_UNAVAILABLE");
47116
- }
47187
+ const stored = readStoredSession(this.file, this.platform, this.acl);
47188
+ if (!stored) return void 0;
47189
+ if (stored.serverUrl !== this.serverUrl) throw new ArtiumError("SESSION_SERVER_MISMATCH");
47190
+ return stored.session;
47117
47191
  }
47118
- write(session, loginGeneration = randomUUID()) {
47192
+ write(session, loginGeneration = randomUUID(), delegated) {
47119
47193
  this.secureDirectory();
47120
47194
  const temporary = join(this.directory, `${randomUUID()}.tmp`);
47121
47195
  try {
47122
- const stored = { ...loginResponseSchema.parse(session), loginGeneration: external_exports.uuid().parse(loginGeneration) };
47196
+ const stored = {
47197
+ ...loginResponseSchema.parse(session),
47198
+ loginGeneration: external_exports.uuid().parse(loginGeneration),
47199
+ ...delegated === void 0 ? {} : { delegated }
47200
+ };
47123
47201
  const file2 = openSync(temporary, "wx", 384);
47124
47202
  try {
47125
47203
  if (this.platform === "win32") this.acl(temporary, false);
@@ -47348,13 +47426,7 @@ var init_http = __esm({
47348
47426
  (token) => this.request(path, method, input2, token),
47349
47427
  (refreshToken) => this.request("/v1/auth/refresh", "POST", { refreshToken })
47350
47428
  );
47351
- let session = previous ? this.reload(previous) : this.sessions.read();
47352
- if (!session) throw new ArtiumError("TOKEN_INVALID", void 0, "Run artium-axi login --username <username> --password-stdin.");
47353
- if (session.status === "password-change-required") throw new ArtiumError("PASSWORD_CHANGE_REQUIRED");
47354
- if (session.accessExpiresAt <= Date.now() + ACCESS_EXPIRY_SKEW_MS) {
47355
- const expiring = session;
47356
- session = await this.sessions.locked(() => this.refresh(expiring), this.cancellation.signal);
47357
- }
47429
+ const session = await this.freshSession(previous);
47358
47430
  let result;
47359
47431
  try {
47360
47432
  result = await this.request(path, method, input2, session.accessToken);
@@ -47366,6 +47438,16 @@ var init_http = __esm({
47366
47438
  if (previous) this.reload(previous);
47367
47439
  return result;
47368
47440
  }
47441
+ async freshSession(previous) {
47442
+ let session = previous ? this.reload(previous) : this.sessions.read();
47443
+ if (!session) throw new ArtiumError("TOKEN_INVALID", void 0, "Run artium-axi login --username <username> --password-stdin.");
47444
+ if (session.status === "password-change-required") throw new ArtiumError("PASSWORD_CHANGE_REQUIRED");
47445
+ if (session.accessExpiresAt <= Date.now() + ACCESS_EXPIRY_SKEW_MS) {
47446
+ const expiring = session;
47447
+ session = await this.sessions.locked(() => this.refresh(expiring), this.cancellation.signal);
47448
+ }
47449
+ return session;
47450
+ }
47369
47451
  // Transfers never refresh/replay a request, including an ambiguous execute or
47370
47452
  // a retrieval whose response was interrupted before headers arrived.
47371
47453
  async transferSession(work) {
@@ -47440,7 +47522,7 @@ var init_http = __esm({
47440
47522
  if (current.accessToken !== previous.accessToken) return current;
47441
47523
  const result = loginResponseSchema.safeParse(await this.request("/v1/auth/refresh", "POST", { refreshToken: current.refreshToken }));
47442
47524
  if (!result.success || result.data.status !== "authenticated") throw new ArtiumError("INVALID_RESPONSE");
47443
- return this.sessions.write(result.data, previous.loginGeneration);
47525
+ return this.sessions.write(result.data, previous.loginGeneration, previous.delegated);
47444
47526
  }
47445
47527
  reload(previous) {
47446
47528
  const current = this.sessions.read();
@@ -95126,10 +95208,12 @@ var init_rewrite = __esm({
95126
95208
 
95127
95209
  // src/cli/views.ts
95128
95210
  function identityView(user, server) {
95211
+ const scope = "roles" in user ? `roles[${user.roles.length}]: ${user.roles.map((role) => JSON.stringify(role)).join(",")}
95212
+ ` : `delegation: ${JSON.stringify(user.delegation.label)}
95213
+ `;
95129
95214
  return `user: ${JSON.stringify(user.username)}
95130
95215
  server: ${JSON.stringify(server)}
95131
- roles[${user.roles.length}]: ${user.roles.map((role) => JSON.stringify(role)).join(",")}
95132
- sessionExpiresAt: ${sessionExpiryView(user.sessionExpiresAt)}
95216
+ ${scope}sessionExpiresAt: ${sessionExpiryView(user.sessionExpiresAt)}
95133
95217
  accessExpiresAt: ${sessionExpiryView(user.accessExpiresAt)}
95134
95218
  note: Access tokens refresh automatically when a refresh token is available.
95135
95219
  `;
@@ -95141,16 +95225,23 @@ function sessionExpiryView(expiresAt, now = Date.now()) {
95141
95225
  }
95142
95226
  function toolsView(tools) {
95143
95227
  if (!tools.length) return "tools: 0 available\nreason: No enabled runtime tool is available through your assigned roles.\ncontact: Ask an administrator to check your role assignments and enabled tools.\nnext[1]:\n - artium-axi whoami\n";
95228
+ const example = tools[0].commands ? "" : ` - artium-axi ${tools[0].name} ${toolManifests[tools[0].name].discovery.example.join(" ")}
95229
+ `;
95144
95230
  return `tools[${tools.length}]{name,status,version,readOnly}:
95145
95231
  ${tools.map((tool) => ` ${tool.name},${tool.status},${JSON.stringify(tool.version)},${tool.readOnly ?? true}`).join("\n")}
95146
- next[2]:
95232
+ next[${example ? 2 : 1}]:
95147
95233
  - artium-axi tools show ${tools[0].name}
95148
- - artium-axi ${tools[0].name} ${toolManifests[tools[0].name].discovery.example.join(" ")}
95149
- `;
95234
+ ${example}`;
95150
95235
  }
95151
95236
  function toolView(tool) {
95152
95237
  const manifest = toolManifests[tool.name];
95153
95238
  if (tool.version !== manifest.version) throw new ArtiumError("INVALID_RESPONSE", "The server tool version differs from the bundled manifest.", "Download the current CLI from /cli/artium-axi.mjs.");
95239
+ if (tool.commands) return `tool: ${tool.name}
95240
+ version: ${JSON.stringify(tool.version)}
95241
+ status: ${tool.status}
95242
+ readOnly: ${tool.readOnly ?? true}
95243
+ commands[${tool.commands.length}]: ${tool.commands.map((command) => JSON.stringify(command)).join(",")}
95244
+ `;
95154
95245
  const commands3 = manifest.discovery.commands;
95155
95246
  const help = rewriteDiscoveryHelp(manifest.discovery.help, tool.name);
95156
95247
  return `tool: ${tool.name}
@@ -95299,6 +95390,7 @@ function validateArguments(args2, prefixHelp) {
95299
95390
  throw new ArtiumError("INVALID_INPUT", message, choices2);
95300
95391
  }
95301
95392
  if (!command) return;
95393
+ if (command === "token") return;
95302
95394
  if (["--version", "-v", "-V"].includes(command) && args2.length === 1) return;
95303
95395
  if (!Object.hasOwn(commands, command) || command === "home" || command === "managed-session" || command === "tools show") {
95304
95396
  fail(command, "artium-axi", `Valid commands: ${rootCommands}. Valid flags: ${rootFlags}.`);
@@ -95349,6 +95441,7 @@ function helpCommand(args2, prefixHelp = false) {
95349
95441
  }
95350
95442
  if (toolSchema.safeParse(args2[0]).success) return prefixHelp && args2.length === 2 ? args2[0] : void 0;
95351
95443
  if (args2[0] === "login" || args2[0] === "passwd") {
95444
+ if (args2[0] === "login" && args2.length === 3 && args2.includes("--token-stdin") && args2.includes("--help")) return "login";
95352
95445
  if (args2[0] === "login" && args2.length === 3 && args2.includes("--sso") && args2.includes("--help")) return "login";
95353
95446
  let requested = false;
95354
95447
  let username = false;
@@ -95389,7 +95482,7 @@ var init_help = __esm({
95389
95482
  flags: ["Repository commands require -R OWNER/NAME. Writes require an administrator-enabled exact operation: preview, then repeat with its --confirm value. api is GET only; deletes, secret set, merge --admin, local git, files and downloads are unavailable. Only gist create/edit with --filename accepts piped stdin."],
95390
95483
  example: "artium-axi gh-axi repo list --limit 1"
95391
95484
  },
95392
- home: { usage: "artium-axi [tools [show <tool>]|whoami|login|passwd|logout|doctor|setup|update|download|<tool> <args>]", purpose: "Show your identity, roles and available tools.", flags: ["--version, -v, -V (default false; print the client package version and exit)"], example: "artium-axi" },
95485
+ home: { usage: "artium-axi [tools [show <tool>]|whoami|login|token|passwd|logout|doctor|setup|update|download|<tool> <args>]", purpose: "Show your identity, roles and available tools.", flags: ["--version, -v, -V (default false; print the client package version and exit)"], example: "artium-axi" },
95393
95486
  setup: {
95394
95487
  usage: "artium-axi setup --host <claude|codex|opencode|pi> [--hook] [--force]",
95395
95488
  purpose: "Install skills for your signed-in account\u2019s granted tools and optional ambient context for Claude Code, Codex or OpenCode.",
@@ -95401,11 +95494,17 @@ var init_help = __esm({
95401
95494
  "tools show": { usage: "artium-axi tools show <tool>", purpose: "Show one available tool and its vetted upstream help.", flags: [], example: "artium-axi tools show falcon-axi" },
95402
95495
  whoami: { usage: "artium-axi whoami", purpose: "Show your identity, roles, session expiry and server.", flags: [], example: "artium-axi whoami" },
95403
95496
  login: {
95404
- usage: "artium-axi login --sso | --username <username> [--password-stdin]",
95405
- purpose: "Sign in through browser SSO (8-hour session) or with a local account.",
95406
- flags: ["--sso (default false; open the displayed URL in any browser and approve your terminal code; no password flags)", "--username <username> (required for local sign-in)", "--password-stdin (default false; local only; otherwise ARTIUM_AXI_PASSWORD or a terminal prompt)"],
95497
+ usage: "artium-axi login --sso | --username <username> [--password-stdin] | --token-stdin",
95498
+ purpose: "Sign in through browser SSO, a local account, or a delegated token.",
95499
+ flags: ["--sso (default false; open the displayed URL in any browser and approve your terminal code; no password flags)", "--username <username> (required for local sign-in)", "--password-stdin (default false; local only; otherwise ARTIUM_AXI_PASSWORD or a terminal prompt)", "--token-stdin (read a delegated token from stdin)"],
95407
95500
  example: "artium-axi login --sso"
95408
95501
  },
95502
+ token: {
95503
+ usage: "artium-axi token create|list|revoke [options]",
95504
+ purpose: "Create, list or revoke delegated tokens.",
95505
+ flags: ["--help (show token command help)"],
95506
+ example: "artium-axi token list"
95507
+ },
95409
95508
  passwd: {
95410
95509
  usage: "artium-axi passwd [--password-stdin]",
95411
95510
  purpose: "Change your password, then sign in again.",
@@ -96188,6 +96287,32 @@ var init_input = __esm({
96188
96287
  }
96189
96288
  });
96190
96289
 
96290
+ // src/shared/proxmox-commands.ts
96291
+ function resolveProxmoxStream(supplied) {
96292
+ const separator = supplied.indexOf("--"), local = supplied.slice(1, separator < 0 ? void 0 : separator);
96293
+ const json2 = local.includes("--json"), options = local.filter((arg) => arg !== "--json");
96294
+ if (local.filter((arg) => arg === "--json").length > 1) throw new ArtiumError("INVALID_INPUT");
96295
+ const args2 = supplied.slice(separator + 1);
96296
+ const route = proxmox_axi_default.streamCommands.find((route2) => route2.command === args2.slice(0, 3).join(" "));
96297
+ return { separator, json: json2, options, args: args2, route };
96298
+ }
96299
+ function resolveProxmoxResult(supplied) {
96300
+ const json2 = supplied.includes("--json"), args2 = supplied.filter((arg) => arg !== "--json");
96301
+ const help = args2.at(-1) === "--help" && (args2.length === 2 || args2.length === 3 && args2[1] === "take");
96302
+ if (!help && (args2.length !== 4 || args2[1] !== "take" || !proxmox_axi_default.writeOperations.includes(args2[2]) || !external_exports.uuid().safeParse(args2[3]).success)) {
96303
+ throw new ArtiumError("INVALID_INPUT");
96304
+ }
96305
+ return { json: json2, args: args2, help };
96306
+ }
96307
+ var init_proxmox_commands = __esm({
96308
+ "src/shared/proxmox-commands.ts"() {
96309
+ "use strict";
96310
+ init_proxmox_axi();
96311
+ init_errors3();
96312
+ init_zod();
96313
+ }
96314
+ });
96315
+
96191
96316
  // src/server/config.ts
96192
96317
  var protectedResultLimits, runnerLimits;
96193
96318
  var init_config = __esm({
@@ -96309,8 +96434,8 @@ var init_private_result = __esm({
96309
96434
  // src/cli/proxmox-result.ts
96310
96435
  async function proxmoxPrivateResult(createClient, supplied, output3) {
96311
96436
  if (supplied[0] !== "result") return false;
96312
- const json2 = supplied.includes("--json"), args2 = supplied.filter((arg) => arg !== "--json");
96313
- if (args2.at(-1) === "--help" && (args2.length === 2 || args2.length === 3 && args2[1] === "take")) {
96437
+ const { json: json2, args: args2, help } = resolveProxmoxResult(supplied);
96438
+ if (help) {
96314
96439
  output3((json2 ? JSON.stringify : encode)({
96315
96440
  usage: "artium-axi proxmox-axi result take <operation> <id>",
96316
96441
  help: [
@@ -96321,9 +96446,6 @@ async function proxmoxPrivateResult(createClient, supplied, output3) {
96321
96446
  }) + "\n");
96322
96447
  return true;
96323
96448
  }
96324
- if (args2.length !== 4 || args2[1] !== "take" || !proxmox_axi_default.writeOperations.includes(args2[2]) || !external_exports.uuid().safeParse(args2[3]).success) {
96325
- throw new ArtiumError("INVALID_INPUT");
96326
- }
96327
96449
  await deliverPrivateResult(createClient, {
96328
96450
  tool: "proxmox-axi",
96329
96451
  operation: args2[2],
@@ -96338,9 +96460,8 @@ var init_proxmox_result = __esm({
96338
96460
  "src/cli/proxmox-result.ts"() {
96339
96461
  "use strict";
96340
96462
  init_dist();
96341
- init_zod();
96342
96463
  init_proxmox_axi();
96343
- init_errors3();
96464
+ init_proxmox_commands();
96344
96465
  init_private_result();
96345
96466
  }
96346
96467
  });
@@ -96583,9 +96704,7 @@ async function openProxmoxStream(client, id, token, signal) {
96583
96704
  async function proxmoxStream(createClient, supplied, output3) {
96584
96705
  if (supplied[0] !== "stream") return false;
96585
96706
  const usage = "artium-axi proxmox-axi stream -- transfer|duplex <native arguments>";
96586
- const separator = supplied.indexOf("--"), local = supplied.slice(1, separator < 0 ? void 0 : separator);
96587
- const json2 = local.includes("--json"), options = local.filter((arg) => arg !== "--json");
96588
- if (local.filter((arg) => arg === "--json").length > 1) throw new ArtiumError("INVALID_INPUT");
96707
+ const { separator, json: json2, options, args: args2, route } = resolveProxmoxStream(supplied);
96589
96708
  const print = (value) => output3("stdout", (json2 ? JSON.stringify(value) : encode(value)) + "\n");
96590
96709
  if (separator < 0 && options.length === 1 && options[0] === "--help") {
96591
96710
  print({ usage, help: [
@@ -96603,8 +96722,6 @@ async function proxmoxStream(createClient, supplied, output3) {
96603
96722
  return true;
96604
96723
  }
96605
96724
  if (separator < 0 || options.length) throw new ArtiumError("INVALID_INPUT", "Use stream -- before native transfer or duplex arguments.", usage);
96606
- const args2 = supplied.slice(separator + 1);
96607
- const route = proxmox_axi_default.streamCommands.find((route2) => route2.command === args2.slice(0, 3).join(" "));
96608
96725
  if (!route) throw new ArtiumError("INVALID_INPUT", "Select a reviewed managed transfer or duplex route.", usage);
96609
96726
  if (args2.includes("--help")) {
96610
96727
  print({
@@ -96800,10 +96917,10 @@ var init_proxmox_stream2 = __esm({
96800
96917
  "use strict";
96801
96918
  init_dist();
96802
96919
  init_zod();
96803
- init_proxmox_axi();
96804
96920
  init_errors3();
96805
96921
  init_version();
96806
96922
  init_proxmox_stream();
96923
+ init_proxmox_commands();
96807
96924
  init_private_result();
96808
96925
  init_input();
96809
96926
  limitSchema = external_exports.object({
@@ -96929,11 +97046,15 @@ var init_scan = __esm({
96929
97046
  #chunks = { stdout: [], stderr: [] };
96930
97047
  #projectedBytes = 0;
96931
97048
  #mintedSecrets = [];
97049
+ #delegationTail = { stdout: "", stderr: "" };
96932
97050
  registerSecrets(values) {
96933
97051
  this.#mintedSecrets.push(...values);
96934
97052
  }
96935
97053
  scan(stream, chunk) {
96936
97054
  if (this.#matched) return true;
97055
+ const text2 = this.#delegationTail[stream] + Buffer.from(chunk).toString("latin1");
97056
+ if (/artd_[A-Za-z0-9_-]{43}/.test(text2)) return this.#matched = true;
97057
+ this.#delegationTail[stream] = text2.slice(-47);
96937
97058
  if (this.output || this.publicContent) this.#chunks[stream].push(Buffer.from(chunk));
96938
97059
  if (this.publicContent) {
96939
97060
  this.#projectedBytes += chunk.length;
@@ -97619,6 +97740,12 @@ var init_arguments = __esm({
97619
97740
  });
97620
97741
 
97621
97742
  // src/shared/ssh-execution.ts
97743
+ function resolveSshManagedCommand(args2) {
97744
+ let prefix = 0;
97745
+ while (["--json", "--help"].includes(args2[prefix])) prefix++;
97746
+ const command = args2[prefix] === "exec" ? "exec" : args2.slice(prefix, prefix + 2).join(" ");
97747
+ return command === "exec" || command.startsWith("execution ") || command.startsWith("connection ") ? command : void 0;
97748
+ }
97622
97749
  var sshExecutionInput, sshPreparation, sshExecutionStatus;
97623
97750
  var init_ssh_execution = __esm({
97624
97751
  "src/shared/ssh-execution.ts"() {
@@ -97737,8 +97864,8 @@ async function sshExecution(args2, createClient, write) {
97737
97864
  write((args2.includes("--json") ? JSON.stringify(value) : encode(value)) + "\n");
97738
97865
  return true;
97739
97866
  }
97740
- const command = args2[prefix] === "exec" ? "exec" : args2.slice(prefix, prefix + 2).join(" ");
97741
- if (!(command === "exec" || command.startsWith("execution ") || command.startsWith("connection "))) return false;
97867
+ const command = resolveSshManagedCommand(args2);
97868
+ if (!command) return false;
97742
97869
  const flags = ["--json", "--help", ...Object.keys(commands2[command]?.flags ?? {}).map((flag) => `--${flag}`)].join(", ");
97743
97870
  let parsed;
97744
97871
  try {
@@ -98144,7 +98271,7 @@ async function kubernetesHosted(args2, createClient, write) {
98144
98271
  const [group, action, ...rest] = args2.slice(prefix);
98145
98272
  if (!["workspace", "session"].includes(group ?? "")) {
98146
98273
  if (args2.includes("--help") && args2.every((arg) => ["--help", "--json"].includes(arg))) {
98147
- const help = {
98274
+ const help2 = {
98148
98275
  command: "artium-axi kubernetes-axi",
98149
98276
  usage: "artium-axi kubernetes-axi <command> [flags]",
98150
98277
  commands: kubernetes_axi_default.discovery.commands,
@@ -98157,31 +98284,16 @@ async function kubernetesHosted(args2, createClient, write) {
98157
98284
  "Use each command with --help. Interactive execution remains unavailable."
98158
98285
  ]
98159
98286
  };
98160
- const text2 = (args2.includes("--json") ? JSON.stringify(help) : encode(help)) + "\n";
98287
+ const text2 = (args2.includes("--json") ? JSON.stringify(help2) : encode(help2)) + "\n";
98161
98288
  write(text2);
98162
98289
  write(text2, "stderr");
98163
98290
  return true;
98164
98291
  }
98165
98292
  return false;
98166
98293
  }
98167
- const separator = rest.indexOf("--"), controls = separator === -1 ? rest : rest.slice(0, separator);
98168
- const native = separator === -1 ? [] : rest.slice(separator + 1);
98169
- const flags = /* @__PURE__ */ new Map(), positionals = [];
98170
- const booleans = ["--json", "--help", "--wait", "--ready", "--confirm"];
98171
- const values = ["--workspace", "--stdin-file", "--input-workspace", "--input-path", "--timeout", "--output-limit", "--digest", "--after", "--output"];
98172
- for (let index = 0; index < controls.length; index++) {
98173
- const word = controls[index];
98174
- if (booleans.includes(word)) {
98175
- if (flags.has(word)) throw new ArtiumError("INVALID_INPUT");
98176
- flags.set(word, "true");
98177
- } else if (values.includes(word)) {
98178
- if (flags.has(word) || controls[index + 1] === void 0 || controls[index + 1].startsWith("--")) throw new ArtiumError("INVALID_INPUT");
98179
- flags.set(word, controls[++index]);
98180
- } else if (word.startsWith("-")) throw new ArtiumError("INVALID_INPUT");
98181
- else positionals.push(word);
98182
- }
98294
+ const { flags, positionals, native, help, route } = kubernetesHostedArguments(rest, group, action);
98183
98295
  const print = (value) => write((prefix || flags.has("--json") ? JSON.stringify(value) : encode(value)) + "\n");
98184
- if (action === "--help" || flags.has("--help") || action === void 0) {
98296
+ if (help) {
98185
98297
  print({
98186
98298
  usage: `artium-axi kubernetes-axi ${group} <command> [flags]`,
98187
98299
  commands: kubernetesHostedCommands.filter((command) => command.startsWith(group)),
@@ -98199,21 +98311,6 @@ async function kubernetesHosted(args2, createClient, write) {
98199
98311
  });
98200
98312
  return true;
98201
98313
  }
98202
- const allowed = {
98203
- "workspace create": [],
98204
- "workspace show": [],
98205
- "workspace delete": [],
98206
- "workspace download": ["--output"],
98207
- "session list": [],
98208
- "session start": values.filter((flag) => !["--digest", "--after", "--output"].includes(flag)),
98209
- "session show": ["--wait", "--ready"],
98210
- "session output": ["--after", "--wait"],
98211
- "session confirm": ["--digest"],
98212
- "session cancel": ["--confirm"],
98213
- "session artifact": ["--output"]
98214
- };
98215
- const route = `${group} ${action}`;
98216
- if (!allowed[route] || [...flags.keys()].some((flag) => flag !== "--json" && !allowed[route].includes(flag)) || route !== "session start" && separator !== -1 || flags.has("--wait") && flags.has("--ready")) throw new ArtiumError("INVALID_INPUT");
98217
98314
  let client;
98218
98315
  const current = () => client ??= createClient();
98219
98316
  const base = `/v1/tools/kubernetes-axi/${group === "workspace" ? "workspaces" : "sessions"}`;
@@ -98349,6 +98446,134 @@ var init_kubernetes2 = __esm({
98349
98446
  }
98350
98447
  });
98351
98448
 
98449
+ // src/cli/token.ts
98450
+ import { fstatSync as fstatSync4, writeSync as writeSync3 } from "node:fs";
98451
+ import { setTimeout as delay2 } from "node:timers/promises";
98452
+ async function tokenCommand(args2, output3, managed2) {
98453
+ const action = args2[0];
98454
+ if (args2.includes("--help")) {
98455
+ output3("usage: artium-axi token create --label <label> --tool <tool> --expires <ISO-date> [--write] [--reusable] [--command <tool:command>] [--exact <tool:command>] [--token-fd <fd>] [--password-stdin|--sso]\n artium-axi token list\n artium-axi token revoke <id>\nCommand picks are exact. Wildcards are not supported yet. API and native selections are broad and require an exact pick.\nRead-only blocks writes, but some reads send data externally or incur costs.\n");
98456
+ return;
98457
+ }
98458
+ if (managed2) throw new ArtiumError("INVALID_INPUT", "Token management is unavailable in managed mode.");
98459
+ if (action === "list" && args2.length === 1) {
98460
+ output3(encode(await new Client().authenticated("/v1/account/tokens", "GET")) + "\n");
98461
+ return;
98462
+ }
98463
+ if (action === "revoke" && args2.length === 2 && external_exports.uuid().safeParse(args2[1]).success) {
98464
+ await new Client().authenticated(`/v1/account/tokens/${args2[1]}/revoke`, "POST");
98465
+ output3("status: revoked\n");
98466
+ return;
98467
+ }
98468
+ if (action === "list" || action === "revoke") throw new ArtiumError(
98469
+ "INVALID_INPUT",
98470
+ "Invalid token command arguments.",
98471
+ action === "list" ? "Use artium-axi token list; valid flags: --help." : "Use artium-axi token revoke <id>; valid flags: --help."
98472
+ );
98473
+ if (action !== "create") throw new ArtiumError("INVALID_INPUT", "Invalid token command.", "Use artium-axi token --help.");
98474
+ const createFlags = ["--label", "--tool", "--expires", "--write", "--reusable", "--command", "--exact", "--token-fd", "--password-stdin", "--sso"];
98475
+ const flags = /* @__PURE__ */ new Map();
98476
+ for (let index = 1; index < args2.length; index++) {
98477
+ const flag = args2[index];
98478
+ if (!createFlags.includes(flag)) throw new ArtiumError(
98479
+ "INVALID_INPUT",
98480
+ flag.startsWith("-") && !/artd_[A-Za-z0-9_-]{43}/.test(flag) ? `Unknown flag ${flag.split("=")[0]} for token create.` : "Unexpected argument for token create.",
98481
+ `Valid flags: --help, ${createFlags.join(", ")}.`
98482
+ );
98483
+ const values = flags.get(flag) ?? [];
98484
+ if (values.length && !["--tool", "--command", "--exact"].includes(flag)) throw new ArtiumError("INVALID_INPUT");
98485
+ const value = ["--write", "--reusable", "--password-stdin", "--sso"].includes(flag) ? "true" : args2[++index];
98486
+ if (!value || value.startsWith("--")) throw new ArtiumError("INVALID_INPUT");
98487
+ if (["--exact", "--command"].includes(flag) && value.includes("*")) throw new ArtiumError(
98488
+ "INVALID_INPUT",
98489
+ "Wildcards are not supported yet.",
98490
+ "Select exact commands or use --tool for tool-wide access."
98491
+ );
98492
+ values.push(value);
98493
+ flags.set(flag, values);
98494
+ }
98495
+ if (flags.has("--sso") && flags.has("--password-stdin")) throw new ArtiumError("INVALID_INPUT");
98496
+ const label = flags.get("--label")?.[0];
98497
+ const expiresAt = Date.parse(flags.get("--expires")?.[0] ?? "");
98498
+ const readTool = (value) => {
98499
+ const tool = toolSchema.safeParse(value);
98500
+ if (!tool.success) throw new ArtiumError("INVALID_INPUT", "Unknown tool.", "Use artium-axi tools to list available tools.");
98501
+ return tool.data;
98502
+ };
98503
+ const tools = (flags.get("--tool") ?? []).map((tool) => ({ tool: readTool(tool) }));
98504
+ const picks = [...flags.get("--exact") ?? [], ...flags.get("--command") ?? []].map((value) => {
98505
+ const separator = value.indexOf(":");
98506
+ if (separator < 0) throw new ArtiumError("INVALID_INPUT");
98507
+ return { tool: readTool(value.slice(0, separator)), commands: [value.slice(separator + 1)] };
98508
+ });
98509
+ if (!label || !Number.isFinite(expiresAt) || !tools.length && !picks.length) throw new ArtiumError("INVALID_INPUT");
98510
+ const fdText = flags.get("--token-fd")?.[0];
98511
+ if (!fdText && !process.stdout.isTTY) throw new ArtiumError("INVALID_INPUT", "A private token destination is required.", "Use --token-fd with an inherited pipe or socket.");
98512
+ const fd = fdText === void 0 ? 1 : Number(fdText);
98513
+ if (fdText !== void 0) {
98514
+ if (!/^\d+$/.test(fdText) || fd < 3) throw new ArtiumError("INVALID_INPUT");
98515
+ try {
98516
+ const stat = fstatSync4(fd);
98517
+ if (!stat.isFIFO() && !stat.isSocket()) throw new Error();
98518
+ writeSync3(fd, Buffer.alloc(0));
98519
+ } catch {
98520
+ throw new ArtiumError("INVALID_INPUT", "The token descriptor must be a writable pipe or socket.");
98521
+ }
98522
+ }
98523
+ if (picks.length) output3("warning: Exact selections may be broad or issue credentials that outlive this token. Revoke issued credentials separately.\n");
98524
+ if (flags.has("--write") && [...tools, ...picks].some((item) => item.tool === "ssh-axi")) {
98525
+ output3("warning: SSH write access reaches every host and sudo grant available to the creator.\n");
98526
+ }
98527
+ const client = new Client();
98528
+ const { accessToken } = await client.freshSession();
98529
+ let proof;
98530
+ if (flags.has("--sso")) {
98531
+ const start = deviceStartResponseSchema.parse(await client.request("/v1/auth/reauth", "POST", {}, accessToken));
98532
+ if (start.verificationUri !== client.serverUrl + "/device") throw new ArtiumError("INVALID_RESPONSE");
98533
+ output3(`status: approval-required
98534
+ open: ${JSON.stringify(start.verificationUri)}
98535
+ code: ${start.userCode}
98536
+ `);
98537
+ while (Date.now() < start.expiresAt) {
98538
+ try {
98539
+ proof = ssoReauthResponseSchema.parse(await client.request("/v1/auth/reauth", "POST", { deviceCode: start.deviceCode }, accessToken));
98540
+ if (reauthResponseSchema.safeParse(proof).success) break;
98541
+ } catch (error62) {
98542
+ if (!(error62 instanceof ArtiumError) || error62.code !== "DEVICE_POLL_LIMITED") throw error62;
98543
+ }
98544
+ await delay2(Math.min(start.intervalMs, Math.max(0, start.expiresAt - Date.now())));
98545
+ }
98546
+ } else {
98547
+ const password = await readPassword(flags.has("--password-stdin"));
98548
+ proof = await client.request("/v1/auth/reauth", "POST", { password }, accessToken);
98549
+ }
98550
+ const { ticket } = reauthResponseSchema.parse(proof);
98551
+ const response = createdDelegationSchema.parse(await client.request("/v1/account/tokens", "POST", {
98552
+ label,
98553
+ scope: { tools: [...tools, ...picks] },
98554
+ readOnly: !flags.has("--write"),
98555
+ reusable: flags.has("--reusable"),
98556
+ expiresAt
98557
+ }, accessToken, false, { "x-artium-reauth-ticket": ticket }));
98558
+ writeSync3(fd, `${response.token}
98559
+ `);
98560
+ output3(`status: created
98561
+ id: ${response.id}
98562
+ expiresAt: ${new Date(response.expiresAt).toISOString()}
98563
+ `);
98564
+ }
98565
+ var init_token = __esm({
98566
+ "src/cli/token.ts"() {
98567
+ "use strict";
98568
+ init_dist();
98569
+ init_zod();
98570
+ init_api2();
98571
+ init_errors3();
98572
+ init_http();
98573
+ init_password();
98574
+ }
98575
+ });
98576
+
98352
98577
  // src/cli/commands.ts
98353
98578
  var commands_exports = {};
98354
98579
  import { resolve as resolve6 } from "node:path";
@@ -98376,16 +98601,13 @@ async function main(args2) {
98376
98601
  const command = args2[0];
98377
98602
  const help = helpCommand(prefixHelp ? [...args2, "--help"] : args2, prefixHelp);
98378
98603
  if (prefixHelp && !help) throw new ArtiumError("INVALID_INPUT", void 0, "Use artium-axi --help for commands.");
98379
- if (help) {
98604
+ const toolWords = args2.slice(1).filter((arg) => !["--json", "--full", "--help", "-h"].includes(arg));
98605
+ const toolDiscovery = toolSchema.safeParse(command).success && (prefixHelp || toolWords.length === 0 || args2.slice(1).some((arg) => ["--help", "-h"].includes(arg)) || toolWords[0] === "help" || toolWords.length === 1 && ["commands", "home"].includes(toolWords[0]));
98606
+ const scopedHelp = toolDiscovery || help && ["home", "tools", "tools show"].includes(help);
98607
+ if (help && !scopedHelp) {
98380
98608
  output2("stdout", commandHelp(help));
98381
98609
  return;
98382
98610
  }
98383
- if (args2.length === 0) {
98384
- const bin = resolve6(process.argv[1]);
98385
- output2("stdout", `bin: ${JSON.stringify(bin)}
98386
- description: Run managed upstream tools through one local sign-in.
98387
- `);
98388
- }
98389
98611
  if (managedMode) {
98390
98612
  if (["passwd", "logout", "setup", "update", "session-context"].includes(args2[0])) {
98391
98613
  throw new ArtiumError(
@@ -98396,6 +98618,44 @@ description: Run managed upstream tools through one local sign-in.
98396
98618
  }
98397
98619
  managed = await ManagedSession.read(args2[0] === "login");
98398
98620
  }
98621
+ if (scopedHelp && (managed || readStoredSession()?.session.delegated)) {
98622
+ const client2 = new Client(process.env, managed);
98623
+ const delegated = managed ? "delegation" in meResponseSchema.parse(await client2.authenticated("/v1/me", "GET")) : client2.sessions.read()?.delegated;
98624
+ if (delegated) {
98625
+ const { tools } = toolsResponseSchema.parse(await client2.authenticated("/v1/tools", "GET"));
98626
+ if (tools.some((tool) => tool.commands === void 0)) throw new ArtiumError("INVALID_RESPONSE");
98627
+ const name = toolDiscovery ? command : help === "tools show" ? args2.slice(2).find((arg) => toolSchema.safeParse(arg).success) : void 0;
98628
+ if (name) {
98629
+ const tool = tools.find((tool2) => tool2.name === name);
98630
+ if (!tool) throw new ArtiumError("TOOL_NOT_GRANTED");
98631
+ if (toolDiscovery && !prefixHelp && toolWords.length > 0 && !(toolWords.length === 1 && ["commands", "home", "help"].includes(toolWords[0]))) {
98632
+ const parsed = runSuccessSchema.safeParse(await client2.authenticated(`/v1/tools/${name}/run`, "POST", { args: args2.slice(1) }));
98633
+ if (!parsed.success || parsed.data.source !== name) throw new ArtiumError("INVALID_RESPONSE");
98634
+ const { truncated } = parsed.data;
98635
+ if (truncated.stdout || truncated.stderr) output2("stderr", `artium-axi: output truncated (${["stdout", "stderr"].filter((stream) => truncated[stream]).join(", ")}).
98636
+ `);
98637
+ output2("stdout", parsed.data.stdout);
98638
+ output2("stderr", parsed.data.stderr);
98639
+ if (parsed.data.exitCode !== 0 && client2.requestId) output2("stderr", `${parsed.data.stderr && !parsed.data.stderr.endsWith("\n") ? "\n" : ""}artium-axi: request_id ${client2.requestId}
98640
+ `);
98641
+ process.exitCode = parsed.data.exitCode;
98642
+ return;
98643
+ }
98644
+ output2("stdout", args2.includes("--json") ? JSON.stringify({ tool: tool.name, commands: tool.commands }) + "\n" : toolView(tool));
98645
+ } else output2("stdout", toolsView(tools));
98646
+ return;
98647
+ }
98648
+ }
98649
+ if (help) {
98650
+ output2("stdout", commandHelp(help));
98651
+ return;
98652
+ }
98653
+ if (args2.length === 0) {
98654
+ const bin = resolve6(process.argv[1]);
98655
+ output2("stdout", `bin: ${JSON.stringify(bin)}
98656
+ description: Run managed upstream tools through one local sign-in.
98657
+ `);
98658
+ }
98399
98659
  if (command === "session-context") {
98400
98660
  output2("stdout", await sessionContext());
98401
98661
  return;
@@ -98408,6 +98668,10 @@ description: Run managed upstream tools through one local sign-in.
98408
98668
  await download(args2.slice(1), (text2) => output2("stdout", text2), managed);
98409
98669
  return;
98410
98670
  }
98671
+ if (command === "token") {
98672
+ await tokenCommand(args2.slice(1), (text2) => output2("stdout", text2), managed);
98673
+ return;
98674
+ }
98411
98675
  if (command === "setup") {
98412
98676
  output2("stdout", await setup(args2.slice(1)));
98413
98677
  return;
@@ -98420,6 +98684,30 @@ description: Run managed upstream tools through one local sign-in.
98420
98684
  }
98421
98685
  if (command === "login" || command === "passwd") {
98422
98686
  const remaining = args2.slice(1);
98687
+ if (command === "login" && (remaining.length === 1 && remaining[0] === "--token-stdin" || remaining.length === 0 && process.env.ARTIUM_AXI_TOKEN !== void 0)) {
98688
+ if (managed && process.env.ARTIUM_AXI_TOKEN !== void 0) throw new ArtiumError("INVALID_INPUT", "Token environment values are refused in managed mode.");
98689
+ const client3 = new Client(process.env, managed);
98690
+ const signIn = async () => {
98691
+ if (!managed) {
98692
+ const current = client3.sessions.read();
98693
+ if (current && !current.delegated) throw new ArtiumError("INVALID_INPUT", "A full session already exists in this configuration directory.", "Use a separate XDG_CONFIG_HOME for the delegated session.");
98694
+ }
98695
+ const token = remaining.length ? await readPassword(true) : process.env.ARTIUM_AXI_TOKEN;
98696
+ if (!/^artd_[A-Za-z0-9_-]{43}$/.test(token)) throw new ArtiumError("INVALID_INPUT");
98697
+ managed?.protect(token);
98698
+ const result2 = loginResponseSchema.safeParse(await client3.request("/v1/auth/delegated", "POST", { token }));
98699
+ if (!result2.success || result2.data.status !== "authenticated") throw new ArtiumError("INVALID_RESPONSE");
98700
+ if (managed) await managed.emit(client3.serverUrl, result2.data);
98701
+ else {
98702
+ client3.sessions.write(result2.data, void 0, true);
98703
+ client3.sessions.writeClientConfig(client3.caFile);
98704
+ }
98705
+ };
98706
+ if (managed) await signIn();
98707
+ else await client3.sessions.locked(signIn);
98708
+ output2("stdout", "status: authenticated\nnext: artium-axi tools\n");
98709
+ return;
98710
+ }
98423
98711
  if (managed && process.env.ARTIUM_AXI_PASSWORD !== void 0) {
98424
98712
  throw new ArtiumError(
98425
98713
  "INVALID_INPUT",
@@ -98608,6 +98896,8 @@ var init_commands = __esm({
98608
98896
  init_session_context();
98609
98897
  init_ssh();
98610
98898
  init_kubernetes2();
98899
+ init_token();
98900
+ init_session();
98611
98901
  failureContext = "main";
98612
98902
  for (const stream of [process.stdout, process.stderr]) {
98613
98903
  stream.on("error", (error62) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knowttl/artium-axi",
3
- "version": "0.0.34",
3
+ "version": "0.0.35",
4
4
  "description": "Client CLI and embedded skill for the Artium managed tools server.",
5
5
  "license": "MIT",
6
6
  "type": "module",