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
oauth.ts5.8 KB · 197 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
/**
 * OAuth 2.0 helpers (Block B6).
 *
 * Stateless utilities for the OAuth provider implemented in
 * `src/routes/oauth.tsx`:
 *
 *   - token / code / secret generation
 *   - constant-time SHA-256 hashing (matches how we store PATs)
 *   - PKCE (RFC 7636) code_challenge verification
 *   - scope parsing + validation
 *   - redirect-URI matching (exact match, no wildcards)
 *
 * All outputs that end up in URLs or Authorization headers are prefix-tagged
 * so they're greppable in logs without leaking the secret portion.
 */

/** Supported OAuth scopes. Add new ones here + document on the consent screen. */
export const SUPPORTED_SCOPES = [
  "read:user",
  "read:repo",
  "write:repo",
  "read:org",
  "write:org",
  "read:issue",
  "write:issue",
  "read:pr",
  "write:pr",
] as const;

export type OauthScope = (typeof SUPPORTED_SCOPES)[number];

/** Default access token TTL (1 hour). */
export const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000;
/** Refresh token TTL (30 days). */
export const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
/** Authorization code TTL (10 min — well within RFC 6749's 10-minute max). */
export const AUTH_CODE_TTL_MS = 10 * 60 * 1000;

function randomHex(byteLen: number): string {
  const bytes = crypto.getRandomValues(new Uint8Array(byteLen));
  let s = "";
  for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
  return s;
}

/** Returns a 20-char client_id like `glc_app_<12 hex>`. */
export function generateClientId(): string {
  return "glc_app_" + randomHex(12);
}

/** Returns a 40-char client secret like `glcs_<32 hex>`. */
export function generateClientSecret(): string {
  return "glcs_" + randomHex(32);
}

export function generateAuthCode(): string {
  return "glca_" + randomHex(24);
}

export function generateAccessToken(): string {
  return "glct_" + randomHex(32);
}

export function generateRefreshToken(): string {
  return "glcr_" + randomHex(32);
}

/** SHA-256 hex digest. Same algorithm as src/routes/tokens.ts. */
export async function sha256Hex(input: string): Promise<string> {
  const data = new TextEncoder().encode(input);
  const digest = await crypto.subtle.digest("SHA-256", data);
  const bytes = new Uint8Array(digest);
  let s = "";
  for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
  return s;
}

/** Base64url (no padding) — used by PKCE. */
export function b64urlFromBytes(bytes: Uint8Array): string {
  let bin = "";
  for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
  return btoa(bin)
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

/**
 * PKCE verification (RFC 7636).
 * For "S256": base64url(SHA-256(verifier)) must equal the challenge.
 * For "plain": the verifier must equal the challenge literally.
 * Returns true when the method is unrecognized but `challenge` is empty —
 * callers should refuse before calling this if PKCE is required.
 */
export async function verifyPkce(opts: {
  challenge: string | null | undefined;
  method: string | null | undefined;
  verifier: string;
}): Promise<boolean> {
  const challenge = (opts.challenge || "").trim();
  if (!challenge) return false;
  const method = (opts.method || "plain").toLowerCase();

  if (method === "s256") {
    const data = new TextEncoder().encode(opts.verifier);
    const digest = await crypto.subtle.digest("SHA-256", data);
    const produced = b64urlFromBytes(new Uint8Array(digest));
    return timingSafeEqual(produced, challenge);
  }
  if (method === "plain") {
    return timingSafeEqual(opts.verifier, challenge);
  }
  return false;
}

/** Constant-time string comparison. */
export function timingSafeEqual(a: string, b: string): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

/**
 * Parse a scope string (space-separated per RFC 6749 or comma-separated for
 * convenience). Unknown scopes are dropped silently; duplicates collapsed.
 */
export function parseScopes(input: string | null | undefined): OauthScope[] {
  if (!input) return [];
  const parts = input.split(/[\s,]+/).filter(Boolean);
  const seen = new Set<string>();
  const out: OauthScope[] = [];
  for (const p of parts) {
    const s = p.trim().toLowerCase();
    if (!s || seen.has(s)) continue;
    if ((SUPPORTED_SCOPES as readonly string[]).includes(s)) {
      out.push(s as OauthScope);
      seen.add(s);
    }
  }
  return out;
}

/** Serialize scopes back to a space-separated string. */
export function serializeScopes(scopes: readonly OauthScope[]): string {
  return scopes.join(" ");
}

/**
 * Parse an app's stored `redirectUris` column (newline-separated).
 * Empty / whitespace-only lines are ignored.
 */
export function parseRedirectUris(stored: string): string[] {
  return stored
    .split(/\r?\n/)
    .map((s) => s.trim())
    .filter(Boolean);
}

/**
 * Validate a single redirect URI for storage:
 *  - must be absolute http(s):// (http only for localhost)
 *  - no fragment (`#...`)
 *  - no wildcards
 */
export function isValidRedirectUri(uri: string): boolean {
  try {
    const u = new URL(uri);
    if (u.protocol !== "http:" && u.protocol !== "https:") return false;
    if (u.protocol === "http:") {
      if (!["localhost", "127.0.0.1", "[::1]"].includes(u.hostname)) {
        return false;
      }
    }
    if (u.hash) return false;
    if (uri.includes("*")) return false;
    return true;
  } catch {
    return false;
  }
}

/** Exact-match check against the app's registered list. */
export function redirectUriAllowed(
  candidate: string,
  registered: readonly string[]
): boolean {
  if (!candidate) return false;
  for (const r of registered) {
    if (timingSafeEqual(candidate, r)) return true;
  }
  return false;
}

export const __test = {
  randomHex,
};