Skip to content

Commit 921f815

Browse files
fix(web,den): enforce app auth callback and backfill Polar paid access (anomalyco#658)
1 parent 18a1116 commit 921f815

4 files changed

Lines changed: 101 additions & 5 deletions

File tree

‎packages/web/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ Frontend for `app.openwork.software`.
2727
- `NEXT_PUBLIC_OPENWORK_APP_CONNECT_URL` (client): Base URL for "Open in App" links.
2828
- Example: `https://openwork.software/app`
2929
- The web panel appends `/connect-remote` and injects worker URL/token params automatically.
30+
- `NEXT_PUBLIC_OPENWORK_AUTH_CALLBACK_URL` (client): Canonical URL used for GitHub auth callback redirects.
31+
- default: `https://app.openwork.software`
3032

3133
## Deploy on Vercel
3234

‎packages/web/components/cloud-control.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,15 @@ const LAST_WORKER_STORAGE_KEY = "openwork:web:last-worker";
7171
const WORKER_STATUS_POLL_MS = 5000;
7272
const DEFAULT_AUTH_NAME = "OpenWork User";
7373
const OPENWORK_APP_CONNECT_BASE_URL = (process.env.NEXT_PUBLIC_OPENWORK_APP_CONNECT_URL ?? "").trim();
74+
const OPENWORK_AUTH_CALLBACK_BASE_URL = (process.env.NEXT_PUBLIC_OPENWORK_AUTH_CALLBACK_URL ?? "https://app.openwork.software").trim();
75+
76+
function getGithubCallbackUrl(): string {
77+
try {
78+
return new URL("/", OPENWORK_AUTH_CALLBACK_BASE_URL || "https://app.openwork.software").toString();
79+
} catch {
80+
return "https://app.openwork.software/";
81+
}
82+
}
7483

7584
function isRecord(value: unknown): value is Record<string, unknown> {
7685
return typeof value === "object" && value !== null;
@@ -1073,7 +1082,7 @@ export function CloudControlPanel() {
10731082
setAuthInfo("Redirecting to GitHub...");
10741083

10751084
try {
1076-
const callbackURL = window.location.href;
1085+
const callbackURL = getGithubCallbackUrl();
10771086
const { response, payload } = await requestJson("/api/auth/sign-in/social", {
10781087
method: "POST",
10791088
body: JSON.stringify({

‎services/den/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ pnpm db:migrate
7373
- `POST /v1/workers`
7474
- Cloud launches return `202` quickly with worker `status=provisioning` and continue provisioning asynchronously.
7575
- Returns `402 payment_required` with Polar checkout URL when paywall is enabled and entitlement is missing.
76+
- Existing Polar customers are matched by `external_customer_id` first, then by email to preserve access for pre-existing paid users.
7677
- `GET /v1/workers/:id`
7778
- Includes latest instance metadata when available.
7879
- `POST /v1/workers/:id/tokens`

‎services/den/src/billing/polar.ts‎

Lines changed: 88 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
1323
export 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+
3250
async 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

82157
function 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

Comments
 (0)