@almyty/auth 0.1.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # @almyty/auth
2
2
 
3
- Browser-based authentication for all almyty CLIs. Credentials are stored at `~/.almyty/credentials.json` (mode 0600) and shared by every almyty package.
3
+ Browser-based authentication for every almyty CLI. Credentials are
4
+ stored at `~/.almyty/credentials.json` (mode `0600`, in a `0700`
5
+ directory) and shared by `@almyty/agents`, `@almyty/chat`,
6
+ `@almyty/skills`, `@almyty/models`, `@almyty/connections`,
7
+ `@almyty/mcp-server` and `@almyty/runner`.
4
8
 
5
9
  ## Quick start
6
10
 
@@ -13,35 +17,96 @@ $ npx @almyty/auth whoami
13
17
 
14
18
  | Command | Description |
15
19
  |---------|-------------|
16
- | `login` | Open browser to authenticate, mint an API key, save credentials |
20
+ | `login` | Open the browser, authenticate, store the token |
17
21
  | `logout` | Remove stored credentials |
18
- | `whoami` | Show current identity (API URL, token prefix) |
22
+ | `whoami` | Show the stored identity and when the token expires |
19
23
 
20
24
  ## Login options
21
25
 
22
26
  | Flag | Description |
23
27
  |------|-------------|
24
28
  | `--token <T>` | Skip the browser and store a token directly (useful for CI) |
25
- | `--no-browser` | Print the login URL instead of opening the browser |
26
- | `--frontend <url>` | Custom frontend URL |
27
- | `--api <url>` | Custom API URL |
29
+ | `--no-browser` | Print the login URL instead of opening a browser |
30
+ | `--frontend <url>` | Frontend origin hosting `/cli-login` (default `https://app.almyty.com`) |
31
+ | `--api <url>` | API origin to store with the token (default `https://api.almyty.com`) |
32
+
33
+ An `http://` API URL is refused for anything but loopback: the JWT
34
+ crosses that connection. A bad URL exits `2` and nothing is written.
35
+
36
+ ## whoami options
37
+
38
+ | Flag | Description |
39
+ |------|-------------|
40
+ | `--verify` | Also call `GET /auth/profile` to confirm the token still works, and list the organizations it can see |
41
+ | `--json` | Machine-readable output |
42
+
43
+ `whoami` reports the token's expiry without a network call: `login`
44
+ reads the `exp` and `email` claims out of the JWT and stores them
45
+ alongside it. An expired token exits `3`, so `whoami` is a usable
46
+ precondition in a script:
47
+
48
+ ```bash
49
+ npx @almyty/auth whoami --verify > /dev/null || npx @almyty/auth login
50
+ ```
51
+
52
+ `whoami` never prints the token — only a first-8/last-4 preview, enough
53
+ to tell two tokens apart in a bug report.
54
+
55
+ ## Global options
56
+
57
+ | Flag | Description |
58
+ |------|-------------|
59
+ | `--json` | Machine-readable output, where the command has any (`whoami`, `logout`) |
60
+ | `--help`, `-h` | Show help |
61
+ | `--version`, `-v` | Print the version |
62
+
63
+ Both `--flag value` and `--flag=value` are accepted.
64
+
65
+ ## Exit codes
66
+
67
+ | Code | Meaning |
68
+ |------|---------|
69
+ | `0` | success |
70
+ | `1` | unexpected error |
71
+ | `2` | usage error (bad flags, unknown command, refused URL) |
72
+ | `3` | not authenticated, expired, or the API rejected the token |
28
73
 
29
74
  ## Environment variables
30
75
 
31
76
  | Variable | Description |
32
77
  |----------|-------------|
33
- | `ALMYTY_TOKEN` | Token override; takes precedence over credentials file |
78
+ | `ALMYTY_TOKEN` | Token override; read instead of the credentials file |
34
79
  | `ALMYTY_URL` | API URL override |
35
80
  | `ALMYTY_FRONTEND_URL` | Frontend URL override (used when generating the login URL) |
81
+ | `NO_COLOR` | Honoured; this CLI emits no ANSI colour anyway |
82
+
83
+ ## Files
84
+
85
+ | Path | Contents |
86
+ |------|----------|
87
+ | `~/.almyty/credentials.json` | The token, the API URL it belongs to, its expiry, the email. Mode `0600`. |
88
+ | `~/.almyty/config.json` | The API and frontend URLs `login` was pointed at, so later commands do not need the flags again. Written only after a login succeeds. |
36
89
 
37
90
  ## How it works
38
91
 
39
- `login` runs entirely on your machine. It starts a loopback HTTP server, opens your browser to the almyty login page, and receives the token via POST body -- never in a URL. No password enters the CLI process.
92
+ `login` runs entirely on your machine. It binds a server to `127.0.0.1`
93
+ on a random port, generates a 32-byte `state` nonce, and opens your
94
+ browser at `{frontend}/cli-login`. The page authenticates you and hands
95
+ the token back to the loopback server, which checks the nonce before
96
+ accepting it. The token travels in a POST body, never in a URL, so it
97
+ does not land in browser history or a proxy log. No password enters the
98
+ CLI process.
99
+
100
+ ## About almyty
40
101
 
41
- ## Docs
102
+ almyty is the full-stack platform for AI agents, agnostic by design: any LLM, any
103
+ API turned into tools, served over MCP, A2A, UTCP, and Agent Skills. Open source,
104
+ no lock-in.
42
105
 
43
- https://almyty.com/docs
106
+ - Website: https://almyty.com
107
+ - Docs: https://docs.almyty.com
108
+ - Source: https://github.com/almyty-inc/almyty
44
109
 
45
- ## License
110
+ This CLI is part of the `@almyty/*` suite (versioned together at 1.x) and works with the almyty platform 0.1 and later.
46
111
 
47
- BSL-1.1
112
+ Apache-2.0 © Almyty Inc.
package/dist/args.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Argument parsing shared in shape (not in code) by every almyty CLI.
3
+ *
4
+ * Conventions, so `almyty agents …` and `almyty auth …` never disagree:
5
+ * - long flags only for options: `--input`, `--json`, `--max-steps`
6
+ * - `--flag value` and `--flag=value` are both accepted. Only the
7
+ * space form used to work, so `--input='{"a":1}'` silently became a
8
+ * flag literally named `input={"a":1}` and the input was dropped.
9
+ * - `-h` / `--help` and `-v` / `--version` are the only short flags
10
+ * - a flag declared boolean never swallows the next token
11
+ * - the first bare word is the command; the rest are positional
12
+ */
13
+ export interface ParsedArgs {
14
+ command?: string;
15
+ positional: string[];
16
+ flags: Record<string, string | boolean>;
17
+ }
18
+ /** Flags every almyty CLI understands, and which never take a value. */
19
+ export declare const COMMON_BOOLEAN_FLAGS: readonly ["help", "version", "json"];
20
+ export declare function parseArgs(argv: string[], booleanFlags?: readonly string[]): ParsedArgs;
21
+ /** A flag's value as a string, or undefined when it was absent or bare. */
22
+ export declare function flagString(flags: ParsedArgs['flags'], name: string): string | undefined;
23
+ /**
24
+ * A flag's value as a finite number. Throws a usage message rather than
25
+ * letting `NaN` reach the API, which answered a 400 with a validation
26
+ * body the user had to decode.
27
+ */
28
+ export declare function flagNumber(flags: ParsedArgs['flags'], name: string): number | undefined;
package/dist/args.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Argument parsing shared in shape (not in code) by every almyty CLI.
3
+ *
4
+ * Conventions, so `almyty agents …` and `almyty auth …` never disagree:
5
+ * - long flags only for options: `--input`, `--json`, `--max-steps`
6
+ * - `--flag value` and `--flag=value` are both accepted. Only the
7
+ * space form used to work, so `--input='{"a":1}'` silently became a
8
+ * flag literally named `input={"a":1}` and the input was dropped.
9
+ * - `-h` / `--help` and `-v` / `--version` are the only short flags
10
+ * - a flag declared boolean never swallows the next token
11
+ * - the first bare word is the command; the rest are positional
12
+ */
13
+ /** Flags every almyty CLI understands, and which never take a value. */
14
+ export const COMMON_BOOLEAN_FLAGS = ['help', 'version', 'json'];
15
+ export function parseArgs(argv, booleanFlags = COMMON_BOOLEAN_FLAGS) {
16
+ const booleans = new Set([...COMMON_BOOLEAN_FLAGS, ...booleanFlags]);
17
+ const result = { positional: [], flags: {} };
18
+ for (let i = 0; i < argv.length; i++) {
19
+ const arg = argv[i];
20
+ if (arg === '-h') {
21
+ result.flags.help = true;
22
+ continue;
23
+ }
24
+ if (arg === '-v') {
25
+ result.flags.version = true;
26
+ continue;
27
+ }
28
+ if (arg === '--') {
29
+ // Everything after `--` is positional, flags included.
30
+ result.positional.push(...argv.slice(i + 1));
31
+ break;
32
+ }
33
+ if (arg.startsWith('--')) {
34
+ const body = arg.slice(2);
35
+ const eq = body.indexOf('=');
36
+ if (eq !== -1) {
37
+ result.flags[body.slice(0, eq)] = body.slice(eq + 1);
38
+ continue;
39
+ }
40
+ if (booleans.has(body)) {
41
+ result.flags[body] = true;
42
+ continue;
43
+ }
44
+ const next = argv[i + 1];
45
+ if (next !== undefined && !next.startsWith('--')) {
46
+ result.flags[body] = next;
47
+ i++;
48
+ }
49
+ else {
50
+ result.flags[body] = true;
51
+ }
52
+ continue;
53
+ }
54
+ if (!result.command)
55
+ result.command = arg;
56
+ else
57
+ result.positional.push(arg);
58
+ }
59
+ return result;
60
+ }
61
+ /** A flag's value as a string, or undefined when it was absent or bare. */
62
+ export function flagString(flags, name) {
63
+ const value = flags[name];
64
+ return typeof value === 'string' ? value : undefined;
65
+ }
66
+ /**
67
+ * A flag's value as a finite number. Throws a usage message rather than
68
+ * letting `NaN` reach the API, which answered a 400 with a validation
69
+ * body the user had to decode.
70
+ */
71
+ export function flagNumber(flags, name) {
72
+ const raw = flagString(flags, name);
73
+ if (raw === undefined)
74
+ return undefined;
75
+ const value = Number(raw);
76
+ if (!Number.isFinite(value)) {
77
+ throw new Error(`--${name} needs a number, got ${JSON.stringify(raw)}`);
78
+ }
79
+ return value;
80
+ }
package/dist/config.d.ts CHANGED
@@ -5,6 +5,12 @@ export interface AlmytyConfig {
5
5
  }
6
6
  export declare function loadConfig(): AlmytyConfig;
7
7
  export declare function saveConfig(config: AlmytyConfig): void;
8
+ /**
9
+ * Refuse an insecure (http://) backend URL for a remote host: the JWT
10
+ * crosses this connection, so plaintext to anything but loopback would
11
+ * leak it. http is allowed only for localhost (local dev).
12
+ */
13
+ export declare function assertSecureBackendUrl(url: string): void;
8
14
  /**
9
15
  * Resolve the API URL from (in order): flag > env > config > default.
10
16
  */
package/dist/config.js CHANGED
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { readFileSync, writeFileSync, existsSync } from 'fs';
10
10
  import { join } from 'path';
11
- import { CREDENTIALS_DIR } from './credentials';
11
+ import { CREDENTIALS_DIR } from './credentials.js';
12
12
  export const CONFIG_FILE = join(CREDENTIALS_DIR, 'config.json');
13
13
  export function loadConfig() {
14
14
  try {
@@ -23,14 +23,39 @@ export function loadConfig() {
23
23
  export function saveConfig(config) {
24
24
  writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + '\n', 'utf-8');
25
25
  }
26
+ /**
27
+ * Refuse an insecure (http://) backend URL for a remote host: the JWT
28
+ * crosses this connection, so plaintext to anything but loopback would
29
+ * leak it. http is allowed only for localhost (local dev).
30
+ */
31
+ export function assertSecureBackendUrl(url) {
32
+ let parsed;
33
+ try {
34
+ parsed = new URL(url);
35
+ }
36
+ catch {
37
+ throw new Error(`Invalid backend URL: ${url}`);
38
+ }
39
+ const host = parsed.hostname;
40
+ const isLoopback = host === 'localhost' ||
41
+ host === '127.0.0.1' ||
42
+ host === '::1' ||
43
+ host.endsWith('.localhost');
44
+ if (parsed.protocol !== 'https:' && !isLoopback) {
45
+ throw new Error(`Refusing an insecure ${parsed.protocol}// backend URL for a remote host: ${url}. ` +
46
+ 'Use https:// (http is only allowed for localhost).');
47
+ }
48
+ }
26
49
  /**
27
50
  * Resolve the API URL from (in order): flag > env > config > default.
28
51
  */
29
52
  export function resolveApiUrl(flagValue) {
30
- return flagValue
31
- || process.env.ALMYTY_URL
32
- || loadConfig().apiUrl
33
- || 'https://api.almyty.com';
53
+ const url = flagValue ||
54
+ process.env.ALMYTY_URL ||
55
+ loadConfig().apiUrl ||
56
+ 'https://api.almyty.com';
57
+ assertSecureBackendUrl(url);
58
+ return url;
34
59
  }
35
60
  /**
36
61
  * Resolve the frontend URL from (in order): flag > env > config > default.
@@ -21,3 +21,49 @@ export declare function clearCredentials(): boolean;
21
21
  * Returns null when no credentials are available.
22
22
  */
23
23
  export declare function resolveCredentials(): StoredCredentials | null;
24
+ export type ExpiryState = 'unknown' | 'valid' | 'expired';
25
+ /**
26
+ * Whether the stored credential has passed its own `expiresAt`.
27
+ *
28
+ * `whoami` used to report a happy identity for a token that expired
29
+ * weeks ago, because it only checked that the file existed. Nothing
30
+ * here contacts the network: an expiry the token itself carries is
31
+ * enough to say "log in again" before any command wastes a round trip.
32
+ */
33
+ export declare function expiryState(creds: StoredCredentials, now?: Date): {
34
+ state: ExpiryState;
35
+ message: string;
36
+ };
37
+ /**
38
+ * The parts of a credential that are safe to print. Never returns the
39
+ * token itself — only a first-8/last-4 preview, enough to tell two
40
+ * tokens apart in a bug report without pasting one into a terminal
41
+ * someone is screen-sharing.
42
+ */
43
+ export declare function credentialSummary(creds: StoredCredentials): {
44
+ url: string;
45
+ frontendUrl?: string;
46
+ email?: string;
47
+ tokenPreview: string;
48
+ };
49
+ /**
50
+ * Read the unverified payload of a JWT.
51
+ *
52
+ * The CLI never validates the signature — the API does that on every
53
+ * call. All this is for is filling in what the token already says
54
+ * about itself (`exp`, `email`) so `whoami` can answer without a round
55
+ * trip, and so an expired token is reported as expired instead of as a
56
+ * working login.
57
+ */
58
+ export declare function jwtClaims(token: string): Record<string, unknown> | null;
59
+ /** The token's own `exp` claim as an ISO string, when it has one. */
60
+ export declare function expiresAtFromToken(token: string): string | undefined;
61
+ /** The token's own `email` claim, when it has one. */
62
+ export declare function emailFromToken(token: string): string | undefined;
63
+ /**
64
+ * Fill in what the token says about itself before storing it, so
65
+ * `whoami` can report an expiry instead of "not recorded". `login`
66
+ * stored only url+token, which is why the expiry check had nothing to
67
+ * check.
68
+ */
69
+ export declare function enrichFromToken(creds: StoredCredentials): StoredCredentials;
@@ -21,16 +21,24 @@ export function loadCredentials() {
21
21
  }
22
22
  }
23
23
  export function saveCredentials(creds) {
24
- mkdirSync(CREDENTIALS_DIR, { recursive: true });
25
- writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2));
26
- // Ensure the file is owner-only readable. writeFileSync's `mode` option
27
- // only applies on creation; chmod is idempotent and safer when the file
28
- // already exists with looser permissions.
24
+ // Owner-only directory (0700). mkdir's mode only applies on creation, so
25
+ // chmod an existing dir too — best-effort (no-op/throw on Windows).
26
+ mkdirSync(CREDENTIALS_DIR, { recursive: true, mode: 0o700 });
27
+ try {
28
+ chmodSync(CREDENTIALS_DIR, 0o700);
29
+ }
30
+ catch {
31
+ /* best-effort */
32
+ }
33
+ // Create the file 0600 from the start (closes the brief world-readable
34
+ // window that exists when a file is created with default perms and only
35
+ // chmod'd afterwards). chmod again for the already-exists case.
36
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify(enrichFromToken(creds), null, 2), { mode: 0o600 });
29
37
  try {
30
38
  chmodSync(CREDENTIALS_FILE, 0o600);
31
39
  }
32
40
  catch {
33
- // Best-effort on platforms (Windows) where chmod may not apply.
41
+ /* best-effort on platforms where chmod may not apply */
34
42
  }
35
43
  }
36
44
  export function clearCredentials() {
@@ -56,3 +64,97 @@ export function resolveCredentials() {
56
64
  }
57
65
  return loadCredentials();
58
66
  }
67
+ /**
68
+ * Whether the stored credential has passed its own `expiresAt`.
69
+ *
70
+ * `whoami` used to report a happy identity for a token that expired
71
+ * weeks ago, because it only checked that the file existed. Nothing
72
+ * here contacts the network: an expiry the token itself carries is
73
+ * enough to say "log in again" before any command wastes a round trip.
74
+ */
75
+ export function expiryState(creds, now = new Date()) {
76
+ if (!creds.expiresAt) {
77
+ return { state: 'unknown', message: 'not recorded' };
78
+ }
79
+ const at = new Date(creds.expiresAt);
80
+ if (Number.isNaN(at.getTime())) {
81
+ return { state: 'unknown', message: `unreadable (${creds.expiresAt})` };
82
+ }
83
+ const deltaMs = at.getTime() - now.getTime();
84
+ if (deltaMs <= 0) {
85
+ return { state: 'expired', message: `expired ${at.toISOString()}` };
86
+ }
87
+ const hours = Math.floor(deltaMs / 3_600_000);
88
+ const remaining = hours >= 48
89
+ ? `${Math.floor(hours / 24)} days`
90
+ : hours >= 1
91
+ ? `${hours}h`
92
+ : `${Math.max(1, Math.round(deltaMs / 60_000))}m`;
93
+ return { state: 'valid', message: `${at.toISOString()} (in ${remaining})` };
94
+ }
95
+ /**
96
+ * The parts of a credential that are safe to print. Never returns the
97
+ * token itself — only a first-8/last-4 preview, enough to tell two
98
+ * tokens apart in a bug report without pasting one into a terminal
99
+ * someone is screen-sharing.
100
+ */
101
+ export function credentialSummary(creds) {
102
+ const token = creds.token ?? '';
103
+ const preview = token.length > 16
104
+ ? `${token.slice(0, 8)}…${token.slice(-4)}`
105
+ : `${'*'.repeat(Math.max(0, token.length))}`;
106
+ return {
107
+ url: creds.url,
108
+ ...(creds.frontendUrl ? { frontendUrl: creds.frontendUrl } : {}),
109
+ ...(creds.email ? { email: creds.email } : {}),
110
+ tokenPreview: preview,
111
+ };
112
+ }
113
+ /**
114
+ * Read the unverified payload of a JWT.
115
+ *
116
+ * The CLI never validates the signature — the API does that on every
117
+ * call. All this is for is filling in what the token already says
118
+ * about itself (`exp`, `email`) so `whoami` can answer without a round
119
+ * trip, and so an expired token is reported as expired instead of as a
120
+ * working login.
121
+ */
122
+ export function jwtClaims(token) {
123
+ const parts = token.split('.');
124
+ if (parts.length !== 3)
125
+ return null;
126
+ try {
127
+ const payload = Buffer.from(parts[1], 'base64url').toString('utf-8');
128
+ const parsed = JSON.parse(payload);
129
+ return parsed && typeof parsed === 'object' ? parsed : null;
130
+ }
131
+ catch {
132
+ return null;
133
+ }
134
+ }
135
+ /** The token's own `exp` claim as an ISO string, when it has one. */
136
+ export function expiresAtFromToken(token) {
137
+ const exp = jwtClaims(token)?.exp;
138
+ if (typeof exp !== 'number' || !Number.isFinite(exp))
139
+ return undefined;
140
+ const at = new Date(exp * 1000);
141
+ return Number.isNaN(at.getTime()) ? undefined : at.toISOString();
142
+ }
143
+ /** The token's own `email` claim, when it has one. */
144
+ export function emailFromToken(token) {
145
+ const email = jwtClaims(token)?.email;
146
+ return typeof email === 'string' && email.length > 0 ? email : undefined;
147
+ }
148
+ /**
149
+ * Fill in what the token says about itself before storing it, so
150
+ * `whoami` can report an expiry instead of "not recorded". `login`
151
+ * stored only url+token, which is why the expiry check had nothing to
152
+ * check.
153
+ */
154
+ export function enrichFromToken(creds) {
155
+ return {
156
+ ...creds,
157
+ email: creds.email ?? emailFromToken(creds.token),
158
+ expiresAt: creds.expiresAt ?? expiresAtFromToken(creds.token),
159
+ };
160
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Exit codes shared by every almyty CLI.
3
+ *
4
+ * Scripts need to tell "you are not logged in" apart from "that agent
5
+ * does not exist" apart from "the run you asked for failed" without
6
+ * grepping stderr. Every almyty CLI uses this same table, so
7
+ * `almyty agents run x || case $? in 3) almyty login;; esac` behaves
8
+ * the same whichever binary produced the code.
9
+ */
10
+ export declare const EXIT: {
11
+ /** Success. */
12
+ readonly OK: 0;
13
+ /** Unexpected failure (a thrown error with no better classification). */
14
+ readonly ERROR: 1;
15
+ /** Bad or missing arguments, or an unknown command. */
16
+ readonly USAGE: 2;
17
+ /** No stored credential, or the API rejected the one we had. */
18
+ readonly AUTH: 3;
19
+ /** The named agent / gateway / skill / run does not exist. */
20
+ readonly NOT_FOUND: 4;
21
+ /** The command ran; the operation it asked for failed. */
22
+ readonly FAILED: 5;
23
+ };
24
+ export type ExitCode = (typeof EXIT)[keyof typeof EXIT];
25
+ /** One line per code, for `--help` output and READMEs. */
26
+ export declare const EXIT_CODE_HELP: string;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Exit codes shared by every almyty CLI.
3
+ *
4
+ * Scripts need to tell "you are not logged in" apart from "that agent
5
+ * does not exist" apart from "the run you asked for failed" without
6
+ * grepping stderr. Every almyty CLI uses this same table, so
7
+ * `almyty agents run x || case $? in 3) almyty login;; esac` behaves
8
+ * the same whichever binary produced the code.
9
+ */
10
+ export const EXIT = {
11
+ /** Success. */
12
+ OK: 0,
13
+ /** Unexpected failure (a thrown error with no better classification). */
14
+ ERROR: 1,
15
+ /** Bad or missing arguments, or an unknown command. */
16
+ USAGE: 2,
17
+ /** No stored credential, or the API rejected the one we had. */
18
+ AUTH: 3,
19
+ /** The named agent / gateway / skill / run does not exist. */
20
+ NOT_FOUND: 4,
21
+ /** The command ran; the operation it asked for failed. */
22
+ FAILED: 5,
23
+ };
24
+ /** One line per code, for `--help` output and READMEs. */
25
+ export const EXIT_CODE_HELP = [
26
+ ' 0 success',
27
+ ' 1 unexpected error',
28
+ ' 2 usage error (bad flags, unknown command)',
29
+ ' 3 not authenticated — run `almyty login`',
30
+ ' 4 not found (agent, gateway, skill, or run)',
31
+ ' 5 the operation ran and failed',
32
+ ].join('\n');
package/dist/index.d.ts CHANGED
@@ -5,6 +5,6 @@
5
5
  * npx @almyty/auth login # browser-based login (default)
6
6
  * npx @almyty/auth login --token <T> # paste a token directly
7
7
  * npx @almyty/auth logout
8
- * npx @almyty/auth whoami
8
+ * npx @almyty/auth whoami [--json] [--verify]
9
9
  */
10
10
  export {};
package/dist/index.js CHANGED
@@ -5,14 +5,22 @@
5
5
  * npx @almyty/auth login # browser-based login (default)
6
6
  * npx @almyty/auth login --token <T> # paste a token directly
7
7
  * npx @almyty/auth logout
8
- * npx @almyty/auth whoami
8
+ * npx @almyty/auth whoami [--json] [--verify]
9
9
  */
10
10
  import { browserLogin } from './browser-login.js';
11
- import { CREDENTIALS_FILE, loadCredentials, saveCredentials, clearCredentials, } from './credentials.js';
12
- const VERSION = '0.1.0';
11
+ import { CREDENTIALS_FILE, credentialSummary, expiryState, loadCredentials, saveCredentials, clearCredentials, } from './credentials.js';
12
+ import { CONFIG_FILE, resolveApiUrl, resolveFrontendUrl, saveConfig, } from './config.js';
13
+ import { parseArgs, flagString } from './args.js';
14
+ import { EXIT } from './exit-codes.js';
15
+ import { VERSION } from './version.js';
16
+ /** Flags that are switches, so they never swallow the next token. */
17
+ const BOOLEAN_FLAGS = ['no-browser', 'verify'];
13
18
  function printHelp() {
14
- console.log(`
15
- @almyty/auth v${VERSION}
19
+ console.log(`@almyty/auth v${VERSION}
20
+
21
+ One login for every almyty CLI. The credentials it writes are read by
22
+ @almyty/agents, @almyty/chat, @almyty/skills, @almyty/models,
23
+ @almyty/connections, @almyty/mcp-server and @almyty/runner.
16
24
 
17
25
  Usage:
18
26
  npx @almyty/auth <command> [options]
@@ -20,81 +28,91 @@ Usage:
20
28
  Commands:
21
29
  login Open the browser, log in, store credentials
22
30
  logout Remove stored credentials
23
- whoami Show the currently logged-in identity
31
+ whoami Show the stored identity and when it expires
24
32
  help Show this help
25
33
 
26
34
  Login options:
27
- --token <T> Skip the browser, store this token directly
28
- --frontend <url> Override the frontend origin (default https://app.almyty.com)
29
- --api <url> Override the API origin (default https://api.almyty.com)
30
- --no-browser Print the URL but don't auto-open the browser
35
+ --token <T> Skip the browser, store this token directly (CI)
36
+ --frontend <url> Frontend origin hosting /cli-login (default https://app.almyty.com)
37
+ --api <url> API origin to store alongside the token (default https://api.almyty.com)
38
+ --no-browser Print the login URL instead of opening a browser
39
+
40
+ whoami options:
41
+ --verify Also call the API to confirm the token still works
42
+ --json Machine-readable output, no decoration
43
+
44
+ Global options:
45
+ --json Machine-readable output where the command has any
46
+ --help, -h Show this help
47
+ --version, -v Print the version
31
48
 
32
49
  Environment:
33
- ALMYTY_TOKEN Token override (skips ~/.almyty/credentials.json)
50
+ ALMYTY_TOKEN Token override (read instead of the credentials file)
34
51
  ALMYTY_URL API URL override
35
52
  ALMYTY_FRONTEND_URL Frontend URL override
53
+ NO_COLOR Honoured; these commands emit no ANSI colour anyway
36
54
 
37
- Credentials:
38
- Stored at ${CREDENTIALS_FILE} (mode 0600). All almyty CLIs (skills,
39
- agents, chat, mcp-server) read from this same file.
55
+ Files:
56
+ ${CREDENTIALS_FILE}
57
+ The token, the API URL it belongs to, and its expiry. Written
58
+ mode 0600 in a 0700 directory.
59
+ ${CONFIG_FILE}
60
+ The API and frontend URLs \`login\` was pointed at, so later
61
+ commands do not need the flags again.
62
+
63
+ Exit codes:
64
+ 0 success
65
+ 1 unexpected error
66
+ 2 usage error (bad flags, unknown command)
67
+ 3 not authenticated, or the stored token was rejected
40
68
  `);
41
69
  }
42
- function parseArgs(argv) {
43
- const result = { flags: {} };
44
- let i = 0;
45
- while (i < argv.length) {
46
- const arg = argv[i];
47
- if (arg === '--help' || arg === '-h') {
48
- result.flags.help = true;
49
- }
50
- else if (arg === '--version' || arg === '-v') {
51
- result.flags.version = true;
52
- }
53
- else if (arg === '--no-browser') {
54
- result.flags.noBrowser = true;
55
- }
56
- else if (arg.startsWith('--')) {
57
- const key = arg.slice(2);
58
- const next = argv[i + 1];
59
- if (next && !next.startsWith('--')) {
60
- result.flags[key] = next;
61
- i++;
62
- }
63
- else {
64
- result.flags[key] = true;
65
- }
66
- }
67
- else if (!result.command) {
68
- result.command = arg;
69
- }
70
- i++;
71
- }
72
- return result;
70
+ function emitJson(value) {
71
+ console.log(JSON.stringify(value, null, 2));
73
72
  }
74
73
  async function cmdLogin(args) {
75
- const { resolveApiUrl, resolveFrontendUrl, saveConfig } = require('./config');
76
- const apiUrl = resolveApiUrl(args.flags.api);
77
- const frontendUrl = resolveFrontendUrl(args.flags.frontend);
78
- // Persist URL config so future commands don't need env vars
79
- saveConfig({ apiUrl, frontendUrl });
74
+ // resolveApiUrl refuses a plaintext remote URL, so do it before
75
+ // anything is written to disk. A bad URL is the user's typo, not an
76
+ // internal failure -- exit 2 so a script can tell the two apart
77
+ // instead of seeing the same 1 it gets for a network blip.
78
+ let apiUrl;
79
+ let frontendUrl;
80
+ try {
81
+ apiUrl = resolveApiUrl(flagString(args.flags, 'api'));
82
+ frontendUrl = resolveFrontendUrl(flagString(args.flags, 'frontend'));
83
+ }
84
+ catch (err) {
85
+ console.error(err.message);
86
+ process.exit(EXIT.USAGE);
87
+ }
80
88
  // Direct token paste — skips the browser entirely.
81
- if (typeof args.flags.token === 'string') {
82
- saveCredentials({ url: apiUrl, token: args.flags.token, frontendUrl });
83
- console.error(`✓ Token saved to ${CREDENTIALS_FILE}`);
89
+ const token = flagString(args.flags, 'token');
90
+ if (token !== undefined) {
91
+ if (token.trim().length === 0) {
92
+ console.error('--token needs a value.');
93
+ process.exit(EXIT.USAGE);
94
+ }
95
+ saveCredentials({ url: apiUrl, token, frontendUrl });
96
+ saveConfig({ apiUrl, frontendUrl });
97
+ console.error(`Token saved to ${CREDENTIALS_FILE}`);
84
98
  return;
85
99
  }
86
100
  try {
87
101
  const result = await browserLogin({
88
102
  frontendUrl,
89
- openBrowser: !args.flags.noBrowser,
103
+ openBrowser: args.flags['no-browser'] !== true,
90
104
  });
91
105
  saveCredentials({
92
106
  url: apiUrl,
93
107
  token: result.token,
94
108
  frontendUrl: result.frontendUrl,
95
109
  });
110
+ // Only once the login succeeded. Persisting the URLs first meant a
111
+ // cancelled `login --api <typo>` left the typo behind for every
112
+ // later command to fail against.
113
+ saveConfig({ apiUrl, frontendUrl });
96
114
  console.error('');
97
- console.error(`✓ Logged in. Credentials saved to ${CREDENTIALS_FILE}`);
115
+ console.error(`Logged in. Credentials saved to ${CREDENTIALS_FILE}`);
98
116
  }
99
117
  catch (err) {
100
118
  console.error('');
@@ -103,33 +121,107 @@ async function cmdLogin(args) {
103
121
  console.error('Alternatives:');
104
122
  console.error(' npx @almyty/auth login --token <T> # paste a token directly');
105
123
  console.error(' npx @almyty/auth login --no-browser # show the URL only');
106
- process.exit(1);
124
+ process.exit(EXIT.AUTH);
107
125
  }
108
126
  }
109
- function cmdLogout() {
127
+ function cmdLogout(args) {
110
128
  const removed = clearCredentials();
111
- if (removed) {
112
- console.error('✓ Logged out.');
129
+ if (args.flags.json) {
130
+ emitJson({ removed, credentialsFile: CREDENTIALS_FILE });
131
+ return;
113
132
  }
114
- else {
115
- console.error('No stored credentials.');
133
+ console.error(removed ? 'Logged out.' : 'No stored credentials.');
134
+ }
135
+ /**
136
+ * Ask the API who this token belongs to. Returns the profile, or a
137
+ * reason string when the token is no longer good for anything.
138
+ */
139
+ async function fetchProfile(url, token) {
140
+ let res;
141
+ try {
142
+ res = await fetch(`${url.replace(/\/$/, '')}/auth/profile`, {
143
+ headers: { Authorization: `Bearer ${token}` },
144
+ });
145
+ }
146
+ catch (err) {
147
+ return { ok: false, reason: `could not reach ${url}: ${err.message}` };
148
+ }
149
+ if (res.status === 401 || res.status === 403) {
150
+ return { ok: false, reason: 'the API rejected this token' };
116
151
  }
152
+ if (!res.ok) {
153
+ return { ok: false, reason: `API error ${res.status}` };
154
+ }
155
+ const body = await res.json().catch(() => null);
156
+ const profile = body?.data ?? body ?? {};
157
+ const organizations = Array.isArray(profile.organizationMemberships)
158
+ ? profile.organizationMemberships
159
+ .map((m) => m?.organization?.slug || m?.organization?.name)
160
+ .filter((s) => typeof s === 'string')
161
+ : [];
162
+ return { ok: true, email: profile.email, organizations };
117
163
  }
118
- function cmdWhoami() {
164
+ async function cmdWhoami(args) {
119
165
  const creds = loadCredentials();
120
- if (!creds) {
121
- console.error('Not logged in. Run: npx @almyty/auth login');
122
- process.exit(1);
123
- }
124
- console.log(`API: ${creds.url}`);
125
- if (creds.frontendUrl)
126
- console.log(`Frontend: ${creds.frontendUrl}`);
127
- if (creds.email)
128
- console.log(`Email: ${creds.email}`);
129
- console.log(`Token: ${creds.token.slice(0, 8)}…${creds.token.slice(-4)}`);
166
+ if (!creds?.token) {
167
+ if (args.flags.json) {
168
+ emitJson({ authenticated: false, credentialsFile: CREDENTIALS_FILE });
169
+ }
170
+ else {
171
+ console.error('Not logged in. Run: npx @almyty/auth login');
172
+ }
173
+ process.exit(EXIT.AUTH);
174
+ }
175
+ const summary = credentialSummary(creds);
176
+ const expiry = expiryState(creds);
177
+ let verified;
178
+ if (args.flags.verify) {
179
+ const profile = await fetchProfile(creds.url, creds.token);
180
+ verified = profile.ok
181
+ ? { ok: true, email: profile.email, organizations: profile.organizations }
182
+ : { ok: false, reason: profile.reason };
183
+ }
184
+ if (args.flags.json) {
185
+ emitJson({
186
+ authenticated: true,
187
+ ...summary,
188
+ expiry: expiry.state,
189
+ expiresAt: creds.expiresAt ?? null,
190
+ credentialsFile: CREDENTIALS_FILE,
191
+ ...(verified ? { verified } : {}),
192
+ });
193
+ }
194
+ else {
195
+ console.log(`API: ${summary.url}`);
196
+ if (summary.frontendUrl)
197
+ console.log(`Frontend: ${summary.frontendUrl}`);
198
+ if (verified?.email || summary.email) {
199
+ console.log(`Email: ${verified?.email ?? summary.email}`);
200
+ }
201
+ console.log(`Token: ${summary.tokenPreview}`);
202
+ console.log(`Expiry: ${expiry.message}`);
203
+ if (verified?.organizations?.length) {
204
+ console.log(`Orgs: ${verified.organizations.join(', ')}`);
205
+ }
206
+ if (verified) {
207
+ console.log(verified.ok
208
+ ? 'Verified: the API accepted this token'
209
+ : `Verified: no — ${verified.reason}`);
210
+ }
211
+ }
212
+ // An expired or rejected credential is not a working login, whatever
213
+ // the file says. Reporting success here meant every other CLI's first
214
+ // call was the one that discovered the token was dead.
215
+ if (expiry.state === 'expired' || verified?.ok === false) {
216
+ if (!args.flags.json) {
217
+ console.error('');
218
+ console.error('Run `npx @almyty/auth login` to refresh it.');
219
+ }
220
+ process.exit(EXIT.AUTH);
221
+ }
130
222
  }
131
223
  async function main() {
132
- const args = parseArgs(process.argv.slice(2));
224
+ const args = parseArgs(process.argv.slice(2), BOOLEAN_FLAGS);
133
225
  if (args.flags.version) {
134
226
  console.log(VERSION);
135
227
  return;
@@ -143,18 +235,18 @@ async function main() {
143
235
  await cmdLogin(args);
144
236
  return;
145
237
  case 'logout':
146
- cmdLogout();
238
+ cmdLogout(args);
147
239
  return;
148
240
  case 'whoami':
149
- cmdWhoami();
241
+ await cmdWhoami(args);
150
242
  return;
151
243
  default:
152
244
  console.error(`Unknown command: ${args.command}`);
153
- printHelp();
154
- process.exit(1);
245
+ console.error('Commands: login, logout, whoami. Run --help for detail.');
246
+ process.exit(EXIT.USAGE);
155
247
  }
156
248
  }
157
249
  main().catch((err) => {
158
250
  console.error(`Error: ${err.message}`);
159
- process.exit(1);
251
+ process.exit(EXIT.ERROR);
160
252
  });
@@ -0,0 +1,2 @@
1
+ export declare function readVersion(fallback?: string): string;
2
+ export declare const VERSION: string;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The CLI's own version, read from its package.json at startup.
3
+ *
4
+ * It used to be a hardcoded string, which drifted: `--version`
5
+ * answered 0.1.0 while the published package was 1.2.0, so a bug
6
+ * report never identified the build it came from. Both `dist/index.js`
7
+ * and `src/index.ts` sit one directory below the package root, so the
8
+ * same relative path resolves for the built bin and for `tsx src/index.ts`.
9
+ */
10
+ import { readFileSync } from 'node:fs';
11
+ export function readVersion(fallback = '0.0.0') {
12
+ try {
13
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
14
+ return typeof pkg.version === 'string' && pkg.version.length > 0
15
+ ? pkg.version
16
+ : fallback;
17
+ }
18
+ catch {
19
+ return fallback;
20
+ }
21
+ }
22
+ export const VERSION = readVersion();
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@almyty/auth",
3
- "version": "0.1.2",
4
- "description": "Browser-based login for almyty CLIs (skills, agents, chat, mcp-server)",
3
+ "version": "1.3.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "Browser-based login shared by every almyty CLI. Run it once and agents, chat, skills, and mcp-server all reuse the credentials.",
5
8
  "type": "module",
6
9
  "main": "dist/index.js",
7
10
  "bin": {
@@ -25,11 +28,23 @@
25
28
  "cli"
26
29
  ],
27
30
  "author": "almyty",
28
- "license": "BSL-1.1",
31
+ "license": "Apache-2.0",
29
32
  "devDependencies": {
30
33
  "@types/node": "^25.4.0",
31
34
  "tsx": "^4.7.0",
32
35
  "typescript": "^5.3.0",
33
36
  "vitest": "^4.1.0"
37
+ },
38
+ "homepage": "https://almyty.com",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/almyty-inc/almyty.git",
42
+ "directory": "packages/auth-cli"
43
+ },
44
+ "bugs": {
45
+ "url": "https://github.com/almyty-inc/almyty/issues"
46
+ },
47
+ "overrides": {
48
+ "postcss": "^8.5.23"
34
49
  }
35
50
  }