@almyty/auth 0.1.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 +47 -0
- package/dist/browser-login.d.ts +59 -0
- package/dist/browser-login.js +379 -0
- package/dist/credentials.d.ts +23 -0
- package/dist/credentials.js +58 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +159 -0
- package/package.json +35 -0
package/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# @almyty/auth
|
|
2
|
+
|
|
3
|
+
Browser-based authentication for all almyty CLIs. Credentials are stored at `~/.almyty/credentials.json` (mode 0600) and shared by every almyty package.
|
|
4
|
+
|
|
5
|
+
## Quick start
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
$ npx @almyty/auth login
|
|
9
|
+
$ npx @almyty/auth whoami
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Commands
|
|
13
|
+
|
|
14
|
+
| Command | Description |
|
|
15
|
+
|---------|-------------|
|
|
16
|
+
| `login` | Open browser to authenticate, mint an API key, save credentials |
|
|
17
|
+
| `logout` | Remove stored credentials |
|
|
18
|
+
| `whoami` | Show current identity (API URL, token prefix) |
|
|
19
|
+
|
|
20
|
+
## Login options
|
|
21
|
+
|
|
22
|
+
| Flag | Description |
|
|
23
|
+
|------|-------------|
|
|
24
|
+
| `--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 |
|
|
28
|
+
|
|
29
|
+
## Environment variables
|
|
30
|
+
|
|
31
|
+
| Variable | Description |
|
|
32
|
+
|----------|-------------|
|
|
33
|
+
| `ALMYTY_TOKEN` | Token override; takes precedence over credentials file |
|
|
34
|
+
| `ALMYTY_URL` | API URL override |
|
|
35
|
+
| `ALMYTY_FRONTEND_URL` | Frontend URL override (used when generating the login URL) |
|
|
36
|
+
|
|
37
|
+
## How it works
|
|
38
|
+
|
|
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.
|
|
40
|
+
|
|
41
|
+
## Docs
|
|
42
|
+
|
|
43
|
+
https://almyty.com/docs
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
BSL-1.1
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-based login flow for almyty CLIs (the @almyty/auth package).
|
|
3
|
+
*
|
|
4
|
+
* Inspired by `gh auth login`, `vercel login`, `wrangler login`. Flow:
|
|
5
|
+
*
|
|
6
|
+
* 1. CLI starts a tiny HTTP server bound to 127.0.0.1 on a random port.
|
|
7
|
+
* 2. CLI generates a high-entropy `state` nonce.
|
|
8
|
+
* 3. CLI opens the user's browser to:
|
|
9
|
+
* {frontendUrl}/cli-login?callback=http://127.0.0.1:PORT/cb&state=STATE
|
|
10
|
+
* 4. The frontend page authenticates the user (existing session OR
|
|
11
|
+
* normal login) and POSTs the user's JWT back to the callback URL
|
|
12
|
+
* with the matching state.
|
|
13
|
+
* 5. The local server validates the state, hands the token to the CLI,
|
|
14
|
+
* shows a success page, and shuts down.
|
|
15
|
+
*
|
|
16
|
+
* Security notes:
|
|
17
|
+
* - The local server only listens on 127.0.0.1 (loopback), so other hosts
|
|
18
|
+
* on the network can never reach it.
|
|
19
|
+
* - The state nonce is verified server-side (in this CLI process), giving
|
|
20
|
+
* us CSRF protection against drive-by callbacks.
|
|
21
|
+
* - We accept ONLY POST for the token submission; GET is reserved for the
|
|
22
|
+
* browser landing page.
|
|
23
|
+
* - The token never appears in a URL — it travels in the POST body so it
|
|
24
|
+
* doesn't get logged in the browser's history or any reverse proxies.
|
|
25
|
+
*
|
|
26
|
+
* Frontend contract (must exist at {frontendUrl}/cli-login):
|
|
27
|
+
*
|
|
28
|
+
* On page load, parse `?callback=...&state=...` from the query string.
|
|
29
|
+
* Validate `callback` starts with `http://127.0.0.1:` and `state` is
|
|
30
|
+
* present. After the user authenticates (or is already logged in),
|
|
31
|
+
* POST { token, state } to the callback URL with Content-Type
|
|
32
|
+
* application/json.
|
|
33
|
+
*/
|
|
34
|
+
export interface BrowserLoginResult {
|
|
35
|
+
token: string;
|
|
36
|
+
frontendUrl: string;
|
|
37
|
+
}
|
|
38
|
+
export interface BrowserLoginOptions {
|
|
39
|
+
/**
|
|
40
|
+
* Frontend origin that hosts the /cli-login page.
|
|
41
|
+
* Defaults to https://app.almyty.com.
|
|
42
|
+
*/
|
|
43
|
+
frontendUrl?: string;
|
|
44
|
+
/**
|
|
45
|
+
* How long to wait for the user to complete the flow before giving up.
|
|
46
|
+
* Defaults to 5 minutes.
|
|
47
|
+
*/
|
|
48
|
+
timeoutMs?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Optional logger; defaults to console.error so we don't pollute stdout.
|
|
51
|
+
*/
|
|
52
|
+
log?: (msg: string) => void;
|
|
53
|
+
/**
|
|
54
|
+
* Whether to actually open the browser. Defaults to true. Useful to
|
|
55
|
+
* disable in tests.
|
|
56
|
+
*/
|
|
57
|
+
openBrowser?: boolean;
|
|
58
|
+
}
|
|
59
|
+
export declare function browserLogin(options?: BrowserLoginOptions): Promise<BrowserLoginResult>;
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-based login flow for almyty CLIs (the @almyty/auth package).
|
|
3
|
+
*
|
|
4
|
+
* Inspired by `gh auth login`, `vercel login`, `wrangler login`. Flow:
|
|
5
|
+
*
|
|
6
|
+
* 1. CLI starts a tiny HTTP server bound to 127.0.0.1 on a random port.
|
|
7
|
+
* 2. CLI generates a high-entropy `state` nonce.
|
|
8
|
+
* 3. CLI opens the user's browser to:
|
|
9
|
+
* {frontendUrl}/cli-login?callback=http://127.0.0.1:PORT/cb&state=STATE
|
|
10
|
+
* 4. The frontend page authenticates the user (existing session OR
|
|
11
|
+
* normal login) and POSTs the user's JWT back to the callback URL
|
|
12
|
+
* with the matching state.
|
|
13
|
+
* 5. The local server validates the state, hands the token to the CLI,
|
|
14
|
+
* shows a success page, and shuts down.
|
|
15
|
+
*
|
|
16
|
+
* Security notes:
|
|
17
|
+
* - The local server only listens on 127.0.0.1 (loopback), so other hosts
|
|
18
|
+
* on the network can never reach it.
|
|
19
|
+
* - The state nonce is verified server-side (in this CLI process), giving
|
|
20
|
+
* us CSRF protection against drive-by callbacks.
|
|
21
|
+
* - We accept ONLY POST for the token submission; GET is reserved for the
|
|
22
|
+
* browser landing page.
|
|
23
|
+
* - The token never appears in a URL — it travels in the POST body so it
|
|
24
|
+
* doesn't get logged in the browser's history or any reverse proxies.
|
|
25
|
+
*
|
|
26
|
+
* Frontend contract (must exist at {frontendUrl}/cli-login):
|
|
27
|
+
*
|
|
28
|
+
* On page load, parse `?callback=...&state=...` from the query string.
|
|
29
|
+
* Validate `callback` starts with `http://127.0.0.1:` and `state` is
|
|
30
|
+
* present. After the user authenticates (or is already logged in),
|
|
31
|
+
* POST { token, state } to the callback URL with Content-Type
|
|
32
|
+
* application/json.
|
|
33
|
+
*/
|
|
34
|
+
import { createServer } from 'http';
|
|
35
|
+
import { randomBytes } from 'crypto';
|
|
36
|
+
import { spawn } from 'child_process';
|
|
37
|
+
const SUCCESS_PAGE = `<!doctype html>
|
|
38
|
+
<html lang="en">
|
|
39
|
+
<head>
|
|
40
|
+
<meta charset="utf-8">
|
|
41
|
+
<title>almyty — login complete</title>
|
|
42
|
+
<style>
|
|
43
|
+
body { font-family: system-ui, -apple-system, sans-serif; background: #09090b; color: #fafafa; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
|
|
44
|
+
.card { text-align: center; padding: 2rem 3rem; border: 1px solid #27272a; border-radius: 8px; background: #18181b; }
|
|
45
|
+
h1 { color: #8b5cf6; margin: 0 0 0.5rem; font-weight: 600; }
|
|
46
|
+
p { margin: 0.5rem 0; color: #a1a1aa; }
|
|
47
|
+
</style>
|
|
48
|
+
</head>
|
|
49
|
+
<body>
|
|
50
|
+
<div class="card">
|
|
51
|
+
<h1>✓ Logged in</h1>
|
|
52
|
+
<p>You can close this tab and return to your terminal.</p>
|
|
53
|
+
</div>
|
|
54
|
+
</body>
|
|
55
|
+
</html>`;
|
|
56
|
+
function openInBrowser(url, log) {
|
|
57
|
+
const platform = process.platform;
|
|
58
|
+
let cmd;
|
|
59
|
+
let args;
|
|
60
|
+
if (platform === 'darwin') {
|
|
61
|
+
cmd = 'open';
|
|
62
|
+
args = [url];
|
|
63
|
+
}
|
|
64
|
+
else if (platform === 'win32') {
|
|
65
|
+
cmd = 'cmd';
|
|
66
|
+
args = ['/c', 'start', '""', url];
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
cmd = 'xdg-open';
|
|
70
|
+
args = [url];
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
74
|
+
child.on('error', () => {
|
|
75
|
+
log(`Could not open browser automatically. Please visit:\n ${url}`);
|
|
76
|
+
});
|
|
77
|
+
child.unref();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
log(`Could not open browser automatically. Please visit:\n ${url}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function readRequestBody(req, maxBytes = 64 * 1024) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const chunks = [];
|
|
86
|
+
let total = 0;
|
|
87
|
+
req.on('data', (chunk) => {
|
|
88
|
+
total += chunk.length;
|
|
89
|
+
if (total > maxBytes) {
|
|
90
|
+
reject(new Error('Request body too large'));
|
|
91
|
+
req.destroy();
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
chunks.push(chunk);
|
|
95
|
+
});
|
|
96
|
+
req.on('end', () => {
|
|
97
|
+
try {
|
|
98
|
+
const raw = Buffer.concat(chunks).toString('utf-8');
|
|
99
|
+
if (!raw) {
|
|
100
|
+
resolve({});
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
// Parse based on Content-Type. The frontend posts a hidden
|
|
104
|
+
// form (application/x-www-form-urlencoded) to sidestep
|
|
105
|
+
// Chrome's Private Network Access blocking of fetch/XHR to
|
|
106
|
+
// loopback; older clients / curl-based smoke tests may still
|
|
107
|
+
// send JSON. Accept both.
|
|
108
|
+
const contentType = (req.headers['content-type'] || '').toLowerCase();
|
|
109
|
+
if (contentType.startsWith('application/x-www-form-urlencoded')) {
|
|
110
|
+
const params = new URLSearchParams(raw);
|
|
111
|
+
const obj = {};
|
|
112
|
+
params.forEach((value, key) => { obj[key] = value; });
|
|
113
|
+
resolve(obj);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
// Default to JSON.
|
|
117
|
+
resolve(JSON.parse(raw));
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
reject(err);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
req.on('error', reject);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
export function browserLogin(options = {}) {
|
|
127
|
+
const frontendUrl = (options.frontendUrl || 'https://app.almyty.com').replace(/\/$/, '');
|
|
128
|
+
const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;
|
|
129
|
+
const log = options.log ?? ((m) => process.stderr.write(m + '\n'));
|
|
130
|
+
const shouldOpen = options.openBrowser ?? true;
|
|
131
|
+
const state = randomBytes(32).toString('hex');
|
|
132
|
+
return new Promise((resolve, reject) => {
|
|
133
|
+
let settled = false;
|
|
134
|
+
const settleResolve = (value) => {
|
|
135
|
+
if (settled)
|
|
136
|
+
return;
|
|
137
|
+
settled = true;
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
server.close();
|
|
140
|
+
resolve(value);
|
|
141
|
+
};
|
|
142
|
+
const settleReject = (err) => {
|
|
143
|
+
if (settled)
|
|
144
|
+
return;
|
|
145
|
+
settled = true;
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
server.close();
|
|
148
|
+
reject(err);
|
|
149
|
+
};
|
|
150
|
+
const debug = process.env.ALMYTY_LOGIN_DEBUG === '1';
|
|
151
|
+
const server = createServer(async (req, res) => {
|
|
152
|
+
if (debug) {
|
|
153
|
+
log(`[debug] ${req.method} ${req.url} origin=${req.headers.origin || '-'} ct=${req.headers['content-type'] || '-'}`);
|
|
154
|
+
}
|
|
155
|
+
// CORS for the frontend POST.
|
|
156
|
+
//
|
|
157
|
+
// Critical: modern Chromium blocks fetches from a public HTTPS
|
|
158
|
+
// origin (app.almyty.com) to a loopback address (127.0.0.1)
|
|
159
|
+
// under the Private Network Access (PNA) policy unless the
|
|
160
|
+
// server explicitly opts in. The browser sends
|
|
161
|
+
// `Access-Control-Request-Private-Network: true` on the preflight
|
|
162
|
+
// and expects `Access-Control-Allow-Private-Network: true` in the
|
|
163
|
+
// response. Without this header, Chrome reports:
|
|
164
|
+
// "Permission was denied for this request to access the
|
|
165
|
+
// `loopback` address space"
|
|
166
|
+
// and the login flow silently times out. Spec:
|
|
167
|
+
// https://wicg.github.io/private-network-access/
|
|
168
|
+
if (req.method === 'OPTIONS') {
|
|
169
|
+
const pnaRequested = req.headers['access-control-request-private-network']?.toLowerCase() === 'true';
|
|
170
|
+
const headers = {
|
|
171
|
+
'Access-Control-Allow-Origin': frontendUrl,
|
|
172
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
173
|
+
'Access-Control-Allow-Headers': 'Content-Type',
|
|
174
|
+
'Access-Control-Max-Age': '600',
|
|
175
|
+
};
|
|
176
|
+
if (pnaRequested) {
|
|
177
|
+
headers['Access-Control-Allow-Private-Network'] = 'true';
|
|
178
|
+
}
|
|
179
|
+
res.writeHead(204, headers);
|
|
180
|
+
res.end();
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const url = req.url || '/';
|
|
184
|
+
// GET / — health check / "you found the local server" page.
|
|
185
|
+
if (req.method === 'GET' && url === '/') {
|
|
186
|
+
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
187
|
+
res.end('almyty CLI login server. Waiting for callback…\n');
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
// GET /cb — token landing page. The frontend redirects the
|
|
191
|
+
// top window here with token+state in the URL fragment
|
|
192
|
+
// (`#token=…&state=…`). Fragments are never transmitted over
|
|
193
|
+
// HTTP, so this page receives an empty URL from the server's
|
|
194
|
+
// perspective. It serves a tiny HTML document whose inline
|
|
195
|
+
// script reads the hash client-side and POSTs the data to
|
|
196
|
+
// /cb-complete as a same-origin fetch (which Chrome's
|
|
197
|
+
// Private Network Access policy does NOT block, because
|
|
198
|
+
// both sides are loopback).
|
|
199
|
+
//
|
|
200
|
+
// This two-step dance is necessary because:
|
|
201
|
+
// - fetch/XHR from HTTPS → loopback is blocked by PNA
|
|
202
|
+
// - hidden-iframe form POST from HTTPS → loopback is
|
|
203
|
+
// silently dropped (server never sees it)
|
|
204
|
+
// - top-window navigation from HTTPS → loopback works
|
|
205
|
+
// - same-origin fetch within loopback works
|
|
206
|
+
if (req.method === 'GET' && url.startsWith('/cb')) {
|
|
207
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
208
|
+
res.end(`<!doctype html>
|
|
209
|
+
<html lang="en">
|
|
210
|
+
<head>
|
|
211
|
+
<meta charset="utf-8">
|
|
212
|
+
<title>almyty — finishing login</title>
|
|
213
|
+
<style>
|
|
214
|
+
body { font-family: system-ui, -apple-system, sans-serif; background: #09090b; color: #fafafa; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
|
|
215
|
+
.card { text-align: center; padding: 2rem 3rem; border: 1px solid #27272a; border-radius: 8px; background: #18181b; max-width: 32rem; }
|
|
216
|
+
h1 { color: #8b5cf6; margin: 0 0 0.5rem; font-weight: 600; font-size: 1.25rem; }
|
|
217
|
+
p { margin: 0.5rem 0; color: #a1a1aa; font-size: 0.875rem; }
|
|
218
|
+
.err { color: #fb7185; }
|
|
219
|
+
</style>
|
|
220
|
+
</head>
|
|
221
|
+
<body>
|
|
222
|
+
<div class="card">
|
|
223
|
+
<h1 id="t">Finishing login…</h1>
|
|
224
|
+
<p id="m">You can close this tab in a moment.</p>
|
|
225
|
+
</div>
|
|
226
|
+
<script>
|
|
227
|
+
(function () {
|
|
228
|
+
var hash = window.location.hash.replace(/^#/, '');
|
|
229
|
+
if (!hash) {
|
|
230
|
+
document.getElementById('t').textContent = 'Login failed';
|
|
231
|
+
document.getElementById('t').className = 'err';
|
|
232
|
+
document.getElementById('m').textContent = 'No credentials were delivered. Return to your terminal and retry.';
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
var params = new URLSearchParams(hash);
|
|
236
|
+
var token = params.get('token');
|
|
237
|
+
var state = params.get('state');
|
|
238
|
+
if (!token || !state) {
|
|
239
|
+
document.getElementById('t').textContent = 'Login failed';
|
|
240
|
+
document.getElementById('t').className = 'err';
|
|
241
|
+
document.getElementById('m').textContent = 'Malformed credentials. Return to your terminal and retry.';
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
// Wipe the fragment out of the URL bar so browsers don't
|
|
245
|
+
// retain the raw token in history even briefly.
|
|
246
|
+
try { history.replaceState({}, '', '/cb'); } catch (_) { /* ignore */ }
|
|
247
|
+
fetch('/cb-complete', {
|
|
248
|
+
method: 'POST',
|
|
249
|
+
headers: { 'Content-Type': 'application/json' },
|
|
250
|
+
body: JSON.stringify({ token: token, state: state }),
|
|
251
|
+
}).then(function (r) {
|
|
252
|
+
if (!r.ok) return r.text().then(function (t) { throw new Error(t || ('HTTP ' + r.status)); });
|
|
253
|
+
window.location.href = '/success';
|
|
254
|
+
}).catch(function (err) {
|
|
255
|
+
document.getElementById('t').textContent = 'Login failed';
|
|
256
|
+
document.getElementById('t').className = 'err';
|
|
257
|
+
document.getElementById('m').textContent = String(err && err.message || err);
|
|
258
|
+
});
|
|
259
|
+
})();
|
|
260
|
+
</script>
|
|
261
|
+
</body>
|
|
262
|
+
</html>`);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
// POST /cb-complete — same-origin delivery from /cb's inline
|
|
266
|
+
// script. This is the only path that actually accepts a token.
|
|
267
|
+
// Kept as a separate endpoint so we can reject stray POSTs to
|
|
268
|
+
// /cb with a clear 405 if anything probes it.
|
|
269
|
+
if (req.method === 'POST' && url.startsWith('/cb-complete')) {
|
|
270
|
+
try {
|
|
271
|
+
const body = await readRequestBody(req);
|
|
272
|
+
if (debug) {
|
|
273
|
+
const keys = Object.keys(body).join(',');
|
|
274
|
+
const stateMatch = body.state === state;
|
|
275
|
+
const tokenPresent = typeof body.token === 'string';
|
|
276
|
+
log(`[debug] POST /cb-complete keys=${keys} stateMatch=${stateMatch} tokenPresent=${tokenPresent}`);
|
|
277
|
+
}
|
|
278
|
+
if (!body.state || body.state !== state) {
|
|
279
|
+
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
280
|
+
res.end('Invalid state');
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (!body.token || typeof body.token !== 'string') {
|
|
284
|
+
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
285
|
+
res.end('Missing token');
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
289
|
+
res.end(JSON.stringify({ ok: true }));
|
|
290
|
+
settleResolve({ token: body.token, frontendUrl });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
catch (err) {
|
|
294
|
+
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
295
|
+
res.end(`Bad request: ${err.message}`);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
// POST /cb — legacy JSON/form delivery path (used by curl
|
|
300
|
+
// smoke tests and any non-browser client that doesn't need
|
|
301
|
+
// the PNA workaround). Kept for backwards compatibility with
|
|
302
|
+
// auth flows that don't involve a browser hash redirect.
|
|
303
|
+
if (req.method === 'POST' && url.startsWith('/cb')) {
|
|
304
|
+
try {
|
|
305
|
+
const body = await readRequestBody(req);
|
|
306
|
+
if (debug) {
|
|
307
|
+
const keys = Object.keys(body).join(',');
|
|
308
|
+
const stateMatch = body.state === state;
|
|
309
|
+
const tokenPresent = typeof body.token === 'string';
|
|
310
|
+
log(`[debug] POST /cb (legacy) keys=${keys} stateMatch=${stateMatch} tokenPresent=${tokenPresent}`);
|
|
311
|
+
}
|
|
312
|
+
if (!body.state || body.state !== state) {
|
|
313
|
+
res.writeHead(400, {
|
|
314
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
315
|
+
'Access-Control-Allow-Origin': frontendUrl,
|
|
316
|
+
});
|
|
317
|
+
res.end('Invalid state');
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (!body.token || typeof body.token !== 'string') {
|
|
321
|
+
res.writeHead(400, {
|
|
322
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
323
|
+
'Access-Control-Allow-Origin': frontendUrl,
|
|
324
|
+
});
|
|
325
|
+
res.end('Missing token');
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
res.writeHead(200, {
|
|
329
|
+
'Content-Type': 'application/json',
|
|
330
|
+
'Access-Control-Allow-Origin': frontendUrl,
|
|
331
|
+
});
|
|
332
|
+
res.end(JSON.stringify({ ok: true }));
|
|
333
|
+
settleResolve({ token: body.token, frontendUrl });
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
catch (err) {
|
|
337
|
+
res.writeHead(400, {
|
|
338
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
339
|
+
'Access-Control-Allow-Origin': frontendUrl,
|
|
340
|
+
});
|
|
341
|
+
res.end(`Bad request: ${err.message}`);
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
// GET /success — landing page after successful POST (the frontend
|
|
346
|
+
// can redirect here so the user sees a friendly confirmation in
|
|
347
|
+
// their browser).
|
|
348
|
+
if (req.method === 'GET' && url.startsWith('/success')) {
|
|
349
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
350
|
+
res.end(SUCCESS_PAGE);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
354
|
+
res.end('Not found');
|
|
355
|
+
});
|
|
356
|
+
server.on('error', (err) => settleReject(err));
|
|
357
|
+
const timer = setTimeout(() => {
|
|
358
|
+
settleReject(new Error(`Login timed out after ${Math.round(timeoutMs / 1000)}s`));
|
|
359
|
+
}, timeoutMs);
|
|
360
|
+
server.listen(0, '127.0.0.1', () => {
|
|
361
|
+
const address = server.address();
|
|
362
|
+
const port = address.port;
|
|
363
|
+
const callbackUrl = `http://127.0.0.1:${port}/cb`;
|
|
364
|
+
const successUrl = `http://127.0.0.1:${port}/success`;
|
|
365
|
+
const loginUrl = `${frontendUrl}/cli-login?callback=${encodeURIComponent(callbackUrl)}` +
|
|
366
|
+
`&success=${encodeURIComponent(successUrl)}&state=${state}`;
|
|
367
|
+
log('');
|
|
368
|
+
log(' almyty login');
|
|
369
|
+
log(` Open your browser to authenticate (auto-opening if available):`);
|
|
370
|
+
log(` ${loginUrl}`);
|
|
371
|
+
log('');
|
|
372
|
+
log(' Waiting for you to complete login in your browser…');
|
|
373
|
+
log(' (Press Ctrl+C to cancel.)');
|
|
374
|
+
if (shouldOpen) {
|
|
375
|
+
openInBrowser(loginUrl, log);
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared credentials store at ~/.almyty/credentials.json.
|
|
3
|
+
*
|
|
4
|
+
* Every almyty CLI (skills, agents, chat, mcp-server) reads from this same
|
|
5
|
+
* file. The file is owner-readable only (mode 0600).
|
|
6
|
+
*/
|
|
7
|
+
export declare const CREDENTIALS_DIR: string;
|
|
8
|
+
export declare const CREDENTIALS_FILE: string;
|
|
9
|
+
export interface StoredCredentials {
|
|
10
|
+
url: string;
|
|
11
|
+
token: string;
|
|
12
|
+
email?: string;
|
|
13
|
+
expiresAt?: string;
|
|
14
|
+
frontendUrl?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function loadCredentials(): StoredCredentials | null;
|
|
17
|
+
export declare function saveCredentials(creds: StoredCredentials): void;
|
|
18
|
+
export declare function clearCredentials(): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the active credentials, preferring environment variables.
|
|
21
|
+
* Returns null when no credentials are available.
|
|
22
|
+
*/
|
|
23
|
+
export declare function resolveCredentials(): StoredCredentials | null;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared credentials store at ~/.almyty/credentials.json.
|
|
3
|
+
*
|
|
4
|
+
* Every almyty CLI (skills, agents, chat, mcp-server) reads from this same
|
|
5
|
+
* file. The file is owner-readable only (mode 0600).
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync, writeFileSync, mkdirSync, unlinkSync, existsSync, chmodSync } from 'fs';
|
|
8
|
+
import { homedir } from 'os';
|
|
9
|
+
import { join } from 'path';
|
|
10
|
+
export const CREDENTIALS_DIR = join(homedir(), '.almyty');
|
|
11
|
+
export const CREDENTIALS_FILE = join(CREDENTIALS_DIR, 'credentials.json');
|
|
12
|
+
export function loadCredentials() {
|
|
13
|
+
try {
|
|
14
|
+
if (!existsSync(CREDENTIALS_FILE))
|
|
15
|
+
return null;
|
|
16
|
+
const data = readFileSync(CREDENTIALS_FILE, 'utf-8');
|
|
17
|
+
return JSON.parse(data);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
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.
|
|
29
|
+
try {
|
|
30
|
+
chmodSync(CREDENTIALS_FILE, 0o600);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// Best-effort on platforms (Windows) where chmod may not apply.
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function clearCredentials() {
|
|
37
|
+
if (!existsSync(CREDENTIALS_FILE))
|
|
38
|
+
return false;
|
|
39
|
+
try {
|
|
40
|
+
unlinkSync(CREDENTIALS_FILE);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Resolve the active credentials, preferring environment variables.
|
|
49
|
+
* Returns null when no credentials are available.
|
|
50
|
+
*/
|
|
51
|
+
export function resolveCredentials() {
|
|
52
|
+
const envToken = process.env.ALMYTY_TOKEN;
|
|
53
|
+
const envUrl = process.env.ALMYTY_URL || 'https://api.almyty.com';
|
|
54
|
+
if (envToken) {
|
|
55
|
+
return { url: envUrl, token: envToken };
|
|
56
|
+
}
|
|
57
|
+
return loadCredentials();
|
|
58
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @almyty/auth — login / logout / whoami for almyty CLIs.
|
|
4
|
+
*
|
|
5
|
+
* npx @almyty/auth login # browser-based login (default)
|
|
6
|
+
* npx @almyty/auth login --token <T> # paste a token directly
|
|
7
|
+
* npx @almyty/auth logout
|
|
8
|
+
* npx @almyty/auth whoami
|
|
9
|
+
*/
|
|
10
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @almyty/auth — login / logout / whoami for almyty CLIs.
|
|
4
|
+
*
|
|
5
|
+
* npx @almyty/auth login # browser-based login (default)
|
|
6
|
+
* npx @almyty/auth login --token <T> # paste a token directly
|
|
7
|
+
* npx @almyty/auth logout
|
|
8
|
+
* npx @almyty/auth whoami
|
|
9
|
+
*/
|
|
10
|
+
import { browserLogin } from './browser-login.js';
|
|
11
|
+
import { CREDENTIALS_FILE, loadCredentials, saveCredentials, clearCredentials, } from './credentials.js';
|
|
12
|
+
const VERSION = '0.1.0';
|
|
13
|
+
function printHelp() {
|
|
14
|
+
console.log(`
|
|
15
|
+
@almyty/auth v${VERSION}
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
npx @almyty/auth <command> [options]
|
|
19
|
+
|
|
20
|
+
Commands:
|
|
21
|
+
login Open the browser, log in, store credentials
|
|
22
|
+
logout Remove stored credentials
|
|
23
|
+
whoami Show the currently logged-in identity
|
|
24
|
+
help Show this help
|
|
25
|
+
|
|
26
|
+
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
|
|
31
|
+
|
|
32
|
+
Environment:
|
|
33
|
+
ALMYTY_TOKEN Token override (skips ~/.almyty/credentials.json)
|
|
34
|
+
ALMYTY_URL API URL override
|
|
35
|
+
ALMYTY_FRONTEND_URL Frontend URL override
|
|
36
|
+
|
|
37
|
+
Credentials:
|
|
38
|
+
Stored at ${CREDENTIALS_FILE} (mode 0600). All almyty CLIs (skills,
|
|
39
|
+
agents, chat, mcp-server) read from this same file.
|
|
40
|
+
`);
|
|
41
|
+
}
|
|
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;
|
|
73
|
+
}
|
|
74
|
+
async function cmdLogin(args) {
|
|
75
|
+
const apiUrl = args.flags.api || process.env.ALMYTY_URL || 'https://api.almyty.com';
|
|
76
|
+
const frontendUrl = args.flags.frontend ||
|
|
77
|
+
process.env.ALMYTY_FRONTEND_URL ||
|
|
78
|
+
'https://app.almyty.com';
|
|
79
|
+
// Direct token paste — skips the browser entirely.
|
|
80
|
+
if (typeof args.flags.token === 'string') {
|
|
81
|
+
saveCredentials({ url: apiUrl, token: args.flags.token, frontendUrl });
|
|
82
|
+
console.error(`✓ Token saved to ${CREDENTIALS_FILE}`);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const result = await browserLogin({
|
|
87
|
+
frontendUrl,
|
|
88
|
+
openBrowser: !args.flags.noBrowser,
|
|
89
|
+
});
|
|
90
|
+
saveCredentials({
|
|
91
|
+
url: apiUrl,
|
|
92
|
+
token: result.token,
|
|
93
|
+
frontendUrl: result.frontendUrl,
|
|
94
|
+
});
|
|
95
|
+
console.error('');
|
|
96
|
+
console.error(`✓ Logged in. Credentials saved to ${CREDENTIALS_FILE}`);
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
console.error('');
|
|
100
|
+
console.error(`Login failed: ${err.message}`);
|
|
101
|
+
console.error('');
|
|
102
|
+
console.error('Alternatives:');
|
|
103
|
+
console.error(' npx @almyty/auth login --token <T> # paste a token directly');
|
|
104
|
+
console.error(' npx @almyty/auth login --no-browser # show the URL only');
|
|
105
|
+
process.exit(1);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function cmdLogout() {
|
|
109
|
+
const removed = clearCredentials();
|
|
110
|
+
if (removed) {
|
|
111
|
+
console.error('✓ Logged out.');
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
console.error('No stored credentials.');
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function cmdWhoami() {
|
|
118
|
+
const creds = loadCredentials();
|
|
119
|
+
if (!creds) {
|
|
120
|
+
console.error('Not logged in. Run: npx @almyty/auth login');
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
console.log(`API: ${creds.url}`);
|
|
124
|
+
if (creds.frontendUrl)
|
|
125
|
+
console.log(`Frontend: ${creds.frontendUrl}`);
|
|
126
|
+
if (creds.email)
|
|
127
|
+
console.log(`Email: ${creds.email}`);
|
|
128
|
+
console.log(`Token: ${creds.token.slice(0, 8)}…${creds.token.slice(-4)}`);
|
|
129
|
+
}
|
|
130
|
+
async function main() {
|
|
131
|
+
const args = parseArgs(process.argv.slice(2));
|
|
132
|
+
if (args.flags.version) {
|
|
133
|
+
console.log(VERSION);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (args.flags.help || !args.command || args.command === 'help') {
|
|
137
|
+
printHelp();
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
switch (args.command) {
|
|
141
|
+
case 'login':
|
|
142
|
+
await cmdLogin(args);
|
|
143
|
+
return;
|
|
144
|
+
case 'logout':
|
|
145
|
+
cmdLogout();
|
|
146
|
+
return;
|
|
147
|
+
case 'whoami':
|
|
148
|
+
cmdWhoami();
|
|
149
|
+
return;
|
|
150
|
+
default:
|
|
151
|
+
console.error(`Unknown command: ${args.command}`);
|
|
152
|
+
printHelp();
|
|
153
|
+
process.exit(1);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
main().catch((err) => {
|
|
157
|
+
console.error(`Error: ${err.message}`);
|
|
158
|
+
process.exit(1);
|
|
159
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@almyty/auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Browser-based login for almyty CLIs (skills, agents, chat, mcp-server)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"almyty-auth": "dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"build": "tsc",
|
|
15
|
+
"dev": "tsx src/index.ts",
|
|
16
|
+
"test": "vitest run",
|
|
17
|
+
"test:watch": "vitest",
|
|
18
|
+
"prepublishOnly": "npm run build"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"almyty",
|
|
22
|
+
"auth",
|
|
23
|
+
"login",
|
|
24
|
+
"oauth",
|
|
25
|
+
"cli"
|
|
26
|
+
],
|
|
27
|
+
"author": "almyty",
|
|
28
|
+
"license": "BSL-1.1",
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^25.4.0",
|
|
31
|
+
"tsx": "^4.7.0",
|
|
32
|
+
"typescript": "^5.3.0",
|
|
33
|
+
"vitest": "^4.1.0"
|
|
34
|
+
}
|
|
35
|
+
}
|