Repository navigation
Expand file tree
/
Copy pathappwrite-auth.ts
More file actions
271 lines (240 loc) · 10.5 KB
/
Copy pathappwrite-auth.ts
File metadata and controls
271 lines (240 loc) · 10.5 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { Account, Client, OAuthProvider } from "appwrite";
import appwriteConfig from "./appwrite-config.js";
export type GuilduoUser = { uid: string; email: string; displayName: string; photoURL?: string };
// The subject is only a discard/matching hint. The server still verifies every
// prefetched GET, and no result may be rendered before account.get succeeds.
export type SessionReadPreparation = (token: string, subjectHint: string) => void;
type AppwriteAccount = { $id?: string; email?: string; name?: string; prefs?: Record<string, unknown> };
type AppwriteAccountPort = {
get: () => Promise<AppwriteAccount>;
createJWT: (params?: { duration?: number }) => Promise<{ jwt?: string }>;
createOAuth2Token: (params: { provider: OAuthProvider; success?: string; failure?: string; scopes?: string[] }) => void | string;
createSession: (params: { userId: string; secret: string }) => Promise<unknown>;
deleteSession: (params: { sessionId: string }) => Promise<unknown>;
};
export type GuilduoAuthState =
| { status: "authenticated"; user: GuilduoUser }
| { status: "signed-out" }
| { status: "oauth-failed" }
| { status: "connection-error"; error: unknown };
type AuthOptions = {
account: AppwriteAccountPort;
getReturnUrl?: () => string;
getOAuthCallback?: () => { userId: string; secret: string } | null;
clearOAuthCallback?: () => void;
now?: () => number;
prepareAccessToken?: boolean;
};
type BrowserLocation = { origin: string; pathname: string; search: string; hash: string; href: string };
type BrowserHistory = { state: unknown; replaceState: (data: unknown, unused: string, url?: string | URL | null) => void };
const endpoint = String(appwriteConfig.endpoint || "").replace(/\/$/, "");
const projectId = String(appwriteConfig.projectId || "");
function assertConfigured(): void {
if (!endpoint || !projectId || projectId === "YOUR_APPWRITE_PROJECT_ID") throw new Error("Appwrite is not configured");
}
function normalizeAccount(account: AppwriteAccount): GuilduoUser {
if (!account || typeof account.$id !== "string" || account.$id.trim() === "") throw new Error("Invalid Appwrite account identity");
const avatar = typeof account.prefs?.avatarUrl === "string" ? account.prefs.avatarUrl : "";
return { uid: account.$id, email: String(account.email || ""), displayName: String(account.name || account.email || ""), ...(avatar ? { photoURL: avatar } : {}) };
}
function isUnauthorized(error: unknown): boolean {
if (!error || typeof error !== "object") return false;
const candidate = error as { code?: unknown; status?: unknown };
return candidate.code === 401 || candidate.status === 401;
}
function sessionSubjectHint(token: string): string {
try {
const payload = token.split(".")[1];
const decoded = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/"))) as { userId?: unknown };
return typeof decoded.userId === "string" ? decoded.userId : "";
} catch { return ""; }
}
function browserReturnUrl(): string {
const browserLocation = (globalThis as unknown as { location?: BrowserLocation }).location;
if (!browserLocation) throw new Error("Browser location is unavailable");
const target = new URL(browserLocation.href);
for (const key of ["auth", "userId", "secret"]) target.searchParams.delete(key);
return target.toString();
}
function browserOAuthCallback(): { userId: string; secret: string } | null {
const browserLocation = (globalThis as unknown as { location?: BrowserLocation }).location;
const params = new URLSearchParams(browserLocation?.search || "");
const userId = params.get("userId") || "";
const secret = params.get("secret") || "";
return userId && secret ? { userId, secret } : null;
}
function clearBrowserAuthParameters(): void {
const browser = globalThis as unknown as { location?: BrowserLocation; history?: BrowserHistory };
if (!browser.location || !browser.history) return;
const current = new URL(browser.location.href);
for (const key of ["auth", "userId", "secret"]) current.searchParams.delete(key);
browser.history.replaceState(browser.history.state, "", `${current.pathname}${current.search}${current.hash}`);
}
function failureUrl(returnUrl: string): string {
const target = new URL(returnUrl);
target.searchParams.set("auth", "failed");
return target.toString();
}
export function createGuilduoAuth(options: AuthOptions) {
const now = options.now || Date.now;
const getReturnUrl = options.getReturnUrl || browserReturnUrl;
const getOAuthCallback = options.getOAuthCallback || browserOAuthCallback;
const clearOAuthCallback = options.clearOAuthCallback || clearBrowserAuthParameters;
let cachedUser: GuilduoUser | null = null;
let cachedJwt = "";
let jwtExpiresAt = 0;
let jwtInFlight: Promise<string> | null = null;
let authGeneration = 0;
async function refreshAccount(): Promise<GuilduoUser> {
const generation = authGeneration;
const account = await options.account.get();
if (generation !== authGeneration) throw { code: 401 };
cachedUser = normalizeAccount(account);
return cachedUser;
}
async function resolveAuthState(prepareRead?: SessionReadPreparation): Promise<GuilduoAuthState> {
const callback = getOAuthCallback();
let callbackError: unknown = null;
if (callback) {
try {
await options.account.createSession(callback);
} catch (error) {
callbackError = error;
} finally {
clearOAuthCallback();
}
}
try {
// Both endpoints verify the session. getAccessToken retains the account
// gate; only the optional read preparation may start before metadata.
const generation = authGeneration;
if (options.prepareAccessToken || prepareRead) void issueAccessToken().then((token) => {
const subject = prepareRead ? sessionSubjectHint(token) : "";
if (generation === authGeneration && token && subject) prepareRead?.(token, subject);
}).catch(() => {});
const user = await refreshAccount();
const tokenSubject = sessionSubjectHint(cachedJwt);
if (tokenSubject && tokenSubject !== user.uid) {
// Account/session changed while the two requests were in flight.
// Discard the old token as well as any speculative workspace result.
authGeneration += 1;
cachedJwt = "";
jwtExpiresAt = 0;
jwtInFlight = null;
}
return { status: "authenticated", user };
} catch (error) {
authGeneration += 1;
jwtInFlight = null;
cachedUser = null;
cachedJwt = "";
jwtExpiresAt = 0;
if (callback) {
if (callbackError && !isUnauthorized(callbackError)) return { status: "connection-error", error: callbackError };
if (isUnauthorized(error)) return { status: "oauth-failed" };
}
if (isUnauthorized(error)) return { status: "signed-out" };
return { status: "connection-error", error };
}
}
async function getAccessToken(forceRefresh = false): Promise<string> {
if (!cachedUser) {
const state = await resolveAuthState();
if (state.status !== "authenticated") return "";
}
return issueAccessToken(forceRefresh);
}
async function issueAccessToken(forceRefresh = false): Promise<string> {
if (jwtInFlight) return jwtInFlight;
if (!forceRefresh && cachedJwt && jwtExpiresAt > now() + 30_000) return cachedJwt;
const generation = authGeneration;
const pending = options.account.createJWT({ duration: 900 }).then((result) => {
if (generation !== authGeneration) return "";
const subject = sessionSubjectHint(String(result.jwt || ""));
if (cachedUser && subject && subject !== cachedUser.uid) throw new Error("Appwrite session changed during token issuance");
cachedJwt = String(result.jwt || "");
jwtExpiresAt = now() + 14 * 60 * 1000;
return cachedJwt;
});
jwtInFlight = pending;
try { return await pending; } finally { if (jwtInFlight === pending) jwtInFlight = null; }
}
function beginGoogleSignIn(): void {
const returnUrl = getReturnUrl();
options.account.createOAuth2Token({
provider: OAuthProvider.Google,
success: returnUrl,
failure: failureUrl(returnUrl),
});
}
async function signOutAccount(): Promise<void> {
authGeneration += 1;
jwtInFlight = null;
try {
await options.account.deleteSession({ sessionId: "current" });
} catch (error) {
if (!isUnauthorized(error)) throw error;
}
cachedUser = null;
cachedJwt = "";
jwtExpiresAt = 0;
}
return {
refreshAccount,
resolveAuthState,
currentAccount: (): GuilduoUser | null => cachedUser,
getAccessToken,
beginGoogleSignIn,
signOutAccount,
};
}
let productionAuth: ReturnType<typeof createGuilduoAuth> | null = null;
function auth(): ReturnType<typeof createGuilduoAuth> {
assertConfigured();
if (!productionAuth) {
const client = new Client().setEndpoint(endpoint).setProject(projectId);
productionAuth = createGuilduoAuth({ account: new Account(client), prepareAccessToken: true });
}
return productionAuth;
}
export function hasOAuthFailure(search = (globalThis as unknown as { location?: BrowserLocation }).location?.search || ""): boolean {
return new URLSearchParams(search).get("auth") === "failed";
}
export function clearOAuthFailure(): void {
clearBrowserAuthParameters();
}
export async function resolveAuthState(prepareRead?: SessionReadPreparation): Promise<GuilduoAuthState> {
if (hasOAuthFailure()) return { status: "oauth-failed" };
try {
return await auth().resolveAuthState(prepareRead);
} catch (error) {
if (error instanceof Error && error.message === "Appwrite is not configured") return { status: "signed-out" };
return { status: "connection-error", error };
}
}
export async function refreshAccount(): Promise<GuilduoUser | null> {
const state = await resolveAuthState();
if (state.status === "authenticated") return state.user;
if (state.status === "connection-error") throw state.error;
return null;
}
export function currentAccount(): GuilduoUser | null {
return productionAuth?.currentAccount() || null;
}
export async function getAccessToken(forceRefresh = false): Promise<string> {
try {
return await auth().getAccessToken(forceRefresh);
} catch (error) {
if (error instanceof Error && error.message === "Appwrite is not configured") return "";
throw error;
}
}
export function beginGoogleSignIn(): void {
auth().beginGoogleSignIn();
}
export async function signOutAccount(): Promise<void> {
if (!productionAuth) {
try { auth(); } catch { return; }
}
await productionAuth?.signOutAccount();
}