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
password-reset.ts8.3 KB · 200 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
/**
 * Block P1 — Password reset flow.
 *
 * Public surface:
 *   - generateResetToken()
 *   - createPasswordResetRequest()  → always { ok: true }
 *   - consumeResetToken()
 *   - inspectResetToken()
 *
 * Security:
 *   - Plaintext token NEVER persists; we store only SHA-256(token).
 *   - createPasswordResetRequest never reveals whether the email exists.
 *   - consumeResetToken rotates the password AND drops every session.
 */

import { eq } from "drizzle-orm";
import { db } from "../db";
import { users, sessions, passwordResetTokens } from "../db/schema";
import { hashPassword } from "./auth";
import { sendEmail, absoluteUrl, type EmailMessage } from "./email";

const RESET_TTL_MS = 60 * 60 * 1000; // 1 hour

// Test seam — swap the email sender without mock.module.
type EmailSender = (msg: EmailMessage) => Promise<unknown> | unknown;
let _emailSender: EmailSender = sendEmail;
export function __setEmailForTests(fn: EmailSender | null): void {
  _emailSender = fn ?? sendEmail;
}

function toHex(bytes: Uint8Array): string {
  let out = "";
  for (let i = 0; i < bytes.length; i++) out += bytes[i]!.toString(16).padStart(2, "0");
  return out;
}

async function sha256Hex(input: string): Promise<string> {
  const buf = new TextEncoder().encode(input);
  const digest = await crypto.subtle.digest("SHA-256", buf);
  return toHex(new Uint8Array(digest));
}

export function generateResetToken(): { plaintext: string; hash: string } {
  const bytes = crypto.getRandomValues(new Uint8Array(32));
  const plaintext = toHex(bytes);
  const hasher = new Bun.CryptoHasher("sha256");
  hasher.update(plaintext);
  const hash = hasher.digest("hex");
  return { plaintext, hash };
}

function escapeHtml(s: string): string {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}

function buildResetEmail(opts: { username: string; resetUrl: string }) {
  const subject = "Reset your Gluecron password";
  const text = [
    `Hi ${opts.username},`,
    "",
    "We received a request to reset the password for your Gluecron account.",
    "",
    `Reset your password: ${opts.resetUrl}`,
    "",
    "This link expires in 1 hour. If you didn't request a reset, ignore",
    "this email — your password won't change.",
    "",
    "— gluecron",
  ].join("\n");

  const safeUser = escapeHtml(opts.username);
  const safeUrl = escapeHtml(opts.resetUrl);
  const html = `<!doctype html>
<html><head><meta charset="utf-8"><title>${escapeHtml(subject)}</title></head>
<body style="margin:0;padding:0;background:#0d1117;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;color:#c9d1d9">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#0d1117">
    <tr><td align="center" style="padding:32px 16px">
      <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;background:#161b22;border:1px solid #30363d;border-radius:12px;overflow:hidden">
        <tr><td style="background:linear-gradient(135deg,#8c6dff 0%,#36c5d6 100%);padding:24px 28px">
          <div style="font-size:20px;font-weight:700;color:#fff;letter-spacing:-0.01em">gluecron</div>
          <div style="font-size:13px;color:rgba(255,255,255,0.85);margin-top:2px">Password reset</div>
        </td></tr>
        <tr><td style="padding:28px">
          <p style="margin:0 0 12px;font-size:15px;color:#e6edf3">Hi ${safeUser},</p>
          <p style="margin:0 0 16px;font-size:14px;line-height:1.55;color:#c9d1d9">We received a request to reset the password for your Gluecron account.</p>
          <p style="margin:0 0 24px"><a href="${safeUrl}" style="display:inline-block;background:linear-gradient(135deg,#8c6dff 0%,#36c5d6 100%);color:#fff;text-decoration:none;font-weight:600;font-size:14px;padding:11px 22px;border-radius:9999px">Reset password</a></p>
          <p style="margin:0 0 8px;font-size:13px;color:#8b949e">Or copy this link into your browser:</p>
          <p style="margin:0 0 24px;font-size:12px;color:#8b949e;word-break:break-all"><a href="${safeUrl}" style="color:#58a6ff;text-decoration:none">${safeUrl}</a></p>
          <p style="margin:0;font-size:12px;color:#8b949e;line-height:1.55">This link expires in 1 hour. If you didn't request a reset, ignore this email — your password won't change.</p>
        </td></tr>
        <tr><td style="padding:16px 28px;border-top:1px solid #30363d;font-size:11px;color:#6e7681">gluecron — AI-native code intelligence</td></tr>
      </table>
    </td></tr>
  </table>
</body></html>`;

  return { subject, text, html };
}

export function buildResetUrl(plaintextToken: string): string {
  const path = `/reset-password?token=${encodeURIComponent(plaintextToken)}&utm_source=password_reset`;
  return absoluteUrl(path);
}

export async function createPasswordResetRequest(
  email: string,
  opts: { requestIp?: string } = {}
): Promise<{ ok: boolean }> {
  const normalized = String(email || "").trim().toLowerCase();
  if (!normalized || !normalized.includes("@")) return { ok: true };

  try {
    const [user] = await db
      .select({ id: users.id, username: users.username, email: users.email })
      .from(users)
      .where(eq(users.email, normalized))
      .limit(1);

    if (!user) {
      console.error(`[password-reset] no user for email=${JSON.stringify(normalized)} ip=${opts.requestIp || "?"} — generic success returned`);
      return { ok: true };
    }

    const { plaintext, hash } = generateResetToken();
    const expiresAt = new Date(Date.now() + RESET_TTL_MS);

    await db.insert(passwordResetTokens).values({
      userId: user.id,
      tokenHash: hash,
      expiresAt,
      requestIp: opts.requestIp || null,
    });

    const resetUrl = buildResetUrl(plaintext);
    const msg = buildResetEmail({ username: user.username, resetUrl });

    // Fire-and-forget — don't block the response on email send.
    Promise.resolve()
      .then(() => _emailSender({ to: user.email, subject: msg.subject, text: msg.text, html: msg.html }))
      .catch((err) => console.error("[password-reset] email send error:", err));

    return { ok: true };
  } catch (err) {
    console.error("[password-reset] createPasswordResetRequest error:", err);
    return { ok: true };
  }
}

export async function consumeResetToken(
  token: string,
  newPassword: string
): Promise<{ ok: boolean; reason?: string }> {
  const plaintext = String(token || "").trim();
  if (!plaintext) return { ok: false, reason: "invalid" };
  if (!newPassword || newPassword.length < 8) return { ok: false, reason: "weak" };

  try {
    const hash = await sha256Hex(plaintext);
    const [row] = await db
      .select()
      .from(passwordResetTokens)
      .where(eq(passwordResetTokens.tokenHash, hash))
      .limit(1);

    if (!row) return { ok: false, reason: "invalid" };
    if (row.usedAt) return { ok: false, reason: "used" };
    if (new Date(row.expiresAt).getTime() < Date.now()) return { ok: false, reason: "expired" };

    const passwordHash = await hashPassword(newPassword);

    await db.update(users).set({ passwordHash, updatedAt: new Date() }).where(eq(users.id, row.userId));
    await db.update(passwordResetTokens).set({ usedAt: new Date() }).where(eq(passwordResetTokens.id, row.id));
    await db.delete(sessions).where(eq(sessions.userId, row.userId));

    return { ok: true };
  } catch (err) {
    console.error("[password-reset] consumeResetToken error:", err);
    return { ok: false, reason: "invalid" };
  }
}

export async function inspectResetToken(token: string): Promise<{ valid: boolean; reason?: string }> {
  const plaintext = String(token || "").trim();
  if (!plaintext) return { valid: false, reason: "invalid" };
  try {
    const hash = await sha256Hex(plaintext);
    const [row] = await db
      .select({ id: passwordResetTokens.id, expiresAt: passwordResetTokens.expiresAt, usedAt: passwordResetTokens.usedAt })
      .from(passwordResetTokens)
      .where(eq(passwordResetTokens.tokenHash, hash))
      .limit(1);
    if (!row) return { valid: false, reason: "invalid" };
    if (row.usedAt) return { valid: false, reason: "used" };
    if (new Date(row.expiresAt).getTime() < Date.now()) return { valid: false, reason: "expired" };
    return { valid: true };
  } catch (err) {
    console.error("[password-reset] inspectResetToken error:", err);
    return { valid: false, reason: "invalid" };
  }
}