@keysentry/cli 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.md +93 -2
- package/bin/keysentry.mjs +338 -0
- package/lib/sso.mjs +337 -0
- package/package.json +26 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 KeySentry AI LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# KeySentry CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Vault credentials, scan for exposed keys, and sign in to the KeySentry Gateway from your terminal.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @keysentry/cli
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
# Authenticate
|
|
15
|
+
keysentry login
|
|
16
|
+
|
|
17
|
+
# Vault a credential (interactive)
|
|
18
|
+
keysentry vault
|
|
19
|
+
|
|
20
|
+
# Vault with flags
|
|
21
|
+
keysentry vault --key="sk-ant-..." --name="prod-anthropic" --env=production --rotate=90
|
|
22
|
+
|
|
23
|
+
# Pipe from environment
|
|
24
|
+
echo $OPENAI_API_KEY | keysentry vault --name="openai-prod"
|
|
25
|
+
|
|
26
|
+
# Scan text for exposed credentials
|
|
27
|
+
cat .env | keysentry scan
|
|
28
|
+
|
|
29
|
+
# Scan clipboard (macOS)
|
|
30
|
+
pbpaste | keysentry scan
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Commands
|
|
34
|
+
|
|
35
|
+
| Command | Description |
|
|
36
|
+
|---------|-------------|
|
|
37
|
+
| `login` | Authenticate with your KeySentry API key |
|
|
38
|
+
| `vault` | Save a credential to your encrypted vault |
|
|
39
|
+
| `scan` | Scan text for exposed credentials (30 patterns) |
|
|
40
|
+
| `status` | Show connection status |
|
|
41
|
+
| `token` | Print a short-lived Gateway sign-in token (Claude Code `apiKeyHelper`) |
|
|
42
|
+
| `help` | Show help |
|
|
43
|
+
|
|
44
|
+
## Gateway sign-in for Claude Code (`keysentry token`)
|
|
45
|
+
|
|
46
|
+
Developers sign in once with their work Microsoft account. After that,
|
|
47
|
+
`keysentry token` prints a short-lived Microsoft Entra ID token that the
|
|
48
|
+
KeySentry Gateway accepts, renewing it quietly in the background. No shared
|
|
49
|
+
API key is handed out.
|
|
50
|
+
|
|
51
|
+
Your IT team deploys this in Claude Code managed settings:
|
|
52
|
+
|
|
53
|
+
```json
|
|
54
|
+
{
|
|
55
|
+
"env": { "ANTHROPIC_BASE_URL": "https://gateway.getkeysentry.com" },
|
|
56
|
+
"apiKeyHelper": "keysentry token --tenant <tenant-id> --client <client-id>"
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`<tenant-id>` and `<client-id>` are the Directory (tenant) ID and the
|
|
61
|
+
Application (client) ID on the Overview page of your company's Entra app.
|
|
62
|
+
|
|
63
|
+
First run: sign in once in a terminal before starting Claude Code. Claude
|
|
64
|
+
Code does not wait for a browser sign-in, so when no sign-in is saved the
|
|
65
|
+
helper stops right away and tells you this command:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
keysentry token --tenant <tenant-id> --client <client-id> --info
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| Option | What it does |
|
|
72
|
+
|--------|--------------|
|
|
73
|
+
| `--tenant <id>` | Directory (tenant) ID (required) |
|
|
74
|
+
| `--client <id>` | Application (client) ID (required) |
|
|
75
|
+
| `--info` | Shows who is signed in and how long the token lasts; prints no token |
|
|
76
|
+
| `--logout` | Removes the saved sign-in from this computer |
|
|
77
|
+
|
|
78
|
+
Where the sign-in is kept: the macOS Keychain on a Mac; elsewhere
|
|
79
|
+
`~/.keysentry/sso/`, readable only by you. The command prints nothing but the
|
|
80
|
+
token on standard output; messages go to standard error.
|
|
81
|
+
|
|
82
|
+
## Auto-Detection
|
|
83
|
+
|
|
84
|
+
Paste any credential and KeySentry automatically detects the platform, type, and suggests rotation:
|
|
85
|
+
|
|
86
|
+
- OpenAI (`sk-proj-`, `sk-`)
|
|
87
|
+
- Anthropic (`sk-ant-`)
|
|
88
|
+
- Google AI (`AIza`)
|
|
89
|
+
- AWS (`AKIA`)
|
|
90
|
+
- GitHub (`ghp_`, `gho_`, `ghs_`)
|
|
91
|
+
- Grok/xAI (`xai-`)
|
|
92
|
+
- Slack (`xoxb-`, `xoxp-`)
|
|
93
|
+
- Stripe (`sk_live_`, `sk_test_`)
|
|
94
|
+
- And 20+ more patterns
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createInterface } from "readline";
|
|
3
|
+
import { homedir } from "os";
|
|
4
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from "fs";
|
|
5
|
+
import { join } from "path";
|
|
6
|
+
import { tokenCommand } from "../lib/sso.mjs";
|
|
7
|
+
|
|
8
|
+
const VERSION = "1.1.0";
|
|
9
|
+
const API_BASE = "https://www.getkeysentry.com";
|
|
10
|
+
const CONFIG_DIR = join(homedir(), ".keysentry");
|
|
11
|
+
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
|
12
|
+
|
|
13
|
+
// ═══ CREDENTIAL PATTERNS ═══
|
|
14
|
+
const PATTERNS = [
|
|
15
|
+
{ prefix: "sk-ant-", platform: "anthropic", type: "api_key", label: "Anthropic API Key", rotation: 90 },
|
|
16
|
+
{ prefix: "sk-proj-", platform: "openai", type: "api_key", label: "OpenAI Project Key", rotation: 90 },
|
|
17
|
+
{ prefix: "sk-svcacct-", platform: "openai", type: "service_account", label: "OpenAI Service Account", rotation: 60 },
|
|
18
|
+
{ prefix: "sk-", platform: "openai", type: "api_key", label: "OpenAI API Key", rotation: 90 },
|
|
19
|
+
{ prefix: "AIza", platform: "google", type: "api_key", label: "Google AI API Key", rotation: 180 },
|
|
20
|
+
{ prefix: "AKIA", platform: "aws", type: "api_key", label: "AWS Access Key", rotation: 90 },
|
|
21
|
+
{ prefix: "ghp_", platform: "github", type: "pat", label: "GitHub PAT", rotation: 60 },
|
|
22
|
+
{ prefix: "gho_", platform: "github", type: "oauth", label: "GitHub OAuth Token", rotation: 90 },
|
|
23
|
+
{ prefix: "ghs_", platform: "github", type: "server_token", label: "GitHub Server Token", rotation: 30 },
|
|
24
|
+
{ prefix: "github_pat_", platform: "github", type: "pat", label: "GitHub Fine-Grained PAT", rotation: 60 },
|
|
25
|
+
{ prefix: "xai-", platform: "xai", type: "api_key", label: "Grok / xAI API Key", rotation: 90 },
|
|
26
|
+
{ prefix: "xoxb-", platform: "slack", type: "bot_token", label: "Slack Bot Token", rotation: 365 },
|
|
27
|
+
{ prefix: "xoxp-", platform: "slack", type: "user_token", label: "Slack User Token", rotation: 365 },
|
|
28
|
+
{ prefix: "glpat-", platform: "gitlab", type: "pat", label: "GitLab PAT", rotation: 60 },
|
|
29
|
+
{ prefix: "ATATT", platform: "atlassian", type: "api_key", label: "Atlassian API Token", rotation: 180 },
|
|
30
|
+
{ prefix: "sk_live_", platform: "stripe", type: "api_key", label: "Stripe Live Key", rotation: 365 },
|
|
31
|
+
{ prefix: "sk_test_", platform: "stripe", type: "api_key", label: "Stripe Test Key", rotation: 365 },
|
|
32
|
+
{ prefix: "SG.", platform: "sendgrid", type: "api_key", label: "SendGrid API Key", rotation: 180 },
|
|
33
|
+
{ prefix: "re_", platform: "resend", type: "api_key", label: "Resend API Key", rotation: 180 },
|
|
34
|
+
{ prefix: "hf_", platform: "huggingface", type: "api_key", label: "Hugging Face Token", rotation: 180 },
|
|
35
|
+
{ prefix: "r8_", platform: "replicate", type: "api_key", label: "Replicate API Token", rotation: 180 },
|
|
36
|
+
{ prefix: "npm_", platform: "npm", type: "api_key", label: "NPM Access Token", rotation: 90 },
|
|
37
|
+
{ prefix: "pypi-", platform: "pypi", type: "api_key", label: "PyPI API Token", rotation: 90 },
|
|
38
|
+
{ prefix: "dop_v1_", platform: "digitalocean", type: "pat", label: "DigitalOcean PAT", rotation: 90 },
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
function detect(key) {
|
|
42
|
+
const sorted = [...PATTERNS].sort((a, b) => b.prefix.length - a.prefix.length);
|
|
43
|
+
for (const p of sorted) {
|
|
44
|
+
if (key.startsWith(p.prefix)) return p;
|
|
45
|
+
}
|
|
46
|
+
if (/^[A-Za-z0-9_-]{32,}$/.test(key)) {
|
|
47
|
+
return { prefix: "", platform: "unknown", type: "api_key", label: "API Key (unknown)", rotation: 90 };
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ═══ CONFIG ═══
|
|
53
|
+
function loadConfig() {
|
|
54
|
+
try {
|
|
55
|
+
if (existsSync(CONFIG_FILE)) return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
|
|
56
|
+
} catch {}
|
|
57
|
+
return {};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function saveConfig(config) {
|
|
61
|
+
if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
62
|
+
// The config holds the org API key: readable by this user only.
|
|
63
|
+
writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
|
|
64
|
+
chmodSync(CONFIG_FILE, 0o600);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ═══ READLINE HELPER ═══
|
|
68
|
+
function ask(question) {
|
|
69
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
70
|
+
return new Promise(resolve => rl.question(question, answer => { rl.close(); resolve(answer.trim()); }));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ═══ COLORS ═══
|
|
74
|
+
const c = {
|
|
75
|
+
green: (s) => `\x1b[32m${s}\x1b[0m`,
|
|
76
|
+
yellow: (s) => `\x1b[33m${s}\x1b[0m`,
|
|
77
|
+
red: (s) => `\x1b[31m${s}\x1b[0m`,
|
|
78
|
+
purple: (s) => `\x1b[35m${s}\x1b[0m`,
|
|
79
|
+
bold: (s) => `\x1b[1m${s}\x1b[0m`,
|
|
80
|
+
dim: (s) => `\x1b[2m${s}\x1b[0m`,
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// ═══ COMMANDS ═══
|
|
84
|
+
async function login() {
|
|
85
|
+
console.log("\n" + c.purple(" KeySentry AI") + " — CLI Authentication\n");
|
|
86
|
+
const apiKey = await ask(" API Key (from Settings > API): ");
|
|
87
|
+
if (!apiKey) { console.log(c.red(" ✗ No API key provided")); process.exit(1); }
|
|
88
|
+
|
|
89
|
+
// Verify the key
|
|
90
|
+
try {
|
|
91
|
+
const res = await fetch(`${API_BASE}/api/cli/auth`, {
|
|
92
|
+
method: "POST",
|
|
93
|
+
headers: { "Content-Type": "application/json" },
|
|
94
|
+
body: JSON.stringify({ apiKey }),
|
|
95
|
+
});
|
|
96
|
+
if (res.ok) {
|
|
97
|
+
const data = await res.json();
|
|
98
|
+
saveConfig({ apiKey, email: data.email });
|
|
99
|
+
console.log(c.green(" ✓ Authenticated as " + (data.email || "unknown")));
|
|
100
|
+
console.log(c.dim(" Config saved to ~/.keysentry/config.json\n"));
|
|
101
|
+
} else {
|
|
102
|
+
console.log(c.red(" ✗ Invalid API key"));
|
|
103
|
+
process.exit(1);
|
|
104
|
+
}
|
|
105
|
+
} catch (err) {
|
|
106
|
+
// For now, save the key and trust it
|
|
107
|
+
saveConfig({ apiKey });
|
|
108
|
+
console.log(c.yellow(" ⚠ Could not verify (offline mode). Key saved.\n"));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function vault(args) {
|
|
113
|
+
const config = loadConfig();
|
|
114
|
+
if (!config.apiKey) {
|
|
115
|
+
console.log(c.red(" ✗ Not authenticated. Run: keysentry login\n"));
|
|
116
|
+
process.exit(1);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const isPiped = !process.stdin.isTTY;
|
|
120
|
+
console.log("\n" + c.purple(" KeySentry AI") + " — Vault Credential\n");
|
|
121
|
+
|
|
122
|
+
// Parse flags
|
|
123
|
+
let key = args.find(a => a.startsWith("--key="))?.split("=")[1];
|
|
124
|
+
let name = args.find(a => a.startsWith("--name="))?.split("=")[1];
|
|
125
|
+
let env = args.find(a => a.startsWith("--env="))?.split("=")[1];
|
|
126
|
+
let rotate = args.find(a => a.startsWith("--rotate="))?.split("=")[1];
|
|
127
|
+
let budget = args.find(a => a.startsWith("--budget="))?.split("=")[1];
|
|
128
|
+
let platform = args.find(a => a.startsWith("--platform="))?.split("=")[1];
|
|
129
|
+
|
|
130
|
+
// Check for piped input
|
|
131
|
+
if (!key && !process.stdin.isTTY) {
|
|
132
|
+
const chunks = [];
|
|
133
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
134
|
+
key = Buffer.concat(chunks).toString().trim();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Interactive mode
|
|
138
|
+
if (!key) {
|
|
139
|
+
key = await ask(" Paste credential: ");
|
|
140
|
+
}
|
|
141
|
+
if (!key) { console.log(c.red(" ✗ No credential provided")); process.exit(1); }
|
|
142
|
+
|
|
143
|
+
// Detect
|
|
144
|
+
const detected = detect(key);
|
|
145
|
+
if (detected) {
|
|
146
|
+
console.log(c.green(` ✨ Detected: ${detected.label}`));
|
|
147
|
+
if (!platform) platform = detected.platform;
|
|
148
|
+
if (!rotate) rotate = String(detected.rotation);
|
|
149
|
+
} else {
|
|
150
|
+
console.log(c.yellow(" ⚠ Unknown credential format"));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Fill missing fields
|
|
154
|
+
if (!name && !isPiped) name = await ask(` Name ${platform ? `(${platform})` : ""}: `);
|
|
155
|
+
if (!name) name = (platform || "key") + "-" + Date.now().toString(36);
|
|
156
|
+
|
|
157
|
+
if (!platform && !isPiped) platform = await ask(" Platform (openai/anthropic/google/aws/...): ");
|
|
158
|
+
if (!platform) platform = "unknown";
|
|
159
|
+
|
|
160
|
+
if (!env && !isPiped) env = await ask(" Environment (production/staging/dev) [production]: ");
|
|
161
|
+
if (!env) env = "production";
|
|
162
|
+
|
|
163
|
+
if (!rotate && !isPiped) rotate = await ask(" Rotation days [90]: ");
|
|
164
|
+
if (!rotate) rotate = "90";
|
|
165
|
+
|
|
166
|
+
if (!budget && !isPiped) {
|
|
167
|
+
const b = await ask(" Monthly budget limit $ (optional): ");
|
|
168
|
+
if (b) budget = b;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Confirm
|
|
172
|
+
console.log("\n " + c.bold("Summary:"));
|
|
173
|
+
console.log(` ${c.dim("Name:")} ${name}`);
|
|
174
|
+
console.log(` ${c.dim("Platform:")} ${platform}`);
|
|
175
|
+
console.log(` ${c.dim("Environment:")} ${env}`);
|
|
176
|
+
console.log(` ${c.dim("Rotation:")} ${rotate} days`);
|
|
177
|
+
if (budget) console.log(` ${c.dim("Budget:")} $${budget}/mo`);
|
|
178
|
+
console.log(` ${c.dim("Key:")} ${key.slice(0, 8)}...${key.slice(-4)}`);
|
|
179
|
+
console.log("");
|
|
180
|
+
|
|
181
|
+
const confirm = isPiped ? "y" : await ask(" Save to vault? (Y/n): ");
|
|
182
|
+
if (confirm.toLowerCase() === "n") { console.log(c.yellow(" Cancelled\n")); process.exit(0); }
|
|
183
|
+
|
|
184
|
+
// Send to API
|
|
185
|
+
try {
|
|
186
|
+
const res = await fetch(`${API_BASE}/api/cli/vault`, {
|
|
187
|
+
method: "POST",
|
|
188
|
+
headers: {
|
|
189
|
+
"Content-Type": "application/json",
|
|
190
|
+
"Authorization": `Bearer ${config.apiKey}`,
|
|
191
|
+
},
|
|
192
|
+
body: JSON.stringify({
|
|
193
|
+
name,
|
|
194
|
+
platform,
|
|
195
|
+
environment: env,
|
|
196
|
+
plainKey: key,
|
|
197
|
+
rotationDays: parseInt(rotate),
|
|
198
|
+
credentialType: detected?.type || "api_key",
|
|
199
|
+
source: "cli",
|
|
200
|
+
}),
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
if (res.ok) {
|
|
204
|
+
const data = await res.json();
|
|
205
|
+
console.log(c.green(" ✓ Saved to KeySentry vault"));
|
|
206
|
+
if (data.credential?.id) console.log(c.dim(` ID: ${data.credential.id}`));
|
|
207
|
+
console.log(c.dim(` Rotation due: ${new Date(Date.now() + parseInt(rotate) * 86400000).toLocaleDateString()}`));
|
|
208
|
+
if (budget) console.log(c.dim(` Budget alert: $${Math.round(budget * 0.8)} (80%)`));
|
|
209
|
+
console.log("");
|
|
210
|
+
} else {
|
|
211
|
+
const err = await res.json().catch(() => ({}));
|
|
212
|
+
console.log(c.red(` ✗ Failed: ${err.error || res.statusText}`));
|
|
213
|
+
}
|
|
214
|
+
} catch (err) {
|
|
215
|
+
console.log(c.red(` ✗ Network error: ${err.message}`));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function scan(args) {
|
|
220
|
+
console.log("\n" + c.purple(" KeySentry AI") + " — Scan for Credentials\n");
|
|
221
|
+
|
|
222
|
+
let text = "";
|
|
223
|
+
|
|
224
|
+
// Check for piped input
|
|
225
|
+
if (!process.stdin.isTTY) {
|
|
226
|
+
const chunks = [];
|
|
227
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
228
|
+
text = Buffer.concat(chunks).toString();
|
|
229
|
+
} else {
|
|
230
|
+
console.log(" Paste text to scan (Ctrl+D when done):\n");
|
|
231
|
+
const chunks = [];
|
|
232
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
233
|
+
text = Buffer.concat(chunks).toString();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Scan for patterns (sorted by prefix length desc to avoid duplicates)
|
|
237
|
+
const found = [];
|
|
238
|
+
const seen = new Set();
|
|
239
|
+
const sorted = [...PATTERNS].sort((a, b) => b.prefix.length - a.prefix.length);
|
|
240
|
+
for (const p of sorted) {
|
|
241
|
+
const regex = new RegExp(p.prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "[A-Za-z0-9_\\-]{8,}", "g");
|
|
242
|
+
const matches = text.match(regex);
|
|
243
|
+
if (matches) {
|
|
244
|
+
matches.forEach(m => { if (!seen.has(m)) { seen.add(m); found.push({ key: m, ...p }); } });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (found.length === 0) {
|
|
249
|
+
console.log(c.green(" ✓ No credentials detected\n"));
|
|
250
|
+
} else {
|
|
251
|
+
console.log(c.red(` ⚠ Found ${found.length} credential(s):\n`));
|
|
252
|
+
found.forEach((f, i) => {
|
|
253
|
+
console.log(` ${i + 1}. ${c.bold(f.label)}`);
|
|
254
|
+
console.log(` ${c.dim(f.key.slice(0, 12) + "..." + f.key.slice(-4))}`);
|
|
255
|
+
console.log(` Platform: ${f.platform} | Type: ${f.type}\n`);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function showHelp() {
|
|
261
|
+
console.log(`
|
|
262
|
+
${c.purple("KeySentry AI")} CLI v${VERSION}
|
|
263
|
+
|
|
264
|
+
${c.bold("COMMANDS")}
|
|
265
|
+
|
|
266
|
+
${c.green("login")} Authenticate with your API key
|
|
267
|
+
${c.green("vault")} Save a credential to your vault
|
|
268
|
+
${c.green("scan")} Scan text for exposed credentials
|
|
269
|
+
${c.green("status")} Show connection status
|
|
270
|
+
${c.green("token")} Print a Gateway sign-in token (for Claude Code)
|
|
271
|
+
${c.green("help")} Show this help
|
|
272
|
+
|
|
273
|
+
${c.bold("VAULT OPTIONS")}
|
|
274
|
+
|
|
275
|
+
--key=<key> Credential value
|
|
276
|
+
--name=<name> Credential name
|
|
277
|
+
--platform=<plat> Platform (openai, anthropic, aws, etc.)
|
|
278
|
+
--env=<env> Environment (production, staging, dev)
|
|
279
|
+
--rotate=<days> Rotation schedule in days
|
|
280
|
+
--budget=<amount> Monthly budget limit in dollars
|
|
281
|
+
|
|
282
|
+
${c.bold("TOKEN OPTIONS")}
|
|
283
|
+
|
|
284
|
+
--tenant <id> Directory (tenant) ID from your Entra app
|
|
285
|
+
--client <id> Application (client) ID from your Entra app
|
|
286
|
+
--info Show who is signed in (no token printed)
|
|
287
|
+
--logout Remove the saved sign-in
|
|
288
|
+
|
|
289
|
+
${c.bold("EXAMPLES")}
|
|
290
|
+
|
|
291
|
+
${c.dim("# Interactive")}
|
|
292
|
+
keysentry vault
|
|
293
|
+
|
|
294
|
+
${c.dim("# One-liner")}
|
|
295
|
+
keysentry vault --key="sk-ant-..." --name="prod-key" --env=production
|
|
296
|
+
|
|
297
|
+
${c.dim("# Pipe from env")}
|
|
298
|
+
echo $ANTHROPIC_API_KEY | keysentry vault --name="from-env"
|
|
299
|
+
|
|
300
|
+
${c.dim("# Scan a file")}
|
|
301
|
+
cat .env | keysentry scan
|
|
302
|
+
|
|
303
|
+
${c.dim("# Scan clipboard (macOS)")}
|
|
304
|
+
pbpaste | keysentry scan
|
|
305
|
+
|
|
306
|
+
${c.dim("# Claude Code setting (IT deploys this in managed settings)")}
|
|
307
|
+
"apiKeyHelper": "keysentry token --tenant <tenant-id> --client <client-id>"
|
|
308
|
+
`);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async function status() {
|
|
312
|
+
const config = loadConfig();
|
|
313
|
+
console.log("\n" + c.purple(" KeySentry AI") + " — Status\n");
|
|
314
|
+
if (config.apiKey) {
|
|
315
|
+
console.log(c.green(" ✓ Authenticated"));
|
|
316
|
+
if (config.email) console.log(c.dim(` Email: ${config.email}`));
|
|
317
|
+
console.log(c.dim(` API: ${API_BASE}`));
|
|
318
|
+
console.log(c.dim(` Config: ${CONFIG_FILE}`));
|
|
319
|
+
} else {
|
|
320
|
+
console.log(c.red(" ✗ Not authenticated"));
|
|
321
|
+
console.log(c.dim(" Run: keysentry login"));
|
|
322
|
+
}
|
|
323
|
+
console.log("");
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ═══ MAIN ═══
|
|
327
|
+
const [,, cmd, ...args] = process.argv;
|
|
328
|
+
|
|
329
|
+
switch (cmd) {
|
|
330
|
+
case "login": await login(); break;
|
|
331
|
+
case "vault": case "v": await vault(args); break;
|
|
332
|
+
case "scan": case "s": await scan(args); break;
|
|
333
|
+
case "status": await status(); break;
|
|
334
|
+
case "token": process.exitCode = await tokenCommand(args); break;
|
|
335
|
+
case "help": case "--help": case "-h": case undefined: showHelp(); break;
|
|
336
|
+
case "--version": case "-v": console.log(VERSION); break;
|
|
337
|
+
default: console.log(c.red(` Unknown command: ${cmd}`)); showHelp();
|
|
338
|
+
}
|
package/lib/sso.mjs
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
// KeySentry CLI — `keysentry token`
|
|
2
|
+
//
|
|
3
|
+
// Prints a short-lived Microsoft Entra ID token for the KeySentry Gateway.
|
|
4
|
+
// Built for Claude Code's `apiKeyHelper` setting:
|
|
5
|
+
//
|
|
6
|
+
// "apiKeyHelper": "keysentry token --tenant <tenant-id> --client <client-id>"
|
|
7
|
+
//
|
|
8
|
+
// Rules this file keeps:
|
|
9
|
+
// - stdout carries ONLY the token (Claude Code fails on any extra line).
|
|
10
|
+
// Every message goes to stderr.
|
|
11
|
+
// - Tokens are never logged, never put in a command line, never sent
|
|
12
|
+
// anywhere except Microsoft's sign-in service.
|
|
13
|
+
// - Saved sign-in: macOS Keychain; elsewhere ~/.keysentry/sso/ (folder 0700,
|
|
14
|
+
// file 0600).
|
|
15
|
+
// - No dependencies. Node built-ins only.
|
|
16
|
+
|
|
17
|
+
import { createServer } from "http";
|
|
18
|
+
import { spawn, spawnSync } from "child_process";
|
|
19
|
+
import { createHash, randomBytes } from "crypto";
|
|
20
|
+
import { homedir, platform } from "os";
|
|
21
|
+
import { join } from "path";
|
|
22
|
+
import {
|
|
23
|
+
chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync,
|
|
24
|
+
} from "fs";
|
|
25
|
+
|
|
26
|
+
const LOGIN_HOST = "https://login.microsoftonline.com";
|
|
27
|
+
const SCOPE = "openid profile email offline_access";
|
|
28
|
+
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
29
|
+
// Hand out a saved token only while it has at least this long left. Claude
|
|
30
|
+
// Code reuses a helper's output for 5 minutes by default, so 10 minutes keeps
|
|
31
|
+
// the Gateway from ever seeing an expired one.
|
|
32
|
+
const MIN_REMAINING_SEC = 10 * 60;
|
|
33
|
+
const SIGN_IN_TIMEOUT_MS = 3 * 60 * 1000;
|
|
34
|
+
const KEYCHAIN_SERVICE = "keysentry-sso";
|
|
35
|
+
|
|
36
|
+
const err = (msg) => process.stderr.write(`keysentry: ${msg}\n`);
|
|
37
|
+
|
|
38
|
+
class TokenError extends Error {}
|
|
39
|
+
|
|
40
|
+
// ─── Arguments ────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
function parseArgs(args) {
|
|
43
|
+
const out = { tenant: "", client: "", logout: false, info: false };
|
|
44
|
+
for (let i = 0; i < args.length; i++) {
|
|
45
|
+
const a = args[i];
|
|
46
|
+
const [flag, inline] = a.includes("=") ? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)] : [a, undefined];
|
|
47
|
+
const value = () => (inline !== undefined ? inline : args[++i] ?? "");
|
|
48
|
+
if (flag === "--tenant") out.tenant = value().trim();
|
|
49
|
+
else if (flag === "--client") out.client = value().trim();
|
|
50
|
+
else if (flag === "--logout") out.logout = true;
|
|
51
|
+
else if (flag === "--info") out.info = true;
|
|
52
|
+
else throw new TokenError(`unknown option ${flag}. Use: keysentry token --tenant <id> --client <id> [--info | --logout]`);
|
|
53
|
+
}
|
|
54
|
+
if (!GUID.test(out.tenant)) throw new TokenError("--tenant must be your Directory (tenant) ID, a GUID from the Entra app's Overview page.");
|
|
55
|
+
if (!GUID.test(out.client)) throw new TokenError("--client must be the Application (client) ID, a GUID from the Entra app's Overview page.");
|
|
56
|
+
out.tenant = out.tenant.toLowerCase();
|
|
57
|
+
out.client = out.client.toLowerCase();
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ─── Saved sign-in ────────────────────────────────────────────────────────
|
|
62
|
+
// Two values per tenant+app: the ID token (≈1 hour) and the refresh token.
|
|
63
|
+
|
|
64
|
+
function keychainStore() {
|
|
65
|
+
const run = (args, input) => spawnSync("/usr/bin/security", args, { input, encoding: "utf8" });
|
|
66
|
+
return {
|
|
67
|
+
name: "macOS Keychain",
|
|
68
|
+
get(account) {
|
|
69
|
+
const r = run(["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account, "-w"]);
|
|
70
|
+
return r.status === 0 ? r.stdout.replace(/\n$/, "") : "";
|
|
71
|
+
},
|
|
72
|
+
set(account, value) {
|
|
73
|
+
// Value goes in on stdin (interactive mode), not on the command line,
|
|
74
|
+
// so it never shows up in a process listing.
|
|
75
|
+
run(["-i"], `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${account} -w ${value}\n`);
|
|
76
|
+
if (this.get(account) === value) return;
|
|
77
|
+
// Interactive mode has a line-length limit on some macOS versions. Fall
|
|
78
|
+
// back to the argument form (visible only to this user's own processes
|
|
79
|
+
// for the instant the command runs).
|
|
80
|
+
const r = run(["add-generic-password", "-U", "-s", KEYCHAIN_SERVICE, "-a", account, "-w", value]);
|
|
81
|
+
if (r.status !== 0 || this.get(account) !== value) throw new TokenError("could not save the sign-in to the macOS Keychain.");
|
|
82
|
+
},
|
|
83
|
+
remove(account) {
|
|
84
|
+
run(["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account]);
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function fileStore() {
|
|
90
|
+
const dir = join(homedir(), ".keysentry", "sso");
|
|
91
|
+
const pathFor = (account) => join(dir, account.replace(/[^a-z0-9._-]/gi, "_") + ".json");
|
|
92
|
+
return {
|
|
93
|
+
name: dir,
|
|
94
|
+
get(account) {
|
|
95
|
+
const p = pathFor(account);
|
|
96
|
+
if (!existsSync(p)) return "";
|
|
97
|
+
try { return String(JSON.parse(readFileSync(p, "utf8")).value || ""); } catch { return ""; }
|
|
98
|
+
},
|
|
99
|
+
set(account, value) {
|
|
100
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
101
|
+
chmodSync(dir, 0o700);
|
|
102
|
+
const p = pathFor(account);
|
|
103
|
+
const tmp = `${p}.${process.pid}.tmp`;
|
|
104
|
+
writeFileSync(tmp, JSON.stringify({ value }), { mode: 0o600 });
|
|
105
|
+
chmodSync(tmp, 0o600);
|
|
106
|
+
renameSync(tmp, p);
|
|
107
|
+
},
|
|
108
|
+
remove(account) {
|
|
109
|
+
const p = pathFor(account);
|
|
110
|
+
if (existsSync(p)) unlinkSync(p);
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const useKeychain = () => platform() === "darwin" && existsSync("/usr/bin/security");
|
|
116
|
+
const store = () => (useKeychain() ? keychainStore() : fileStore());
|
|
117
|
+
|
|
118
|
+
// ─── Token helpers ────────────────────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
function claimsOf(jwt) {
|
|
121
|
+
try {
|
|
122
|
+
const part = jwt.split(".")[1];
|
|
123
|
+
return JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
124
|
+
} catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Light checks only: the Gateway verifies the signature. These stop us from
|
|
130
|
+
// handing out a token for the wrong tenant or app, or one about to expire.
|
|
131
|
+
function usable(idToken, opts, minRemaining = MIN_REMAINING_SEC) {
|
|
132
|
+
if (!idToken) return false;
|
|
133
|
+
const c = claimsOf(idToken);
|
|
134
|
+
if (!c) return false;
|
|
135
|
+
const now = Math.floor(Date.now() / 1000);
|
|
136
|
+
return c.aud === opts.client && String(c.tid || "").toLowerCase() === opts.tenant && typeof c.exp === "number" && c.exp - now >= minRemaining;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function tokenRequest(opts, params) {
|
|
140
|
+
const body = new URLSearchParams({ client_id: opts.client, scope: SCOPE, ...params });
|
|
141
|
+
let res;
|
|
142
|
+
try {
|
|
143
|
+
res = await fetch(`${LOGIN_HOST}/${opts.tenant}/oauth2/v2.0/token`, {
|
|
144
|
+
method: "POST",
|
|
145
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
146
|
+
body,
|
|
147
|
+
signal: AbortSignal.timeout(20_000),
|
|
148
|
+
});
|
|
149
|
+
} catch {
|
|
150
|
+
throw new TokenError("could not reach Microsoft sign-in (login.microsoftonline.com). Check your network.");
|
|
151
|
+
}
|
|
152
|
+
let data = {};
|
|
153
|
+
try { data = await res.json(); } catch { /* handled below */ }
|
|
154
|
+
if (!res.ok || !data.id_token) {
|
|
155
|
+
// error + first line of error_description are safe to show (no tokens in them).
|
|
156
|
+
const code = typeof data.error === "string" ? data.error : `HTTP ${res.status}`;
|
|
157
|
+
const desc = typeof data.error_description === "string" ? data.error_description.split(/\r?\n/)[0] : "";
|
|
158
|
+
const e = new TokenError(`Microsoft sign-in refused the request (${code})${desc ? `: ${desc}` : ""}`);
|
|
159
|
+
e.code = code;
|
|
160
|
+
throw e;
|
|
161
|
+
}
|
|
162
|
+
return data;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function save(opts, s, data) {
|
|
166
|
+
const base = `${opts.tenant}.${opts.client}`;
|
|
167
|
+
s.set(`${base}.id`, data.id_token);
|
|
168
|
+
if (data.refresh_token) s.set(`${base}.refresh`, data.refresh_token);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ─── Browser sign-in (authorization code + PKCE, loopback redirect) ──────
|
|
172
|
+
|
|
173
|
+
function openBrowser(url) {
|
|
174
|
+
const os = platform();
|
|
175
|
+
const [cmd, args] =
|
|
176
|
+
os === "darwin" ? ["open", [url]]
|
|
177
|
+
: os === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
178
|
+
: ["xdg-open", [url]];
|
|
179
|
+
try {
|
|
180
|
+
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
|
|
181
|
+
child.on("error", () => {});
|
|
182
|
+
child.unref();
|
|
183
|
+
} catch { /* the URL is printed too */ }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const page = (title, line) =>
|
|
187
|
+
`<!doctype html><meta charset="utf-8"><title>KeySentry</title>` +
|
|
188
|
+
`<body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;color:#222">` +
|
|
189
|
+
`<h2>${title}</h2><p>${line}</p></body>`;
|
|
190
|
+
|
|
191
|
+
const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (ch) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[ch]));
|
|
192
|
+
|
|
193
|
+
async function browserSignIn(opts) {
|
|
194
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
195
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
196
|
+
const state = randomBytes(16).toString("base64url");
|
|
197
|
+
const nonce = randomBytes(16).toString("base64url");
|
|
198
|
+
|
|
199
|
+
const server = createServer();
|
|
200
|
+
await new Promise((resolve, reject) => {
|
|
201
|
+
server.once("error", reject);
|
|
202
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
203
|
+
});
|
|
204
|
+
const port = server.address().port;
|
|
205
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
206
|
+
|
|
207
|
+
const authUrl = `${LOGIN_HOST}/${opts.tenant}/oauth2/v2.0/authorize?` + new URLSearchParams({
|
|
208
|
+
client_id: opts.client,
|
|
209
|
+
response_type: "code",
|
|
210
|
+
response_mode: "query",
|
|
211
|
+
redirect_uri: redirectUri,
|
|
212
|
+
scope: SCOPE,
|
|
213
|
+
state,
|
|
214
|
+
nonce,
|
|
215
|
+
code_challenge: challenge,
|
|
216
|
+
code_challenge_method: "S256",
|
|
217
|
+
prompt: "select_account",
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
err("sign in with your work Microsoft account in the browser window that just opened.");
|
|
221
|
+
err(`if no window opened, open this link: ${authUrl}`);
|
|
222
|
+
openBrowser(authUrl);
|
|
223
|
+
|
|
224
|
+
try {
|
|
225
|
+
const code = await new Promise((resolve, reject) => {
|
|
226
|
+
const timer = setTimeout(() => reject(new TokenError("sign-in timed out after 3 minutes. Run the command again.")), SIGN_IN_TIMEOUT_MS);
|
|
227
|
+
server.on("request", (req, res) => {
|
|
228
|
+
const url = new URL(req.url || "/", redirectUri);
|
|
229
|
+
if (url.pathname !== "/callback") { res.writeHead(404).end(); return; }
|
|
230
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
231
|
+
res.setHeader("Cache-Control", "no-store");
|
|
232
|
+
if (url.searchParams.get("state") !== state) {
|
|
233
|
+
res.writeHead(400).end(page("Sign-in not completed", "This response did not match the sign-in KeySentry started. Close this tab and try again."));
|
|
234
|
+
return; // keep waiting for the real response
|
|
235
|
+
}
|
|
236
|
+
clearTimeout(timer);
|
|
237
|
+
const e = url.searchParams.get("error");
|
|
238
|
+
if (e) {
|
|
239
|
+
const desc = (url.searchParams.get("error_description") || "").split(/\r?\n/)[0];
|
|
240
|
+
res.writeHead(400).end(page("Sign-in not completed", `Microsoft returned: ${escapeHtml(e)}. ${escapeHtml(desc)}`));
|
|
241
|
+
reject(new TokenError(`Microsoft sign-in returned ${e}${desc ? `: ${desc}` : ""}`));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const c = url.searchParams.get("code");
|
|
245
|
+
if (!c) {
|
|
246
|
+
res.writeHead(400).end(page("Sign-in not completed", "No sign-in code came back. Close this tab and try again."));
|
|
247
|
+
reject(new TokenError("no sign-in code came back from Microsoft."));
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
res.writeHead(200).end(page("Signed in to KeySentry", "You can close this tab and go back to your terminal."));
|
|
251
|
+
resolve(c);
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
const data = await tokenRequest(opts, {
|
|
256
|
+
grant_type: "authorization_code",
|
|
257
|
+
code,
|
|
258
|
+
redirect_uri: redirectUri,
|
|
259
|
+
code_verifier: verifier,
|
|
260
|
+
});
|
|
261
|
+
const c = claimsOf(data.id_token);
|
|
262
|
+
if (!c || c.nonce !== nonce) throw new TokenError("the sign-in response failed its replay check. Run the command again.");
|
|
263
|
+
return data;
|
|
264
|
+
} finally {
|
|
265
|
+
server.close();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ─── Command ──────────────────────────────────────────────────────────────
|
|
270
|
+
|
|
271
|
+
async function getToken(opts) {
|
|
272
|
+
const s = store();
|
|
273
|
+
const base = `${opts.tenant}.${opts.client}`;
|
|
274
|
+
|
|
275
|
+
const saved = s.get(`${base}.id`);
|
|
276
|
+
if (usable(saved, opts)) return saved;
|
|
277
|
+
|
|
278
|
+
const refresh = s.get(`${base}.refresh`);
|
|
279
|
+
if (refresh) {
|
|
280
|
+
try {
|
|
281
|
+
const data = await tokenRequest(opts, { grant_type: "refresh_token", refresh_token: refresh });
|
|
282
|
+
if (usable(data.id_token, opts, 60)) {
|
|
283
|
+
save(opts, s, data);
|
|
284
|
+
return data.id_token;
|
|
285
|
+
}
|
|
286
|
+
} catch (e) {
|
|
287
|
+
// invalid_grant = sign-in expired or was revoked (password change,
|
|
288
|
+
// admin sign-out, account disabled). Fall through to a fresh sign-in.
|
|
289
|
+
// Anything else (network down) is a real failure.
|
|
290
|
+
if (e.code !== "invalid_grant" && e.code !== "interaction_required") throw e;
|
|
291
|
+
s.remove(`${base}.refresh`);
|
|
292
|
+
s.remove(`${base}.id`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Browser sign-in only when a person is at the terminal. When Claude Code
|
|
297
|
+
// (or any tool) runs us with stdout captured, it won't wait for a browser,
|
|
298
|
+
// so stop right away with the command to run instead.
|
|
299
|
+
if (!process.stdout.isTTY && !opts.info) {
|
|
300
|
+
throw new TokenError(`not signed in to the KeySentry Gateway on this computer. In a terminal, run: keysentry token --tenant ${opts.tenant} --client ${opts.client} --info`);
|
|
301
|
+
}
|
|
302
|
+
const data = await browserSignIn(opts);
|
|
303
|
+
if (!usable(data.id_token, opts, 60)) throw new TokenError("Microsoft returned a token for a different tenant or app. Check --tenant and --client.");
|
|
304
|
+
save(opts, s, data);
|
|
305
|
+
err("signed in.");
|
|
306
|
+
return data.id_token;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function tokenCommand(args) {
|
|
310
|
+
try {
|
|
311
|
+
const opts = parseArgs(args);
|
|
312
|
+
const s = store();
|
|
313
|
+
const base = `${opts.tenant}.${opts.client}`;
|
|
314
|
+
|
|
315
|
+
if (opts.logout) {
|
|
316
|
+
s.remove(`${base}.id`);
|
|
317
|
+
s.remove(`${base}.refresh`);
|
|
318
|
+
err(`signed out (removed the saved sign-in from ${s.name}).`);
|
|
319
|
+
return 0;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const token = await getToken(opts);
|
|
323
|
+
|
|
324
|
+
if (opts.info) {
|
|
325
|
+
const c = claimsOf(token) || {};
|
|
326
|
+
const mins = Math.max(0, Math.floor((c.exp - Date.now() / 1000) / 60));
|
|
327
|
+
err(`signed in as ${c.preferred_username || c.email || c.upn || "unknown"}; token good for about ${mins} more minutes; saved in ${s.name}.`);
|
|
328
|
+
return 0;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
process.stdout.write(token + "\n");
|
|
332
|
+
return 0;
|
|
333
|
+
} catch (e) {
|
|
334
|
+
err(e instanceof TokenError ? e.message : `unexpected error: ${e && e.message ? e.message : e}`);
|
|
335
|
+
return 1;
|
|
336
|
+
}
|
|
337
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@keysentry/cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "KeySentry AI CLI — vault credentials and sign in to the KeySentry Gateway from your terminal",
|
|
5
|
+
"bin": {
|
|
6
|
+
"keysentry": "bin/keysentry.mjs"
|
|
7
|
+
},
|
|
8
|
+
"files": [
|
|
9
|
+
"LICENSE",
|
|
10
|
+
"bin/",
|
|
11
|
+
"lib/",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18.17"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public",
|
|
20
|
+
"provenance": true
|
|
21
|
+
},
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/rdnetech/keysentry-cli.git"
|
|
26
|
+
},
|
|
27
|
+
"keywords": ["keysentry", "credentials", "api-keys", "vault", "security", "gateway", "entra", "claude-code"]
|
|
28
|
+
}
|