@@ -10,6 +10,16 @@ type PolarCheckoutSession = {
1010 url ?: string
1111}
1212
13+ type PolarCustomer = {
14+ id ?: string
15+ email ?: string
16+ external_id ?: string | null
17+ }
18+
19+ type PolarCustomerList = {
20+ items ?: PolarCustomer [ ]
21+ }
22+
1323export type CloudWorkerAccess =
1424 | {
1525 allowed : true
@@ -29,6 +39,14 @@ function sanitizeApiBase(value: string) {
2939 return value . replace ( / \/ + $ / , "" )
3040}
3141
42+ function parseJson < T > ( text : string ) : T | null {
43+ if ( ! text ) {
44+ return null
45+ }
46+
47+ return JSON . parse ( text ) as T
48+ }
49+
3250async function polarFetch ( path : string , init : RequestInit = { } ) {
3351 const headers = new Headers ( init . headers )
3452 headers . set ( "Authorization" , `Bearer ${ env . polar . accessToken } ` )
@@ -61,7 +79,7 @@ function assertPaywallConfig() {
6179 }
6280}
6381
64- async function getCustomerState ( externalCustomerId : string ) : Promise < PolarCustomerState | null > {
82+ async function getCustomerStateByExternalId ( externalCustomerId : string ) : Promise < PolarCustomerState | null > {
6583 const encodedExternalId = encodeURIComponent ( externalCustomerId )
6684 const response = await polarFetch ( `/v1/customers/external/${ encodedExternalId } /state` , {
6785 method : "GET" ,
@@ -76,7 +94,64 @@ async function getCustomerState(externalCustomerId: string): Promise<PolarCustom
7694 throw new Error ( `Polar customer state lookup failed (${ response . status } ): ${ text . slice ( 0 , 400 ) } ` )
7795 }
7896
79- return text ? ( JSON . parse ( text ) as PolarCustomerState ) : null
97+ return parseJson < PolarCustomerState > ( text )
98+ }
99+
100+ async function getCustomerStateById ( customerId : string ) : Promise < PolarCustomerState | null > {
101+ const encodedCustomerId = encodeURIComponent ( customerId )
102+ const response = await polarFetch ( `/v1/customers/${ encodedCustomerId } /state` , {
103+ method : "GET" ,
104+ } )
105+
106+ if ( response . status === 404 ) {
107+ return null
108+ }
109+
110+ const text = await response . text ( )
111+ if ( ! response . ok ) {
112+ throw new Error ( `Polar customer state lookup by ID failed (${ response . status } ): ${ text . slice ( 0 , 400 ) } ` )
113+ }
114+
115+ return parseJson < PolarCustomerState > ( text )
116+ }
117+
118+ async function getCustomerByEmail ( email : string ) : Promise < PolarCustomer | null > {
119+ const normalizedEmail = email . trim ( ) . toLowerCase ( )
120+ if ( ! normalizedEmail ) {
121+ return null
122+ }
123+
124+ const encodedEmail = encodeURIComponent ( normalizedEmail )
125+ const response = await polarFetch ( `/v1/customers/?email=${ encodedEmail } ` , {
126+ method : "GET" ,
127+ } )
128+ const text = await response . text ( )
129+ if ( ! response . ok ) {
130+ throw new Error ( `Polar customer lookup by email failed (${ response . status } ): ${ text . slice ( 0 , 400 ) } ` )
131+ }
132+
133+ const payload = parseJson < PolarCustomerList > ( text )
134+ const customers = payload ?. items ?? [ ]
135+ const exact = customers . find ( ( customer ) => customer . email ?. trim ( ) . toLowerCase ( ) === normalizedEmail )
136+ return exact ?? customers [ 0 ] ?? null
137+ }
138+
139+ async function linkCustomerExternalId ( customer : PolarCustomer , externalCustomerId : string ) : Promise < void > {
140+ if ( ! customer . id ) {
141+ return
142+ }
143+
144+ if ( typeof customer . external_id === "string" && customer . external_id . length > 0 ) {
145+ return
146+ }
147+
148+ const encodedCustomerId = encodeURIComponent ( customer . id )
149+ await polarFetch ( `/v1/customers/${ encodedCustomerId } ` , {
150+ method : "PATCH" ,
151+ body : JSON . stringify ( {
152+ external_id : externalCustomerId ,
153+ } ) ,
154+ } )
80155}
81156
82157function hasRequiredBenefit ( state : PolarCustomerState | null ) {
@@ -122,11 +197,20 @@ export async function requireCloudWorkerAccess(input: CloudAccessInput): Promise
122197
123198 assertPaywallConfig ( )
124199
125- const state = await getCustomerState ( input . userId )
126- if ( hasRequiredBenefit ( state ) ) {
200+ const externalState = await getCustomerStateByExternalId ( input . userId )
201+ if ( hasRequiredBenefit ( externalState ) ) {
127202 return { allowed : true }
128203 }
129204
205+ const customer = await getCustomerByEmail ( input . email )
206+ if ( customer ?. id ) {
207+ const emailState = await getCustomerStateById ( customer . id )
208+ if ( hasRequiredBenefit ( emailState ) ) {
209+ await linkCustomerExternalId ( customer , input . userId ) . catch ( ( ) => undefined )
210+ return { allowed : true }
211+ }
212+ }
213+
130214 const checkoutUrl = await createCheckoutSession ( input )
131215 return {
132216 allowed : false ,
0 commit comments