-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeys.js
More file actions
199 lines (185 loc) · 7.34 KB
/
keys.js
File metadata and controls
199 lines (185 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// /account/keys. Project-namespaced key admin.
// Loads projects, renders tabs, loads keys per active project, create + revoke.
(function () {
let currentProject = 'default';
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
}[c]));
}
function fmtDate(iso) {
if (!iso) return ',';
try { return new Date(iso).toISOString().slice(0, 10); } catch { return iso; }
}
function normalizeProject(name) {
return String(name || 'default').trim().toLowerCase().replace(/[^a-z0-9_-]/g, '-').slice(0, 30) || 'default';
}
function attachCopy(scope) {
(scope || document).querySelectorAll('[data-copy]').forEach((btn) => {
if (btn.__nipBound) return;
btn.__nipBound = true;
btn.addEventListener('click', async () => {
const target = document.querySelector(btn.dataset.copy);
if (!target) return;
try {
await navigator.clipboard.writeText(target.textContent.trim());
const orig = btn.textContent;
btn.textContent = 'Copied';
setTimeout(() => (btn.textContent = orig), 1400);
} catch {
btn.textContent = 'Copy failed';
}
});
});
}
const tabsRow = document.getElementById('projects-tabs-row');
const newProjBtn = document.getElementById('projects-new');
const list = document.getElementById('keys-list');
const form = document.getElementById('keys-create-form');
const labelEl = document.getElementById('keys-label');
const freshBox = document.getElementById('keys-just-created');
const freshVal = document.getElementById('keys-fresh-value');
const createInProj = document.getElementById('create-in-project');
function setActiveProject(name) {
currentProject = name;
createInProj.textContent = name;
tabsRow.querySelectorAll('[data-project]').forEach((el) => {
el.classList.toggle('is-active', el.dataset.project === name);
});
loadKeys(name);
}
async function loadProjects() {
try {
const r = await fetch('/api/projects', { credentials: 'same-origin' });
if (r.status === 401) {
window.location.href = '/?error=signin_required';
return;
}
const data = await r.json();
renderTabs(data.projects || [{ name: 'default', key_count: 0 }]);
} catch {
renderTabs([{ name: 'default', key_count: 0 }]);
}
}
function renderTabs(projects) {
// include currentProject even if no keys yet (just created)
if (!projects.find((p) => p.name === currentProject)) {
projects.push({ name: currentProject, key_count: 0 });
}
tabsRow.innerHTML = projects.map((p) => `
<button type="button" class="acct-projects-tab${p.name === currentProject ? ' is-active' : ''}" data-project="${esc(p.name)}">
<span class="acct-projects-tab-name">${esc(p.name)}</span>
<span class="acct-projects-tab-count">${p.key_count}</span>
</button>
`).join('');
tabsRow.querySelectorAll('[data-project]').forEach((el) => {
el.addEventListener('click', () => setActiveProject(el.dataset.project));
});
createInProj.textContent = currentProject;
}
async function loadKeys(project) {
list.innerHTML = '<p class="acct-keys-empty">Loading…</p>';
try {
const r = await fetch(`/api/keys?project=${encodeURIComponent(project)}`, { credentials: 'same-origin' });
if (r.status === 401) {
window.location.href = '/?error=signin_required';
return;
}
const data = await r.json();
if (!data.keys || data.keys.length === 0) {
list.innerHTML = `<p class="acct-keys-empty">No keys in <strong>${esc(project)}</strong> yet. Generate one above.</p>`;
return;
}
list.innerHTML = data.keys.map(renderKey).join('');
attachCopy(list);
list.querySelectorAll('[data-revoke]').forEach((btn) => {
btn.addEventListener('click', () => revokeKey(btn.dataset.revoke));
});
} catch {
list.innerHTML = '<p class="acct-keys-empty">Failed to load. Refresh.</p>';
}
}
function renderKey(k) {
const safe = `kid-${esc(k.id).replace(/[^a-z0-9]/gi, '')}`;
return `<div class="acct-key-card">
<div class="acct-key-head">
<p class="acct-key-kicker">${esc(k.label || 'unnamed').toUpperCase()}</p>
<span class="acct-key-status">active</span>
</div>
<div class="acct-key-row">
<code id="${safe}">${esc(k.key)}</code>
<button class="acct-btn" data-copy="#${safe}">Copy</button>
<button class="acct-btn acct-btn-danger" data-revoke="${esc(k.id)}">Revoke</button>
</div>
<p class="acct-key-meta">Created ${fmtDate(k.created_at)}${k.last_used_at ? ` · last used ${fmtDate(k.last_used_at)}` : ' · never used'}</p>
</div>`;
}
async function revokeKey(id) {
if (!confirm('Revoke this key? Any service using it will start failing.')) return;
try {
const r = await fetch(`/api/keys?id=${encodeURIComponent(id)}`, {
method: 'DELETE',
credentials: 'same-origin',
});
if (!r.ok) {
const d = await r.json().catch(() => ({}));
alert('Revoke failed: ' + (d.error || r.statusText));
return;
}
await loadProjects();
await loadKeys(currentProject);
} catch {
alert('Network error. Try again.');
}
}
newProjBtn.addEventListener('click', () => {
const raw = prompt('New project name (a-z, 0-9, dash, underscore. Max 30 chars):');
if (!raw) return;
const name = normalizeProject(raw);
if (!name) return;
// virtual tab. Switches focus; actually created when first key is generated
if (!Array.from(tabsRow.querySelectorAll('[data-project]')).find((b) => b.dataset.project === name)) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'acct-projects-tab';
btn.dataset.project = name;
btn.innerHTML = `<span class="acct-projects-tab-name">${esc(name)}</span><span class="acct-projects-tab-count">0</span>`;
btn.addEventListener('click', () => setActiveProject(name));
tabsRow.appendChild(btn);
}
setActiveProject(name);
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const label = (labelEl.value || '').trim() || 'unnamed';
const btn = form.querySelector('button[type="submit"]');
const orig = btn.textContent;
btn.disabled = true; btn.textContent = 'Generating…';
try {
const r = await fetch('/api/keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ label, project: currentProject }),
});
const data = await r.json();
if (!r.ok) {
alert(data.error === 'max_keys_reached'
? `You have reached the ${data.limit}-key limit across all projects. Revoke an unused key first.`
: 'Failed to create key: ' + (data.error || r.statusText));
return;
}
freshVal.textContent = data.key;
freshBox.hidden = false;
labelEl.value = '';
attachCopy(freshBox);
await loadProjects();
await loadKeys(currentProject);
} catch {
alert('Network error. Try again.');
} finally {
btn.disabled = false; btn.textContent = orig;
}
});
loadProjects().then(() => loadKeys(currentProject));
})();