onenoly11 commited on
Commit
b98da66
·
verified ·
1 Parent(s): 1224285

Create api/pi-auth-complete.ts

Browse files
Files changed (1) hide show
  1. api/pi-auth-complete.ts +49 -0
api/pi-auth-complete.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { VercelRequest, VercelResponse } from "@vercel/node";
2
+ import crypto from "crypto";
3
+
4
+ const SESSION_TTL_SECONDS = 10 * 60; // 10 minutes
5
+ const FORGE_SESSION_SECRET = process.env.FORGE_SESSION_SECRET!;
6
+
7
+ function signSession(payload: any): string {
8
+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
9
+ const sig = crypto
10
+ .createHmac("sha256", FORGE_SESSION_SECRET)
11
+ .update(body)
12
+ .digest("base64url");
13
+ return `${body}.${sig}`;
14
+ }
15
+
16
+ export default async function handler(req: VercelRequest, res: VercelResponse) {
17
+ if (req.method !== "POST") return res.status(405).end();
18
+
19
+ try {
20
+ const authResult = req.body;
21
+
22
+ // For now we trust authResult structure (replace with actual Pi verification):
23
+ const pi_uid = authResult.user?.uid;
24
+ const username = authResult.user?.username;
25
+ if (!pi_uid || !username) {
26
+ return res.status(400).json({ error: "Missing user info from Pi." });
27
+ }
28
+
29
+ // Mint short-lived Forge Session Token
30
+ const now = Math.floor(Date.now() / 1000);
31
+ const payload = {
32
+ pi_uid,
33
+ username,
34
+ iat: now,
35
+ exp: now + SESSION_TTL_SECONDS,
36
+ scope: "agent-session"
37
+ };
38
+
39
+ const session_token = signSession(payload);
40
+
41
+ return res.status(200).json({
42
+ status: "ok",
43
+ session_token
44
+ });
45
+ } catch (e: any) {
46
+ console.error(e);
47
+ return res.status(500).json({ error: "pi_auth_failed", message: e.message });
48
+ }
49
+ }