@silkweave/auth 2.6.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,621 @@
1
+ import { randomBytes, randomUUID } from "crypto";
2
+ import { SignJWT, jwtVerify } from "jose";
3
+ import { existsSync, readFileSync, writeFileSync } from "fs";
4
+ //#region src/store/memory-store.ts
5
+ function withTtl$1(map, key) {
6
+ const item = map.get(key);
7
+ if (!item) return;
8
+ if (item.expiresAt < Date.now() / 1e3) {
9
+ map.delete(key);
10
+ return;
11
+ }
12
+ return item;
13
+ }
14
+ function createMemoryStore() {
15
+ const authCodes = /* @__PURE__ */ new Map();
16
+ const pendingAuths = /* @__PURE__ */ new Map();
17
+ const pkceVerifiers = /* @__PURE__ */ new Map();
18
+ const clients = /* @__PURE__ */ new Map();
19
+ const refreshTokens = /* @__PURE__ */ new Map();
20
+ return {
21
+ async saveAuthCode(code, data) {
22
+ authCodes.set(code, data);
23
+ },
24
+ async getAuthCode(code) {
25
+ return withTtl$1(authCodes, code);
26
+ },
27
+ async deleteAuthCode(code) {
28
+ authCodes.delete(code);
29
+ },
30
+ async savePendingAuth(state, data) {
31
+ pendingAuths.set(state, data);
32
+ },
33
+ async getPendingAuth(state) {
34
+ return withTtl$1(pendingAuths, state);
35
+ },
36
+ async deletePendingAuth(state) {
37
+ pendingAuths.delete(state);
38
+ },
39
+ async savePkceVerifier(state, verifier) {
40
+ pkceVerifiers.set(state, {
41
+ verifier,
42
+ expiresAt: Date.now() / 1e3 + 600
43
+ });
44
+ },
45
+ async getPkceVerifier(state) {
46
+ const item = pkceVerifiers.get(state);
47
+ if (!item) return;
48
+ if (item.expiresAt < Date.now() / 1e3) {
49
+ pkceVerifiers.delete(state);
50
+ return;
51
+ }
52
+ return item.verifier;
53
+ },
54
+ async deletePkceVerifier(state) {
55
+ pkceVerifiers.delete(state);
56
+ },
57
+ async saveClient(clientId, data) {
58
+ clients.set(clientId, data);
59
+ },
60
+ async getClient(clientId) {
61
+ return clients.get(clientId);
62
+ },
63
+ async saveRefreshToken(token, data) {
64
+ refreshTokens.set(token, data);
65
+ },
66
+ async getRefreshToken(token) {
67
+ return withTtl$1(refreshTokens, token);
68
+ },
69
+ async deleteRefreshToken(token) {
70
+ refreshTokens.delete(token);
71
+ }
72
+ };
73
+ }
74
+ //#endregion
75
+ //#region src/provider/uri.ts
76
+ function matchRedirectUri(uri, patterns) {
77
+ return patterns.some((pattern) => {
78
+ return patternToRegex(pattern).test(uri);
79
+ });
80
+ }
81
+ function patternToRegex(pattern) {
82
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
83
+ return new RegExp(`^${escaped}$`);
84
+ }
85
+ //#endregion
86
+ //#region src/provider/proxy.ts
87
+ const CORS_HEADERS = {
88
+ "Access-Control-Allow-Origin": "*",
89
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
90
+ "Access-Control-Allow-Headers": "*"
91
+ };
92
+ function generateCode() {
93
+ return randomBytes(32).toString("base64url");
94
+ }
95
+ async function generatePkce() {
96
+ const verifier = randomBytes(32).toString("base64url");
97
+ const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
98
+ return {
99
+ verifier,
100
+ challenge: Buffer.from(hash).toString("base64url")
101
+ };
102
+ }
103
+ async function verifyPkce(verifier, challenge) {
104
+ const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
105
+ return Buffer.from(hash).toString("base64url") === challenge;
106
+ }
107
+ function jsonResponse(status, body, headers = {}) {
108
+ return {
109
+ status,
110
+ headers: {
111
+ "Content-Type": "application/json",
112
+ ...CORS_HEADERS,
113
+ ...headers
114
+ },
115
+ body
116
+ };
117
+ }
118
+ function redirectResponse(url) {
119
+ return {
120
+ status: 302,
121
+ headers: {
122
+ Location: url,
123
+ ...CORS_HEADERS
124
+ },
125
+ body: void 0
126
+ };
127
+ }
128
+ function errorResponse(status, error, description) {
129
+ return jsonResponse(status, {
130
+ error,
131
+ error_description: description
132
+ });
133
+ }
134
+ async function signAccessToken(key, opts) {
135
+ const now = Math.floor(Date.now() / 1e3);
136
+ return new SignJWT({
137
+ scope: opts.scopes.join(" "),
138
+ email: opts.email
139
+ }).setProtectedHeader({ alg: "HS256" }).setSubject(opts.sub ?? opts.email ?? opts.clientId).setIssuer(opts.issuer).setAudience(opts.issuer).setIssuedAt(now).setExpirationTime(now + opts.ttl).sign(key);
140
+ }
141
+ async function handleRegister(req, store, allowedRedirectUris) {
142
+ const body = req.body;
143
+ if (!body) return errorResponse(400, "invalid_request", "Missing request body");
144
+ const redirectUris = body.redirect_uris;
145
+ if (!redirectUris) return errorResponse(400, "invalid_request", "redirect_uris is required");
146
+ let uris;
147
+ try {
148
+ uris = typeof redirectUris === "string" ? JSON.parse(redirectUris) : redirectUris;
149
+ } catch {
150
+ uris = [redirectUris];
151
+ }
152
+ if (!Array.isArray(uris) || uris.length === 0) return errorResponse(400, "invalid_request", "redirect_uris must be a non-empty array");
153
+ for (const uri of uris) if (!matchRedirectUri(uri, allowedRedirectUris)) return errorResponse(400, "invalid_redirect_uri", `Redirect URI not allowed: ${uri}`);
154
+ const clientId = randomUUID();
155
+ const clientSecret = randomBytes(32).toString("base64url");
156
+ const registration = {
157
+ clientId,
158
+ clientSecret,
159
+ redirectUris: uris,
160
+ clientName: body.client_name,
161
+ createdAt: Date.now() / 1e3
162
+ };
163
+ await store.saveClient(clientId, registration);
164
+ return jsonResponse(201, {
165
+ client_id: clientId,
166
+ client_secret: clientSecret,
167
+ redirect_uris: uris,
168
+ client_name: body.client_name,
169
+ token_endpoint_auth_method: "none"
170
+ });
171
+ }
172
+ async function resolveClient(clientId, store, allowedRedirectUris) {
173
+ const existing = await store.getClient(clientId);
174
+ if (existing) return existing;
175
+ if (!clientId.startsWith("https://")) return errorResponse(400, "invalid_client", "Unknown client_id");
176
+ try {
177
+ const metaRes = await fetch(clientId);
178
+ if (!metaRes.ok) return errorResponse(400, "invalid_client", "Failed to fetch client metadata document");
179
+ const meta = await metaRes.json();
180
+ const metaRedirectUris = meta.redirect_uris;
181
+ if (!Array.isArray(metaRedirectUris) || metaRedirectUris.length === 0) return errorResponse(400, "invalid_client", "Client metadata must include redirect_uris");
182
+ for (const uri of metaRedirectUris) if (!matchRedirectUri(uri, allowedRedirectUris)) return errorResponse(400, "invalid_redirect_uri", `Redirect URI not allowed: ${uri}`);
183
+ const client = {
184
+ clientId,
185
+ clientSecret: "",
186
+ redirectUris: metaRedirectUris,
187
+ clientName: meta.client_name,
188
+ createdAt: Date.now() / 1e3
189
+ };
190
+ await store.saveClient(clientId, client);
191
+ return client;
192
+ } catch {
193
+ return errorResponse(400, "invalid_client", "Failed to fetch client metadata document");
194
+ }
195
+ }
196
+ async function exchangeUpstreamCode(code, config, callbackPath, pkceVerifier) {
197
+ const tokenBody = new URLSearchParams({
198
+ grant_type: "authorization_code",
199
+ code,
200
+ redirect_uri: `${config.resourceUrl}${callbackPath}`,
201
+ client_id: config.clientId,
202
+ client_secret: config.clientSecret,
203
+ code_verifier: pkceVerifier
204
+ });
205
+ const tokenResponse = await fetch(config.tokenUrl, {
206
+ method: "POST",
207
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
208
+ body: tokenBody.toString()
209
+ });
210
+ if (!tokenResponse.ok) {
211
+ const errorBody = await tokenResponse.text();
212
+ console.error("Upstream token exchange failed:", errorBody);
213
+ return errorResponse(502, "upstream_error", "Failed to exchange code with upstream provider");
214
+ }
215
+ const tokens = await tokenResponse.json();
216
+ return {
217
+ accessToken: tokens.access_token,
218
+ idToken: tokens.id_token
219
+ };
220
+ }
221
+ async function fetchUserinfo(userinfoUrl, accessToken) {
222
+ if (!userinfoUrl || !accessToken) return {};
223
+ try {
224
+ const res = await fetch(userinfoUrl, { headers: { Authorization: `Bearer ${accessToken}` } });
225
+ if (res.ok) {
226
+ const userinfo = await res.json();
227
+ return {
228
+ email: userinfo.email,
229
+ sub: userinfo.sub
230
+ };
231
+ }
232
+ } catch {}
233
+ return {};
234
+ }
235
+ async function handleRefreshToken(body, store, getSigningKey, config) {
236
+ const refreshToken = body.refresh_token;
237
+ if (!refreshToken) return errorResponse(400, "invalid_request", "Missing refresh_token");
238
+ const tokenData = await store.getRefreshToken(refreshToken);
239
+ if (!tokenData) return errorResponse(400, "invalid_grant", "Invalid or expired refresh token");
240
+ return jsonResponse(200, {
241
+ access_token: await signAccessToken(await getSigningKey(), {
242
+ scopes: tokenData.scopes,
243
+ email: tokenData.email,
244
+ sub: tokenData.sub,
245
+ clientId: tokenData.clientId,
246
+ issuer: config.resourceUrl,
247
+ ttl: config.tokenTtl
248
+ }),
249
+ token_type: "Bearer",
250
+ expires_in: config.tokenTtl,
251
+ scope: tokenData.scopes.join(" "),
252
+ refresh_token: refreshToken
253
+ });
254
+ }
255
+ async function handleAuthorizationCode(body, store, getSigningKey, config) {
256
+ const code = body.code;
257
+ const redirectUri = body.redirect_uri;
258
+ const clientId = body.client_id;
259
+ const codeVerifier = body.code_verifier;
260
+ if (!code || !codeVerifier || !clientId) return errorResponse(400, "invalid_request", "Missing required parameters");
261
+ const authCode = await store.getAuthCode(code);
262
+ if (!authCode) return errorResponse(400, "invalid_grant", "Invalid or expired authorization code");
263
+ await store.deleteAuthCode(code);
264
+ if (authCode.clientId !== clientId) return errorResponse(400, "invalid_grant", "client_id mismatch");
265
+ if (redirectUri && authCode.redirectUri !== redirectUri) return errorResponse(400, "invalid_grant", "redirect_uri mismatch");
266
+ if (!await verifyPkce(codeVerifier, authCode.codeChallenge)) return errorResponse(400, "invalid_grant", "PKCE verification failed");
267
+ const accessToken = await signAccessToken(await getSigningKey(), {
268
+ scopes: authCode.scopes,
269
+ email: authCode.email,
270
+ sub: authCode.sub,
271
+ clientId: authCode.clientId,
272
+ issuer: config.resourceUrl,
273
+ ttl: config.tokenTtl
274
+ });
275
+ const refreshToken = randomBytes(32).toString("base64url");
276
+ await store.saveRefreshToken(refreshToken, {
277
+ clientId: authCode.clientId,
278
+ scopes: authCode.scopes,
279
+ email: authCode.email,
280
+ sub: authCode.sub,
281
+ expiresAt: Math.floor(Date.now() / 1e3) + 720 * 3600
282
+ });
283
+ return jsonResponse(200, {
284
+ access_token: accessToken,
285
+ token_type: "Bearer",
286
+ expires_in: config.tokenTtl,
287
+ scope: authCode.scopes.join(" "),
288
+ refresh_token: refreshToken
289
+ });
290
+ }
291
+ function createOAuthProxy(config) {
292
+ const store = config.store ?? createMemoryStore();
293
+ const callbackPath = config.callbackPath ?? "/auth/callback";
294
+ const tokenTtl = config.tokenTtl ?? 3600;
295
+ const scopes = config.requiredScopes ?? [];
296
+ let signingKey = null;
297
+ async function getSigningKey() {
298
+ if (signingKey) return signingKey;
299
+ if (config.signingKey) signingKey = new TextEncoder().encode(config.signingKey);
300
+ else signingKey = randomBytes(32);
301
+ return signingKey;
302
+ }
303
+ return {
304
+ metadata() {
305
+ return jsonResponse(200, {
306
+ issuer: config.resourceUrl,
307
+ authorization_endpoint: `${config.resourceUrl}/authorize`,
308
+ token_endpoint: `${config.resourceUrl}/token`,
309
+ registration_endpoint: `${config.resourceUrl}/register`,
310
+ response_types_supported: ["code"],
311
+ grant_types_supported: ["authorization_code", "refresh_token"],
312
+ code_challenge_methods_supported: ["S256"],
313
+ token_endpoint_auth_methods_supported: ["none", "client_secret_post"],
314
+ scopes_supported: scopes
315
+ }, { "Cache-Control": "max-age=3600" });
316
+ },
317
+ register(req) {
318
+ return handleRegister(req, store, config.redirectUris);
319
+ },
320
+ async authorize(req) {
321
+ const params = req.url.searchParams;
322
+ const responseType = params.get("response_type");
323
+ const clientId = params.get("client_id");
324
+ const redirectUri = params.get("redirect_uri");
325
+ const scope = params.get("scope") ?? "";
326
+ const clientState = params.get("state") ?? "";
327
+ const codeChallenge = params.get("code_challenge");
328
+ const codeChallengeMethod = params.get("code_challenge_method");
329
+ const resource = params.get("resource");
330
+ if (responseType !== "code") return errorResponse(400, "unsupported_response_type", "Only response_type=code is supported");
331
+ if (!clientId) return errorResponse(400, "invalid_request", "client_id is required");
332
+ if (!redirectUri) return errorResponse(400, "invalid_request", "redirect_uri is required");
333
+ if (!codeChallenge || codeChallengeMethod !== "S256") return errorResponse(400, "invalid_request", "PKCE with S256 is required");
334
+ const result = await resolveClient(clientId, store, config.redirectUris);
335
+ if ("status" in result) return result;
336
+ if (!result.redirectUris.includes(redirectUri)) return errorResponse(400, "invalid_redirect_uri", "redirect_uri does not match registered URIs");
337
+ const proxyState = randomUUID();
338
+ const pkce = await generatePkce();
339
+ await store.savePendingAuth(proxyState, {
340
+ clientId,
341
+ redirectUri,
342
+ codeChallenge,
343
+ codeChallengeMethod,
344
+ scope,
345
+ clientState,
346
+ resource: resource ?? void 0,
347
+ expiresAt: Date.now() / 1e3 + 600
348
+ });
349
+ await store.savePkceVerifier(proxyState, pkce.verifier);
350
+ const upstreamScopes = scopes.length > 0 ? scopes.join(" ") : scope;
351
+ const upstreamUrl = new URL(config.authorizeUrl);
352
+ upstreamUrl.searchParams.set("response_type", "code");
353
+ upstreamUrl.searchParams.set("client_id", config.clientId);
354
+ upstreamUrl.searchParams.set("redirect_uri", `${config.resourceUrl}${callbackPath}`);
355
+ upstreamUrl.searchParams.set("scope", upstreamScopes);
356
+ upstreamUrl.searchParams.set("state", proxyState);
357
+ upstreamUrl.searchParams.set("code_challenge", pkce.challenge);
358
+ upstreamUrl.searchParams.set("code_challenge_method", "S256");
359
+ if (params.has("access_type")) upstreamUrl.searchParams.set("access_type", params.get("access_type"));
360
+ return redirectResponse(upstreamUrl.toString());
361
+ },
362
+ async callback(req) {
363
+ const params = req.url.searchParams;
364
+ const upstreamCode = params.get("code");
365
+ const proxyState = params.get("state");
366
+ const upstreamError = params.get("error");
367
+ if (upstreamError) return errorResponse(400, "upstream_error", params.get("error_description") ?? upstreamError);
368
+ if (!upstreamCode || !proxyState) return errorResponse(400, "invalid_request", "Missing code or state");
369
+ const pending = await store.getPendingAuth(proxyState);
370
+ if (!pending) return errorResponse(400, "invalid_request", "Unknown or expired state");
371
+ const pkceVerifier = await store.getPkceVerifier(proxyState);
372
+ if (!pkceVerifier) return errorResponse(400, "invalid_request", "Missing PKCE verifier");
373
+ await store.deletePendingAuth(proxyState);
374
+ await store.deletePkceVerifier(proxyState);
375
+ const upstream = await exchangeUpstreamCode(upstreamCode, config, callbackPath, pkceVerifier);
376
+ if ("status" in upstream) return upstream;
377
+ const userinfo = await fetchUserinfo(config.userinfoUrl, upstream.accessToken);
378
+ const mcpCode = generateCode();
379
+ await store.saveAuthCode(mcpCode, {
380
+ clientId: pending.clientId,
381
+ redirectUri: pending.redirectUri,
382
+ codeChallenge: pending.codeChallenge,
383
+ codeChallengeMethod: pending.codeChallengeMethod,
384
+ scopes: pending.scope.split(" ").filter(Boolean),
385
+ upstreamAccessToken: upstream.accessToken,
386
+ upstreamIdToken: upstream.idToken,
387
+ email: userinfo.email,
388
+ sub: userinfo.sub,
389
+ expiresAt: Date.now() / 1e3 + 600
390
+ });
391
+ const clientRedirect = new URL(pending.redirectUri);
392
+ clientRedirect.searchParams.set("code", mcpCode);
393
+ if (pending.clientState) clientRedirect.searchParams.set("state", pending.clientState);
394
+ return redirectResponse(clientRedirect.toString());
395
+ },
396
+ async token(req) {
397
+ const body = req.body;
398
+ if (!body) return errorResponse(400, "invalid_request", "Missing request body");
399
+ const tokenConfig = {
400
+ resourceUrl: config.resourceUrl,
401
+ tokenTtl
402
+ };
403
+ if (body.grant_type === "refresh_token") return handleRefreshToken(body, store, getSigningKey, tokenConfig);
404
+ if (body.grant_type !== "authorization_code") return errorResponse(400, "unsupported_grant_type", "Supported grant types: authorization_code, refresh_token");
405
+ return handleAuthorizationCode(body, store, getSigningKey, tokenConfig);
406
+ },
407
+ async verifyToken(token) {
408
+ try {
409
+ const { payload } = await jwtVerify(token, await getSigningKey(), {
410
+ issuer: config.resourceUrl,
411
+ audience: config.resourceUrl
412
+ });
413
+ return {
414
+ token,
415
+ clientId: payload.sub ?? void 0,
416
+ scopes: typeof payload.scope === "string" ? payload.scope.split(" ").filter(Boolean) : [],
417
+ expiresAt: payload.exp,
418
+ email: payload.email
419
+ };
420
+ } catch {
421
+ return;
422
+ }
423
+ }
424
+ };
425
+ }
426
+ //#endregion
427
+ //#region src/provider/google.ts
428
+ function google(options) {
429
+ const provider = createOAuthProxy({
430
+ authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
431
+ tokenUrl: "https://oauth2.googleapis.com/token",
432
+ userinfoUrl: "https://openidconnect.googleapis.com/v1/userinfo",
433
+ clientId: options.clientId,
434
+ clientSecret: options.clientSecret,
435
+ resourceUrl: options.resourceUrl,
436
+ redirectUris: options.redirectUris,
437
+ requiredScopes: options.requiredScopes ?? ["openid", "email"],
438
+ callbackPath: options.callbackPath,
439
+ signingKey: options.signingKey,
440
+ tokenTtl: options.tokenTtl,
441
+ store: options.store
442
+ });
443
+ return {
444
+ verifyToken: (token) => provider.verifyToken(token),
445
+ required: true,
446
+ resourceUrl: options.resourceUrl,
447
+ authorizationServers: [options.resourceUrl],
448
+ provider,
449
+ callbackPath: options.callbackPath ?? "/auth/callback"
450
+ };
451
+ }
452
+ //#endregion
453
+ //#region src/store/json-store.ts
454
+ function withTtl(obj, key) {
455
+ const item = obj[key];
456
+ if (!item) return;
457
+ if (item.expiresAt < Date.now() / 1e3) {
458
+ delete obj[key];
459
+ return;
460
+ }
461
+ return item;
462
+ }
463
+ function writeJsonStore(path, store) {
464
+ writeFileSync(path, JSON.stringify(store, null, 2), "utf-8");
465
+ }
466
+ function readJsonStore(path) {
467
+ if (!existsSync(path)) return {
468
+ authCodes: {},
469
+ pendingAuths: {},
470
+ pkceVerifiers: {},
471
+ clients: {},
472
+ refreshTokens: {}
473
+ };
474
+ const data = JSON.parse(readFileSync(path, "utf-8"));
475
+ if (!data.refreshTokens) data.refreshTokens = {};
476
+ return data;
477
+ }
478
+ function createJsonStore(path) {
479
+ const store = readJsonStore(path);
480
+ return {
481
+ async saveAuthCode(code, data) {
482
+ store.authCodes[code] = data;
483
+ writeJsonStore(path, store);
484
+ },
485
+ async getAuthCode(code) {
486
+ return withTtl(store.authCodes, code);
487
+ },
488
+ async deleteAuthCode(code) {
489
+ delete store.authCodes[code];
490
+ writeJsonStore(path, store);
491
+ },
492
+ async savePendingAuth(state, data) {
493
+ store.pendingAuths[state] = data;
494
+ writeJsonStore(path, store);
495
+ },
496
+ async getPendingAuth(state) {
497
+ return withTtl(store.pendingAuths, state);
498
+ },
499
+ async deletePendingAuth(state) {
500
+ delete store.pendingAuths[state];
501
+ writeJsonStore(path, store);
502
+ },
503
+ async savePkceVerifier(state, verifier) {
504
+ store.pkceVerifiers[state] = {
505
+ verifier,
506
+ expiresAt: Date.now() / 1e3 + 600
507
+ };
508
+ writeJsonStore(path, store);
509
+ },
510
+ async getPkceVerifier(state) {
511
+ const item = store.pkceVerifiers[state];
512
+ if (!item) return;
513
+ if (item.expiresAt < Date.now() / 1e3) {
514
+ delete store.pkceVerifiers[state];
515
+ writeJsonStore(path, store);
516
+ return;
517
+ }
518
+ return item.verifier;
519
+ },
520
+ async deletePkceVerifier(state) {
521
+ delete store.pkceVerifiers[state];
522
+ writeJsonStore(path, store);
523
+ },
524
+ async saveClient(clientId, data) {
525
+ store.clients[clientId] = data;
526
+ writeJsonStore(path, store);
527
+ },
528
+ async getClient(clientId) {
529
+ return store.clients[clientId];
530
+ },
531
+ async saveRefreshToken(token, data) {
532
+ store.refreshTokens[token] = data;
533
+ writeJsonStore(path, store);
534
+ },
535
+ async getRefreshToken(token) {
536
+ return withTtl(store.refreshTokens, token);
537
+ },
538
+ async deleteRefreshToken(token) {
539
+ delete store.refreshTokens[token];
540
+ writeJsonStore(path, store);
541
+ }
542
+ };
543
+ }
544
+ //#endregion
545
+ //#region src/store/redis-store.ts
546
+ function createRedisStore(options) {
547
+ const { client, prefix = "silkweave:oauth:" } = options;
548
+ function key(namespace, id) {
549
+ return `${prefix}${namespace}:${id}`;
550
+ }
551
+ function ttlFromExpiry(expiresAt) {
552
+ const seconds = Math.floor(expiresAt - Date.now() / 1e3);
553
+ return seconds > 0 ? seconds : void 0;
554
+ }
555
+ async function save(namespace, id, data, expiresAt) {
556
+ const opts = {};
557
+ const ttl = expiresAt != null ? ttlFromExpiry(expiresAt) : void 0;
558
+ if (ttl != null) opts.ex = ttl;
559
+ await client.set(key(namespace, id), JSON.stringify(data), opts);
560
+ }
561
+ async function load(namespace, id) {
562
+ const raw = await client.get(key(namespace, id));
563
+ if (raw == null) return;
564
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
565
+ }
566
+ async function remove(namespace, id) {
567
+ await client.del(key(namespace, id));
568
+ }
569
+ return {
570
+ async saveAuthCode(code, data) {
571
+ await save("auth-code", code, data, data.expiresAt);
572
+ },
573
+ async getAuthCode(code) {
574
+ return load("auth-code", code);
575
+ },
576
+ async deleteAuthCode(code) {
577
+ await remove("auth-code", code);
578
+ },
579
+ async savePendingAuth(state, data) {
580
+ await save("pending-auth", state, data, data.expiresAt);
581
+ },
582
+ async getPendingAuth(state) {
583
+ return load("pending-auth", state);
584
+ },
585
+ async deletePendingAuth(state) {
586
+ await remove("pending-auth", state);
587
+ },
588
+ async savePkceVerifier(state, verifier) {
589
+ const expiresAt = Date.now() / 1e3 + 600;
590
+ await save("pkce-verifier", state, {
591
+ verifier,
592
+ expiresAt
593
+ }, expiresAt);
594
+ },
595
+ async getPkceVerifier(state) {
596
+ return (await load("pkce-verifier", state))?.verifier;
597
+ },
598
+ async deletePkceVerifier(state) {
599
+ await remove("pkce-verifier", state);
600
+ },
601
+ async saveClient(clientId, data) {
602
+ await save("client", clientId, data);
603
+ },
604
+ async getClient(clientId) {
605
+ return load("client", clientId);
606
+ },
607
+ async saveRefreshToken(token, data) {
608
+ await save("refresh-token", token, data, data.expiresAt);
609
+ },
610
+ async getRefreshToken(token) {
611
+ return load("refresh-token", token);
612
+ },
613
+ async deleteRefreshToken(token) {
614
+ await remove("refresh-token", token);
615
+ }
616
+ };
617
+ }
618
+ //#endregion
619
+ export { createJsonStore, createMemoryStore, createOAuthProxy, createRedisStore, google, matchRedirectUri };
620
+
621
+ //# sourceMappingURL=oauth.mjs.map