Line data Source code
1 : import { z } from 'zod'
2 :
3 2352 : const zClaims = z.object({
4 : sub: z.string().min(1),
5 : email: z.string().optional(),
6 : name: z.string().optional(),
7 : workspace_id: z.string().optional()
8 : })
9 :
10 : export interface AccessTokenIdentity {
11 : userId: string
12 : email?: string
13 : name?: string
14 : workspaceId?: string
15 : }
16 :
17 117 : function decodeSegment(segment: string): unknown {
18 117 : const base64 = segment.replace(/-/g, '+').replace(/_/g, '/')
19 117 : const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))
20 117 : return JSON.parse(new TextDecoder().decode(bytes))
21 : }
22 :
23 : /**
24 : * The account and workspace the Cloud access token was issued for, read from
25 : * its claims as Desktop does. Nothing here grants access: Cloud verifies the
26 : * signature on every request.
27 : */
28 117 : export function readAccessTokenIdentity(
29 : accessToken: string
30 : ): AccessTokenIdentity | undefined {
31 117 : const payload = accessToken.split('.').at(1)
32 117 : if (payload === undefined) return undefined
33 117 : let decoded: unknown
34 117 : try {
35 117 : decoded = decodeSegment(payload)
36 : } catch {
37 0 : return undefined
38 : }
39 117 : const claims = zClaims.safeParse(decoded)
40 117 : if (!claims.success) return undefined
41 117 : const { sub, email, name, workspace_id } = claims.data
42 117 : return { userId: sub, email, name, workspaceId: workspace_id }
43 : }
|