forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.ts
More file actions
170 lines (148 loc) · 4.87 KB
/
Copy pathtoken.ts
File metadata and controls
170 lines (148 loc) · 4.87 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import { ANTIGRAVITY_CLIENT_ID, ANTIGRAVITY_CLIENT_SECRET } from "../constants";
import { formatRefreshParts, parseRefreshParts, calculateTokenExpiry } from "./auth";
import { clearCachedAuth, storeCachedAuth } from "./cache";
import { createLogger } from "./logger";
import { invalidateProjectContextCache } from "./project";
import type { OAuthAuthDetails, PluginClient, RefreshParts } from "./types";
const log = createLogger("token");
interface OAuthErrorPayload {
error?:
| string
| {
code?: string;
status?: string;
message?: string;
};
error_description?: string;
}
/**
* Parses OAuth error payloads returned by Google token endpoints, tolerating varied shapes.
*/
function parseOAuthErrorPayload(text: string | undefined): { code?: string; description?: string } {
if (!text) {
return {};
}
try {
const payload = JSON.parse(text) as OAuthErrorPayload;
if (!payload || typeof payload !== "object") {
return { description: text };
}
let code: string | undefined;
if (typeof payload.error === "string") {
code = payload.error;
} else if (payload.error && typeof payload.error === "object") {
code = payload.error.status ?? payload.error.code;
if (!payload.error_description && payload.error.message) {
return { code, description: payload.error.message };
}
}
const description = payload.error_description;
if (description) {
return { code, description };
}
if (payload.error && typeof payload.error === "object" && payload.error.message) {
return { code, description: payload.error.message };
}
return { code };
} catch {
return { description: text };
}
}
export class AntigravityTokenRefreshError extends Error {
code?: string;
description?: string;
status: number;
statusText: string;
constructor(options: {
message: string;
code?: string;
description?: string;
status: number;
statusText: string;
}) {
super(options.message);
this.name = "AntigravityTokenRefreshError";
this.code = options.code;
this.description = options.description;
this.status = options.status;
this.statusText = options.statusText;
}
}
/**
* Refreshes an Antigravity OAuth access token, updates persisted credentials, and handles revocation.
*/
export async function refreshAccessToken(
auth: OAuthAuthDetails,
client: PluginClient,
providerId: string,
): Promise<OAuthAuthDetails | undefined> {
const parts = parseRefreshParts(auth.refresh);
if (!parts.refreshToken) {
return undefined;
}
try {
const startTime = Date.now();
const response = await fetch("https://oauth2.googleapis.com/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: parts.refreshToken,
client_id: ANTIGRAVITY_CLIENT_ID,
client_secret: ANTIGRAVITY_CLIENT_SECRET,
}),
});
if (!response.ok) {
let errorText: string | undefined;
try {
errorText = await response.text();
} catch {
errorText = undefined;
}
const { code, description } = parseOAuthErrorPayload(errorText);
const details = [code, description ?? errorText].filter(Boolean).join(": ");
const baseMessage = `Antigravity token refresh failed (${response.status} ${response.statusText})`;
const message = details ? `${baseMessage} - ${details}` : baseMessage;
log.warn("Token refresh failed", { status: response.status, code, details });
if (code === "invalid_grant") {
log.warn("Google revoked the stored refresh token - reauthentication required");
invalidateProjectContextCache(auth.refresh);
clearCachedAuth(auth.refresh);
}
throw new AntigravityTokenRefreshError({
message,
code,
description: description ?? errorText,
status: response.status,
statusText: response.statusText,
});
}
const payload = (await response.json()) as {
access_token: string;
expires_in: number;
refresh_token?: string;
};
const refreshedParts: RefreshParts = {
refreshToken: payload.refresh_token ?? parts.refreshToken,
projectId: parts.projectId,
managedProjectId: parts.managedProjectId,
};
const updatedAuth: OAuthAuthDetails = {
...auth,
access: payload.access_token,
expires: calculateTokenExpiry(startTime, payload.expires_in),
refresh: formatRefreshParts(refreshedParts),
};
storeCachedAuth(updatedAuth);
invalidateProjectContextCache(auth.refresh);
return updatedAuth;
} catch (error) {
if (error instanceof AntigravityTokenRefreshError) {
throw error;
}
log.error("Unexpected token refresh error", { error: String(error) });
return undefined;
}
}