@stackframe/stack-shared 2.1.0 → 2.2.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.
Files changed (61) hide show
  1. package/dist/helpers/password.d.ts +2 -2
  2. package/dist/helpers/password.d.ts.map +1 -1
  3. package/dist/helpers/password.js +8 -29
  4. package/dist/hooks/use-async-callback.d.ts +3 -0
  5. package/dist/hooks/use-async-callback.d.ts.map +1 -0
  6. package/dist/hooks/use-async-callback.js +32 -0
  7. package/dist/hooks/use-async-external-store.d.ts +0 -1
  8. package/dist/hooks/use-strict-memo.d.ts +0 -1
  9. package/dist/index.d.ts +1 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/interface/adminInterface.d.ts +0 -1
  13. package/dist/interface/clientInterface.d.ts +21 -25
  14. package/dist/interface/clientInterface.d.ts.map +1 -1
  15. package/dist/interface/clientInterface.js +109 -67
  16. package/dist/interface/serverInterface.d.ts +0 -1
  17. package/dist/interface/serverInterface.d.ts.map +1 -1
  18. package/dist/known-errors.d.ts +202 -0
  19. package/dist/known-errors.d.ts.map +1 -0
  20. package/dist/known-errors.js +316 -0
  21. package/dist/utils/arrays.d.ts +0 -1
  22. package/dist/utils/bytes.d.ts +0 -1
  23. package/dist/utils/caches.d.ts +3 -1
  24. package/dist/utils/caches.d.ts.map +1 -1
  25. package/dist/utils/caches.js +18 -14
  26. package/dist/utils/crypto.d.ts +4 -1
  27. package/dist/utils/crypto.d.ts.map +1 -1
  28. package/dist/utils/crypto.js +5 -1
  29. package/dist/utils/dates.d.ts +0 -1
  30. package/dist/utils/dom.d.ts +0 -1
  31. package/dist/utils/env.d.ts +0 -1
  32. package/dist/utils/errors.d.ts +13 -8
  33. package/dist/utils/errors.d.ts.map +1 -1
  34. package/dist/utils/errors.js +44 -3
  35. package/dist/utils/functions.d.ts +2 -0
  36. package/dist/utils/functions.d.ts.map +1 -0
  37. package/dist/utils/functions.js +6 -0
  38. package/dist/utils/html.d.ts +0 -1
  39. package/dist/utils/json.d.ts +0 -1
  40. package/dist/utils/jwt.d.ts +0 -1
  41. package/dist/utils/maps.d.ts +0 -1
  42. package/dist/utils/math.d.ts +0 -1
  43. package/dist/utils/numbers.d.ts +0 -1
  44. package/dist/utils/objects.d.ts +2 -1
  45. package/dist/utils/objects.d.ts.map +1 -1
  46. package/dist/utils/objects.js +6 -0
  47. package/dist/utils/password.d.ts +0 -1
  48. package/dist/utils/promises.d.ts +3 -2
  49. package/dist/utils/promises.d.ts.map +1 -1
  50. package/dist/utils/promises.js +24 -4
  51. package/dist/utils/react.d.ts +0 -1
  52. package/dist/utils/results.d.ts +0 -1
  53. package/dist/utils/stores.d.ts +2 -3
  54. package/dist/utils/stores.d.ts.map +1 -1
  55. package/dist/utils/stores.js +32 -19
  56. package/dist/utils/strings.d.ts +0 -1
  57. package/dist/utils/types.d.ts +4 -1
  58. package/dist/utils/types.d.ts.map +1 -1
  59. package/dist/utils/types.js +3 -0
  60. package/dist/utils/uuids.d.ts +0 -1
  61. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- export declare function getPasswordError(password: string): string | null;
2
- //# sourceMappingURL=password.d.ts.map
1
+ import { KnownErrors } from "..";
2
+ export declare function getPasswordError(password: string): KnownErrors["PasswordRequirementsNotMet"] | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"password.d.ts","sourceRoot":"","sources":["../../src/helpers/password.ts"],"names":[],"mappings":"AAoBA,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAsBhE"}
1
+ {"version":3,"file":"password.d.ts","sourceRoot":"","sources":["../../src/helpers/password.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC;AAKjC,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAAC,4BAA4B,CAAC,GAAG,SAAS,CAUxG"}
@@ -1,33 +1,12 @@
1
- function checkPasswordTooShort(password) {
2
- return password.length >= 8;
3
- }
4
- function checkPasswordTooLong(password) {
5
- return password.length <= 64;
6
- }
7
- function checkPasswordCharacters(password) {
8
- return /^[a-zA-Z0-9!@#$%^&*()_+?]+$/.test(password);
9
- }
10
- function checkPasswordContainsLetter(password) {
11
- return /[a-zA-Z]/.test(password);
12
- }
13
- function checkPasswordContainsNumber(password) {
14
- return /[0-9]/.test(password);
15
- }
1
+ import { KnownErrors } from "..";
2
+ const minLength = 8;
3
+ const maxLength = 256;
16
4
  export function getPasswordError(password) {
17
- if (!checkPasswordTooShort(password)) {
18
- return "password must be at least 8 characters long";
19
- }
20
- if (!checkPasswordTooLong(password)) {
21
- return "password must be at most 64 characters long";
22
- }
23
- if (!checkPasswordCharacters(password)) {
24
- return "password must contain only letters, numbers, and the following special characters: !@#$%^&*()_+?";
25
- }
26
- if (!checkPasswordContainsLetter(password)) {
27
- return "password must contain at least one letter";
5
+ if (password.length < minLength) {
6
+ return new KnownErrors.PasswordTooShort(minLength);
28
7
  }
29
- if (!checkPasswordContainsNumber(password)) {
30
- return "password must contain at least one number";
8
+ if (password.length > maxLength) {
9
+ return new KnownErrors.PasswordTooLong(maxLength);
31
10
  }
32
- return null;
11
+ return undefined;
33
12
  }
@@ -0,0 +1,3 @@
1
+ import React from "react";
2
+ export declare function useAsyncCallback<A extends any[], R>(callback: (...args: A) => Promise<R>, deps: React.DependencyList): [cb: (...args: A) => Promise<R>, loading: boolean, error: unknown | undefined];
3
+ export declare function useAsyncCallbackWithLoggedError<A extends any[], R>(callback: (...args: A) => Promise<R>, deps: React.DependencyList): [cb: (...args: A) => Promise<R>, loading: boolean];
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-async-callback.d.ts","sourceRoot":"","sources":["../../src/hooks/use-async-callback.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,GAAG,EAAE,EAAE,CAAC,EACjD,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EACpC,IAAI,EAAE,KAAK,CAAC,cAAc,GACzB,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC,CAoBhF;AAED,wBAAgB,+BAA+B,CAAC,CAAC,SAAS,GAAG,EAAE,EAAE,CAAC,EAChE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EACpC,IAAI,EAAE,KAAK,CAAC,cAAc,GACzB,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAWpD"}
@@ -0,0 +1,32 @@
1
+ import React from "react";
2
+ import { captureError } from "../utils/errors";
3
+ export function useAsyncCallback(callback, deps) {
4
+ const [error, setError] = React.useState(undefined);
5
+ const [loadingCount, setLoadingCount] = React.useState(0);
6
+ const cb = React.useCallback(async (...args) => {
7
+ setLoadingCount((c) => c + 1);
8
+ try {
9
+ return await callback(...args);
10
+ }
11
+ catch (e) {
12
+ setError(e);
13
+ throw e;
14
+ }
15
+ finally {
16
+ setLoadingCount((c) => c - 1);
17
+ }
18
+ }, deps);
19
+ return [cb, loadingCount > 0, error];
20
+ }
21
+ export function useAsyncCallbackWithLoggedError(callback, deps) {
22
+ const [newCallback, loading] = useAsyncCallback(async (...args) => {
23
+ try {
24
+ return await callback(...args);
25
+ }
26
+ catch (e) {
27
+ captureError("async-callback", e);
28
+ throw e;
29
+ }
30
+ }, deps);
31
+ return [newCallback, loading];
32
+ }
@@ -2,4 +2,3 @@ import { AsyncResult } from "../utils/results";
2
2
  export declare function useAsyncExternalStore<T>(subscribe: (callback: (t: T) => void) => (() => void)): AsyncResult<T, never> & {
3
3
  status: "ok" | "pending";
4
4
  };
5
- //# sourceMappingURL=use-async-external-store.d.ts.map
@@ -4,4 +4,3 @@
4
4
  * The most recent value will be kept from garbage collection until one of the dependencies becomes unreachable. This may be true even after the component no longer renders. Be wary of memory leaks.
5
5
  */
6
6
  export declare function useStrictMemo<T>(callback: () => T, dependencies: any[]): T;
7
- //# sourceMappingURL=use-strict-memo.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  export { StackClientInterface, UserJson as UserJson, UserCustomizableJson, ClientProjectJson, ProjectJson, OAuthProviderConfigJson, getProductionModeErrors, } from "./interface/clientInterface";
2
2
  export { StackServerInterface, ServerUserJson, ServerUserCustomizableJson, } from "./interface/serverInterface";
3
3
  export { StackAdminInterface, ApiKeySetBaseJson, ApiKeySetFirstViewJson, ApiKeySetJson, } from "./interface/adminInterface";
4
- export { fetchTokenPrefix } from "./helpers/fetch-token";
5
- //# sourceMappingURL=index.d.ts.map
4
+ export { KnownError, KnownErrors, } from "./known-errors";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,QAAQ,IAAI,QAAQ,EACpB,oBAAoB,EACpB,iBAAiB,EACjB,WAAW,EACX,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,0BAA0B,GAC3B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,QAAQ,IAAI,QAAQ,EACpB,oBAAoB,EACpB,iBAAiB,EACjB,WAAW,EACX,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,0BAA0B,GAC3B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,UAAU,EACV,WAAW,GACZ,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { StackClientInterface, getProductionModeErrors, } from "./interface/clientInterface";
2
2
  export { StackServerInterface, } from "./interface/serverInterface";
3
3
  export { StackAdminInterface, } from "./interface/adminInterface";
4
- export { fetchTokenPrefix } from "./helpers/fetch-token";
4
+ export { KnownError, KnownErrors, } from "./known-errors";
@@ -76,4 +76,3 @@ export declare class StackAdminInterface extends StackServerInterface {
76
76
  revokeApiKeySetById(id: string): Promise<void>;
77
77
  getApiKeySet(id: string, tokenStore: TokenStore): Promise<ApiKeySetJson>;
78
78
  }
79
- //# sourceMappingURL=adminInterface.d.ts.map
@@ -1,8 +1,8 @@
1
1
  import * as oauth from 'oauth4webapi';
2
- import { SignInErrorCode, SignUpErrorCode, EmailVerificationLinkErrorCode, PasswordResetLinkErrorCode, KnownErrorCode } from "../utils/types";
3
2
  import { Result } from "../utils/results";
4
3
  import { ReadonlyJson } from '../utils/json';
5
4
  import { AsyncStore, ReadonlyAsyncStore } from '../utils/stores';
5
+ import { KnownErrors } from '../known-errors';
6
6
  export type UserCustomizableJson = {
7
7
  readonly projectId: string;
8
8
  readonly displayName: string | null;
@@ -16,6 +16,7 @@ export type UserJson = UserCustomizableJson & {
16
16
  readonly clientMetadata: ReadonlyJson;
17
17
  readonly profileImageUrl: string | null;
18
18
  readonly signedUpAtMillis: number;
19
+ readonly authMethod: "credential" | "oauth";
19
20
  };
20
21
  export type ClientProjectJson = {
21
22
  readonly id: string;
@@ -105,32 +106,28 @@ export declare class StackClientInterface {
105
106
  accessToken: string | null;
106
107
  }>;
107
108
  }>;
108
- protected sendClientRequestAndCatchKnownError<E extends KnownErrorCode>(path: string, requestOptions: RequestInit, tokenStoreOrNull: TokenStore | null, errorCodes: readonly E[]): Promise<({
109
- status: "ok";
110
- data: Response & {
111
- usedTokens: Readonly<{
112
- refreshToken: string | null;
113
- accessToken: string | null;
114
- }>;
115
- };
116
- } & {
117
- status: "ok";
118
- }) | ({
119
- status: "error";
120
- error: E;
121
- } & {
122
- status: "error";
123
- })>;
109
+ protected sendClientRequestAndCatchKnownError<E extends typeof KnownErrors[keyof KnownErrors]>(path: string, requestOptions: RequestInit, tokenStoreOrNull: TokenStore | null, errorsToCatch: readonly E[]): Promise<Result<Response & {
110
+ usedTokens: TokenObject;
111
+ }, InstanceType<E>>>;
124
112
  private sendClientRequestInner;
125
- sendForgotPasswordEmail(email: string, redirectUrl: string): Promise<PasswordResetLinkErrorCode | undefined>;
113
+ private _processResponse;
114
+ sendForgotPasswordEmail(email: string, redirectUrl: string): Promise<KnownErrors["UserNotFound"] | undefined>;
115
+ sendVerificationEmail(emailVerificationRedirectUrl: string, tokenStore: TokenStore): Promise<KnownErrors["EmailAlreadyVerified"] | undefined>;
126
116
  resetPassword(options: {
127
- password: string;
128
117
  code: string;
129
- }): Promise<PasswordResetLinkErrorCode | undefined>;
130
- verifyPasswordResetCode(code: string): Promise<PasswordResetLinkErrorCode | undefined>;
131
- verifyEmail(code: string): Promise<EmailVerificationLinkErrorCode | undefined>;
132
- signInWithCredential(email: string, password: string, tokenStore: TokenStore): Promise<SignInErrorCode | undefined>;
133
- signUpWithCredential(email: string, password: string, emailVerificationRedirectUrl: string, tokenStore: TokenStore): Promise<SignUpErrorCode | undefined>;
118
+ } & ({
119
+ password: string;
120
+ } | {
121
+ onlyVerifyCode: boolean;
122
+ })): Promise<KnownErrors["PasswordResetError"] | undefined>;
123
+ updatePassword(options: {
124
+ oldPassword: string;
125
+ newPassword: string;
126
+ }, tokenStore: TokenStore): Promise<KnownErrors["PasswordMismatch"] | KnownErrors["PasswordRequirementsNotMet"] | undefined>;
127
+ verifyPasswordResetCode(code: string): Promise<KnownErrors["PasswordResetCodeError"] | undefined>;
128
+ verifyEmail(code: string): Promise<KnownErrors["EmailVerificationError"] | undefined>;
129
+ signInWithCredential(email: string, password: string, tokenStore: TokenStore): Promise<KnownErrors["EmailPasswordMismatch"] | undefined>;
130
+ signUpWithCredential(email: string, password: string, emailVerificationRedirectUrl: string, tokenStore: TokenStore): Promise<KnownErrors["UserEmailAlreadyExists"] | undefined>;
134
131
  getOAuthUrl(provider: string, redirectUrl: string, codeChallenge: string, state: string): Promise<string>;
135
132
  callOAuthCallback(oauthParams: URLSearchParams, redirectUri: string, codeVerifier: string, state: string, tokenStore: TokenStore): Promise<oauth.OAuth2TokenEndpointResponse>;
136
133
  signOut(tokenStore: TokenStore): Promise<void>;
@@ -141,4 +138,3 @@ export declare class StackClientInterface {
141
138
  createProject(project: Pick<ProjectJson, "displayName" | "description">, tokenStore: TokenStore): Promise<ProjectJson>;
142
139
  }
143
140
  export declare function getProductionModeErrors(project: ProjectJson): ProductionModeError[];
144
- //# sourceMappingURL=clientInterface.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"clientInterface.d.ts","sourceRoot":"","sources":["../../src/interface/clientInterface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAGtC,OAAO,EAGL,eAAe,EACf,eAAe,EAKf,8BAA8B,EAG9B,0BAA0B,EAC1B,cAAc,EACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAe,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAa,MAAM,eAAe,CAAC;AAGxD,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAGjE,MAAM,MAAM,oBAAoB,GAAG;IACjC,QAAQ,CAAC,SAAS,EAAE,MAAM,C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AE,CAAC;IAU5D,aAAa,CACjB,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,GAAG,aAAa,CAAC,EACzD,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,WAAW,CAAC;CAmBxB;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,WAAW,GAAG,mBAAmB,EAAE,CA0CnF"}
@@ -1,10 +1,9 @@
1
1
  import * as oauth from 'oauth4webapi';
2
2
  import crypto from "crypto";
3
- import { AccessTokenExpiredErrorCode, GrantInvalidErrorCode, KnownErrorCodes, KnownError, SignUpErrorCodes, SignInErrorCodes, EmailVerificationLinkErrorCodes, PasswordResetLinkErrorCodes, } from "../utils/types";
4
- import { AsyncResult, Result } from "../utils/results";
5
- import { parseJson } from '../utils/json';
6
- import { typedAssign } from '../utils/objects';
3
+ import { Result } from "../utils/results";
7
4
  import { AsyncStore } from '../utils/stores';
5
+ import { KnownError, KnownErrors } from '../known-errors';
6
+ import { StackAssertionError } from '../utils/errors';
8
7
  export const sharedProviders = [
9
8
  "shared-github",
10
9
  "shared-google",
@@ -64,32 +63,31 @@ export class StackClientInterface {
64
63
  client_secret: this.options.publishableClientKey,
65
64
  token_endpoint_auth_method: 'client_secret_basic',
66
65
  };
67
- const response = await oauth.refreshTokenGrantRequest(as, client, refreshToken);
68
- if (!response.ok) {
69
- const error = await response.text();
70
- let errorJsonResult = parseJson(error);
71
- if (response.status === 401
72
- && errorJsonResult.status === "ok"
73
- && errorJsonResult.data
74
- && errorJsonResult.data.error_code === GrantInvalidErrorCode) {
66
+ const rawResponse = await oauth.refreshTokenGrantRequest(as, client, refreshToken);
67
+ const response = await this._processResponse(rawResponse);
68
+ if (response.status === "error") {
69
+ const error = response.error;
70
+ if (error instanceof KnownErrors.RefreshTokenError) {
75
71
  return tokenStore.set({
76
72
  accessToken: null,
77
73
  refreshToken: null,
78
74
  });
79
75
  }
80
- throw new Error(`Failed to send refresh token request: ${response.status} ${error}`);
76
+ throw error;
77
+ }
78
+ if (!response.data.ok) {
79
+ const body = await response.data.text();
80
+ throw new Error(`Failed to send refresh token request: ${response.status} ${body}`);
81
81
  }
82
82
  let challenges;
83
- if ((challenges = oauth.parseWwwAuthenticateChallenges(response))) {
84
- for (const challenge of challenges) {
85
- console.error('WWW-Authenticate Challenge', challenge);
86
- }
87
- throw new Error(); // Handle WWW-Authenticate Challenges as needed
83
+ if ((challenges = oauth.parseWwwAuthenticateChallenges(response.data))) {
84
+ // TODO Handle WWW-Authenticate Challenges as needed
85
+ throw new StackAssertionError("OAuth WWW-Authenticate challenge not implemented", { challenges });
88
86
  }
89
- const result = await oauth.processRefreshTokenResponse(as, client, response);
87
+ const result = await oauth.processRefreshTokenResponse(as, client, response.data);
90
88
  if (oauth.isOAuth2Error(result)) {
91
- console.error('Error Response', result);
92
- throw new Error(); // Handle OAuth 2.0 response body error
89
+ // TODO Handle OAuth 2.0 response body error
90
+ throw new StackAssertionError("OAuth error", { result });
93
91
  }
94
92
  tokenStore.update(old => ({
95
93
  accessToken: result.access_token ?? null,
@@ -103,13 +101,15 @@ export class StackClientInterface {
103
101
  });
104
102
  return await Result.orThrowAsync(Result.retry(() => this.sendClientRequestInner(path, requestOptions, tokenStore), 5, { exponentialDelayBase: 1000 }));
105
103
  }
106
- async sendClientRequestAndCatchKnownError(path, requestOptions, tokenStoreOrNull, errorCodes) {
104
+ async sendClientRequestAndCatchKnownError(path, requestOptions, tokenStoreOrNull, errorsToCatch) {
107
105
  try {
108
106
  return Result.ok(await this.sendClientRequest(path, requestOptions, tokenStoreOrNull));
109
107
  }
110
108
  catch (e) {
111
- if (e instanceof KnownError && errorCodes.some(code => code === e.errorCode)) {
112
- return Result.error(e.errorCode);
109
+ for (const errorType of errorsToCatch) {
110
+ if (e instanceof errorType) {
111
+ return Result.error(e);
112
+ }
113
113
  }
114
114
  throw e;
115
115
  }
@@ -126,23 +126,46 @@ export class StackClientInterface {
126
126
  }
127
127
  const url = this.getApiUrl() + path;
128
128
  const params = {
129
+ /**
130
+ * This fetch may be cross-origin, in which case we don't want to send cookies of the
131
+ * original origin (this is the default behaviour of `credentials`).
132
+ *
133
+ * To help debugging, also omit cookies on same-origin, so we don't accidentally
134
+ * implement reliance on cookies anywhere.
135
+ */
136
+ credentials: "omit",
129
137
  ...options,
130
138
  headers: {
139
+ "X-Stack-Override-Error-Status": "true",
140
+ "X-Stack-Project-Id": this.projectId,
131
141
  ...tokenObj.accessToken ? {
132
- "authorization": "StackSession " + tokenObj.accessToken,
142
+ "Authorization": "StackSession " + tokenObj.accessToken,
133
143
  } : {},
134
- "x-stack-project-id": this.projectId,
135
144
  ...'publishableClientKey' in this.options ? {
136
- "x-stack-publishable-client-key": this.options.publishableClientKey,
145
+ "X-Stack-Publishable-Client-Key": this.options.publishableClientKey,
137
146
  } : {},
138
147
  ...'projectOwnerTokens' in this.options ? {
139
- "x-stack-admin-access-token": AsyncResult.or(this.options.projectOwnerTokens?.get(), null)?.accessToken ?? "",
148
+ "X-Stack-Admin-Access-Token": (await this.options.projectOwnerTokens?.getOrWait())?.accessToken ?? "",
140
149
  } : {},
141
150
  ...options.headers,
142
151
  },
143
152
  };
144
- const res = await fetch(url, params);
145
- typedAssign(res, {
153
+ const rawRes = await fetch(url, params);
154
+ const processedRes = await this._processResponse(rawRes);
155
+ if (processedRes.status === "error") {
156
+ // If the access token is expired, reset it and retry
157
+ if (processedRes.error instanceof KnownErrors.AccessTokenExpired) {
158
+ tokenStore.set({
159
+ accessToken: null,
160
+ refreshToken: tokenObj.refreshToken,
161
+ });
162
+ return Result.error(new Error("Access token expired"));
163
+ }
164
+ // Known errors are client side errors, and should hence not be retried (except for access token expired above).
165
+ // Hence, throw instead of returning an error
166
+ throw processedRes.error;
167
+ }
168
+ const res = Object.assign(processedRes.data, {
146
169
  usedTokens: tokenObj,
147
170
  });
148
171
  if (res.ok) {
@@ -150,27 +173,31 @@ export class StackClientInterface {
150
173
  }
151
174
  else {
152
175
  const error = await res.text();
153
- let errorJsonResult = parseJson(error);
154
- if (res.status === 401
155
- && errorJsonResult.status === "ok"
156
- && errorJsonResult.data
157
- && errorJsonResult.data.error_code === AccessTokenExpiredErrorCode) {
158
- tokenStore.set({
159
- accessToken: null,
160
- refreshToken: tokenObj.refreshToken,
161
- });
162
- return Result.error(new Error("Access token expired"));
163
- }
164
- if (res.status >= 400 && res.status <= 599
165
- && errorJsonResult.status === "ok"
166
- && errorJsonResult.data
167
- && KnownErrorCodes.includes(errorJsonResult.data.error_code)) {
168
- throw new KnownError(errorJsonResult.data.error_code);
169
- }
170
176
  // Do not retry, throw error instead of returning one
171
177
  throw new Error(`Failed to send request to ${url}: ${res.status} ${error}`);
172
178
  }
173
179
  }
180
+ async _processResponse(rawRes) {
181
+ let res = rawRes;
182
+ if (rawRes.headers.has("x-stack-actual-status")) {
183
+ const actualStatus = Number(rawRes.headers.get("x-stack-actual-status"));
184
+ res = new Response(rawRes.body, {
185
+ status: actualStatus,
186
+ statusText: rawRes.statusText,
187
+ headers: rawRes.headers,
188
+ });
189
+ }
190
+ // Handle known errors
191
+ if (res.headers.has("x-stack-known-error")) {
192
+ const errorJson = await res.json();
193
+ if (res.headers.get("x-stack-known-error") !== errorJson.code) {
194
+ throw new Error("Mismatch between x-stack-known-error header and error code in body; the server's response is invalid");
195
+ }
196
+ const error = KnownError.fromJson(errorJson);
197
+ return Result.error(error);
198
+ }
199
+ return Result.ok(res);
200
+ }
174
201
  async sendForgotPasswordEmail(email, redirectUrl) {
175
202
  const res = await this.sendClientRequestAndCatchKnownError("/auth/forgot-password", {
176
203
  method: "POST",
@@ -181,7 +208,21 @@ export class StackClientInterface {
181
208
  email,
182
209
  redirectUrl,
183
210
  }),
184
- }, null, PasswordResetLinkErrorCodes);
211
+ }, null, [KnownErrors.UserNotFound]);
212
+ if (res.status === "error") {
213
+ return res.error;
214
+ }
215
+ }
216
+ async sendVerificationEmail(emailVerificationRedirectUrl, tokenStore) {
217
+ const res = await this.sendClientRequestAndCatchKnownError("/auth/send-verification-email", {
218
+ method: "POST",
219
+ headers: {
220
+ "Content-Type": "application/json"
221
+ },
222
+ body: JSON.stringify({
223
+ emailVerificationRedirectUrl,
224
+ }),
225
+ }, tokenStore, [KnownErrors.EmailAlreadyVerified]);
185
226
  if (res.status === "error") {
186
227
  return res.error;
187
228
  }
@@ -193,26 +234,30 @@ export class StackClientInterface {
193
234
  "Content-Type": "application/json"
194
235
  },
195
236
  body: JSON.stringify(options),
196
- }, null, PasswordResetLinkErrorCodes);
237
+ }, null, [KnownErrors.PasswordResetError]);
197
238
  if (res.status === "error") {
198
239
  return res.error;
199
240
  }
200
241
  }
201
- async verifyPasswordResetCode(code) {
202
- const res = await this.sendClientRequestAndCatchKnownError("/auth/password-reset", {
242
+ async updatePassword(options, tokenStore) {
243
+ const res = await this.sendClientRequestAndCatchKnownError("/auth/update-password", {
203
244
  method: "POST",
204
245
  headers: {
205
246
  "Content-Type": "application/json"
206
247
  },
207
- body: JSON.stringify({
208
- code,
209
- onlyVerifyCode: true,
210
- }),
211
- }, null, PasswordResetLinkErrorCodes);
248
+ body: JSON.stringify(options),
249
+ }, tokenStore, [KnownErrors.PasswordMismatch, KnownErrors.PasswordRequirementsNotMet]);
212
250
  if (res.status === "error") {
213
251
  return res.error;
214
252
  }
215
253
  }
254
+ async verifyPasswordResetCode(code) {
255
+ const res = await this.resetPassword({ code, onlyVerifyCode: true });
256
+ if (res && !(res instanceof KnownErrors.PasswordResetCodeError)) {
257
+ throw res;
258
+ }
259
+ return res;
260
+ }
216
261
  async verifyEmail(code) {
217
262
  const res = await this.sendClientRequestAndCatchKnownError("/auth/email-verification", {
218
263
  method: "POST",
@@ -222,7 +267,7 @@ export class StackClientInterface {
222
267
  body: JSON.stringify({
223
268
  code,
224
269
  }),
225
- }, null, EmailVerificationLinkErrorCodes);
270
+ }, null, [KnownErrors.EmailVerificationError]);
226
271
  if (res.status === "error") {
227
272
  return res.error;
228
273
  }
@@ -237,7 +282,7 @@ export class StackClientInterface {
237
282
  email,
238
283
  password,
239
284
  }),
240
- }, tokenStore, SignInErrorCodes);
285
+ }, tokenStore, [KnownErrors.EmailPasswordMismatch]);
241
286
  if (res.status === "error") {
242
287
  return res.error;
243
288
  }
@@ -258,7 +303,7 @@ export class StackClientInterface {
258
303
  password,
259
304
  emailVerificationRedirectUrl,
260
305
  }),
261
- }, tokenStore, SignUpErrorCodes);
306
+ }, tokenStore, [KnownErrors.UserEmailAlreadyExists]);
262
307
  if (res.status === "error") {
263
308
  return res.error;
264
309
  }
@@ -309,21 +354,18 @@ export class StackClientInterface {
309
354
  };
310
355
  const params = oauth.validateAuthResponse(as, client, oauthParams, state);
311
356
  if (oauth.isOAuth2Error(params)) {
312
- console.error('Error validating OAuth response', params);
313
- throw new Error("Error validating OAuth response"); // Handle OAuth 2.0 redirect error
357
+ throw new StackAssertionError("Error validating OAuth response", { params }); // Handle OAuth 2.0 redirect error
314
358
  }
315
359
  const response = await oauth.authorizationCodeGrantRequest(as, client, params, redirectUri, codeVerifier);
316
360
  let challenges;
317
361
  if ((challenges = oauth.parseWwwAuthenticateChallenges(response))) {
318
- for (const challenge of challenges) {
319
- console.error('WWW-Authenticate Challenge', challenge);
320
- }
321
- throw new Error(); // Handle WWW-Authenticate Challenges as needed
362
+ // TODO Handle WWW-Authenticate Challenges as needed
363
+ throw new StackAssertionError("OAuth WWW-Authenticate challenge not implemented", { challenges });
322
364
  }
323
365
  const result = await oauth.processAuthorizationCodeOAuth2Response(as, client, response);
324
366
  if (oauth.isOAuth2Error(result)) {
325
- console.error('Error Response', result);
326
- throw new Error(); // Handle OAuth 2.0 response body error
367
+ // TODO Handle OAuth 2.0 response body error
368
+ throw new StackAssertionError("OAuth error", { result });
327
369
  }
328
370
  tokenStore.update(old => ({
329
371
  accessToken: result.access_token ?? null,
@@ -28,4 +28,3 @@ export declare class StackServerInterface extends StackClientInterface {
28
28
  setServerUserCustomizableData(userId: string, update: Partial<ServerUserCustomizableJson>): Promise<void>;
29
29
  deleteServerUser(userId: string): Promise<void>;
30
30
  }
31
- //# sourceMappingURL=serverInterface.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serverInterface.d.ts","sourceRoot":"","sources":["../../src/interface/serverInterface.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,QAAQ,EACR,UAAU,EACV,oBAAoB,EACpB,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAG1C,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG;IACtC,QAAQ,CAAC,cAAc,EAAE,YAAY,CAAC;CACvC,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG,oBAAoB,GAAG;IAC9D,QAAQ,CAAC,cAAc,EAAE,YAAY,CAAC;IACtC,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,QAAQ,CAAC,oBAAoB,EAAE,OAAO,CAAC;CACxC,CAAA;AAGD,MAAM,MAAM,4BAA4B,GAAG,CACvC,sBAAsB,GACtB,CACE;IACA,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CAClC,GACC;IACA,QAAQ,CAAC,kBAAkB,EAAE,kBAAkB,CAAC;CACjD,CACF,CACF,CAAC;AAGF,qBAAa,oBAAqB,SAAQ,oBAAoB;IAChC,OAAO,EAAE,4BAA4B;gBAArC,OAAO,EAAE,4BAA4B;cAIjD,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,GAAG,IAAI;;;;;;IAc7F,oBAAoB,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IAW7E,SAAS,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;IAKtC,6BAA6B,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,0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