-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathroute.ts
More file actions
47 lines (40 loc) · 1.51 KB
/
Copy pathroute.ts
File metadata and controls
47 lines (40 loc) · 1.51 KB
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
import { ApiError } from '@/lib/errors'
import fs from 'fs'
import { NextRequest, NextResponse } from 'next/server'
import path from 'path'
/**
* Internal endpoint for NextAuth to post refresh tokens.
* This endpoint is protected by an optional INTERNAL_TOKEN_DELIVERY_SECRET header.
* It persists the latest token payload to ./logs/spotify_tokens.json for the server to read.
*/
const LOG_DIR = path.resolve(process.cwd(), 'logs')
const OUT_FILE = path.join(LOG_DIR, 'spotify_tokens.json')
export async function POST(req: NextRequest) {
try {
const secretHeader = req.headers.get('x-internal-token-secret') || ''
const expected = process.env.INTERNAL_TOKEN_DELIVERY_SECRET || ''
if (expected && secretHeader !== expected) {
throw new ApiError(401, 'Unauthorized')
}
const payload = await req.json()
// ensure logs dir
if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true })
// write timestamped record (overwrite with latest)
const record = {
receivedAt: Date.now(),
payload,
}
fs.writeFileSync(OUT_FILE, JSON.stringify(record, null, 2), 'utf8')
console.log('Received token-delivery:', payload.sub ?? payload.provider)
return NextResponse.json({ ok: true })
} catch (err) {
if (err instanceof ApiError) {
return NextResponse.json(
{ error: err.message },
{ status: err.statusCode }
)
}
console.error('token-delivery error:', err)
return NextResponse.json({ error: 'server_error' }, { status: 500 })
}
}