@stackframe/stack-shared 2.3.6 → 2.4.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.
@@ -62,7 +62,7 @@ export type ApiKeySetCreateOptions = {
62
62
  export declare class StackAdminInterface extends StackServerInterface {
63
63
  readonly options: AdminAuthApplicationOptions;
64
64
  constructor(options: AdminAuthApplicationOptions);
65
- protected sendAdminRequest(path: string, options: RequestInit, tokenStore: TokenStore | null): Promise<Response & {
65
+ protected sendAdminRequest(path: string, options: RequestInit, tokenStore: TokenStore | null, requestType?: "admin"): Promise<Response & {
66
66
  usedTokens: Readonly<{
67
67
  refreshToken: string | null;
68
68
  accessToken: string | null;
@@ -5,14 +5,14 @@ export class StackAdminInterface extends StackServerInterface {
5
5
  super(options);
6
6
  this.options = options;
7
7
  }
8
- async sendAdminRequest(path, options, tokenStore) {
8
+ async sendAdminRequest(path, options, tokenStore, requestType = "admin") {
9
9
  return await this.sendServerRequest(path, {
10
10
  ...options,
11
11
  headers: {
12
12
  "x-stack-super-secret-admin-key": "superSecretAdminKey" in this.options ? this.options.superSecretAdminKey : "",
13
13
  ...options.headers,
14
14
  },
15
- }, tokenStore);
15
+ }, tokenStore, requestType);
16
16
  }
17
17
  async getProject(options) {
18
18
  const response = await this.sendAdminRequest("/projects/" + encodeURIComponent(this.projectId), {
@@ -105,7 +105,7 @@ export declare class StackClientInterface {
105
105
  getSessionCookieName(): string;
106
106
  getApiUrl(): string;
107
107
  protected refreshAccessToken(tokenStore: TokenStore): Promise<void>;
108
- protected sendClientRequest(path: string, requestOptions: RequestInit, tokenStoreOrNull: TokenStore | null): Promise<Response & {
108
+ protected sendClientRequest(path: string, requestOptions: RequestInit, tokenStoreOrNull: TokenStore | null, requestType?: "client" | "server" | "admin"): Promise<Response & {
109
109
  usedTokens: Readonly<{
110
110
  refreshToken: string | null;
111
111
  accessToken: string | null;
@@ -94,12 +94,12 @@ export class StackClientInterface {
94
94
  refreshToken: result.refresh_token ?? old?.refreshToken ?? null,
95
95
  }));
96
96
  }
97
- async sendClientRequest(path, requestOptions, tokenStoreOrNull) {
97
+ async sendClientRequest(path, requestOptions, tokenStoreOrNull, requestType = "client") {
98
98
  const tokenStore = tokenStoreOrNull ?? new AsyncStore({
99
99
  accessToken: null,
100
100
  refreshToken: null,
101
101
  });
102
- return await Result.orThrowAsync(Result.retry(() => this.sendClientRequestInner(path, requestOptions, tokenStore), 5, { exponentialDelayBase: 1000 }));
102
+ return await Result.orThrowAsync(Result.retry(() => this.sendClientRequestInner(path, requestOptions, tokenStore, requestType), 5, { exponentialDelayBase: 1000 }));
103
103
  }
104
104
  async sendClientRequestAndCatchKnownError(path, requestOptions, tokenStoreOrNull, errorsToCatch) {
105
105
  try {
@@ -118,7 +118,7 @@ export class StackClientInterface {
118
118
  /**
119
119
  * This object will be modified for future retries, so it should be passed by reference.
120
120
  */
121
- tokenStore) {
121
+ tokenStore, requestType) {
122
122
  let tokenObj = await tokenStore.getOrWait();
123
123
  if (!tokenObj.accessToken && tokenObj.refreshToken) {
124
124
  await this.refreshAccessToken(tokenStore);
@@ -138,6 +138,7 @@ export class StackClientInterface {
138
138
  headers: {
139
139
  "X-Stack-Override-Error-Status": "true",
140
140
  "X-Stack-Project-Id": this.projectId,
141
+ "X-Stack-Request-Type": requestType,
141
142
  ...tokenObj.accessToken ? {
142
143
  "Authorization": "StackSession " + tokenObj.accessToken,
143
144
  } : {},
@@ -17,7 +17,7 @@ export type ServerAuthApplicationOptions = (ClientInterfaceOptions & ({
17
17
  export declare class StackServerInterface extends StackClientInterface {
18
18
  options: ServerAuthApplicationOptions;
19
19
  constructor(options: ServerAuthApplicationOptions);
20
- protected sendServerRequest(path: string, options: RequestInit, tokenStore: TokenStore | null): Promise<Response & {
20
+ protected sendServerRequest(path: string, options: RequestInit, tokenStore: TokenStore | null, requestType?: "server" | "admin"): Promise<Response & {
21
21
  usedTokens: Readonly<{
22
22
  refreshToken: string | null;
23
23
  accessToken: string | null;
@@ -6,14 +6,14 @@ export class StackServerInterface extends StackClientInterface {
6
6
  super(options);
7
7
  this.options = options;
8
8
  }
9
- async sendServerRequest(path, options, tokenStore) {
9
+ async sendServerRequest(path, options, tokenStore, requestType = "server") {
10
10
  return await this.sendClientRequest(path, {
11
11
  ...options,
12
12
  headers: {
13
13
  "x-stack-secret-server-key": "secretServerKey" in this.options ? this.options.secretServerKey : "",
14
14
  ...options.headers,
15
15
  },
16
- }, tokenStore);
16
+ }, tokenStore, requestType);
17
17
  }
18
18
  async getServerUserByToken(tokenStore) {
19
19
  const response = await this.sendServerRequest("/current-user?server=true", {}, tokenStore);
@@ -58,6 +58,15 @@ export declare const KnownErrors: {
58
58
  InvalidProjectAuthentication: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"INVALID_PROJECT_AUTHENTICATION">, [statusCode: number, humanReadableMessage: string, details?: Json | undefined]> & {
59
59
  errorCode: "INVALID_PROJECT_AUTHENTICATION";
60
60
  };
61
+ ProjectKeyWithoutRequestType: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"INVALID_PROJECT_AUTHENTICATION"> & KnownErrorBrand<"PROJECT_KEY_WITHOUT_REQUEST_TYPE">, []> & {
62
+ errorCode: "PROJECT_KEY_WITHOUT_REQUEST_TYPE";
63
+ };
64
+ InvalidRequestType: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"INVALID_PROJECT_AUTHENTICATION"> & KnownErrorBrand<"INVALID_REQUEST_TYPE">, [requestType: string]> & {
65
+ errorCode: "INVALID_REQUEST_TYPE";
66
+ };
67
+ RequestTypeWithoutProjectId: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"INVALID_PROJECT_AUTHENTICATION"> & KnownErrorBrand<"REQUEST_TYPE_WITHOUT_PROJECT_ID">, [requestType: "client" | "server" | "admin"]> & {
68
+ errorCode: "REQUEST_TYPE_WITHOUT_PROJECT_ID";
69
+ };
61
70
  InvalidPublishableClientKey: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"INVALID_PROJECT_AUTHENTICATION"> & KnownErrorBrand<"INVALID_PUBLISHABLE_CLIENT_KEY">, []> & {
62
71
  errorCode: "INVALID_PUBLISHABLE_CLIENT_KEY";
63
72
  };
@@ -79,6 +88,9 @@ export declare const KnownErrors: {
79
88
  InvalidProjectForAdminAccessToken: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"INVALID_PROJECT_AUTHENTICATION"> & KnownErrorBrand<"INVALID_ADMIN_ACCESS_TOKEN"> & KnownErrorBrand<"INVALID_PROJECT_FOR_ADMIN_ACCESS_TOKEN">, []> & {
80
89
  errorCode: "INVALID_PROJECT_FOR_ADMIN_ACCESS_TOKEN";
81
90
  };
91
+ AdminAccessTokenIsNotAdmin: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"INVALID_PROJECT_AUTHENTICATION"> & KnownErrorBrand<"INVALID_ADMIN_ACCESS_TOKEN"> & KnownErrorBrand<"ADMIN_ACCESS_TOKEN_IS_NOT_ADMIN">, []> & {
92
+ errorCode: "ADMIN_ACCESS_TOKEN_IS_NOT_ADMIN";
93
+ };
82
94
  ProjectAuthenticationRequired: KnownErrorConstructor<KnownError & KnownErrorBrand<"PROJECT_AUTHENTICATION_ERROR"> & KnownErrorBrand<"PROJECT_AUTHENTICATION_REQUIRED">, [statusCode: number, humanReadableMessage: string, details?: Json | undefined]> & {
83
95
  errorCode: "PROJECT_AUTHENTICATION_REQUIRED";
84
96
  };
@@ -1,5 +1,6 @@
1
1
  import { StatusError, throwErr, throwStackErr } from "./utils/errors";
2
2
  import { identityArgs } from "./utils/functions";
3
+ import { deindent } from "./utils/strings";
3
4
  export class KnownError extends StatusError {
4
5
  statusCode;
5
6
  humanReadableMessage;
@@ -80,7 +81,13 @@ const SchemaError = createKnownErrorConstructor(KnownError, "SCHEMA_ERROR", (mes
80
81
  ], (json) => [json.message]);
81
82
  const AllOverloadsFailed = createKnownErrorConstructor(KnownError, "ALL_OVERLOADS_FAILED", (overloadErrors) => [
82
83
  400,
83
- "This endpoint has multiple overloads, but they all failed to process the request.",
84
+ deindent `
85
+ This endpoint has multiple overloads, but they all failed to process the request.
86
+
87
+ ${overloadErrors.map((e, i) => deindent `
88
+ Overload ${i + 1}: ${JSON.stringify(e, undefined, 2)}
89
+ `).join("\n\n")}
90
+ `,
84
91
  {
85
92
  overloads: overloadErrors,
86
93
  },
@@ -89,6 +96,23 @@ const AllOverloadsFailed = createKnownErrorConstructor(KnownError, "ALL_OVERLOAD
89
96
  ]);
90
97
  const ProjectAuthenticationError = createKnownErrorConstructor(KnownError, "PROJECT_AUTHENTICATION_ERROR", "inherit", "inherit");
91
98
  const InvalidProjectAuthentication = createKnownErrorConstructor(ProjectAuthenticationError, "INVALID_PROJECT_AUTHENTICATION", "inherit", "inherit");
99
+ const ProjectKeyWithoutRequestType = createKnownErrorConstructor(InvalidProjectAuthentication, "PROJECT_KEY_WITHOUT_REQUEST_TYPE", () => [
100
+ 400,
101
+ "Either an API key or an admin access token was provided, but the x-stack-request-type header is missing. Set it to 'client', 'server', or 'admin' as appropriate.",
102
+ ], () => []);
103
+ const InvalidRequestType = createKnownErrorConstructor(InvalidProjectAuthentication, "INVALID_REQUEST_TYPE", (requestType) => [
104
+ 400,
105
+ `The x-stack-request-type header must be 'client', 'server', or 'admin', but was '${requestType}'.`,
106
+ ], (json) => [
107
+ json.details?.requestType ?? throwErr("requestType not found in InvalidRequestType details"),
108
+ ]);
109
+ const RequestTypeWithoutProjectId = createKnownErrorConstructor(InvalidProjectAuthentication, "REQUEST_TYPE_WITHOUT_PROJECT_ID", (requestType) => [
110
+ 400,
111
+ `The x-stack-request-type header was '${requestType}', but the x-stack-project-id header was not provided.`,
112
+ {
113
+ requestType,
114
+ },
115
+ ], (json) => [json.requestType]);
92
116
  const InvalidPublishableClientKey = createKnownErrorConstructor(InvalidProjectAuthentication, "INVALID_PUBLISHABLE_CLIENT_KEY", () => [
93
117
  401,
94
118
  "The publishable key is not valid for the given project. Does the project and/or the key exist?",
@@ -114,6 +138,10 @@ const InvalidProjectForAdminAccessToken = createKnownErrorConstructor(InvalidAdm
114
138
  401,
115
139
  "Admin access token not valid for this project.",
116
140
  ], () => []);
141
+ const AdminAccessTokenIsNotAdmin = createKnownErrorConstructor(InvalidAdminAccessToken, "ADMIN_ACCESS_TOKEN_IS_NOT_ADMIN", () => [
142
+ 401,
143
+ "Admin access token does not have the required permissions to access this project.",
144
+ ], () => []);
117
145
  const ProjectAuthenticationRequired = createKnownErrorConstructor(ProjectAuthenticationError, "PROJECT_AUTHENTICATION_REQUIRED", "inherit", "inherit");
118
146
  const ClientAuthenticationRequired = createKnownErrorConstructor(ProjectAuthenticationRequired, "CLIENT_AUTHENTICATION_REQUIRED", () => [
119
147
  401,
@@ -274,6 +302,9 @@ export const KnownErrors = {
274
302
  AllOverloadsFailed,
275
303
  ProjectAuthenticationError,
276
304
  InvalidProjectAuthentication,
305
+ ProjectKeyWithoutRequestType,
306
+ InvalidRequestType,
307
+ RequestTypeWithoutProjectId,
277
308
  InvalidPublishableClientKey,
278
309
  InvalidSecretServerKey,
279
310
  InvalidSuperSecretAdminKey,
@@ -281,6 +312,7 @@ export const KnownErrors = {
281
312
  UnparsableAdminAccessToken,
282
313
  AdminAccessTokenExpired,
283
314
  InvalidProjectForAdminAccessToken,
315
+ AdminAccessTokenIsNotAdmin,
284
316
  ProjectAuthenticationRequired,
285
317
  ClientAuthenticationRequired,
286
318
  ServerAuthenticationRequired,
@@ -28,7 +28,12 @@ export function registerErrorSink(sink) {
28
28
  }
29
29
  errorSinks.add(sink);
30
30
  }
31
- registerErrorSink((location, ...args) => console.error(`Error in ${location}:`, ...args));
31
+ registerErrorSink((location, ...args) => {
32
+ console.error(`Error in ${location}:`, ...args);
33
+ if (process.env.NODE_ENV === "development") {
34
+ debugger;
35
+ }
36
+ });
32
37
  export function captureError(location, error) {
33
38
  for (const sink of errorSinks) {
34
39
  sink(location, error);
@@ -1,5 +1,6 @@
1
1
  export declare function typedToLowercase<S extends string>(s: S): Lowercase<S>;
2
2
  export declare function typedToUppercase<S extends string>(s: S): Uppercase<S>;
3
+ export declare function typedCapitalize<S extends string>(s: S): Capitalize<S>;
3
4
  /**
4
5
  * Returns all whitespace character at the start of the string.
5
6
  *
@@ -4,6 +4,9 @@ export function typedToLowercase(s) {
4
4
  export function typedToUppercase(s) {
5
5
  return s.toUpperCase();
6
6
  }
7
+ export function typedCapitalize(s) {
8
+ return s.charAt(0).toUpperCase() + s.slice(1);
9
+ }
7
10
  /**
8
11
  * Returns all whitespace character at the start of the string.
9
12
  *
@@ -0,0 +1 @@
1
+ export type IsAny<T> = 0 extends (1 & T) ? true : false;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackframe/stack-shared",
3
- "version": "2.3.6",
3
+ "version": "2.4.0",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "files": [
@@ -8,7 +8,16 @@
8
8
  "dist"
9
9
  ],
10
10
  "peerDependencies": {
11
- "react": "^18.2"
11
+ "react": "^18.2",
12
+ "yup": "^1.4.0"
13
+ },
14
+ "peerDependenciesMeta": {
15
+ "react": {
16
+ "optional": true
17
+ },
18
+ "yup": {
19
+ "optional": true
20
+ }
12
21
  },
13
22
  "dependencies": {
14
23
  "bcrypt": "^5.1.1",