Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
passkeys.tsx14.9 KB · 428 lines
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
 * WebAuthn passkey routes (Block B5).
 *
 * Registration (authed):
 *   POST /api/passkeys/register/options    → challenge + pubkey-cred-params
 *   POST /api/passkeys/register/verify     → save credential
 *   GET  /settings/passkeys                → list + add + rename + delete
 *   POST /settings/passkeys/:id/delete
 *   POST /settings/passkeys/:id/rename
 *
 * Authentication (unauthed):
 *   POST /api/passkeys/auth/options        → challenge (username optional)
 *   POST /api/passkeys/auth/verify         → issues full session on success
 *
 * The browser-side glue lives in `/views/components.tsx`
 * (`PasskeyScript`) — vanilla JS using the native `navigator.credentials` API.
 */

import { Hono } from "hono";
import { setCookie } from "hono/cookie";
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import { users, userPasskeys, sessions } from "../db/schema";
import type { AuthEnv } from "../middleware/auth";
import { requireAuth } from "../middleware/auth";
import { Layout } from "../views/layout";
import {
  startRegistration,
  finishRegistration,
  startAuthentication,
  finishAuthentication,
} from "../lib/webauthn";
import {
  generateSessionToken,
  sessionCookieOptions,
  sessionExpiry,
} from "../lib/auth";
import { audit } from "../lib/notify";

const passkeys = new Hono<AuthEnv>();

passkeys.use("/settings/passkeys", requireAuth);
passkeys.use("/settings/passkeys/*", requireAuth);
passkeys.use("/api/passkeys/register/*", requireAuth);

// --- Settings UI ------------------------------------------------------------

passkeys.get("/settings/passkeys", async (c) => {
  const user = c.get("user")!;
  const error = c.req.query("error");
  const success = c.req.query("success");

  let keys: (typeof userPasskeys.$inferSelect)[] = [];
  try {
    keys = await db
      .select()
      .from(userPasskeys)
      .where(eq(userPasskeys.userId, user.id));
  } catch (err) {
    console.error("[passkeys] list:", err);
  }

  return c.html(
    <Layout title="Passkeys" user={user}>
      <div class="settings-container">
        <div class="breadcrumb">
          <a href="/settings">settings</a>
          <span>/</span>
          <span>passkeys</span>
        </div>
        <h2>Passkeys</h2>
        {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
        {success && (
          <div class="auth-success">{decodeURIComponent(success)}</div>
        )}
        <p style="color: var(--text-muted); font-size: 13px">
          Passkeys are a phishing-resistant replacement for passwords. Your
          device stores the private key and never shares it — sign-in is a
          single Touch ID / Face ID / security-key tap.
        </p>

        <div style="margin: 16px 0">
          <button
            type="button"
            id="pk-add-btn"
            class="btn btn-primary"
          >
            Add a passkey
          </button>
          <span
            id="pk-add-status"
            style="color: var(--text-muted); font-size: 13px; margin-left: 8px"
          />
        </div>

        <div
          style="border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden"
        >
          {keys.length === 0 ? (
            <div
              style="padding: 16px; color: var(--text-muted); font-size: 13px; background: var(--bg-secondary)"
            >
              No passkeys registered yet.
            </div>
          ) : (
            keys.map((k) => (
              <div
                style="padding: 10px 16px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: var(--bg-secondary)"
              >
                <div>
                  <strong>{k.name}</strong>
                  <div
                    style="color: var(--text-muted); font-size: 12px; margin-top: 2px"
                  >
                    added {new Date(k.createdAt).toLocaleDateString()}
                    {k.lastUsedAt &&
                      ` · last used ${new Date(k.lastUsedAt).toLocaleDateString()}`}
                  </div>
                </div>
                <div style="display: flex; gap: 6px">
                  <form
                    method="POST"
                    action={`/settings/passkeys/${k.id}/rename`}
                    style="display: flex; gap: 4px"
                  >
                    <input
                      type="text"
                      name="name"
                      defaultValue={k.name}
                      maxLength={60}
                      style="width: 160px"
                    />
                    <button type="submit" class="btn btn-sm">
                      save
                    </button>
                  </form>
                  <form
                    method="POST"
                    action={`/settings/passkeys/${k.id}/delete`}
                    onsubmit="return confirm('Remove this passkey?')"
                  >
                    <button type="submit" class="btn btn-sm btn-danger">
                      remove
                    </button>
                  </form>
                </div>
              </div>
            ))
          )}
        </div>

        <script
          dangerouslySetInnerHTML={{
            __html: /* js */ `
              (function () {
                const btn = document.getElementById('pk-add-btn');
                const status = document.getElementById('pk-add-status');
                if (!btn) return;
                function b64uToBuf(s) {
                  s = s.replace(/-/g,'+').replace(/_/g,'/');
                  while (s.length % 4) s += '=';
                  const bin = atob(s);
                  const buf = new Uint8Array(bin.length);
                  for (let i=0;i<bin.length;i++) buf[i] = bin.charCodeAt(i);
                  return buf.buffer;
                }
                function bufToB64u(buf) {
                  const bytes = new Uint8Array(buf);
                  let bin = '';
                  for (let i=0;i<bytes.length;i++) bin += String.fromCharCode(bytes[i]);
                  return btoa(bin).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,'');
                }
                btn.addEventListener('click', async function () {
                  if (!window.PublicKeyCredential) {
                    status.textContent = 'Passkeys not supported in this browser.';
                    return;
                  }
                  status.textContent = 'Preparing…';
                  try {
                    const optsRes = await fetch('/api/passkeys/register/options', {
                      method: 'POST',
                      headers: { 'content-type': 'application/json' },
                      body: '{}'
                    });
                    if (!optsRes.ok) throw new Error('options failed');
                    const { options, sessionKey } = await optsRes.json();
                    options.challenge = b64uToBuf(options.challenge);
                    options.user.id = b64uToBuf(options.user.id);
                    if (options.excludeCredentials) {
                      options.excludeCredentials = options.excludeCredentials.map(function (c) {
                        return Object.assign({}, c, { id: b64uToBuf(c.id) });
                      });
                    }
                    status.textContent = 'Touch your authenticator…';
                    const cred = await navigator.credentials.create({ publicKey: options });
                    const resp = {
                      id: cred.id,
                      rawId: bufToB64u(cred.rawId),
                      type: cred.type,
                      response: {
                        clientDataJSON: bufToB64u(cred.response.clientDataJSON),
                        attestationObject: bufToB64u(cred.response.attestationObject),
                        transports: cred.response.getTransports ? cred.response.getTransports() : []
                      },
                      clientExtensionResults: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
                    };
                    const verifyRes = await fetch('/api/passkeys/register/verify', {
                      method: 'POST',
                      headers: { 'content-type': 'application/json' },
                      body: JSON.stringify({ sessionKey: sessionKey, response: resp })
                    });
                    if (!verifyRes.ok) {
                      const j = await verifyRes.json().catch(() => ({}));
                      throw new Error(j.error || 'verify failed');
                    }
                    status.textContent = 'Saved. Reloading…';
                    window.location.reload();
                  } catch (e) {
                    status.textContent = 'Error: ' + (e && e.message ? e.message : e);
                  }
                });
              })();
            `,
          }}
        />
      </div>
    </Layout>
  );
});

passkeys.post("/settings/passkeys/:id/delete", async (c) => {
  const user = c.get("user")!;
  const id = c.req.param("id");
  try {
    const [row] = await db
      .select({ id: userPasskeys.id, userId: userPasskeys.userId })
      .from(userPasskeys)
      .where(eq(userPasskeys.id, id))
      .limit(1);
    if (!row || row.userId !== user.id) {
      return c.redirect("/settings/passkeys?error=Not+found");
    }
    await db.delete(userPasskeys).where(eq(userPasskeys.id, id));
    await audit({
      userId: user.id,
      action: "passkey.delete",
      targetType: "passkey",
      targetId: id,
    });
    return c.redirect("/settings/passkeys?success=Passkey+removed");
  } catch (err) {
    console.error("[passkeys] delete:", err);
    return c.redirect("/settings/passkeys?error=Service+unavailable");
  }
});

passkeys.post("/settings/passkeys/:id/rename", async (c) => {
  const user = c.get("user")!;
  const id = c.req.param("id");
  const body = await c.req.parseBody();
  const name = String(body.name || "").trim().slice(0, 60);
  if (!name) {
    return c.redirect("/settings/passkeys?error=Name+required");
  }
  try {
    const [row] = await db
      .select({ id: userPasskeys.id, userId: userPasskeys.userId })
      .from(userPasskeys)
      .where(eq(userPasskeys.id, id))
      .limit(1);
    if (!row || row.userId !== user.id) {
      return c.redirect("/settings/passkeys?error=Not+found");
    }
    await db
      .update(userPasskeys)
      .set({ name })
      .where(eq(userPasskeys.id, id));
    return c.redirect("/settings/passkeys?success=Renamed");
  } catch (err) {
    console.error("[passkeys] rename:", err);
    return c.redirect("/settings/passkeys?error=Service+unavailable");
  }
});

// --- Registration JSON endpoints (authed) -----------------------------------

passkeys.post("/api/passkeys/register/options", async (c) => {
  const user = c.get("user")!;
  try {
    const existing = await db
      .select({ credentialId: userPasskeys.credentialId })
      .from(userPasskeys)
      .where(eq(userPasskeys.userId, user.id));
    const { options, sessionKey } = await startRegistration({
      userId: user.id,
      userName: user.username,
      userDisplayName: user.displayName || user.username,
      excludeCredentialIds: existing.map((e) => e.credentialId),
    });
    return c.json({ options, sessionKey });
  } catch (err) {
    console.error("[passkeys] register/options:", err);
    return c.json({ error: "Service unavailable" }, 503);
  }
});

passkeys.post("/api/passkeys/register/verify", async (c) => {
  const user = c.get("user")!;
  let body: { sessionKey: string; response: any };
  try {
    body = await c.req.json();
  } catch {
    return c.json({ error: "Invalid JSON" }, 400);
  }
  if (!body.sessionKey || !body.response) {
    return c.json({ error: "sessionKey and response required" }, 400);
  }
  const result = await finishRegistration({
    sessionKey: body.sessionKey,
    response: body.response,
  });
  if (!result.ok) return c.json({ error: result.error }, 400);

  try {
    const transports = Array.isArray(body.response?.response?.transports)
      ? JSON.stringify(body.response.response.transports)
      : null;
    await db.insert(userPasskeys).values({
      userId: user.id,
      credentialId: result.credentialId,
      publicKey: result.publicKey,
      counter: result.counter,
      transports,
    });
    await audit({
      userId: user.id,
      action: "passkey.create",
      targetType: "passkey",
      metadata: { credentialId: result.credentialId },
    });
    return c.json({ ok: true });
  } catch (err: any) {
    if (String(err?.message || err).includes("user_passkeys")) {
      return c.json({ error: "Credential already registered" }, 409);
    }
    console.error("[passkeys] register save:", err);
    return c.json({ error: "Service unavailable" }, 503);
  }
});

// --- Authentication JSON endpoints (unauthed) -------------------------------

passkeys.post("/api/passkeys/auth/options", async (c) => {
  let body: { username?: string };
  try {
    body = await c.req.json();
  } catch {
    body = {};
  }
  try {
    let userId: string | undefined;
    let allowCreds: string[] = [];
    if (body.username) {
      const [u] = await db
        .select({ id: users.id })
        .from(users)
        .where(eq(users.username, body.username.trim().toLowerCase()))
        .limit(1);
      if (u) {
        userId = u.id;
        const rows = await db
          .select({ credentialId: userPasskeys.credentialId })
          .from(userPasskeys)
          .where(eq(userPasskeys.userId, u.id));
        allowCreds = rows.map((r) => r.credentialId);
      }
    }
    const { options, sessionKey } = await startAuthentication({
      userId,
      allowCredentialIds: allowCreds,
    });
    return c.json({ options, sessionKey });
  } catch (err) {
    console.error("[passkeys] auth/options:", err);
    return c.json({ error: "Service unavailable" }, 503);
  }
});

passkeys.post("/api/passkeys/auth/verify", async (c) => {
  let body: { sessionKey: string; response: any };
  try {
    body = await c.req.json();
  } catch {
    return c.json({ error: "Invalid JSON" }, 400);
  }
  if (!body.sessionKey || !body.response) {
    return c.json({ error: "sessionKey and response required" }, 400);
  }
  const result = await finishAuthentication({
    sessionKey: body.sessionKey,
    response: body.response,
  });
  if (!result.ok) return c.json({ error: result.error }, 400);

  try {
    // Passkey is phishing-resistant + user-verifying; skip TOTP prompt.
    const token = generateSessionToken();
    await db.insert(sessions).values({
      userId: result.userId,
      token,
      expiresAt: sessionExpiry(),
      requires2fa: false,
    });
    setCookie(c, "session", token, sessionCookieOptions());
    await audit({
      userId: result.userId,
      action: "passkey.login",
      targetType: "passkey",
      metadata: { credentialId: result.credentialId },
    });
    return c.json({ ok: true });
  } catch (err) {
    console.error("[passkeys] auth/verify:", err);
    return c.json({ error: "Service unavailable" }, 503);
  }
});

export default passkeys;