@tern-secure/backend 1.2.0-canary.v20250919134427 → 1.2.0-canary.v20251002175916

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.
Files changed (78) hide show
  1. package/auth/package.json +5 -0
  2. package/dist/admin/index.d.ts +1 -1
  3. package/dist/admin/index.d.ts.map +1 -1
  4. package/dist/admin/index.js +200 -182
  5. package/dist/admin/index.js.map +1 -1
  6. package/dist/admin/index.mjs +23 -489
  7. package/dist/admin/index.mjs.map +1 -1
  8. package/dist/admin/nextSessionTernSecure.d.ts.map +1 -1
  9. package/dist/admin/sessionTernSecure.d.ts +27 -5
  10. package/dist/admin/sessionTernSecure.d.ts.map +1 -1
  11. package/dist/auth/getauth.d.ts +15 -0
  12. package/dist/auth/getauth.d.ts.map +1 -0
  13. package/dist/auth/index.d.ts +2 -0
  14. package/dist/auth/index.d.ts.map +1 -0
  15. package/dist/auth/index.js +694 -0
  16. package/dist/auth/index.js.map +1 -0
  17. package/dist/auth/index.mjs +53 -0
  18. package/dist/auth/index.mjs.map +1 -0
  19. package/dist/{chunk-ZIO4EKS5.mjs → chunk-4SGWLAJG.mjs} +8 -31
  20. package/dist/chunk-4SGWLAJG.mjs.map +1 -0
  21. package/dist/chunk-NEPV6OWI.mjs +550 -0
  22. package/dist/chunk-NEPV6OWI.mjs.map +1 -0
  23. package/dist/chunk-YKIA5EBF.mjs +142 -0
  24. package/dist/chunk-YKIA5EBF.mjs.map +1 -0
  25. package/dist/constants.d.ts +4 -5
  26. package/dist/constants.d.ts.map +1 -1
  27. package/dist/fireRestApi/createFireApi.d.ts +12 -0
  28. package/dist/fireRestApi/createFireApi.d.ts.map +1 -0
  29. package/dist/fireRestApi/emulator.d.ts +4 -0
  30. package/dist/fireRestApi/emulator.d.ts.map +1 -0
  31. package/dist/fireRestApi/endpointUrl.d.ts +6 -0
  32. package/dist/fireRestApi/endpointUrl.d.ts.map +1 -0
  33. package/dist/fireRestApi/endpoints/AbstractApi.d.ts +7 -0
  34. package/dist/fireRestApi/endpoints/AbstractApi.d.ts.map +1 -0
  35. package/dist/fireRestApi/endpoints/EmailApi.d.ts +14 -0
  36. package/dist/fireRestApi/endpoints/EmailApi.d.ts.map +1 -0
  37. package/dist/fireRestApi/endpoints/PasswordApi.d.ts +20 -0
  38. package/dist/fireRestApi/endpoints/PasswordApi.d.ts.map +1 -0
  39. package/dist/fireRestApi/endpoints/SignInTokenApi.d.ts +11 -0
  40. package/dist/fireRestApi/endpoints/SignInTokenApi.d.ts.map +1 -0
  41. package/dist/fireRestApi/endpoints/SignUpApi.d.ts +11 -0
  42. package/dist/fireRestApi/endpoints/SignUpApi.d.ts.map +1 -0
  43. package/dist/fireRestApi/endpoints/TokenApi.d.ts +21 -0
  44. package/dist/fireRestApi/endpoints/TokenApi.d.ts.map +1 -0
  45. package/dist/fireRestApi/endpoints/index.d.ts +6 -0
  46. package/dist/fireRestApi/endpoints/index.d.ts.map +1 -0
  47. package/dist/fireRestApi/index.d.ts +2 -0
  48. package/dist/fireRestApi/index.d.ts.map +1 -0
  49. package/dist/fireRestApi/request.d.ts +34 -0
  50. package/dist/fireRestApi/request.d.ts.map +1 -0
  51. package/dist/fireRestApi/resources/JSON.d.ts +50 -0
  52. package/dist/fireRestApi/resources/JSON.d.ts.map +1 -0
  53. package/dist/fireRestApi/resources/Token.d.ts +13 -0
  54. package/dist/fireRestApi/resources/Token.d.ts.map +1 -0
  55. package/dist/index.d.ts +1 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +271 -75
  58. package/dist/index.js.map +1 -1
  59. package/dist/index.mjs +257 -179
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/instance/backendFireInstance.d.ts +4 -4
  62. package/dist/instance/backendFireInstance.d.ts.map +1 -1
  63. package/dist/instance/backendInstanceEdge.d.ts +2 -2
  64. package/dist/instance/backendInstanceEdge.d.ts.map +1 -1
  65. package/dist/tokens/authstate.d.ts +1 -1
  66. package/dist/tokens/authstate.d.ts.map +1 -1
  67. package/dist/tokens/keys.d.ts.map +1 -1
  68. package/dist/tokens/request.d.ts +3 -3
  69. package/dist/tokens/request.d.ts.map +1 -1
  70. package/dist/tokens/requestFire.d.ts.map +1 -1
  71. package/dist/tokens/types.d.ts +5 -2
  72. package/dist/tokens/types.d.ts.map +1 -1
  73. package/dist/utils/options.d.ts +1 -1
  74. package/dist/utils/options.d.ts.map +1 -1
  75. package/package.json +14 -3
  76. package/dist/admin/gemini.sessionTernSecure.d.ts +0 -8
  77. package/dist/admin/gemini.sessionTernSecure.d.ts.map +0 -1
  78. package/dist/chunk-ZIO4EKS5.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,18 +1,13 @@
1
1
  import {
2
- CACHE_CONTROL_REGEX,
3
- DEFAULT_CACHE_DURATION,
4
- MAX_CACHE_LAST_UPDATED_AT_SECONDS,
5
- SESSION_COOKIE_PUBLIC_KEYS_URL,
2
+ verifyToken
3
+ } from "./chunk-YKIA5EBF.mjs";
4
+ import {
6
5
  constants,
7
- createTernSecureRequest,
8
- getSessionConfig
9
- } from "./chunk-ZIO4EKS5.mjs";
6
+ createTernSecureRequest
7
+ } from "./chunk-4SGWLAJG.mjs";
10
8
  import {
11
9
  TokenVerificationError,
12
- TokenVerificationErrorReason,
13
- mapJwtPayloadToDecodedIdToken,
14
- ternDecodeJwt,
15
- verifyJwt
10
+ mapJwtPayloadToDecodedIdToken
16
11
  } from "./chunk-WZYVAHZ3.mjs";
17
12
 
18
13
  // src/tokens/authstate.ts
@@ -85,10 +80,11 @@ function signedIn(sessionClaims, headers = new Headers(), token) {
85
80
  headers
86
81
  };
87
82
  }
88
- function signedOut(reason, headers = new Headers()) {
83
+ function signedOut(reason, message = "", headers = new Headers()) {
89
84
  return decorateHeaders({
90
85
  status: AuthStatus.SignedOut,
91
86
  reason,
87
+ message,
92
88
  isSignedIn: false,
93
89
  auth: () => signedOutAuthObject(),
94
90
  token: null,
@@ -113,19 +109,139 @@ var decorateHeaders = (requestState) => {
113
109
  return requestState;
114
110
  };
115
111
 
116
- // src/api/endpoints/SessionApi.ts
117
- var rootPath = "/sessions";
118
- var SessionApi = class {
112
+ // src/fireRestApi/endpoints/AbstractApi.ts
113
+ var AbstractAPI = class {
119
114
  constructor(request) {
120
115
  this.request = request;
121
116
  }
122
- async createSession(params) {
117
+ requireApiKey(apiKey) {
118
+ if (!apiKey) {
119
+ throw new Error("A valid API key is required.");
120
+ }
121
+ }
122
+ };
123
+
124
+ // src/fireRestApi/endpoints/EmailApi.ts
125
+ var EmailApi = class extends AbstractAPI {
126
+ async verifyEmailVerification(apiKey, params) {
127
+ this.requireApiKey(apiKey);
128
+ const { ...restParams } = params;
123
129
  return this.request({
130
+ endpoint: "sendOobCode",
124
131
  method: "POST",
125
- path: rootPath,
126
- bodyParams: params
132
+ bodyParams: restParams
127
133
  });
128
134
  }
135
+ async confirmEmailVerification(apiKey, params) {
136
+ this.requireApiKey(apiKey);
137
+ const { ...restParams } = params;
138
+ return this.request({
139
+ endpoint: "sendOobCode",
140
+ method: "POST",
141
+ bodyParams: restParams
142
+ });
143
+ }
144
+ };
145
+
146
+ // src/fireRestApi/endpoints/PasswordApi.ts
147
+ var PasswordApi = class extends AbstractAPI {
148
+ async verifyPasswordResetCode(apiKey, params) {
149
+ this.requireApiKey(apiKey);
150
+ const { ...restParams } = params;
151
+ return this.request({
152
+ endpoint: "passwordReset",
153
+ method: "POST",
154
+ bodyParams: restParams
155
+ });
156
+ }
157
+ async confirmPasswordReset(apiKey, params) {
158
+ this.requireApiKey(apiKey);
159
+ const { ...restParams } = params;
160
+ return this.request({
161
+ endpoint: "passwordReset",
162
+ method: "POST",
163
+ bodyParams: restParams
164
+ });
165
+ }
166
+ async changePassword(apiKey, params) {
167
+ this.requireApiKey(apiKey);
168
+ const { ...restParams } = params;
169
+ return this.request({
170
+ endpoint: "passwordReset",
171
+ method: "POST",
172
+ bodyParams: restParams
173
+ });
174
+ }
175
+ };
176
+
177
+ // src/fireRestApi/endpoints/SignInTokenApi.ts
178
+ var SignInTokenApi = class extends AbstractAPI {
179
+ async createCustomToken(apiKey, params) {
180
+ try {
181
+ this.requireApiKey(apiKey);
182
+ const { ...restParams } = params;
183
+ const response = await this.request({
184
+ endpoint: "signInWithCustomToken",
185
+ method: "POST",
186
+ bodyParams: restParams
187
+ });
188
+ if (response.errors) {
189
+ const errorMessage = response.errors[0]?.message || "Failed to create custom token";
190
+ throw new Error(errorMessage);
191
+ }
192
+ return response.data;
193
+ } catch (error) {
194
+ const contextualMessage = `Failed to create custom token: ${error instanceof Error ? error.message : "Unknown error"}`;
195
+ throw new Error(contextualMessage);
196
+ }
197
+ }
198
+ };
199
+
200
+ // src/fireRestApi/endpoints/SignUpApi.ts
201
+ var SignUpApi = class extends AbstractAPI {
202
+ async createCustomToken(apiKey, params) {
203
+ this.requireApiKey(apiKey);
204
+ const { ...restParams } = params;
205
+ return this.request({
206
+ endpoint: "signUp",
207
+ method: "POST",
208
+ bodyParams: restParams
209
+ });
210
+ }
211
+ };
212
+
213
+ // src/fireRestApi/endpoints/TokenApi.ts
214
+ var TokenApi = class extends AbstractAPI {
215
+ async refreshToken(apiKey, params) {
216
+ this.requireApiKey(apiKey);
217
+ const { ...restParams } = params;
218
+ return this.request({
219
+ endpoint: "refreshToken",
220
+ method: "POST",
221
+ bodyParams: restParams
222
+ });
223
+ }
224
+ async exchangeCustomForIdAndRefreshTokens(apiKey, params) {
225
+ try {
226
+ this.requireApiKey(apiKey);
227
+ const { ...restParams } = params;
228
+ const response = await this.request({
229
+ endpoint: "signInWithCustomToken",
230
+ method: "POST",
231
+ apiKey,
232
+ bodyParams: restParams
233
+ });
234
+ if (response.errors) {
235
+ const errorMessage = response.errors[0]?.message || "Failed to create custom token";
236
+ console.error("Error response from exchangeCustomForIdAndRefreshTokens:", response.errors);
237
+ throw new Error(errorMessage);
238
+ }
239
+ return response.data;
240
+ } catch (error) {
241
+ const contextualMessage = `Failed to create custom token: ${error instanceof Error ? error.message : "Unknown error"}`;
242
+ throw new Error(contextualMessage);
243
+ }
244
+ }
129
245
  };
130
246
 
131
247
  // src/runtime.ts
@@ -144,20 +260,69 @@ var runtime = {
144
260
  Response: globalThis.Response
145
261
  };
146
262
 
147
- // src/utils/path.ts
148
- var SEPARATOR = "/";
149
- var MULTIPLE_SEPARATOR_REGEX = new RegExp("(?<!:)" + SEPARATOR + "{1,}", "g");
150
- function joinPaths(...args) {
151
- return args.filter((p) => p).join(SEPARATOR).replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);
263
+ // src/fireRestApi/emulator.ts
264
+ var FIREBASE_AUTH_EMULATOR_HOST = process.env.FIREBASE_AUTH_EMULATOR_HOST;
265
+ function emulatorHost() {
266
+ if (typeof process === "undefined") return void 0;
267
+ return FIREBASE_AUTH_EMULATOR_HOST;
268
+ }
269
+ function useEmulator() {
270
+ return !!emulatorHost();
152
271
  }
153
272
 
154
- // src/api/request.ts
273
+ // src/fireRestApi/endpointUrl.ts
274
+ var getRefreshTokenEndpoint = (apiKey) => {
275
+ return `https://securetoken.googleapis.com/v1/token?key=${apiKey}`;
276
+ };
277
+ var signInWithPassword = (apiKey) => {
278
+ return `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${apiKey}`;
279
+ };
280
+ var signUpEndpoint = (apiKey) => {
281
+ return `https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${apiKey}`;
282
+ };
283
+ var getCustomTokenEndpoint = (apiKey) => {
284
+ if (useEmulator() && FIREBASE_AUTH_EMULATOR_HOST) {
285
+ let protocol = "http://";
286
+ if (FIREBASE_AUTH_EMULATOR_HOST.startsWith("http://")) {
287
+ protocol = "";
288
+ }
289
+ return `${protocol}${FIREBASE_AUTH_EMULATOR_HOST}/identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${apiKey}`;
290
+ }
291
+ return `https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${apiKey}`;
292
+ };
293
+ var passwordResetEndpoint = (apiKey) => {
294
+ return `https://identitytoolkit.googleapis.com/v1/accounts:resetPassword?key=${apiKey}`;
295
+ };
296
+
297
+ // src/fireRestApi/request.ts
298
+ var FIREBASE_ENDPOINT_MAP = {
299
+ refreshToken: getRefreshTokenEndpoint,
300
+ signInWithPassword,
301
+ signUp: signUpEndpoint,
302
+ signInWithCustomToken: getCustomTokenEndpoint,
303
+ passwordReset: passwordResetEndpoint,
304
+ sendOobCode: signInWithPassword
305
+ };
155
306
  function createRequest(options) {
156
307
  const requestFn = async (requestOptions) => {
157
- const { apiUrl, apiVersion } = options;
158
- const { path, method, queryParams, headerParams, bodyParams, formData } = requestOptions;
159
- const url = joinPaths(apiUrl, apiVersion, path);
160
- const finalUrl = new URL(url);
308
+ const { endpoint, method, apiKey, queryParams, headerParams, bodyParams, formData } = requestOptions;
309
+ if (!apiKey) {
310
+ return {
311
+ data: null,
312
+ errors: [
313
+ {
314
+ code: "missing_api_key",
315
+ message: "Firebase API key is required"
316
+ }
317
+ ]
318
+ };
319
+ }
320
+ const endpointUrl = FIREBASE_ENDPOINT_MAP[endpoint](apiKey);
321
+ const finalUrl = new URL(endpointUrl);
322
+ console.log("endpoint url:", endpointUrl);
323
+ console.log("Final URL href:", finalUrl.href);
324
+ console.log("Final URL:", finalUrl);
325
+ console.log("Method:", method);
161
326
  if (queryParams) {
162
327
  Object.entries(queryParams).forEach(([key, value]) => {
163
328
  if (value) {
@@ -236,16 +401,24 @@ function parseError(error) {
236
401
  };
237
402
  }
238
403
 
239
- // src/api/createBackendApi.ts
240
- function createBackendApi(options) {
404
+ // src/fireRestApi/createFireApi.ts
405
+ function createFireApi(options) {
241
406
  const request = createRequest(options);
242
407
  return {
243
- sessions: new SessionApi(request)
408
+ email: new EmailApi(request),
409
+ password: new PasswordApi(request),
410
+ signIn: new SignInTokenApi(request),
411
+ signUp: new SignUpApi(request),
412
+ tokens: new TokenApi(request)
244
413
  };
245
414
  }
246
415
 
416
+ // src/tokens/request.ts
417
+ import { getCookieName, getCookiePrefix } from "@tern-secure/shared/cookie";
418
+
247
419
  // src/utils/options.ts
248
420
  var defaultOptions = {
421
+ apiKey: void 0,
249
422
  apiUrl: void 0,
250
423
  apiVersion: void 0
251
424
  };
@@ -256,134 +429,8 @@ function mergePreDefinedOptions(userOptions = {}) {
256
429
  };
257
430
  }
258
431
 
259
- // src/tokens/keys.ts
260
- var cache = {};
261
- var lastUpdatedAt = 0;
262
- var googleExpiresAt = 0;
263
- function getFromCache(kid) {
264
- return cache[kid];
265
- }
266
- function getCacheValues() {
267
- return Object.values(cache);
268
- }
269
- function setInCache(kid, certificate, shouldExpire = true) {
270
- cache[kid] = certificate;
271
- lastUpdatedAt = shouldExpire ? Date.now() : -1;
272
- }
273
- async function fetchPublicKeys(keyUrl) {
274
- const url = new URL(keyUrl);
275
- const response = await fetch(url);
276
- if (!response.ok) {
277
- throw new TokenVerificationError({
278
- message: `Error loading public keys from ${url.href} with code=${response.status} `,
279
- reason: TokenVerificationErrorReason.TokenInvalid
280
- });
281
- }
282
- const data = await response.json();
283
- const expiresAt = getExpiresAt(response);
284
- return {
285
- keys: data,
286
- expiresAt
287
- };
288
- }
289
- async function loadJWKFromRemote({
290
- keyURL = SESSION_COOKIE_PUBLIC_KEYS_URL,
291
- skipJwksCache,
292
- kid
293
- }) {
294
- if (skipJwksCache || isCacheExpired() || !getFromCache(kid)) {
295
- const { keys, expiresAt } = await fetchPublicKeys(keyURL);
296
- if (!keys || Object.keys(keys).length === 0) {
297
- throw new TokenVerificationError({
298
- message: `The JWKS endpoint ${keyURL} returned no keys`,
299
- reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad
300
- });
301
- }
302
- googleExpiresAt = expiresAt;
303
- Object.entries(keys).forEach(([keyId, cert2]) => {
304
- setInCache(keyId, cert2);
305
- });
306
- }
307
- const cert = getFromCache(kid);
308
- if (!cert) {
309
- getCacheValues();
310
- const availableKids = Object.keys(cache).sort().join(", ");
311
- throw new TokenVerificationError({
312
- message: `No public key found for kid "${kid}". Available kids: [${availableKids}]`,
313
- reason: TokenVerificationErrorReason.TokenInvalid
314
- });
315
- }
316
- return cert;
317
- }
318
- function isCacheExpired() {
319
- const now = Date.now();
320
- if (lastUpdatedAt === -1) {
321
- return false;
322
- }
323
- const cacheAge = now - lastUpdatedAt;
324
- const maxCacheAge = MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1e3;
325
- const localCacheExpired = cacheAge >= maxCacheAge;
326
- const googleCacheExpired = now >= googleExpiresAt;
327
- const isExpired = localCacheExpired || googleCacheExpired;
328
- if (isExpired) {
329
- cache = {};
330
- }
331
- return isExpired;
332
- }
333
- function getExpiresAt(res) {
334
- const cacheControlHeader = res.headers.get("cache-control");
335
- if (!cacheControlHeader) {
336
- return Date.now() + DEFAULT_CACHE_DURATION;
337
- }
338
- const maxAgeMatch = cacheControlHeader.match(CACHE_CONTROL_REGEX);
339
- const maxAge = maxAgeMatch ? parseInt(maxAgeMatch[1], 10) : DEFAULT_CACHE_DURATION / 1e3;
340
- return Date.now() + maxAge * 1e3;
341
- }
342
-
343
- // src/tokens/verify.ts
344
- async function verifyToken(token, options) {
345
- const { data: decodedResult, errors } = ternDecodeJwt(token);
346
- if (errors) {
347
- return { errors };
348
- }
349
- const { header } = decodedResult;
350
- const { kid } = header;
351
- if (!kid) {
352
- return {
353
- errors: [
354
- new TokenVerificationError({
355
- reason: TokenVerificationErrorReason.TokenInvalid,
356
- message: 'JWT "kid" header is missing.'
357
- })
358
- ]
359
- };
360
- }
361
- try {
362
- const key = options.jwtKey || await loadJWKFromRemote({ ...options, kid });
363
- if (!key) {
364
- return {
365
- errors: [
366
- new TokenVerificationError({
367
- reason: TokenVerificationErrorReason.TokenInvalid,
368
- message: `No public key found for kid "${kid}".`
369
- })
370
- ]
371
- };
372
- }
373
- return await verifyJwt(token, { ...options, key });
374
- } catch (error) {
375
- if (error instanceof TokenVerificationError) {
376
- return { errors: [error] };
377
- }
378
- return {
379
- errors: [error]
380
- };
381
- }
382
- }
383
-
384
432
  // src/tokens/request.ts
385
433
  var BEARER_PREFIX = "Bearer ";
386
- var AUTH_COOKIE_NAME = "_session_cookie";
387
434
  function extractTokenFromHeader(request) {
388
435
  const authHeader = request.headers.get("Authorization");
389
436
  if (!authHeader || !authHeader.startsWith(BEARER_PREFIX)) {
@@ -391,12 +438,16 @@ function extractTokenFromHeader(request) {
391
438
  }
392
439
  return authHeader.slice(BEARER_PREFIX.length);
393
440
  }
394
- function extractTokenFromCookie(request, opts) {
441
+ function extractTokenFromCookie(request) {
395
442
  const cookieHeader = request.headers.get("Cookie") || void 0;
396
- const sessionName = getSessionConfig(opts).COOKIE_NAME;
397
443
  if (!cookieHeader) {
398
444
  return null;
399
445
  }
446
+ const cookiePrefix = getCookiePrefix();
447
+ const idTokenCookieName = getCookieName(
448
+ constants.Cookies.IdToken,
449
+ cookiePrefix
450
+ );
400
451
  const cookies = cookieHeader.split(";").reduce(
401
452
  (acc, cookie) => {
402
453
  const [name, value] = cookie.trim().split("=");
@@ -405,35 +456,63 @@ function extractTokenFromCookie(request, opts) {
405
456
  },
406
457
  {}
407
458
  );
408
- return cookies[AUTH_COOKIE_NAME] || null;
459
+ return idTokenCookieName || null;
409
460
  }
410
461
  function hasAuthorizationHeader(request) {
411
462
  return request.headers.has("Authorization");
412
463
  }
413
464
  async function authenticateRequest(request, options) {
465
+ async function refreshToken() {
466
+ try {
467
+ const response = await options.apiClient?.tokens.refreshToken(options.firebaseConfig?.apiKey || "", {
468
+ format: "cookie",
469
+ refresh_token: "",
470
+ expired_token: "",
471
+ request_origin: options.apiUrl || ""
472
+ });
473
+ } catch (error) {
474
+ console.error("Error refreshing token:", error);
475
+ }
476
+ }
414
477
  async function authenticateRequestWithTokenInCookie() {
415
- const token = extractTokenFromCookie(request, options);
478
+ const token = extractTokenFromCookie(request);
416
479
  if (!token) {
417
480
  return signedOut(AuthErrorReason.SessionTokenMissing);
418
481
  }
419
- const { data, errors } = await verifyToken(token, options);
420
- if (errors) {
421
- throw errors[0];
482
+ try {
483
+ const { data, errors } = await verifyToken(token, options);
484
+ if (errors) {
485
+ throw errors[0];
486
+ }
487
+ const signedInRequestState = signedIn(data, void 0, token);
488
+ return signedInRequestState;
489
+ } catch (err) {
490
+ return handleError(err, "cookie");
422
491
  }
423
- const signedInRequestState = signedIn(data, void 0, token);
424
- return signedInRequestState;
425
492
  }
426
493
  async function authenticateRequestWithTokenInHeader() {
427
494
  const token = extractTokenFromHeader(request);
428
495
  if (!token) {
429
- return signedOut(AuthErrorReason.SessionTokenMissing);
496
+ return signedOut(AuthErrorReason.SessionTokenMissing, "");
430
497
  }
431
- const { data, errors } = await verifyToken(token, options);
432
- if (errors) {
433
- throw errors[0];
498
+ try {
499
+ const { data, errors } = await verifyToken(token, options);
500
+ if (errors) {
501
+ throw errors[0];
502
+ }
503
+ const signedInRequestState = signedIn(data, void 0, token);
504
+ return signedInRequestState;
505
+ } catch (err) {
506
+ return handleError(err, "header");
434
507
  }
435
- const signedInRequestState = signedIn(data, void 0, token);
436
- return signedInRequestState;
508
+ }
509
+ async function handleError(err, tokenCarrier) {
510
+ if (!(err instanceof TokenVerificationError)) {
511
+ return signedOut(AuthErrorReason.UnexpectedError);
512
+ }
513
+ let refreshError;
514
+ err.tokenCarrier = tokenCarrier;
515
+ return signedOut(err.reason, err.getFullMessage());
437
516
  }
438
517
  if (hasAuthorizationHeader(request)) {
439
518
  return authenticateRequestWithTokenInHeader();
@@ -455,7 +534,7 @@ function createAuthenticateRequest(params) {
455
534
  // src/instance/backendInstanceEdge.ts
456
535
  function createBackendInstanceClient(options) {
457
536
  const opts = { ...options };
458
- const apiClient = createBackendApi(opts);
537
+ const apiClient = createFireApi(opts);
459
538
  const requestState = createAuthenticateRequest({ options: opts, apiClient });
460
539
  return {
461
540
  ...apiClient,
@@ -479,7 +558,7 @@ function mergePreDefinedOptions2(preDefinedOptions, options) {
479
558
  );
480
559
  }
481
560
  var BEARER_PREFIX2 = "Bearer ";
482
- var AUTH_COOKIE_NAME2 = "_session_cookie";
561
+ var AUTH_COOKIE_NAME = "_session_cookie";
483
562
  function extractTokenFromHeader2(request) {
484
563
  const authHeader = request.headers.get("Authorization");
485
564
  if (!authHeader || !authHeader.startsWith(BEARER_PREFIX2)) {
@@ -487,9 +566,8 @@ function extractTokenFromHeader2(request) {
487
566
  }
488
567
  return authHeader.slice(BEARER_PREFIX2.length);
489
568
  }
490
- function extractTokenFromCookie2(request, opts) {
569
+ function extractTokenFromCookie2(request) {
491
570
  const cookieHeader = request.headers.get("Cookie") || void 0;
492
- const sessionName = getSessionConfig(opts).COOKIE_NAME;
493
571
  if (!cookieHeader) {
494
572
  return null;
495
573
  }
@@ -501,14 +579,14 @@ function extractTokenFromCookie2(request, opts) {
501
579
  },
502
580
  {}
503
581
  );
504
- return cookies[AUTH_COOKIE_NAME2] || null;
582
+ return cookies[AUTH_COOKIE_NAME] || null;
505
583
  }
506
584
  function hasAuthorizationHeader2(request) {
507
585
  return request.headers.has("Authorization");
508
586
  }
509
587
  async function authenticateRequest2(request, options) {
510
588
  async function authenticateRequestWithTokenInCookie() {
511
- const token = extractTokenFromCookie2(request, options);
589
+ const token = extractTokenFromCookie2(request);
512
590
  if (!token) {
513
591
  return signedOut(AuthErrorReason.SessionTokenMissing);
514
592
  }
@@ -550,7 +628,7 @@ function createFireAuthenticateRequest(params) {
550
628
  // src/instance/backendFireInstance.ts
551
629
  function createFireClient(options) {
552
630
  const opts = { ...options };
553
- const apiClient = createBackendApi(opts);
631
+ const apiClient = createFireApi(opts);
554
632
  const requestState = createFireAuthenticateRequest({ options: opts });
555
633
  return {
556
634
  ...apiClient,