File size: 6,422 Bytes
654b283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createRepo, repoExists, uploadFile, whoAmI } from "@huggingface/hub";
import type { NextRequest } from "next/server";
import { z } from "zod";

import type { SignupSession } from "./session";

const DEFAULT_HUB_URL = "https://huggingface.co";
const OAUTH_SCOPE = "openid profile email";
const EVENT_NAME = "Humanity's Last Hackathon";
const EVENT_OBJECTIVE = "Write Mac Metal kernels with Codex.";

const tokenResponseSchema = z.object({
  access_token: z.string().min(1),
  expires_in: z.number().int().positive(),
  scope: z.string().min(1),
  token_type: z.string().min(1),
});

const userInfoSchema = z.object({
  sub: z.string().min(1),
  name: z.string(),
  preferred_username: z.string().min(1),
  email: z.string().email().optional(),
  email_verified: z.boolean().optional(),
  picture: z.string().url(),
  profile: z.string().url(),
  website: z.string().url().optional(),
  isPro: z.boolean(),
});

export interface SignupRecord {
  schemaVersion: 2;
  event: {
    name: string;
    objective: string;
  };
  signedUpAt: string;
  source: {
    type: "huggingface-oauth";
    scope: string;
  };
  participant: {
    hf: {
      id: string;
      username: string;
      fullName: string;
      email: string;
      emailVerified: boolean;
      avatarUrl: string;
      profileUrl: string;
      website: string | null;
      isPro: boolean;
    };
  };
}

function getHubUrl(): string {
  return (process.env.HF_HUB_URL?.trim() || DEFAULT_HUB_URL).replace(/\/+$/, "");
}

function requireEnv(name: string): string {
  const value = process.env[name]?.trim();

  if (!value) {
    throw new Error(`Missing ${name}.`);
  }

  return value;
}

export function getAppUrl(request?: NextRequest): string {
  const configured = process.env.APP_URL?.trim();

  if (configured) {
    return configured.replace(/\/+$/, "");
  }

  if (!request) {
    return "http://localhost:3000";
  }

  const forwardedProto = request.headers.get("x-forwarded-proto");
  const forwardedHost = request.headers.get("x-forwarded-host") ?? request.headers.get("host");

  if (forwardedProto && forwardedHost) {
    return `${forwardedProto}://${forwardedHost}`;
  }

  return new URL(request.url).origin;
}

export function getOAuthRedirectUri(request?: NextRequest): string {
  return `${getAppUrl(request)}/api/auth/huggingface/callback`;
}

export function createOAuthAuthorizationUrl(params: {
  state: string;
  codeChallenge: string;
  request?: NextRequest;
}): string {
  const search = new URLSearchParams({
    client_id: requireEnv("HF_OAUTH_CLIENT_ID"),
    redirect_uri: getOAuthRedirectUri(params.request),
    response_type: "code",
    scope: OAUTH_SCOPE,
    state: params.state,
    code_challenge: params.codeChallenge,
    code_challenge_method: "S256",
  });

  return `${getHubUrl()}/oauth/authorize?${search.toString()}`;
}

export async function exchangeCodeForToken(params: {
  code: string;
  codeVerifier: string;
  redirectUri: string;
}) {
  const response = await fetch(`${getHubUrl()}/oauth/token`, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code: params.code,
      redirect_uri: params.redirectUri,
      client_id: requireEnv("HF_OAUTH_CLIENT_ID"),
      client_secret: requireEnv("HF_OAUTH_CLIENT_SECRET"),
      code_verifier: params.codeVerifier,
    }),
  });

  if (!response.ok) {
    throw new Error(`Hugging Face token exchange failed with status ${response.status}.`);
  }

  return tokenResponseSchema.parse(await response.json());
}

export async function fetchUserInfo(accessToken: string) {
  const response = await fetch(`${getHubUrl()}/oauth/userinfo`, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });

  if (!response.ok) {
    throw new Error(`Hugging Face userinfo failed with status ${response.status}.`);
  }

  return userInfoSchema.parse(await response.json());
}

export async function fetchViewer(accessToken: string) {
  const viewer = await whoAmI({ accessToken });

  if (viewer.type !== "user") {
    throw new Error("Expected a user account from Hugging Face OAuth.");
  }

  return viewer;
}

export function createSignupRecord(params: { session: SignupSession }): SignupRecord {
  const signedUpAt = new Date().toISOString();

  return {
    schemaVersion: 2,
    event: {
      name: EVENT_NAME,
      objective: EVENT_OBJECTIVE,
    },
    signedUpAt,
    source: {
      type: "huggingface-oauth",
      scope: OAUTH_SCOPE,
    },
    participant: {
      hf: {
        id: params.session.id,
        username: params.session.username,
        fullName: params.session.name,
        email: params.session.email,
        emailVerified: params.session.emailVerified,
        avatarUrl: params.session.avatarUrl,
        profileUrl: params.session.profileUrl,
        website: params.session.website,
        isPro: params.session.isPro,
      },
    },
  };
}

function createDatasetReadme(): string {
  return `---
tags:
- private
- registrations
- hackathon
---

# Humanity's Last Hackathon Signups

Private registration dataset for the Humanity's Last Hackathon landing page.

- Event: ${EVENT_NAME}
- Objective: ${EVENT_OBJECTIVE}
- Source: simple Hugging Face OAuth signup app

Each participant record is stored at \`signups/<hf-user-id>.json\`.
`;
}

export async function storeSignupRecord(record: SignupRecord) {
  const repo = {
    type: "dataset" as const,
    name: requireEnv("HF_DATASET_REPO"),
  };

  const accessToken = requireEnv("HF_DATASET_WRITE_TOKEN");
  const filePath = `signups/${record.participant.hf.id}.json`;

  if (!(await repoExists({ repo, accessToken }))) {
    await createRepo({
      repo,
      accessToken,
      private: true,
      files: [
        {
          path: "README.md",
          content: new Blob([createDatasetReadme()], { type: "text/markdown" }),
        },
      ],
    });
  }

  await uploadFile({
    repo,
    accessToken,
    file: {
      path: filePath,
      content: new Blob([`${JSON.stringify(record, null, 2)}\n`], {
        type: "application/json",
      }),
    },
    commitTitle: `Register ${record.participant.hf.username} for Humanity's Last Hackathon`,
    commitDescription: "Write or update a signup record from the Hugging Face OAuth signup app.",
  });

  return {
    repoName: repo.name,
    path: filePath,
  };
}