CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | /**
* API tokens — personal access tokens for automation.
*/
import { Hono } from "hono";
import { eq } from "drizzle-orm";
import { db } from "../db";
import { apiTokens } from "../db/schema";
import { Layout } from "../views/layout";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
Container,
PageHeader,
Section,
Alert,
EmptyState,
ListItem,
Flex,
Form,
FormGroup,
Input,
Button,
InlineCode,
Text,
} from "../views/ui";
const tokens = new Hono<AuthEnv>();
tokens.use("/settings/tokens*", softAuth, requireAuth);
tokens.use("/api/user/tokens*", softAuth, requireAuth);
function generateToken(): string {
const bytes = crypto.getRandomValues(new Uint8Array(32));
return (
"glc_" +
Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("")
);
}
async function hashToken(token: string): Promise<string> {
const data = new TextEncoder().encode(token);
const hash = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
// Token settings page
tokens.get("/settings/tokens", async (c) => {
const user = c.get("user")!;
const success = c.req.query("success");
const newToken = c.req.query("new_token");
const userTokens = await db
.select()
.from(apiTokens)
.where(eq(apiTokens.userId, user.id));
return c.html(
<Layout title="API Tokens" user={user}>
<Container class="settings-container">
<PageHeader title="Personal access tokens" />
{success && (
<Alert variant="success">
{decodeURIComponent(success)}
</Alert>
)}
{newToken && (
<Alert variant="success">
<span style="font-family: var(--font-mono); word-break: break-all">
New token (copy now — it won't be shown again):{" "}
<strong>{decodeURIComponent(newToken)}</strong>
</span>
</Alert>
)}
<div style="margin-top: 16px">
{userTokens.length === 0 ? (
<EmptyState>
<Text muted>No tokens yet.</Text>
</EmptyState>
) : (
userTokens.map((token) => (
<ListItem>
<div>
<strong>{token.name}</strong>
<div class="ssh-key-meta">
<InlineCode>{token.tokenPrefix}...</InlineCode>
<span style="margin-left: 8px">
Scopes: {token.scopes}
</span>
{token.lastUsedAt && (
<span>
{" "}
| Last used{" "}
{new Date(token.lastUsedAt).toLocaleDateString()}
</span>
)}
</div>
</div>
<form
method="post"
action={`/settings/tokens/${token.id}/delete`}
method="POST"
>
<Button type="submit" variant="danger" size="sm">
Revoke
</Button>
</Form>
</ListItem>
))
)}
</div>
<h3 style="margin-top: 24px; margin-bottom: 12px">
Generate new token
</h3>
<form method="post" action="/settings/tokens">
<div class="form-group">
<label for="name">Token name</label>
<input
type="text"
id="name"
name="name"
required
placeholder="e.g. CI/CD pipeline"
/>
</div>
<div class="form-group">
<label>Scopes</label>
<div style="display: flex; gap: 16px; flex-wrap: wrap">
{["repo", "user", "admin"].map((scope) => (
<label style="display: flex; align-items: center; gap: 4px; font-size: 14px; cursor: pointer">
<input
type="checkbox"
name="scopes"
value={scope}
checked={scope === "repo"}
/>{" "}
{scope}
</label>
))}
</div>
</div>
<button type="submit" class="btn btn-primary">
Generate token
</button>
</form>
</div>
</Layout>
);
});
// Create token
tokens.post("/settings/tokens", async (c) => {
const user = c.get("user")!;
const body = await c.req.parseBody();
const name = String(body.name || "").trim();
let scopes: string;
const rawScopes = body.scopes;
if (Array.isArray(rawScopes)) {
scopes = rawScopes.join(",");
} else {
scopes = String(rawScopes || "repo");
}
if (!name) {
return c.redirect("/settings/tokens?error=Name+is+required");
}
const token = generateToken();
const tokenH = await hashToken(token);
await db.insert(apiTokens).values({
userId: user.id,
name,
tokenHash: tokenH,
tokenPrefix: token.slice(0, 12),
scopes,
});
return c.redirect(
`/settings/tokens?new_token=${encodeURIComponent(token)}`
);
});
// Delete token
tokens.post("/settings/tokens/:id/delete", async (c) => {
const user = c.get("user")!;
const tokenId = c.req.param("id");
const [token] = await db
.select()
.from(apiTokens)
.where(eq(apiTokens.id, tokenId))
.limit(1);
if (!token || token.userId !== user.id) {
return c.redirect("/settings/tokens");
}
await db.delete(apiTokens).where(eq(apiTokens.id, tokenId));
return c.redirect("/settings/tokens?success=Token+revoked");
});
// API endpoint
tokens.get("/api/user/tokens", async (c) => {
const user = c.get("user")!;
const userTokens = await db
.select({
id: apiTokens.id,
name: apiTokens.name,
tokenPrefix: apiTokens.tokenPrefix,
scopes: apiTokens.scopes,
lastUsedAt: apiTokens.lastUsedAt,
createdAt: apiTokens.createdAt,
})
.from(apiTokens)
.where(eq(apiTokens.userId, user.id));
return c.json(userTokens);
});
export default tokens;
|