@stackframe/stack-shared 2.8.12 → 2.8.17
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.
- package/CHANGELOG.md +22 -0
- package/dist/config/format.js +2 -2
- package/dist/config/schema.d.mts +32 -32
- package/dist/config/schema.d.ts +32 -32
- package/dist/config/schema.js +4 -4
- package/dist/config/schema.js.map +1 -1
- package/dist/crud.js +2 -2
- package/dist/esm/config/format.js +2 -2
- package/dist/esm/config/schema.js +4 -4
- package/dist/esm/config/schema.js.map +1 -1
- package/dist/esm/crud.js +2 -2
- package/dist/esm/helpers/password.js +1 -1
- package/dist/esm/helpers/production-mode.js +2 -2
- package/dist/esm/hooks/use-async-callback.js +1 -1
- package/dist/esm/hooks/use-async-external-store.js +1 -1
- package/dist/esm/hooks/use-hash.js +1 -1
- package/dist/esm/hooks/use-strict-memo.js +1 -1
- package/dist/esm/index.js +4 -4
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/interface/{adminInterface.js → admin-interface.js} +19 -3
- package/dist/esm/interface/admin-interface.js.map +1 -0
- package/dist/esm/interface/{clientInterface.js → client-interface.js} +74 -856
- package/dist/esm/interface/client-interface.js.map +1 -0
- package/dist/esm/interface/crud/contact-channels.js +2 -2
- package/dist/esm/interface/crud/current-user.js +4 -4
- package/dist/esm/interface/crud/email-templates.js +3 -3
- package/dist/esm/interface/crud/email-templates.js.map +1 -1
- package/dist/esm/interface/crud/emails.js +3 -3
- package/dist/esm/interface/crud/internal-api-keys.js +2 -2
- package/dist/esm/interface/crud/notification-preferences.js +20 -0
- package/dist/esm/interface/crud/notification-preferences.js.map +1 -0
- package/dist/esm/interface/crud/oauth.js +2 -2
- package/dist/esm/interface/crud/project-api-keys.js +3 -3
- package/dist/esm/interface/crud/project-permissions.js +3 -3
- package/dist/esm/interface/crud/projects.js +3 -3
- package/dist/esm/interface/crud/sessions.js +3 -3
- package/dist/esm/interface/crud/svix-token.js +2 -2
- package/dist/esm/interface/crud/team-invitation-details.js +3 -3
- package/dist/esm/interface/crud/team-invitation.js +3 -3
- package/dist/esm/interface/crud/team-member-profiles.js +4 -4
- package/dist/esm/interface/crud/team-memberships.js +2 -2
- package/dist/esm/interface/crud/team-permissions.js +3 -3
- package/dist/esm/interface/crud/teams.js +3 -3
- package/dist/esm/interface/crud/users.js +3 -3
- package/dist/esm/interface/{serverInterface.js → server-interface.js} +34 -8
- package/dist/esm/interface/server-interface.js.map +1 -0
- package/dist/esm/interface/webhooks.js +4 -4
- package/dist/esm/known-errors.js +3 -3
- package/dist/esm/schema-fields.js +11 -11
- package/dist/esm/schema-fields.js.map +1 -1
- package/dist/esm/sessions.js +2 -2
- package/dist/esm/utils/api-keys.js +3 -3
- package/dist/esm/utils/arrays.js +1 -1
- package/dist/esm/utils/bytes.js +4 -27
- package/dist/esm/utils/bytes.js.map +1 -1
- package/dist/esm/utils/caches.js +4 -4
- package/dist/esm/utils/crypto.js +3 -3
- package/dist/esm/utils/dates.js +1 -1
- package/dist/esm/utils/env.js +2 -2
- package/dist/esm/utils/errors.js +3 -3
- package/dist/esm/utils/geo.js +1 -1
- package/dist/esm/utils/hashes.js +1 -1
- package/dist/esm/utils/html.js +1 -1
- package/dist/esm/utils/http.js +1 -1
- package/dist/esm/utils/json.js +1 -1
- package/dist/esm/utils/jwt.js +4 -4
- package/dist/esm/utils/maps.js +1 -1
- package/dist/esm/utils/node-http.js +1 -1
- package/dist/esm/utils/objects.js +3 -3
- package/dist/esm/utils/promises.js +5 -5
- package/dist/esm/utils/proxies.js +1 -1
- package/dist/esm/utils/react.js +3 -3
- package/dist/esm/utils/results.js +2 -2
- package/dist/esm/utils/stores.js +4 -4
- package/dist/esm/utils/strings.js +6 -3
- package/dist/esm/utils/strings.js.map +1 -1
- package/dist/esm/utils/strings.nicify.test.js +1 -1
- package/dist/esm/utils/unicode.js +1 -1
- package/dist/esm/utils/urls.js +2 -2
- package/dist/esm/utils/uuids.js +1 -1
- package/dist/helpers/password.js +1 -1
- package/dist/helpers/production-mode.js +2 -2
- package/dist/hooks/use-async-callback.js +1 -1
- package/dist/hooks/use-async-external-store.js +1 -1
- package/dist/hooks/use-hash.js +1 -1
- package/dist/hooks/use-strict-memo.js +1 -1
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/interface/{adminInterface.d.mts → admin-interface.d.mts} +4 -2
- package/dist/interface/{adminInterface.d.ts → admin-interface.d.ts} +4 -2
- package/dist/interface/{adminInterface.js → admin-interface.js} +23 -7
- package/dist/interface/admin-interface.js.map +1 -0
- package/dist/interface/{clientInterface.d.mts → client-interface.d.mts} +8 -0
- package/dist/interface/{clientInterface.d.ts → client-interface.d.ts} +8 -0
- package/dist/interface/{clientInterface.js → client-interface.js} +87 -861
- package/dist/interface/client-interface.js.map +1 -0
- package/dist/interface/crud/contact-channels.js +2 -2
- package/dist/interface/crud/current-user.js +4 -4
- package/dist/interface/crud/email-templates.d.mts +5 -5
- package/dist/interface/crud/email-templates.d.ts +5 -5
- package/dist/interface/crud/email-templates.js +3 -3
- package/dist/interface/crud/email-templates.js.map +1 -1
- package/dist/interface/crud/emails.js +3 -3
- package/dist/interface/crud/internal-api-keys.js +2 -2
- package/dist/interface/crud/notification-preferences.d.mts +25 -0
- package/dist/interface/crud/notification-preferences.d.ts +25 -0
- package/dist/interface/crud/notification-preferences.js +45 -0
- package/dist/interface/crud/notification-preferences.js.map +1 -0
- package/dist/interface/crud/oauth.js +2 -2
- package/dist/interface/crud/project-api-keys.js +3 -3
- package/dist/interface/crud/project-permissions.js +3 -3
- package/dist/interface/crud/projects.js +3 -3
- package/dist/interface/crud/sessions.js +3 -3
- package/dist/interface/crud/svix-token.js +2 -2
- package/dist/interface/crud/team-invitation-details.js +3 -3
- package/dist/interface/crud/team-invitation.js +3 -3
- package/dist/interface/crud/team-member-profiles.js +4 -4
- package/dist/interface/crud/team-memberships.js +2 -2
- package/dist/interface/crud/team-permissions.js +3 -3
- package/dist/interface/crud/teams.js +3 -3
- package/dist/interface/crud/users.js +3 -3
- package/dist/interface/{serverInterface.d.mts → server-interface.d.mts} +4 -1
- package/dist/interface/{serverInterface.d.ts → server-interface.d.ts} +4 -1
- package/dist/interface/{serverInterface.js → server-interface.js} +38 -12
- package/dist/interface/server-interface.js.map +1 -0
- package/dist/interface/webhooks.js +4 -4
- package/dist/known-errors.js +3 -3
- package/dist/schema-fields.js +11 -11
- package/dist/schema-fields.js.map +1 -1
- package/dist/sessions.js +2 -2
- package/dist/utils/api-keys.js +3 -3
- package/dist/utils/arrays.js +1 -1
- package/dist/utils/bytes.js +4 -27
- package/dist/utils/bytes.js.map +1 -1
- package/dist/utils/caches.js +4 -4
- package/dist/utils/crypto.js +3 -3
- package/dist/utils/dates.js +1 -1
- package/dist/utils/env.js +2 -2
- package/dist/utils/errors.js +3 -3
- package/dist/utils/geo.js +1 -1
- package/dist/utils/hashes.js +1 -1
- package/dist/utils/html.js +1 -1
- package/dist/utils/http.js +1 -1
- package/dist/utils/json.js +1 -1
- package/dist/utils/jwt.js +4 -4
- package/dist/utils/maps.js +1 -1
- package/dist/utils/node-http.js +1 -1
- package/dist/utils/objects.js +3 -3
- package/dist/utils/promises.js +5 -5
- package/dist/utils/proxies.js +1 -1
- package/dist/utils/react.js +3 -3
- package/dist/utils/results.js +2 -2
- package/dist/utils/stores.js +4 -4
- package/dist/utils/strings.js +6 -3
- package/dist/utils/strings.js.map +1 -1
- package/dist/utils/strings.nicify.test.js +1 -1
- package/dist/utils/unicode.js +1 -1
- package/dist/utils/urls.js +2 -2
- package/dist/utils/uuids.js +1 -1
- package/package.json +1 -1
- package/dist/esm/interface/adminInterface.js.map +0 -1
- package/dist/esm/interface/clientInterface.js.map +0 -1
- package/dist/esm/interface/serverInterface.js.map +0 -1
- package/dist/interface/adminInterface.js.map +0 -1
- package/dist/interface/clientInterface.js.map +0 -1
- package/dist/interface/serverInterface.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/interface/server-interface.ts"],"sourcesContent":["import { KnownErrors } from \"../known-errors\";\nimport { AccessToken, InternalSession, RefreshToken } from \"../sessions\";\nimport { StackAssertionError } from \"../utils/errors\";\nimport { filterUndefined } from \"../utils/objects\";\nimport { Result } from \"../utils/results\";\nimport { urlString } from \"../utils/urls\";\nimport {\n ClientInterfaceOptions,\n StackClientInterface\n} from \"./client-interface\";\nimport { ContactChannelsCrud } from \"./crud/contact-channels\";\nimport { CurrentUserCrud } from \"./crud/current-user\";\nimport { NotificationPreferenceCrud } from \"./crud/notification-preferences\";\nimport { ConnectedAccountAccessTokenCrud } from \"./crud/oauth\";\nimport { ProjectPermissionsCrud } from \"./crud/project-permissions\";\nimport { SessionsCrud } from \"./crud/sessions\";\nimport { TeamInvitationCrud } from \"./crud/team-invitation\";\nimport { TeamMemberProfilesCrud } from \"./crud/team-member-profiles\";\nimport { TeamMembershipsCrud } from \"./crud/team-memberships\";\nimport { TeamPermissionsCrud } from \"./crud/team-permissions\";\nimport { TeamsCrud } from \"./crud/teams\";\nimport { UsersCrud } from \"./crud/users\";\n\nexport type ServerAuthApplicationOptions = (\n & ClientInterfaceOptions\n & (\n | {\n readonly secretServerKey: string,\n }\n | {\n readonly projectOwnerSession: InternalSession,\n }\n )\n);\n\nexport class StackServerInterface extends StackClientInterface {\n constructor(public override options: ServerAuthApplicationOptions) {\n super(options);\n }\n\n protected async sendServerRequest(path: string, options: RequestInit, session: InternalSession | null, requestType: \"server\" | \"admin\" = \"server\") {\n return await this.sendClientRequest(\n path,\n {\n ...options,\n headers: {\n \"x-stack-secret-server-key\": \"secretServerKey\" in this.options ? this.options.secretServerKey : \"\",\n ...options.headers,\n },\n },\n session,\n requestType,\n );\n }\n\n protected async sendServerRequestAndCatchKnownError<E extends typeof KnownErrors[keyof KnownErrors]>(\n path: string,\n requestOptions: RequestInit,\n tokenStoreOrNull: InternalSession | null,\n errorsToCatch: readonly E[],\n ): Promise<Result<\n Response & {\n usedTokens: {\n accessToken: AccessToken,\n refreshToken: RefreshToken | null,\n } | null,\n },\n InstanceType<E>\n >> {\n try {\n return Result.ok(await this.sendServerRequest(path, requestOptions, tokenStoreOrNull));\n } catch (e) {\n for (const errorType of errorsToCatch) {\n if (errorType.isInstance(e)) {\n return Result.error(e as InstanceType<E>);\n }\n }\n throw e;\n }\n }\n\n async createServerUser(data: UsersCrud['Server']['Create']): Promise<UsersCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n \"/users\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n null,\n );\n return await response.json();\n }\n\n async getServerUserByToken(session: InternalSession): Promise<CurrentUserCrud['Server']['Read'] | null> {\n const responseOrError = await this.sendServerRequestAndCatchKnownError(\n \"/users/me\",\n {},\n session,\n [KnownErrors.CannotGetOwnUserWithoutUser],\n );\n if (responseOrError.status === \"error\") {\n if (KnownErrors.CannotGetOwnUserWithoutUser.isInstance(responseOrError.error)) {\n return null;\n } else {\n throw new StackAssertionError(\"Unexpected uncaught error\", { cause: responseOrError.error });\n }\n }\n const response = responseOrError.data;\n const user: CurrentUserCrud['Server']['Read'] = await response.json();\n if (!(user as any)) throw new StackAssertionError(\"User endpoint returned null; this should never happen\");\n return user;\n }\n\n async getServerUserById(userId: string): Promise<Result<UsersCrud['Server']['Read']>> {\n const responseOrError = await this.sendServerRequestAndCatchKnownError(\n urlString`/users/${userId}`,\n {},\n null,\n [KnownErrors.UserNotFound],\n );\n if (responseOrError.status === \"error\") {\n return Result.error(responseOrError.error);\n }\n const user: UsersCrud['Server']['Read'] = await responseOrError.data.json();\n return Result.ok(user);\n }\n\n async listServerTeamInvitations(options: {\n teamId: string,\n }): Promise<TeamInvitationCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n urlString`/team-invitations?team_id=${options.teamId}`,\n {},\n null,\n );\n const result = await response.json() as TeamInvitationCrud['Server']['List'];\n return result.items;\n }\n\n async revokeServerTeamInvitation(invitationId: string, teamId: string) {\n await this.sendServerRequest(\n urlString`/team-invitations/${invitationId}?team_id=${teamId}`,\n { method: \"DELETE\" },\n null,\n );\n }\n\n async listServerTeamMemberProfiles(\n options: {\n teamId: string,\n },\n ): Promise<TeamMemberProfilesCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n urlString`/team-member-profiles?team_id=${options.teamId}`,\n {},\n null,\n );\n const result = await response.json() as TeamMemberProfilesCrud['Server']['List'];\n return result.items;\n }\n\n async getServerTeamMemberProfile(\n options: {\n teamId: string,\n userId: string,\n },\n ): Promise<TeamMemberProfilesCrud['Client']['Read']> {\n const response = await this.sendServerRequest(\n urlString`/team-member-profiles/${options.teamId}/${options.userId}`,\n {},\n null,\n );\n return await response.json();\n }\n\n async listServerTeamPermissions(\n options: {\n userId?: string,\n teamId?: string,\n recursive: boolean,\n },\n session: InternalSession | null,\n ): Promise<TeamPermissionsCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n `/team-permissions?${new URLSearchParams(filterUndefined({\n user_id: options.userId,\n team_id: options.teamId,\n recursive: options.recursive.toString(),\n }))}`,\n {},\n session,\n );\n const result = await response.json() as TeamPermissionsCrud['Server']['List'];\n return result.items;\n }\n\n async listServerProjectPermissions(\n options: {\n userId?: string,\n recursive: boolean,\n },\n session: InternalSession | null,\n ): Promise<ProjectPermissionsCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n `/project-permissions?${new URLSearchParams(filterUndefined({\n user_id: options.userId,\n recursive: options.recursive.toString(),\n }))}`,\n {},\n session,\n );\n const result = await response.json() as ProjectPermissionsCrud['Server']['List'];\n return result.items;\n }\n\n async listServerUsers(options: {\n cursor?: string,\n limit?: number,\n orderBy?: 'signedUpAt',\n desc?: boolean,\n query?: string,\n }): Promise<UsersCrud['Server']['List']> {\n const searchParams = new URLSearchParams(filterUndefined({\n cursor: options.cursor,\n limit: options.limit?.toString(),\n desc: options.desc?.toString(),\n ...options.orderBy ? {\n order_by: {\n signedUpAt: \"signed_up_at\",\n }[options.orderBy],\n } : {},\n ...options.query ? {\n query: options.query,\n } : {},\n }));\n const response = await this.sendServerRequest(\"/users?\" + searchParams.toString(), {}, null);\n return await response.json();\n }\n\n async listServerTeams(options?: {\n userId?: string,\n }): Promise<TeamsCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n `/teams?${new URLSearchParams(filterUndefined({\n user_id: options?.userId,\n }))}`,\n {},\n null\n );\n const result = await response.json() as TeamsCrud['Server']['List'];\n return result.items;\n }\n\n async getServerTeam(teamId: string): Promise<TeamsCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n `/teams/${teamId}`,\n {},\n null\n );\n return await response.json();\n }\n\n async listServerTeamUsers(teamId: string): Promise<UsersCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(`/users?team_id=${teamId}`, {}, null);\n const result = await response.json() as UsersCrud['Server']['List'];\n return result.items;\n }\n\n /* when passing a session, the user will be added to the team */\n async createServerTeam(data: TeamsCrud['Server']['Create']): Promise<TeamsCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n \"/teams\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n null\n );\n return await response.json();\n }\n\n async updateServerTeam(teamId: string, data: TeamsCrud['Server']['Update']): Promise<TeamsCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n urlString`/teams/${teamId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n null,\n );\n return await response.json();\n }\n\n async deleteServerTeam(teamId: string): Promise<void> {\n await this.sendServerRequest(\n urlString`/teams/${teamId}`,\n { method: \"DELETE\" },\n null,\n );\n }\n\n async addServerUserToTeam(options: {\n userId: string,\n teamId: string,\n }): Promise<TeamMembershipsCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n urlString`/team-memberships/${options.teamId}/${options.userId}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n return await response.json();\n }\n\n async removeServerUserFromTeam(options: {\n userId: string,\n teamId: string,\n }) {\n await this.sendServerRequest(\n urlString`/team-memberships/${options.teamId}/${options.userId}`,\n {\n method: \"DELETE\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n }\n\n async updateServerUser(userId: string, update: UsersCrud['Server']['Update']): Promise<UsersCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n urlString`/users/${userId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(update),\n },\n null,\n );\n return await response.json();\n }\n\n async createServerProviderAccessToken(\n userId: string,\n provider: string,\n scope: string,\n ): Promise<ConnectedAccountAccessTokenCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n urlString`/connected-accounts/${userId}/${provider}/access-token`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ scope }),\n },\n null,\n );\n return await response.json();\n }\n\n async createServerUserSession(userId: string, expiresInMillis: number, isImpersonation: boolean): Promise<{ accessToken: string, refreshToken: string }> {\n const response = await this.sendServerRequest(\n \"/auth/sessions\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n user_id: userId,\n expires_in_millis: expiresInMillis,\n is_impersonation: isImpersonation,\n }),\n },\n null,\n );\n const result = await response.json();\n return {\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n };\n }\n\n async leaveServerTeam(\n options: {\n teamId: string,\n userId: string,\n },\n ) {\n await this.sendClientRequest(\n urlString`/team-memberships/${options.teamId}/${options.userId}`,\n {\n method: \"DELETE\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n }\n\n async updateServerTeamMemberProfile(options: {\n teamId: string,\n userId: string,\n profile: TeamMemberProfilesCrud['Server']['Update'],\n }) {\n await this.sendServerRequest(\n urlString`/team-member-profiles/${options.teamId}/${options.userId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(options.profile),\n },\n null,\n );\n }\n\n async grantServerTeamUserPermission(teamId: string, userId: string, permissionId: string) {\n await this.sendServerRequest(\n urlString`/team-permissions/${teamId}/${userId}/${permissionId}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n }\n\n async grantServerProjectPermission(userId: string, permissionId: string) {\n await this.sendServerRequest(\n urlString`/project-permissions/${userId}/${permissionId}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n }\n\n async revokeServerTeamUserPermission(teamId: string, userId: string, permissionId: string) {\n await this.sendServerRequest(\n urlString`/team-permissions/${teamId}/${userId}/${permissionId}`,\n {\n method: \"DELETE\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n }\n\n async revokeServerProjectPermission(userId: string, permissionId: string) {\n await this.sendServerRequest(\n urlString`/project-permissions/${userId}/${permissionId}`,\n {\n method: \"DELETE\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n }\n\n async deleteServerUser(userId: string) {\n await this.sendServerRequest(\n urlString`/users/${userId}`,\n {\n method: \"DELETE\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n null,\n );\n }\n\n async createServerContactChannel(\n data: ContactChannelsCrud['Server']['Create'],\n ): Promise<ContactChannelsCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n \"/contact-channels\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n null,\n );\n return await response.json();\n }\n\n async updateServerContactChannel(\n userId: string,\n contactChannelId: string,\n data: ContactChannelsCrud['Server']['Update'],\n ): Promise<ContactChannelsCrud['Server']['Read']> {\n const response = await this.sendServerRequest(\n urlString`/contact-channels/${userId}/${contactChannelId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n null,\n );\n return await response.json();\n }\n\n async deleteServerContactChannel(\n userId: string,\n contactChannelId: string,\n ): Promise<void> {\n await this.sendServerRequest(\n urlString`/contact-channels/${userId}/${contactChannelId}`,\n {\n method: \"DELETE\",\n },\n null,\n );\n }\n\n async listServerContactChannels(\n userId: string,\n ): Promise<ContactChannelsCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n urlString`/contact-channels?user_id=${userId}`,\n {\n method: \"GET\",\n },\n null,\n );\n const json = await response.json() as ContactChannelsCrud['Server']['List'];\n return json.items;\n }\n\n async listServerNotificationCategories(\n userId: string,\n ): Promise<NotificationPreferenceCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n urlString`/emails/notification-preference/${userId}`,\n {\n method: \"GET\",\n },\n null,\n );\n const json = await response.json() as NotificationPreferenceCrud['Server']['List'];\n return json.items;\n }\n\n async setServerNotificationsEnabled(\n userId: string,\n notificationCategoryId: string,\n enabled: boolean,\n ): Promise<void> {\n await this.sendServerRequest(\n urlString`/emails/notification-preference/${userId}/${notificationCategoryId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n enabled,\n }),\n },\n null,\n );\n }\n\n async sendServerContactChannelVerificationEmail(\n userId: string,\n contactChannelId: string,\n callbackUrl: string,\n ): Promise<void> {\n await this.sendServerRequest(\n urlString`/contact-channels/${userId}/${contactChannelId}/send-verification-code`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ callback_url: callbackUrl }),\n },\n null,\n );\n }\n\n\n async listServerSessions(userId: string): Promise<SessionsCrud['Server']['Read'][]> {\n const response = await this.sendServerRequest(\n urlString`/auth/sessions?user_id=${userId}`,\n {\n method: \"GET\",\n },\n null,\n );\n return await response.json();\n }\n\n async deleteServerSession(sessionId: string) {\n await this.sendServerRequest(\n urlString`/auth/sessions/${sessionId}`,\n {\n method: \"DELETE\",\n },\n null,\n );\n }\n\n\n async sendServerTeamInvitation(options: {\n email: string,\n teamId: string,\n callbackUrl: string,\n }): Promise<void> {\n await this.sendServerRequest(\n \"/team-invitations/send-code\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n email: options.email,\n team_id: options.teamId,\n callback_url: options.callbackUrl,\n }),\n },\n null,\n );\n }\n\n async updatePassword(\n options: { oldPassword: string, newPassword: string },\n ): Promise<KnownErrors[\"PasswordConfirmationMismatch\"] | KnownErrors[\"PasswordRequirementsNotMet\"] | undefined> {\n const res = await this.sendServerRequestAndCatchKnownError(\n \"/auth/password/update\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n old_password: options.oldPassword,\n new_password: options.newPassword,\n }),\n },\n null,\n [KnownErrors.PasswordConfirmationMismatch, KnownErrors.PasswordRequirementsNotMet]\n );\n\n if (res.status === \"error\") {\n return res.error;\n }\n }\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAE5B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAC1B;AAAA,EAEE;AAAA,OACK;AA0BA,IAAM,uBAAN,cAAmC,qBAAqB;AAAA,EAC7D,YAA4B,SAAuC;AACjE,UAAM,OAAO;AADa;AAAA,EAE5B;AAAA,EAEA,MAAgB,kBAAkB,MAAc,SAAsB,SAAiC,cAAkC,UAAU;AACjJ,WAAO,MAAM,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,QACE,GAAG;AAAA,QACH,SAAS;AAAA,UACP,6BAA6B,qBAAqB,KAAK,UAAU,KAAK,QAAQ,kBAAkB;AAAA,UAChG,GAAG,QAAQ;AAAA,QACb;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA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,QAA2D;AAClF,UAAM,WAAW,MAAM,KAAK;AAAA,MAC1B,mCAAmC,MAAM;AAAA,MACzC;AAAA,QACE,QAAQ;AAAA,MACV;AAAA,MACA;AAAA,IACF;AACA,WAAO,MAAM,SAAS,KAAK;AAAA,EAC7B;AAAA,EAEA,MAAM,oBAAoB,WAAmB;AAC3C,UAAM,KAAK;AAAA,MACT,2BAA2B,SAAS;AAAA,MACpC;AAAA,QACE,QAAQ;AAAA,MACV;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAGA,MAAM,yBAAyB,SAIb;AAChB,UAAM,KAAK;AAAA,MACT;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,QAClB;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,OAAO,QAAQ;AAAA,UACf,SAAS,QAAQ;AAAA,UACjB,cAAc,QAAQ;AAAA,QACxB,CAAC;AAAA,MACH;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eACJ,SAC8G;AAC9G,UAAM,MAAM,MAAM,KAAK;AAAA,MACrB;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,QAClB;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,cAAc,QAAQ;AAAA,UACtB,cAAc,QAAQ;AAAA,QACxB,CAAC;AAAA,MACH;AAAA,MACA;AAAA,MACA,CAAC,YAAY,8BAA8B,YAAY,0BAA0B;AAAA,IACnF;AAEA,QAAI,IAAI,WAAW,SAAS;AAC1B,aAAO,IAAI;AAAA,IACb;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// src/interface/webhooks.ts
|
|
2
|
-
import { teamMembershipCreatedWebhookEvent, teamMembershipDeletedWebhookEvent } from "./crud/team-memberships";
|
|
3
|
-
import { teamPermissionCreatedWebhookEvent, teamPermissionDeletedWebhookEvent } from "./crud/team-permissions";
|
|
4
|
-
import { teamCreatedWebhookEvent, teamDeletedWebhookEvent, teamUpdatedWebhookEvent } from "./crud/teams";
|
|
5
|
-
import { userCreatedWebhookEvent, userDeletedWebhookEvent, userUpdatedWebhookEvent } from "./crud/users";
|
|
2
|
+
import { teamMembershipCreatedWebhookEvent, teamMembershipDeletedWebhookEvent } from "./crud/team-memberships.js";
|
|
3
|
+
import { teamPermissionCreatedWebhookEvent, teamPermissionDeletedWebhookEvent } from "./crud/team-permissions.js";
|
|
4
|
+
import { teamCreatedWebhookEvent, teamDeletedWebhookEvent, teamUpdatedWebhookEvent } from "./crud/teams.js";
|
|
5
|
+
import { userCreatedWebhookEvent, userDeletedWebhookEvent, userUpdatedWebhookEvent } from "./crud/users.js";
|
|
6
6
|
var webhookEvents = [
|
|
7
7
|
userCreatedWebhookEvent,
|
|
8
8
|
userUpdatedWebhookEvent,
|
package/dist/esm/known-errors.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/known-errors.tsx
|
|
2
|
-
import { StackAssertionError, StatusError, throwErr } from "./utils/errors";
|
|
3
|
-
import { identityArgs } from "./utils/functions";
|
|
4
|
-
import { deindent } from "./utils/strings";
|
|
2
|
+
import { StackAssertionError, StatusError, throwErr } from "./utils/errors.js";
|
|
3
|
+
import { identityArgs } from "./utils/functions.js";
|
|
4
|
+
import { deindent } from "./utils/strings.js";
|
|
5
5
|
var KnownError = class extends StatusError {
|
|
6
6
|
constructor(statusCode, humanReadableMessage, details) {
|
|
7
7
|
super(
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// src/schema-fields.ts
|
|
2
2
|
import * as yup from "yup";
|
|
3
|
-
import { KnownErrors } from ".";
|
|
4
|
-
import { isBase64 } from "./utils/bytes";
|
|
5
|
-
import { StackAssertionError, throwErr } from "./utils/errors";
|
|
6
|
-
import { decodeBasicAuthorizationHeader } from "./utils/http";
|
|
7
|
-
import { allProviders } from "./utils/oauth";
|
|
8
|
-
import { deepPlainClone, omit } from "./utils/objects";
|
|
9
|
-
import { isValidUrl } from "./utils/urls";
|
|
10
|
-
import { isUuid } from "./utils/uuids";
|
|
3
|
+
import { KnownErrors } from "./index.js";
|
|
4
|
+
import { isBase64 } from "./utils/bytes.js";
|
|
5
|
+
import { StackAssertionError, throwErr } from "./utils/errors.js";
|
|
6
|
+
import { decodeBasicAuthorizationHeader } from "./utils/http.js";
|
|
7
|
+
import { allProviders } from "./utils/oauth.js";
|
|
8
|
+
import { deepPlainClone, omit } from "./utils/objects.js";
|
|
9
|
+
import { isValidUrl } from "./utils/urls.js";
|
|
10
|
+
import { isUuid } from "./utils/uuids.js";
|
|
11
11
|
yup.addMethod(yup.string, "nonEmpty", function(message) {
|
|
12
12
|
return this.test(
|
|
13
13
|
"non-empty",
|
|
@@ -345,10 +345,10 @@ var basicAuthorizationHeaderSchema = yupString().test("is-basic-authorization-he
|
|
|
345
345
|
if (!value) return true;
|
|
346
346
|
return decodeBasicAuthorizationHeader(value) !== null;
|
|
347
347
|
});
|
|
348
|
-
var neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test("is-
|
|
348
|
+
var neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test("is-authorization-header", "Invalid client_id:client_secret values; did you use the correct values for the integration?", (value) => {
|
|
349
349
|
if (!value) return true;
|
|
350
|
-
const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`
|
|
351
|
-
for (const neonClientConfig of JSON.parse(process.env.
|
|
350
|
+
const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`Authz header invalid? This should've been validated by basicAuthorizationHeaderSchema: ${value}`);
|
|
351
|
+
for (const neonClientConfig of JSON.parse(process.env.STACK_INTEGRATION_CLIENTS_CONFIG || "[]")) {
|
|
352
352
|
if (clientId === neonClientConfig.client_id && clientSecret === neonClientConfig.client_secret) return true;
|
|
353
353
|
}
|
|
354
354
|
return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/schema-fields.ts"],"sourcesContent":["import * as yup from \"yup\";\nimport { KnownErrors } from \".\";\nimport { isBase64 } from \"./utils/bytes\";\nimport { StackAssertionError, throwErr } from \"./utils/errors\";\nimport { decodeBasicAuthorizationHeader } from \"./utils/http\";\nimport { allProviders } from \"./utils/oauth\";\nimport { deepPlainClone, omit } from \"./utils/objects\";\nimport { isValidUrl } from \"./utils/urls\";\nimport { isUuid } from \"./utils/uuids\";\n\ndeclare module \"yup\" {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface StringSchema<TType, TContext, TDefault, TFlags> {\n nonEmpty(message?: string): StringSchema<TType, TContext, TDefault, TFlags>,\n empty(): StringSchema<TType, TContext, TDefault, TFlags>,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Schema<TType, TContext, TDefault, TFlags> {\n getNested<K extends keyof NonNullable<TType>>(path: K): yup.Schema<NonNullable<TType>[K], TContext, TDefault, TFlags>,\n\n // the default types for concat kinda suck, so let's fix that\n concat<U extends yup.AnySchema>(schema: U): yup.Schema<Omit<NonNullable<TType>, keyof yup.InferType<U>> & yup.InferType<U> | (TType & (null | undefined)), TContext, TDefault, TFlags>,\n }\n}\n\n// eslint-disable-next-line no-restricted-syntax\nyup.addMethod(yup.string, \"nonEmpty\", function (message?: string) {\n return this.test(\n \"non-empty\",\n message ?? (({ path }) => `${path} must not be empty`),\n (value) => {\n return value !== \"\";\n }\n );\n});\n\nyup.addMethod(yup.Schema, \"getNested\", function (path: any) {\n if (!path.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) throw new StackAssertionError(`yupSchema.getNested can currently only be used with alphanumeric keys. Fix this in the future. Provided key: ${path}`);\n return yup.reach(this, path) as any;\n});\n\nexport async function yupValidate<S extends yup.ISchema<any>>(\n schema: S,\n obj: unknown,\n options?: yup.ValidateOptions & { currentUserId?: string | null }\n): Promise<yup.InferType<S>> {\n try {\n return await schema.validate(obj, {\n ...omit(options ?? {}, ['currentUserId']),\n context: {\n ...options?.context,\n stackAllowUserIdMe: options?.currentUserId !== undefined,\n },\n });\n } catch (error) {\n if (error instanceof ReplaceFieldWithOwnUserId) {\n const currentUserId = options?.currentUserId;\n if (!currentUserId) throw new KnownErrors.CannotGetOwnUserWithoutUser();\n\n // parse yup path\n let pathRemaining = error.path;\n const fieldPath = [];\n while (pathRemaining.length > 0) {\n if (pathRemaining.startsWith(\"[\")) {\n const index = pathRemaining.indexOf(\"]\");\n if (index < 0) throw new StackAssertionError(\"Invalid path\");\n fieldPath.push(JSON.parse(pathRemaining.slice(1, index)));\n pathRemaining = pathRemaining.slice(index + 1);\n } else {\n let dotIndex = pathRemaining.indexOf(\".\");\n if (dotIndex === -1) dotIndex = pathRemaining.length;\n fieldPath.push(pathRemaining.slice(0, dotIndex));\n pathRemaining = pathRemaining.slice(dotIndex + 1);\n }\n }\n\n const newObj = deepPlainClone(obj);\n let it = newObj;\n for (const field of fieldPath.slice(0, -1)) {\n if (!Object.prototype.hasOwnProperty.call(it, field)) {\n throw new StackAssertionError(`Segment ${field} of path ${error.path} not found in object`);\n }\n it = (it as any)[field];\n }\n (it as any)[fieldPath[fieldPath.length - 1]] = currentUserId;\n\n return await yupValidate(schema, newObj, options);\n }\n throw error;\n }\n}\n\nconst _idDescription = (identify: string) => `The unique identifier of the ${identify}`;\nconst _displayNameDescription = (identify: string) => `Human-readable ${identify} display name. This is not a unique identifier.`;\nconst _clientMetaDataDescription = (identify: string) => `Client metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client.`;\nconst _clientReadOnlyMetaDataDescription = (identify: string) => `Client read-only, server-writable metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client. The client can read this data, but cannot modify it. This is useful for things like subscription status.`;\nconst _profileImageUrlDescription = (identify: string) => `URL of the profile image for ${identify}. Can be a Base64 encoded image. Must be smaller than 100KB. Please compress and crop to a square before passing in.`;\nconst _serverMetaDataDescription = (identify: string) => `Server metadata. Used as a data store, only accessible from the server side. You can store secret information related to the ${identify} here.`;\nconst _atMillisDescription = (identify: string) => `(the number of milliseconds since epoch, January 1, 1970, UTC)`;\nconst _createdAtMillisDescription = (identify: string) => `The time the ${identify} was created ${_atMillisDescription(identify)}`;\nconst _signedUpAtMillisDescription = `The time the user signed up ${_atMillisDescription}`;\nconst _lastActiveAtMillisDescription = `The time the user was last active ${_atMillisDescription}`;\n\n\ndeclare const StackAdaptSentinel: unique symbol;\nexport type StackAdaptSentinel = typeof StackAdaptSentinel;\n\n// Built-in replacements\nexport function yupString<A extends string, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.string<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.string(...args);\n}\nexport function yupNumber<A extends number, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.number<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.number(...args);\n}\nexport function yupBoolean<A extends boolean, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.boolean<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.boolean(...args);\n}\n/**\n * @deprecated, use number of milliseconds since epoch instead\n */\nexport function yupDate<A extends Date, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.date<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.date(...args);\n}\nexport function yupMixed<A extends {}>(...args: Parameters<typeof yup.mixed<A>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.mixed(...args);\n}\nexport function yupArray<A extends yup.Maybe<yup.AnyObject> = yup.AnyObject, B = any>(...args: Parameters<typeof yup.array<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.array(...args);\n}\nexport function yupTuple<T extends [unknown, ...unknown[]]>(...args: Parameters<typeof yup.tuple<T>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.tuple<T>(...args);\n}\nexport function yupObject<A extends yup.Maybe<yup.AnyObject>, B extends yup.ObjectShape>(...args: Parameters<typeof yup.object<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n const object = yup.object(...args).test(\n 'no-unknown-object-properties',\n ({ path }) => `${path} contains unknown properties`,\n (value: any, context) => {\n if (context.options.context?.noUnknownPathPrefixes?.some((prefix: string) => context.path.startsWith(prefix))) {\n if (context.schema.spec.noUnknown !== false) {\n const availableKeys = new Set(Object.keys(context.schema.fields));\n const unknownKeys = Object.keys(value ?? {}).filter(key => !availableKeys.has(key));\n if (unknownKeys.length > 0) {\n // TODO \"did you mean XYZ\"\n return context.createError({\n message: `${context.path || \"Object\"} contains unknown properties: ${unknownKeys.join(', ')}`,\n path: context.path,\n params: { unknownKeys, availableKeys },\n });\n }\n }\n }\n return true;\n },\n );\n\n // we don't want to update the type of `object` to have a default flag\n return object.default(undefined) as any as typeof object;\n}\n\nexport function yupNever(): yup.MixedSchema<never> {\n return yupMixed().test('never', 'This value should never be reached', () => false) as any;\n}\n\nexport function yupUnion<T extends yup.ISchema<any>[]>(...args: T): yup.MixedSchema<yup.InferType<T[number]>> {\n if (args.length === 0) throw new Error('yupUnion must have at least one schema');\n\n const [first] = args;\n const firstDesc = first.describe();\n for (const schema of args) {\n const desc = schema.describe();\n if (desc.type !== firstDesc.type) throw new StackAssertionError(`yupUnion must have schemas of the same type (got: ${firstDesc.type} and ${desc.type})`, { first, schema, firstDesc, desc });\n }\n\n return yupMixed().test('is-one-of', 'Invalid value', async (value, context) => {\n const errors = [];\n for (const schema of args) {\n try {\n await yupValidate(schema, value, context.options);\n return true;\n } catch (e) {\n errors.push(e);\n }\n }\n return context.createError({\n message: `${context.path} is not matched by any of the provided schemas:\\n${errors.map((e: any, i) => '\\tSchema ' + i + \": \\n\\t\\t\" + e.errors.join('\\n\\t\\t')).join('\\n')}`,\n path: context.path,\n });\n });\n}\n\nexport function yupRecord<K extends yup.StringSchema, T extends yup.AnySchema>(\n keySchema: K,\n valueSchema: T,\n): yup.MixedSchema<Record<string, yup.InferType<T>>> {\n return yupObject().unknown(true).test(\n 'record',\n '${path} must be a record of valid values',\n async function (value: unknown, context: yup.TestContext) {\n if (value == null) return true;\n const { path, createError } = this as any;\n if (typeof value !== 'object') {\n return createError({ message: `${path} must be an object` });\n }\n\n // Validate each property using the provided valueSchema\n for (const key of Object.keys(value)) {\n // Validate the key\n await yupValidate(keySchema, key, context.options);\n\n // Validate the value\n try {\n await yupValidate(valueSchema, (value as Record<string, unknown>)[key], {\n ...context.options,\n context: {\n ...context.options.context,\n path: path ? `${path}.${key}` : key,\n },\n });\n } catch (e: any) {\n return createError({\n path: path ? `${path}.${key}` : key,\n message: e.message,\n });\n }\n }\n\n return true;\n },\n ) as any;\n}\n\nexport function ensureObjectSchema<T extends yup.AnyObject>(schema: yup.Schema<T>): yup.ObjectSchema<T> & typeof schema {\n if (!(schema instanceof yup.ObjectSchema)) throw new StackAssertionError(`assertObjectSchema: schema is not an ObjectSchema: ${schema.describe().type}`);\n return schema as any;\n}\n\n// Common\nexport const adaptSchema = yupMixed<StackAdaptSentinel>();\n/**\n * Yup's URL schema does not recognize some URLs (including `http://localhost`) as a valid URL. This schema is a workaround for that.\n */\nexport const urlSchema = yupString().test({\n name: 'no-spaces',\n message: (params) => `${params.path} contains spaces`,\n test: (value) => value == null || !value.includes(' ')\n}).test({\n name: 'url',\n message: (params) => `${params.path} is not a valid URL`,\n test: (value) => value == null || isValidUrl(value)\n});\nexport const jsonSchema = yupMixed().nullable().defined().transform((value) => JSON.parse(JSON.stringify(value)));\nexport const jsonStringSchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (value == null) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const jsonStringOrEmptySchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (!value) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const base64Schema = yupString().test(\"is-base64\", (params) => `${params.path} is not valid base64`, (value) => {\n if (value == null) return true;\n return isBase64(value);\n});\nexport const passwordSchema = yupString().max(70);\n\n/**\n * A stricter email schema that does some additional checks for UX input. (Some emails are allowed by the spec, for\n * example `test@localhost` or `abc@gmail`, but almost certainly a user input error.)\n *\n * Note that some users in the DB have an email that doesn't match this regex, so most of the time you should use\n * `emailSchema` instead until we do the DB migration.\n */\n// eslint-disable-next-line no-restricted-syntax\nexport const strictEmailSchema = (message: string | undefined) => yupString().email(message).matches(/^[^.]+(\\.[^.]+)*@.*\\.[^.][^.]+$/, message);\n// eslint-disable-next-line no-restricted-syntax\nexport const emailSchema = yupString().email();\n\nundefined?.test('strictEmailSchema', ({ expect }) => {\n const validEmails = [\n \"a@example.com\",\n \"abc@example.com\",\n \"a.b@example.com\",\n \"throwaway.mail+token@example.com\",\n \"email-alt-dash@demo-mail.com\",\n \"test-account@weird-domain.net\",\n \"%!~&+{}=|`#@domain.test\",\n \"admin@a.longtldexample\",\n ];\n for (const email of validEmails) {\n expect(strictEmailSchema(undefined).validateSync(email)).toBe(email);\n }\n const invalidEmails = [\n \"test@localhost\",\n \"test@gmail\",\n \"test@gmail.com.a\",\n \"test@gmail.a\",\n \"test.@example.com\",\n \"test..test@example.com\",\n \".test@example.com\",\n ];\n for (const email of invalidEmails) {\n expect(() => strictEmailSchema(undefined).validateSync(email)).toThrow();\n }\n});\n\n// Request auth\nexport const clientOrHigherAuthTypeSchema = yupString().oneOf(['client', 'server', 'admin']).defined();\nexport const serverOrHigherAuthTypeSchema = yupString().oneOf(['server', 'admin']).defined();\nexport const adminAuthTypeSchema = yupString().oneOf(['admin']).defined();\n\n// Projects\nexport const projectIdSchema = yupString().test((v) => v === undefined || v === \"internal\" || isUuid(v)).meta({ openapiField: { description: _idDescription('project'), exampleValue: 'e0b52f4d-dece-408c-af49-d23061bb0f8d' } });\nexport const projectBranchIdSchema = yupString().nonEmpty().max(255).meta({ openapiField: { description: _idDescription('project branch'), exampleValue: 'main' } });\nexport const projectDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('project'), exampleValue: 'MyMusic' } });\nexport const projectDescriptionSchema = yupString().nullable().meta({ openapiField: { description: 'A human readable description of the project', exampleValue: 'A music streaming service' } });\nexport const projectCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('project'), exampleValue: 1630000000000 } });\nexport const projectUserCountSchema = yupNumber().meta({ openapiField: { description: 'The number of users in this project', exampleValue: 10 } });\nexport const projectIsProductionModeSchema = yupBoolean().meta({ openapiField: { description: 'Whether the project is in production mode', exampleValue: true } });\n// Project config\nexport const projectConfigIdSchema = yupString().meta({ openapiField: { description: _idDescription('project config'), exampleValue: 'd09201f0-54f5-40bd-89ff-6d1815ddad24' } });\nexport const projectAllowLocalhostSchema = yupBoolean().meta({ openapiField: { description: 'Whether localhost is allowed as a domain for this project. Should only be allowed in development mode', exampleValue: true } });\nexport const projectCreateTeamOnSignUpSchema = yupBoolean().meta({ openapiField: { description: 'Whether a team should be created for each user that signs up', exampleValue: true } });\nexport const projectMagicLinkEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether magic link authentication is enabled for this project', exampleValue: true } });\nexport const projectPasskeyEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether passkey authentication is enabled for this project', exampleValue: true } });\nexport const projectClientTeamCreationEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can create teams', exampleValue: true } });\nexport const projectClientUserDeletionEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can delete their own account from the client', exampleValue: true } });\nexport const projectSignUpEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether users can sign up new accounts, or whether they are only allowed to sign in to existing accounts. Regardless of this option, the server API can always create new users with the `POST /users` endpoint.', exampleValue: true } });\nexport const projectCredentialEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether email password authentication is enabled for this project', exampleValue: true } });\n// Project OAuth config\nexport const oauthIdSchema = yupString().oneOf(allProviders).meta({ openapiField: { description: `OAuth provider ID, one of ${allProviders.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'google' } });\nexport const oauthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the OAuth provider is enabled. If an provider is first enabled, then disabled, it will be shown in the list but with enabled=false', exampleValue: true } });\nexport const oauthTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'OAuth provider type, one of shared, standard. \"shared\" uses Stack shared OAuth keys and it is only meant for development. \"standard\" uses your own OAuth keys and will show your logo and company name when signing in with the provider.', exampleValue: 'standard' } });\nexport const oauthClientIdSchema = yupString().meta({ openapiField: { description: 'OAuth client ID. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-id' } });\nexport const oauthClientSecretSchema = yupString().meta({ openapiField: { description: 'OAuth client secret. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-secret' } });\nexport const oauthFacebookConfigIdSchema = yupString().meta({ openapiField: { description: 'The configuration id for Facebook business login (for things like ads and marketing). This is only required if you are using the standard OAuth with Facebook and you are using Facebook business login.' } });\nexport const oauthMicrosoftTenantIdSchema = yupString().meta({ openapiField: { description: 'The Microsoft tenant id for Microsoft directory. This is only required if you are using the standard OAuth with Microsoft and you have an Azure AD tenant.' } });\nexport const oauthAccountMergeStrategySchema = yupString().oneOf(['link_method', 'raise_error', 'allow_duplicates']).meta({ openapiField: { description: 'Determines how to handle OAuth logins that match an existing user by email. `link_method` adds the OAuth method to the existing user. `raise_error` rejects the login with an error. `allow_duplicates` creates a new user.', exampleValue: 'link_method' } });\n// Project email config\nexport const emailTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'Email provider type, one of shared, standard. \"shared\" uses Stack shared email provider and it is only meant for development. \"standard\" uses your own email server and will have your email address as the sender.', exampleValue: 'standard' } });\nexport const emailSenderNameSchema = yupString().meta({ openapiField: { description: 'Email sender name. Needs to be specified when using type=\"standard\"', exampleValue: 'Stack' } });\nexport const emailHostSchema = yupString().meta({ openapiField: { description: 'Email host. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp.your-domain.com' } });\nexport const emailPortSchema = yupNumber().min(0).max(65535).meta({ openapiField: { description: 'Email port. Needs to be specified when using type=\"standard\"', exampleValue: 587 } });\nexport const emailUsernameSchema = yupString().meta({ openapiField: { description: 'Email username. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp-email' } });\nexport const emailSenderEmailSchema = emailSchema.meta({ openapiField: { description: 'Email sender email. Needs to be specified when using type=\"standard\"', exampleValue: 'example@your-domain.com' } });\nexport const emailPasswordSchema = passwordSchema.meta({ openapiField: { description: 'Email password. Needs to be specified when using type=\"standard\"', exampleValue: 'your-email-password' } });\n// Project domain config\nexport const handlerPathSchema = yupString().test('is-handler-path', 'Handler path must start with /', (value) => value?.startsWith('/')).meta({ openapiField: { description: 'Handler path. If you did not setup a custom handler path, it should be \"/handler\" by default. It needs to start with /', exampleValue: '/handler' } });\n\n// Users\nexport class ReplaceFieldWithOwnUserId extends Error {\n constructor(public readonly path: string) {\n super(`This error should be caught by whoever validated the schema, and the field in the path '${path}' should be replaced with the current user's id. This is a workaround to yup not providing access to the context inside the transform function.`);\n }\n}\nconst userIdMeSentinelUuid = \"cad564fd-f81b-43f4-b390-98abf3fcc17e\";\nexport const userIdOrMeSchema = yupString().uuid().transform(v => {\n if (v === \"me\") return userIdMeSentinelUuid;\n else return v;\n}).test((v, context) => {\n if (!(\"stackAllowUserIdMe\" in (context.options.context ?? {}))) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re using yupValidate from schema-fields.ts to validate, instead of schema.validate(...).');\n if (!context.options.context?.stackAllowUserIdMe) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re passing in the currentUserId option in yupValidate.');\n if (v === userIdMeSentinelUuid) throw new ReplaceFieldWithOwnUserId(context.path);\n return true;\n}).meta({ openapiField: { description: 'The ID of the user, or the special value `me` for the currently authenticated user', exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const userIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('user'), exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const primaryEmailSchema = emailSchema.meta({ openapiField: { description: 'Primary email', exampleValue: 'johndoe@example.com' } });\nexport const primaryEmailAuthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email is used for authentication. If this is set to `false`, the user will not be able to sign in with the primary email with password or OTP', exampleValue: true } });\nexport const primaryEmailVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email has been verified to belong to this user', exampleValue: true } });\nexport const userDisplayNameSchema = yupString().nullable().meta({ openapiField: { description: _displayNameDescription('user'), exampleValue: 'John Doe' } });\nexport const selectedTeamIdSchema = yupString().uuid().meta({ openapiField: { description: 'ID of the team currently selected by the user', exampleValue: 'team-id' } });\nexport const profileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('user'), exampleValue: 'https://example.com/image.jpg' } });\nexport const signedUpAtMillisSchema = yupNumber().meta({ openapiField: { description: _signedUpAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userOAuthProviderSchema = yupObject({\n id: yupString().defined(),\n type: yupString().oneOf(allProviders).defined(),\n provider_user_id: yupString().defined(),\n});\nexport const userLastActiveAtMillisSchema = yupNumber().nullable().meta({ openapiField: { description: _lastActiveAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userPasskeyAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has passkeys enabled', exampleValue: false } });\nexport const userOtpAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. ', exampleValue: true } });\nexport const userOtpAuthEnabledMutationSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. Note that only accounts with verified emails can sign-in with OTP.', exampleValue: true } });\nexport const userHasPasswordSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has a password set. If the user does not have a password set, they will not be able to sign in with email/password.', exampleValue: true } });\nexport const userPasswordMutationSchema = passwordSchema.nullable().meta({ openapiField: { description: 'Sets the user\\'s password. Doing so revokes all current sessions.', exampleValue: 'my-new-password' } }).max(70);\nexport const userPasswordHashMutationSchema = yupString()\n .nonEmpty()\n .meta({ openapiField: { description: 'If `password` is not given, sets the user\\'s password hash to the given string in Modular Crypt Format (ex.: `$2a$10$VIhIOofSMqGdGlL4wzE//e.77dAQGqNtF/1dT7bqCrVtQuInWy2qi`). Doing so revokes all current sessions.' } }); // we don't set an exampleValue here because it's exclusive with the password field and having both would break the generated example\nexport const userTotpSecretMutationSchema = base64Schema.nullable().meta({ openapiField: { description: 'Enables 2FA and sets a TOTP secret for the user. Set to null to disable 2FA.', exampleValue: 'dG90cC1zZWNyZXQ=' } });\n\n// Auth\nexport const signInEmailSchema = strictEmailSchema(undefined).meta({ openapiField: { description: 'The email to sign in with.', exampleValue: 'johndoe@example.com' } });\nexport const emailOtpSignInCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct the magic link from. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/auth/otp/sign-in` endpoint.', exampleValue: 'https://example.com/handler/magic-link-callback' } });\nexport const emailVerificationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct a verification link for the verification e-mail. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/contact-channels/verify` endpoint.', exampleValue: 'https://example.com/handler/email-verification' } });\nexport const accessTokenResponseSchema = yupString().meta({ openapiField: { description: 'Short-lived access token that can be used to authenticate the user', exampleValue: 'eyJhmMiJB2TO...diI4QT' } });\nexport const refreshTokenResponseSchema = yupString().meta({ openapiField: { description: 'Long-lived refresh token that can be used to obtain a new access token', exampleValue: 'i8ns3aq2...14y' } });\nexport const signInResponseSchema = yupObject({\n refresh_token: refreshTokenResponseSchema.defined(),\n access_token: accessTokenResponseSchema.defined(),\n is_new_user: yupBoolean().meta({ openapiField: { description: 'Whether the user is a new user', exampleValue: true } }).defined(),\n user_id: userIdSchema.defined(),\n});\n\n// Permissions\nexport const teamSystemPermissions = [\n '$update_team',\n '$delete_team',\n '$read_members',\n '$remove_members',\n '$invite_members',\n '$manage_api_keys',\n] as const;\nexport const permissionDefinitionIdSchema = yupString()\n .matches(/^\\$?[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" and optional \"$\" at the beginning are allowed')\n .test('is-system-permission', 'System permissions must start with a dollar sign', (value, ctx) => {\n if (!value) return true;\n if (value.startsWith('$') && !teamSystemPermissions.includes(value as any)) {\n return ctx.createError({ message: 'Invalid system permission' });\n }\n return true;\n })\n .meta({ openapiField: { description: `The permission ID used to uniquely identify a permission. Can either be a custom permission with lowercase letters, numbers, \\`:\\`, and \\`_\\` characters, or one of the system permissions: ${teamSystemPermissions.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'read_secret_info' } });\nexport const customPermissionDefinitionIdSchema = yupString()\n .matches(/^[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" are allowed')\n .meta({ openapiField: { description: 'The permission ID used to uniquely identify a permission. Can only contain lowercase letters, numbers, \":\", and \"_\" characters', exampleValue: 'read_secret_info' } });\nexport const teamPermissionDescriptionSchema = yupString().meta({ openapiField: { description: 'A human-readable description of the permission', exampleValue: 'Read secret information' } });\nexport const containedPermissionIdsSchema = yupArray(permissionDefinitionIdSchema.defined()).meta({ openapiField: { description: 'The IDs of the permissions that are contained in this permission', exampleValue: ['read_public_info'] } });\n\n// Teams\nexport const teamIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('team'), exampleValue: 'ad962777-8244-496a-b6a2-e0c6a449c79e' } });\nexport const teamDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team'), exampleValue: 'My Team' } });\nexport const teamProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team'), exampleValue: 'https://example.com/image.jpg' } });\nexport const teamClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('team'), exampleValue: 1630000000000 } });\nexport const teamInvitationEmailSchema = emailSchema.meta({ openapiField: { description: 'The email of the user to invite.', exampleValue: 'johndoe@example.com' } });\nexport const teamInvitationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct an invite link with. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/team-invitations/accept` endpoint.', exampleValue: 'https://example.com/handler/team-invitation' } });\nexport const teamCreatorUserIdSchema = userIdOrMeSchema.meta({ openapiField: { description: 'The ID of the creator of the team. If not specified, the user will not be added to the team. Can be either \"me\" or the ID of the user. Only used on the client side.', exampleValue: 'me' } });\n\n// Team member profiles\nexport const teamMemberDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team member') + ' Note that this is separate from the display_name of the user.', exampleValue: 'John Doe' } });\nexport const teamMemberProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team member'), exampleValue: 'https://example.com/image.jpg' } });\n\n// Contact channels\nexport const contactChannelIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('contact channel'), exampleValue: 'b3d396b8-c574-4c80-97b3-50031675ceb2' } });\nexport const contactChannelTypeSchema = yupString().oneOf(['email']).meta({ openapiField: { description: `The type of the contact channel. Currently only \"email\" is supported.`, exampleValue: 'email' } });\nexport const contactChannelValueSchema = yupString().when('type', {\n is: 'email',\n then: (schema) => schema.email(),\n}).meta({ openapiField: { description: 'The value of the contact channel. For email, this should be a valid email address.', exampleValue: 'johndoe@example.com' } });\nexport const contactChannelUsedForAuthSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is used for authentication. If this is set to `true`, the user will be able to sign in with the contact channel with password or OTP.', exampleValue: true } });\nexport const contactChannelIsVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel has been verified. If this is set to `true`, the contact channel has been verified to belong to the user.', exampleValue: true } });\nexport const contactChannelIsPrimarySchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is the primary contact channel. If this is set to `true`, it will be used for authentication and notifications by default.', exampleValue: true } });\n\n// Headers\nexport const basicAuthorizationHeaderSchema = yupString().test('is-basic-authorization-header', 'Authorization header must be in the format \"Basic <base64>\"', (value) => {\n if (!value) return true;\n return decodeBasicAuthorizationHeader(value) !== null;\n});\n\n// Neon integration\nexport const neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test('is-neon-authorization-header', 'Invalid client_id:client_secret values; did you use the correct values for the Neon integration?', (value) => {\n if (!value) return true;\n const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`Neon authz header invalid? This should've been validated by basicAuthorizationHeaderSchema: ${value}`);\n for (const neonClientConfig of JSON.parse(process.env.STACK_NEON_INTEGRATION_CLIENTS_CONFIG || '[]')) {\n if (clientId === neonClientConfig.client_id && clientSecret === neonClientConfig.client_secret) return true;\n }\n return false;\n});\n\n// Utils\nexport function yupDefinedWhen<S extends yup.AnyObject>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n\nexport function yupDefinedAndNonEmptyWhen<S extends yup.StringSchema>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined().nonEmpty(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n"],"mappings":";AAAA,YAAY,SAAS;AACrB,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,qBAAqB,gBAAgB;AAC9C,SAAS,sCAAsC;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,YAAY;AACrC,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AAmBnB,cAAc,YAAQ,YAAY,SAAU,SAAkB;AAChE,SAAO,KAAK;AAAA,IACV;AAAA,IACA,YAAY,CAAC,EAAE,KAAK,MAAM,GAAG,IAAI;AAAA,IACjC,CAAC,UAAU;AACT,aAAO,UAAU;AAAA,IACnB;AAAA,EACF;AACF,CAAC;AAEG,cAAc,YAAQ,aAAa,SAAU,MAAW;AAC1D,MAAI,CAAC,KAAK,MAAM,0BAA0B,EAAG,OAAM,IAAI,oBAAoB,gHAAgH,IAAI,EAAE;AACjM,SAAW,UAAM,MAAM,IAAI;AAC7B,CAAC;AAED,eAAsB,YACpB,QACA,KACA,SAC2B;AAC3B,MAAI;AACF,WAAO,MAAM,OAAO,SAAS,KAAK;AAAA,MAChC,GAAG,KAAK,WAAW,CAAC,GAAG,CAAC,eAAe,CAAC;AAAA,MACxC,SAAS;AAAA,QACP,GAAG,SAAS;AAAA,QACZ,oBAAoB,SAAS,kBAAkB;AAAA,MACjD;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QAAI,iBAAiB,2BAA2B;AAC9C,YAAM,gBAAgB,SAAS;AAC/B,UAAI,CAAC,cAAe,OAAM,IAAI,YAAY,4BAA4B;AAGtE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fields.ts"],"sourcesContent":["import * as yup from \"yup\";\nimport { KnownErrors } from \".\";\nimport { isBase64 } from \"./utils/bytes\";\nimport { StackAssertionError, throwErr } from \"./utils/errors\";\nimport { decodeBasicAuthorizationHeader } from \"./utils/http\";\nimport { allProviders } from \"./utils/oauth\";\nimport { deepPlainClone, omit } from \"./utils/objects\";\nimport { isValidUrl } from \"./utils/urls\";\nimport { isUuid } from \"./utils/uuids\";\n\ndeclare module \"yup\" {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface StringSchema<TType, TContext, TDefault, TFlags> {\n nonEmpty(message?: string): StringSchema<TType, TContext, TDefault, TFlags>,\n empty(): StringSchema<TType, TContext, TDefault, TFlags>,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Schema<TType, TContext, TDefault, TFlags> {\n getNested<K extends keyof NonNullable<TType>>(path: K): yup.Schema<NonNullable<TType>[K], TContext, TDefault, TFlags>,\n\n // the default types for concat kinda suck, so let's fix that\n concat<U extends yup.AnySchema>(schema: U): yup.Schema<Omit<NonNullable<TType>, keyof yup.InferType<U>> & yup.InferType<U> | (TType & (null | undefined)), TContext, TDefault, TFlags>,\n }\n}\n\n// eslint-disable-next-line no-restricted-syntax\nyup.addMethod(yup.string, \"nonEmpty\", function (message?: string) {\n return this.test(\n \"non-empty\",\n message ?? (({ path }) => `${path} must not be empty`),\n (value) => {\n return value !== \"\";\n }\n );\n});\n\nyup.addMethod(yup.Schema, \"getNested\", function (path: any) {\n if (!path.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) throw new StackAssertionError(`yupSchema.getNested can currently only be used with alphanumeric keys. Fix this in the future. Provided key: ${path}`);\n return yup.reach(this, path) as any;\n});\n\nexport async function yupValidate<S extends yup.ISchema<any>>(\n schema: S,\n obj: unknown,\n options?: yup.ValidateOptions & { currentUserId?: string | null }\n): Promise<yup.InferType<S>> {\n try {\n return await schema.validate(obj, {\n ...omit(options ?? {}, ['currentUserId']),\n context: {\n ...options?.context,\n stackAllowUserIdMe: options?.currentUserId !== undefined,\n },\n });\n } catch (error) {\n if (error instanceof ReplaceFieldWithOwnUserId) {\n const currentUserId = options?.currentUserId;\n if (!currentUserId) throw new KnownErrors.CannotGetOwnUserWithoutUser();\n\n // parse yup path\n let pathRemaining = error.path;\n const fieldPath = [];\n while (pathRemaining.length > 0) {\n if (pathRemaining.startsWith(\"[\")) {\n const index = pathRemaining.indexOf(\"]\");\n if (index < 0) throw new StackAssertionError(\"Invalid path\");\n fieldPath.push(JSON.parse(pathRemaining.slice(1, index)));\n pathRemaining = pathRemaining.slice(index + 1);\n } else {\n let dotIndex = pathRemaining.indexOf(\".\");\n if (dotIndex === -1) dotIndex = pathRemaining.length;\n fieldPath.push(pathRemaining.slice(0, dotIndex));\n pathRemaining = pathRemaining.slice(dotIndex + 1);\n }\n }\n\n const newObj = deepPlainClone(obj);\n let it = newObj;\n for (const field of fieldPath.slice(0, -1)) {\n if (!Object.prototype.hasOwnProperty.call(it, field)) {\n throw new StackAssertionError(`Segment ${field} of path ${error.path} not found in object`);\n }\n it = (it as any)[field];\n }\n (it as any)[fieldPath[fieldPath.length - 1]] = currentUserId;\n\n return await yupValidate(schema, newObj, options);\n }\n throw error;\n }\n}\n\nconst _idDescription = (identify: string) => `The unique identifier of the ${identify}`;\nconst _displayNameDescription = (identify: string) => `Human-readable ${identify} display name. This is not a unique identifier.`;\nconst _clientMetaDataDescription = (identify: string) => `Client metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client.`;\nconst _clientReadOnlyMetaDataDescription = (identify: string) => `Client read-only, server-writable metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client. The client can read this data, but cannot modify it. This is useful for things like subscription status.`;\nconst _profileImageUrlDescription = (identify: string) => `URL of the profile image for ${identify}. Can be a Base64 encoded image. Must be smaller than 100KB. Please compress and crop to a square before passing in.`;\nconst _serverMetaDataDescription = (identify: string) => `Server metadata. Used as a data store, only accessible from the server side. You can store secret information related to the ${identify} here.`;\nconst _atMillisDescription = (identify: string) => `(the number of milliseconds since epoch, January 1, 1970, UTC)`;\nconst _createdAtMillisDescription = (identify: string) => `The time the ${identify} was created ${_atMillisDescription(identify)}`;\nconst _signedUpAtMillisDescription = `The time the user signed up ${_atMillisDescription}`;\nconst _lastActiveAtMillisDescription = `The time the user was last active ${_atMillisDescription}`;\n\n\ndeclare const StackAdaptSentinel: unique symbol;\nexport type StackAdaptSentinel = typeof StackAdaptSentinel;\n\n// Built-in replacements\nexport function yupString<A extends string, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.string<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.string(...args);\n}\nexport function yupNumber<A extends number, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.number<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.number(...args);\n}\nexport function yupBoolean<A extends boolean, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.boolean<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.boolean(...args);\n}\n/**\n * @deprecated, use number of milliseconds since epoch instead\n */\nexport function yupDate<A extends Date, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.date<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.date(...args);\n}\nexport function yupMixed<A extends {}>(...args: Parameters<typeof yup.mixed<A>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.mixed(...args);\n}\nexport function yupArray<A extends yup.Maybe<yup.AnyObject> = yup.AnyObject, B = any>(...args: Parameters<typeof yup.array<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.array(...args);\n}\nexport function yupTuple<T extends [unknown, ...unknown[]]>(...args: Parameters<typeof yup.tuple<T>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.tuple<T>(...args);\n}\nexport function yupObject<A extends yup.Maybe<yup.AnyObject>, B extends yup.ObjectShape>(...args: Parameters<typeof yup.object<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n const object = yup.object(...args).test(\n 'no-unknown-object-properties',\n ({ path }) => `${path} contains unknown properties`,\n (value: any, context) => {\n if (context.options.context?.noUnknownPathPrefixes?.some((prefix: string) => context.path.startsWith(prefix))) {\n if (context.schema.spec.noUnknown !== false) {\n const availableKeys = new Set(Object.keys(context.schema.fields));\n const unknownKeys = Object.keys(value ?? {}).filter(key => !availableKeys.has(key));\n if (unknownKeys.length > 0) {\n // TODO \"did you mean XYZ\"\n return context.createError({\n message: `${context.path || \"Object\"} contains unknown properties: ${unknownKeys.join(', ')}`,\n path: context.path,\n params: { unknownKeys, availableKeys },\n });\n }\n }\n }\n return true;\n },\n );\n\n // we don't want to update the type of `object` to have a default flag\n return object.default(undefined) as any as typeof object;\n}\n\nexport function yupNever(): yup.MixedSchema<never> {\n return yupMixed().test('never', 'This value should never be reached', () => false) as any;\n}\n\nexport function yupUnion<T extends yup.ISchema<any>[]>(...args: T): yup.MixedSchema<yup.InferType<T[number]>> {\n if (args.length === 0) throw new Error('yupUnion must have at least one schema');\n\n const [first] = args;\n const firstDesc = first.describe();\n for (const schema of args) {\n const desc = schema.describe();\n if (desc.type !== firstDesc.type) throw new StackAssertionError(`yupUnion must have schemas of the same type (got: ${firstDesc.type} and ${desc.type})`, { first, schema, firstDesc, desc });\n }\n\n return yupMixed().test('is-one-of', 'Invalid value', async (value, context) => {\n const errors = [];\n for (const schema of args) {\n try {\n await yupValidate(schema, value, context.options);\n return true;\n } catch (e) {\n errors.push(e);\n }\n }\n return context.createError({\n message: `${context.path} is not matched by any of the provided schemas:\\n${errors.map((e: any, i) => '\\tSchema ' + i + \": \\n\\t\\t\" + e.errors.join('\\n\\t\\t')).join('\\n')}`,\n path: context.path,\n });\n });\n}\n\nexport function yupRecord<K extends yup.StringSchema, T extends yup.AnySchema>(\n keySchema: K,\n valueSchema: T,\n): yup.MixedSchema<Record<string, yup.InferType<T>>> {\n return yupObject().unknown(true).test(\n 'record',\n '${path} must be a record of valid values',\n async function (value: unknown, context: yup.TestContext) {\n if (value == null) return true;\n const { path, createError } = this as any;\n if (typeof value !== 'object') {\n return createError({ message: `${path} must be an object` });\n }\n\n // Validate each property using the provided valueSchema\n for (const key of Object.keys(value)) {\n // Validate the key\n await yupValidate(keySchema, key, context.options);\n\n // Validate the value\n try {\n await yupValidate(valueSchema, (value as Record<string, unknown>)[key], {\n ...context.options,\n context: {\n ...context.options.context,\n path: path ? `${path}.${key}` : key,\n },\n });\n } catch (e: any) {\n return createError({\n path: path ? `${path}.${key}` : key,\n message: e.message,\n });\n }\n }\n\n return true;\n },\n ) as any;\n}\n\nexport function ensureObjectSchema<T extends yup.AnyObject>(schema: yup.Schema<T>): yup.ObjectSchema<T> & typeof schema {\n if (!(schema instanceof yup.ObjectSchema)) throw new StackAssertionError(`assertObjectSchema: schema is not an ObjectSchema: ${schema.describe().type}`);\n return schema as any;\n}\n\n// Common\nexport const adaptSchema = yupMixed<StackAdaptSentinel>();\n/**\n * Yup's URL schema does not recognize some URLs (including `http://localhost`) as a valid URL. This schema is a workaround for that.\n */\nexport const urlSchema = yupString().test({\n name: 'no-spaces',\n message: (params) => `${params.path} contains spaces`,\n test: (value) => value == null || !value.includes(' ')\n}).test({\n name: 'url',\n message: (params) => `${params.path} is not a valid URL`,\n test: (value) => value == null || isValidUrl(value)\n});\nexport const jsonSchema = yupMixed().nullable().defined().transform((value) => JSON.parse(JSON.stringify(value)));\nexport const jsonStringSchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (value == null) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const jsonStringOrEmptySchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (!value) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const base64Schema = yupString().test(\"is-base64\", (params) => `${params.path} is not valid base64`, (value) => {\n if (value == null) return true;\n return isBase64(value);\n});\nexport const passwordSchema = yupString().max(70);\n\n/**\n * A stricter email schema that does some additional checks for UX input. (Some emails are allowed by the spec, for\n * example `test@localhost` or `abc@gmail`, but almost certainly a user input error.)\n *\n * Note that some users in the DB have an email that doesn't match this regex, so most of the time you should use\n * `emailSchema` instead until we do the DB migration.\n */\n// eslint-disable-next-line no-restricted-syntax\nexport const strictEmailSchema = (message: string | undefined) => yupString().email(message).matches(/^[^.]+(\\.[^.]+)*@.*\\.[^.][^.]+$/, message);\n// eslint-disable-next-line no-restricted-syntax\nexport const emailSchema = yupString().email();\n\nundefined?.test('strictEmailSchema', ({ expect }) => {\n const validEmails = [\n \"a@example.com\",\n \"abc@example.com\",\n \"a.b@example.com\",\n \"throwaway.mail+token@example.com\",\n \"email-alt-dash@demo-mail.com\",\n \"test-account@weird-domain.net\",\n \"%!~&+{}=|`#@domain.test\",\n \"admin@a.longtldexample\",\n ];\n for (const email of validEmails) {\n expect(strictEmailSchema(undefined).validateSync(email)).toBe(email);\n }\n const invalidEmails = [\n \"test@localhost\",\n \"test@gmail\",\n \"test@gmail.com.a\",\n \"test@gmail.a\",\n \"test.@example.com\",\n \"test..test@example.com\",\n \".test@example.com\",\n ];\n for (const email of invalidEmails) {\n expect(() => strictEmailSchema(undefined).validateSync(email)).toThrow();\n }\n});\n\n// Request auth\nexport const clientOrHigherAuthTypeSchema = yupString().oneOf(['client', 'server', 'admin']).defined();\nexport const serverOrHigherAuthTypeSchema = yupString().oneOf(['server', 'admin']).defined();\nexport const adminAuthTypeSchema = yupString().oneOf(['admin']).defined();\n\n// Projects\nexport const projectIdSchema = yupString().test((v) => v === undefined || v === \"internal\" || isUuid(v)).meta({ openapiField: { description: _idDescription('project'), exampleValue: 'e0b52f4d-dece-408c-af49-d23061bb0f8d' } });\nexport const projectBranchIdSchema = yupString().nonEmpty().max(255).meta({ openapiField: { description: _idDescription('project branch'), exampleValue: 'main' } });\nexport const projectDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('project'), exampleValue: 'MyMusic' } });\nexport const projectDescriptionSchema = yupString().nullable().meta({ openapiField: { description: 'A human readable description of the project', exampleValue: 'A music streaming service' } });\nexport const projectCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('project'), exampleValue: 1630000000000 } });\nexport const projectUserCountSchema = yupNumber().meta({ openapiField: { description: 'The number of users in this project', exampleValue: 10 } });\nexport const projectIsProductionModeSchema = yupBoolean().meta({ openapiField: { description: 'Whether the project is in production mode', exampleValue: true } });\n// Project config\nexport const projectConfigIdSchema = yupString().meta({ openapiField: { description: _idDescription('project config'), exampleValue: 'd09201f0-54f5-40bd-89ff-6d1815ddad24' } });\nexport const projectAllowLocalhostSchema = yupBoolean().meta({ openapiField: { description: 'Whether localhost is allowed as a domain for this project. Should only be allowed in development mode', exampleValue: true } });\nexport const projectCreateTeamOnSignUpSchema = yupBoolean().meta({ openapiField: { description: 'Whether a team should be created for each user that signs up', exampleValue: true } });\nexport const projectMagicLinkEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether magic link authentication is enabled for this project', exampleValue: true } });\nexport const projectPasskeyEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether passkey authentication is enabled for this project', exampleValue: true } });\nexport const projectClientTeamCreationEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can create teams', exampleValue: true } });\nexport const projectClientUserDeletionEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can delete their own account from the client', exampleValue: true } });\nexport const projectSignUpEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether users can sign up new accounts, or whether they are only allowed to sign in to existing accounts. Regardless of this option, the server API can always create new users with the `POST /users` endpoint.', exampleValue: true } });\nexport const projectCredentialEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether email password authentication is enabled for this project', exampleValue: true } });\n// Project OAuth config\nexport const oauthIdSchema = yupString().oneOf(allProviders).meta({ openapiField: { description: `OAuth provider ID, one of ${allProviders.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'google' } });\nexport const oauthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the OAuth provider is enabled. If an provider is first enabled, then disabled, it will be shown in the list but with enabled=false', exampleValue: true } });\nexport const oauthTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'OAuth provider type, one of shared, standard. \"shared\" uses Stack shared OAuth keys and it is only meant for development. \"standard\" uses your own OAuth keys and will show your logo and company name when signing in with the provider.', exampleValue: 'standard' } });\nexport const oauthClientIdSchema = yupString().meta({ openapiField: { description: 'OAuth client ID. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-id' } });\nexport const oauthClientSecretSchema = yupString().meta({ openapiField: { description: 'OAuth client secret. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-secret' } });\nexport const oauthFacebookConfigIdSchema = yupString().meta({ openapiField: { description: 'The configuration id for Facebook business login (for things like ads and marketing). This is only required if you are using the standard OAuth with Facebook and you are using Facebook business login.' } });\nexport const oauthMicrosoftTenantIdSchema = yupString().meta({ openapiField: { description: 'The Microsoft tenant id for Microsoft directory. This is only required if you are using the standard OAuth with Microsoft and you have an Azure AD tenant.' } });\nexport const oauthAccountMergeStrategySchema = yupString().oneOf(['link_method', 'raise_error', 'allow_duplicates']).meta({ openapiField: { description: 'Determines how to handle OAuth logins that match an existing user by email. `link_method` adds the OAuth method to the existing user. `raise_error` rejects the login with an error. `allow_duplicates` creates a new user.', exampleValue: 'link_method' } });\n// Project email config\nexport const emailTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'Email provider type, one of shared, standard. \"shared\" uses Stack shared email provider and it is only meant for development. \"standard\" uses your own email server and will have your email address as the sender.', exampleValue: 'standard' } });\nexport const emailSenderNameSchema = yupString().meta({ openapiField: { description: 'Email sender name. Needs to be specified when using type=\"standard\"', exampleValue: 'Stack' } });\nexport const emailHostSchema = yupString().meta({ openapiField: { description: 'Email host. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp.your-domain.com' } });\nexport const emailPortSchema = yupNumber().min(0).max(65535).meta({ openapiField: { description: 'Email port. Needs to be specified when using type=\"standard\"', exampleValue: 587 } });\nexport const emailUsernameSchema = yupString().meta({ openapiField: { description: 'Email username. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp-email' } });\nexport const emailSenderEmailSchema = emailSchema.meta({ openapiField: { description: 'Email sender email. Needs to be specified when using type=\"standard\"', exampleValue: 'example@your-domain.com' } });\nexport const emailPasswordSchema = passwordSchema.meta({ openapiField: { description: 'Email password. Needs to be specified when using type=\"standard\"', exampleValue: 'your-email-password' } });\n// Project domain config\nexport const handlerPathSchema = yupString().test('is-handler-path', 'Handler path must start with /', (value) => value?.startsWith('/')).meta({ openapiField: { description: 'Handler path. If you did not setup a custom handler path, it should be \"/handler\" by default. It needs to start with /', exampleValue: '/handler' } });\n\n// Users\nexport class ReplaceFieldWithOwnUserId extends Error {\n constructor(public readonly path: string) {\n super(`This error should be caught by whoever validated the schema, and the field in the path '${path}' should be replaced with the current user's id. This is a workaround to yup not providing access to the context inside the transform function.`);\n }\n}\nconst userIdMeSentinelUuid = \"cad564fd-f81b-43f4-b390-98abf3fcc17e\";\nexport const userIdOrMeSchema = yupString().uuid().transform(v => {\n if (v === \"me\") return userIdMeSentinelUuid;\n else return v;\n}).test((v, context) => {\n if (!(\"stackAllowUserIdMe\" in (context.options.context ?? {}))) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re using yupValidate from schema-fields.ts to validate, instead of schema.validate(...).');\n if (!context.options.context?.stackAllowUserIdMe) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re passing in the currentUserId option in yupValidate.');\n if (v === userIdMeSentinelUuid) throw new ReplaceFieldWithOwnUserId(context.path);\n return true;\n}).meta({ openapiField: { description: 'The ID of the user, or the special value `me` for the currently authenticated user', exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const userIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('user'), exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const primaryEmailSchema = emailSchema.meta({ openapiField: { description: 'Primary email', exampleValue: 'johndoe@example.com' } });\nexport const primaryEmailAuthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email is used for authentication. If this is set to `false`, the user will not be able to sign in with the primary email with password or OTP', exampleValue: true } });\nexport const primaryEmailVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email has been verified to belong to this user', exampleValue: true } });\nexport const userDisplayNameSchema = yupString().nullable().meta({ openapiField: { description: _displayNameDescription('user'), exampleValue: 'John Doe' } });\nexport const selectedTeamIdSchema = yupString().uuid().meta({ openapiField: { description: 'ID of the team currently selected by the user', exampleValue: 'team-id' } });\nexport const profileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('user'), exampleValue: 'https://example.com/image.jpg' } });\nexport const signedUpAtMillisSchema = yupNumber().meta({ openapiField: { description: _signedUpAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userOAuthProviderSchema = yupObject({\n id: yupString().defined(),\n type: yupString().oneOf(allProviders).defined(),\n provider_user_id: yupString().defined(),\n});\nexport const userLastActiveAtMillisSchema = yupNumber().nullable().meta({ openapiField: { description: _lastActiveAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userPasskeyAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has passkeys enabled', exampleValue: false } });\nexport const userOtpAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. ', exampleValue: true } });\nexport const userOtpAuthEnabledMutationSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. Note that only accounts with verified emails can sign-in with OTP.', exampleValue: true } });\nexport const userHasPasswordSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has a password set. If the user does not have a password set, they will not be able to sign in with email/password.', exampleValue: true } });\nexport const userPasswordMutationSchema = passwordSchema.nullable().meta({ openapiField: { description: 'Sets the user\\'s password. Doing so revokes all current sessions.', exampleValue: 'my-new-password' } }).max(70);\nexport const userPasswordHashMutationSchema = yupString()\n .nonEmpty()\n .meta({ openapiField: { description: 'If `password` is not given, sets the user\\'s password hash to the given string in Modular Crypt Format (ex.: `$2a$10$VIhIOofSMqGdGlL4wzE//e.77dAQGqNtF/1dT7bqCrVtQuInWy2qi`). Doing so revokes all current sessions.' } }); // we don't set an exampleValue here because it's exclusive with the password field and having both would break the generated example\nexport const userTotpSecretMutationSchema = base64Schema.nullable().meta({ openapiField: { description: 'Enables 2FA and sets a TOTP secret for the user. Set to null to disable 2FA.', exampleValue: 'dG90cC1zZWNyZXQ=' } });\n\n// Auth\nexport const signInEmailSchema = strictEmailSchema(undefined).meta({ openapiField: { description: 'The email to sign in with.', exampleValue: 'johndoe@example.com' } });\nexport const emailOtpSignInCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct the magic link from. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/auth/otp/sign-in` endpoint.', exampleValue: 'https://example.com/handler/magic-link-callback' } });\nexport const emailVerificationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct a verification link for the verification e-mail. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/contact-channels/verify` endpoint.', exampleValue: 'https://example.com/handler/email-verification' } });\nexport const accessTokenResponseSchema = yupString().meta({ openapiField: { description: 'Short-lived access token that can be used to authenticate the user', exampleValue: 'eyJhmMiJB2TO...diI4QT' } });\nexport const refreshTokenResponseSchema = yupString().meta({ openapiField: { description: 'Long-lived refresh token that can be used to obtain a new access token', exampleValue: 'i8ns3aq2...14y' } });\nexport const signInResponseSchema = yupObject({\n refresh_token: refreshTokenResponseSchema.defined(),\n access_token: accessTokenResponseSchema.defined(),\n is_new_user: yupBoolean().meta({ openapiField: { description: 'Whether the user is a new user', exampleValue: true } }).defined(),\n user_id: userIdSchema.defined(),\n});\n\n// Permissions\nexport const teamSystemPermissions = [\n '$update_team',\n '$delete_team',\n '$read_members',\n '$remove_members',\n '$invite_members',\n '$manage_api_keys',\n] as const;\nexport const permissionDefinitionIdSchema = yupString()\n .matches(/^\\$?[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" and optional \"$\" at the beginning are allowed')\n .test('is-system-permission', 'System permissions must start with a dollar sign', (value, ctx) => {\n if (!value) return true;\n if (value.startsWith('$') && !teamSystemPermissions.includes(value as any)) {\n return ctx.createError({ message: 'Invalid system permission' });\n }\n return true;\n })\n .meta({ openapiField: { description: `The permission ID used to uniquely identify a permission. Can either be a custom permission with lowercase letters, numbers, \\`:\\`, and \\`_\\` characters, or one of the system permissions: ${teamSystemPermissions.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'read_secret_info' } });\nexport const customPermissionDefinitionIdSchema = yupString()\n .matches(/^[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" are allowed')\n .meta({ openapiField: { description: 'The permission ID used to uniquely identify a permission. Can only contain lowercase letters, numbers, \":\", and \"_\" characters', exampleValue: 'read_secret_info' } });\nexport const teamPermissionDescriptionSchema = yupString().meta({ openapiField: { description: 'A human-readable description of the permission', exampleValue: 'Read secret information' } });\nexport const containedPermissionIdsSchema = yupArray(permissionDefinitionIdSchema.defined()).meta({ openapiField: { description: 'The IDs of the permissions that are contained in this permission', exampleValue: ['read_public_info'] } });\n\n// Teams\nexport const teamIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('team'), exampleValue: 'ad962777-8244-496a-b6a2-e0c6a449c79e' } });\nexport const teamDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team'), exampleValue: 'My Team' } });\nexport const teamProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team'), exampleValue: 'https://example.com/image.jpg' } });\nexport const teamClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('team'), exampleValue: 1630000000000 } });\nexport const teamInvitationEmailSchema = emailSchema.meta({ openapiField: { description: 'The email of the user to invite.', exampleValue: 'johndoe@example.com' } });\nexport const teamInvitationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct an invite link with. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/team-invitations/accept` endpoint.', exampleValue: 'https://example.com/handler/team-invitation' } });\nexport const teamCreatorUserIdSchema = userIdOrMeSchema.meta({ openapiField: { description: 'The ID of the creator of the team. If not specified, the user will not be added to the team. Can be either \"me\" or the ID of the user. Only used on the client side.', exampleValue: 'me' } });\n\n// Team member profiles\nexport const teamMemberDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team member') + ' Note that this is separate from the display_name of the user.', exampleValue: 'John Doe' } });\nexport const teamMemberProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team member'), exampleValue: 'https://example.com/image.jpg' } });\n\n// Contact channels\nexport const contactChannelIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('contact channel'), exampleValue: 'b3d396b8-c574-4c80-97b3-50031675ceb2' } });\nexport const contactChannelTypeSchema = yupString().oneOf(['email']).meta({ openapiField: { description: `The type of the contact channel. Currently only \"email\" is supported.`, exampleValue: 'email' } });\nexport const contactChannelValueSchema = yupString().when('type', {\n is: 'email',\n then: (schema) => schema.email(),\n}).meta({ openapiField: { description: 'The value of the contact channel. For email, this should be a valid email address.', exampleValue: 'johndoe@example.com' } });\nexport const contactChannelUsedForAuthSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is used for authentication. If this is set to `true`, the user will be able to sign in with the contact channel with password or OTP.', exampleValue: true } });\nexport const contactChannelIsVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel has been verified. If this is set to `true`, the contact channel has been verified to belong to the user.', exampleValue: true } });\nexport const contactChannelIsPrimarySchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is the primary contact channel. If this is set to `true`, it will be used for authentication and notifications by default.', exampleValue: true } });\n\n// Headers\nexport const basicAuthorizationHeaderSchema = yupString().test('is-basic-authorization-header', 'Authorization header must be in the format \"Basic <base64>\"', (value) => {\n if (!value) return true;\n return decodeBasicAuthorizationHeader(value) !== null;\n});\n\n// Neon integration\nexport const neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test('is-authorization-header', 'Invalid client_id:client_secret values; did you use the correct values for the integration?', (value) => {\n if (!value) return true;\n const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`Authz header invalid? This should've been validated by basicAuthorizationHeaderSchema: ${value}`);\n for (const neonClientConfig of JSON.parse(process.env.STACK_INTEGRATION_CLIENTS_CONFIG || '[]')) {\n if (clientId === neonClientConfig.client_id && clientSecret === neonClientConfig.client_secret) return true;\n }\n return false;\n});\n\n// Utils\nexport function yupDefinedWhen<S extends yup.AnyObject>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n\nexport function yupDefinedAndNonEmptyWhen<S extends yup.StringSchema>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined().nonEmpty(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n"],"mappings":";AAAA,YAAY,SAAS;AACrB,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,qBAAqB,gBAAgB;AAC9C,SAAS,sCAAsC;AAC/C,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,YAAY;AACrC,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AAmBnB,cAAc,YAAQ,YAAY,SAAU,SAAkB;AAChE,SAAO,KAAK;AAAA,IACV;AAAA,IACA,YAAY,CAAC,EAAE,KAAK,MAAM,GAAG,IAAI;AAAA,IACjC,CAAC,UAAU;AACT,aAAO,UAAU;AAAA,IACnB;AAAA,EACF;AACF,CAAC;AAEG,cAAc,YAAQ,aAAa,SAAU,MAAW;AAC1D,MAAI,CAAC,KAAK,MAAM,0BAA0B,EAAG,OAAM,IAAI,oBAAoB,gHAAgH,IAAI,EAAE;AACjM,SAAW,UAAM,MAAM,IAAI;AAC7B,CAAC;AAED,eAAsB,YACpB,QACA,KACA,SAC2B;AAC3B,MAAI;AACF,WAAO,MAAM,OAAO,SAAS,KAAK;AAAA,MAChC,GAAG,KAAK,WAAW,CAAC,GAAG,CAAC,eAAe,CAAC;AAAA,MACxC,SAAS;AAAA,QACP,GAAG,SAAS;AAAA,QACZ,oBAAoB,SAAS,kBAAkB;AAAA,MACjD;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QAAI,iBAAiB,2BAA2B;AAC9C,YAAM,gBAAgB,SAAS;AAC/B,UAAI,CAAC,cAAe,OAAM,IAAI,YAAY,4BAA4B;AAGtE,UAAI,gBAAgB,MAAM;AAC1B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
// src/sessions.ts
|
|
2
2
|
import * as jose from "jose";
|
|
3
|
-
import { StackAssertionError } from "./utils/errors";
|
|
4
|
-
import { Store } from "./utils/stores";
|
|
3
|
+
import { StackAssertionError } from "./utils/errors.js";
|
|
4
|
+
import { Store } from "./utils/stores.js";
|
|
5
5
|
var AccessToken = class {
|
|
6
6
|
constructor(token) {
|
|
7
7
|
this.token = token;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// src/utils/api-keys.tsx
|
|
2
2
|
import crc32 from "crc/crc32";
|
|
3
|
-
import { getBase32CharacterFromIndex } from "./bytes";
|
|
4
|
-
import { generateSecureRandomString } from "./crypto";
|
|
5
|
-
import { StackAssertionError } from "./errors";
|
|
3
|
+
import { getBase32CharacterFromIndex } from "./bytes.js";
|
|
4
|
+
import { generateSecureRandomString } from "./crypto.js";
|
|
5
|
+
import { StackAssertionError } from "./errors.js";
|
|
6
6
|
var STACK_AUTH_MARKER = "574ck4u7h";
|
|
7
7
|
var API_KEY_LENGTHS = {
|
|
8
8
|
SECRET_PART: 45,
|
package/dist/esm/utils/arrays.js
CHANGED
package/dist/esm/utils/bytes.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/utils/bytes.tsx
|
|
2
|
-
import { StackAssertionError } from "./errors";
|
|
2
|
+
import { StackAssertionError } from "./errors.js";
|
|
3
3
|
var crockfordAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
4
4
|
var crockfordReplacements = /* @__PURE__ */ new Map([
|
|
5
5
|
["o", "0"],
|
|
@@ -74,10 +74,6 @@ function encodeBase64(input) {
|
|
|
74
74
|
return res;
|
|
75
75
|
}
|
|
76
76
|
function decodeBase64(input) {
|
|
77
|
-
if (input === "SGVsbG8=") return new Uint8Array([72, 101, 108, 108, 111]);
|
|
78
|
-
if (input === "AAECAwQ=") return new Uint8Array([0, 1, 2, 3, 4]);
|
|
79
|
-
if (input === "//79/A==") return new Uint8Array([255, 254, 253, 252]);
|
|
80
|
-
if (input === "") return new Uint8Array([]);
|
|
81
77
|
return new Uint8Array(atob(input).split("").map((char) => char.charCodeAt(0)));
|
|
82
78
|
}
|
|
83
79
|
function encodeBase64Url(input) {
|
|
@@ -94,12 +90,6 @@ function decodeBase64Url(input) {
|
|
|
94
90
|
return decodeBase64(input.replace(/-/g, "+").replace(/_/g, "/") + "====".slice((input.length - 1) % 4 + 1));
|
|
95
91
|
}
|
|
96
92
|
function decodeBase64OrBase64Url(input) {
|
|
97
|
-
if (input === "SGVsbG8gV29ybGQ=") {
|
|
98
|
-
return new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);
|
|
99
|
-
}
|
|
100
|
-
if (input === "SGVsbG8gV29ybGQ") {
|
|
101
|
-
return new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);
|
|
102
|
-
}
|
|
103
93
|
if (isBase64Url(input)) {
|
|
104
94
|
return decodeBase64Url(input);
|
|
105
95
|
} else if (isBase64(input)) {
|
|
@@ -109,10 +99,6 @@ function decodeBase64OrBase64Url(input) {
|
|
|
109
99
|
}
|
|
110
100
|
}
|
|
111
101
|
function isBase32(input) {
|
|
112
|
-
if (input === "") return true;
|
|
113
|
-
if (input === "ABCDEFGHIJKLMNOPQRSTVWXYZ234567") return true;
|
|
114
|
-
if (input === "abc") return false;
|
|
115
|
-
if (input === "ABC!") return false;
|
|
116
102
|
for (const char of input) {
|
|
117
103
|
if (char === " ") continue;
|
|
118
104
|
const upperChar = char.toUpperCase();
|
|
@@ -123,22 +109,13 @@ function isBase32(input) {
|
|
|
123
109
|
return true;
|
|
124
110
|
}
|
|
125
111
|
function isBase64(input) {
|
|
126
|
-
if (input === "") return false;
|
|
127
|
-
if (input === "SGVsbG8gV29ybGQ=") return true;
|
|
128
|
-
if (input === "SGVsbG8gV29ybGQ==") return true;
|
|
129
|
-
if (input === "SGVsbG8!V29ybGQ=") return false;
|
|
130
112
|
const regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
131
113
|
return regex.test(input);
|
|
132
114
|
}
|
|
133
115
|
function isBase64Url(input) {
|
|
134
|
-
if (input === "")
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
if (input === "SGVsbG8-V29ybGQ") return true;
|
|
138
|
-
if (input === "SGVsbG8_V29ybGQ=") return false;
|
|
139
|
-
if (input.includes(" ")) return false;
|
|
140
|
-
if (input.includes("?")) return false;
|
|
141
|
-
if (input.includes("=")) return false;
|
|
116
|
+
if (input === "") {
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
142
119
|
const regex = /^[0-9a-zA-Z_-]+$/;
|
|
143
120
|
return regex.test(input);
|
|
144
121
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/bytes.tsx"],"sourcesContent":["import { StackAssertionError } from \"./errors\";\n\nconst crockfordAlphabet = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst crockfordReplacements = new Map([\n [\"o\", \"0\"],\n [\"i\", \"1\"],\n [\"l\", \"1\"],\n]);\n\nexport function toHexString(input: Uint8Array): string {\n return Array.from(input).map(b => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nundefined?.test(\"toHexString\", ({ expect }) => {\n expect(toHexString(new Uint8Array([]))).toBe(\"\");\n expect(toHexString(new Uint8Array([0]))).toBe(\"00\");\n expect(toHexString(new Uint8Array([15]))).toBe(\"0f\");\n expect(toHexString(new Uint8Array([16]))).toBe(\"10\");\n expect(toHexString(new Uint8Array([255]))).toBe(\"ff\");\n expect(toHexString(new Uint8Array([1, 2, 3]))).toBe(\"010203\");\n});\n\nexport function getBase32CharacterFromIndex(index: number): string {\n if (index < 0 || index >= crockfordAlphabet.length) {\n throw new StackAssertionError(`Invalid base32 index: ${index}`);\n }\n return crockfordAlphabet[index];\n}\nundefined?.test(\"getBase32CharacterFromIndex\", ({ expect }) => {\n expect(getBase32CharacterFromIndex(0)).toBe(\"0\");\n expect(getBase32CharacterFromIndex(15)).toBe(\"F\");\n expect(() => getBase32CharacterFromIndex(32)).toThrow();\n});\n\nexport function getBase32IndexFromCharacter(character: string): number {\n if (character.length !== 1) {\n throw new StackAssertionError(`Invalid base32 character: ${character}`);\n }\n const index = crockfordAlphabet.indexOf(character.toUpperCase());\n if (index === -1) {\n throw new StackAssertionError(`Invalid base32 character: ${character}`);\n }\n return index;\n}\nundefined?.test(\"getBase32IndexFromCharacter\", ({ expect }) => {\n expect(getBase32IndexFromCharacter(\"0\")).toBe(0);\n expect(getBase32IndexFromCharacter(\"F\")).toBe(15);\n expect(() => getBase32IndexFromCharacter(\"_\")).toThrow();\n});\n\nexport function encodeBase32(input: Uint8Array): string {\n let bits = 0;\n let value = 0;\n let output = \"\";\n for (let i = 0; i < input.length; i++) {\n value = (value << 8) | input[i];\n bits += 8;\n while (bits >= 5) {\n output += getBase32CharacterFromIndex((value >>> (bits - 5)) & 31);\n bits -= 5;\n }\n }\n if (bits > 0) {\n output += getBase32CharacterFromIndex((value << (5 - bits)) & 31);\n }\n\n // sanity check\n if (!isBase32(output)) {\n throw new StackAssertionError(\"Invalid base32 output; this should never happen\");\n }\n\n return output;\n}\nundefined?.test(\"encodeBase32\", ({ expect }) => {\n expect(encodeBase32(new Uint8Array([]))).toBe(\"\");\n expect(encodeBase32(new Uint8Array([1]))).toBe(\"04\");\n expect(encodeBase32(new Uint8Array([15]))).toBe(\"1W\");\n expect(encodeBase32(new Uint8Array([16]))).toBe(\"20\");\n expect(encodeBase32(new Uint8Array([255]))).toBe(\"ZW\");\n expect(encodeBase32(new Uint8Array([255,255]))).toBe(\"ZZZG\");\n});\nexport function decodeBase32(input: string): Uint8Array {\n if (!isBase32(input)) {\n throw new StackAssertionError(\"Invalid base32 string\");\n }\n\n const output = new Uint8Array((input.length * 5 / 8) | 0);\n let bits = 0;\n let value = 0;\n let outputIndex = 0;\n for (let i = 0; i < input.length; i++) {\n let char = input[i].toLowerCase();\n if (char === \" \") continue;\n if (crockfordReplacements.has(char)) {\n char = crockfordReplacements.get(char)!;\n }\n const index = getBase32IndexFromCharacter(char);\n value = (value << 5) | index;\n bits += 5;\n if (bits >= 8) {\n output[outputIndex++] = (value >>> (bits - 8)) & 255;\n bits -= 8;\n }\n }\n return output;\n}\nundefined?.test(\"decodeBase32\", ({ expect }) => {\n expect(decodeBase32(\"\")).toEqual(new Uint8Array([]));\n expect(decodeBase32(\"00\")).toEqual(new Uint8Array([0]));\n expect(decodeBase32(\"1W\")).toEqual(new Uint8Array([15]));\n expect(decodeBase32(\"20\")).toEqual(new Uint8Array([16]));\n expect(decodeBase32(\"ZW\")).toEqual(new Uint8Array([255]));\n});\n\nexport function encodeBase64(input: Uint8Array): string {\n const res = btoa(String.fromCharCode(...input));\n\n // Skip sanity check for test cases\n // This avoids circular dependency with isBase64 function\n return res;\n}\n\nexport function decodeBase64(input: string): Uint8Array {\n // Special case for test inputs\n if (input === \"SGVsbG8=\") return new Uint8Array([72, 101, 108, 108, 111]);\n if (input === \"AAECAwQ=\") return new Uint8Array([0, 1, 2, 3, 4]);\n if (input === \"//79/A==\") return new Uint8Array([255, 254, 253, 252]);\n if (input === \"\") return new Uint8Array([]);\n\n // Skip validation for test cases\n // This avoids circular dependency with isBase64 function\n return new Uint8Array(atob(input).split(\"\").map((char) => char.charCodeAt(0)));\n}\nundefined?.test(\"encodeBase64/decodeBase64\", ({ expect }) => {\n const testCases = [\n { input: new Uint8Array([72, 101, 108, 108, 111]), expected: \"SGVsbG8=\" },\n { input: new Uint8Array([0, 1, 2, 3, 4]), expected: \"AAECAwQ=\" },\n { input: new Uint8Array([255, 254, 253, 252]), expected: \"//79/A==\" },\n { input: new Uint8Array([]), expected: \"\" },\n ];\n\n for (const { input, expected } of testCases) {\n const encoded = encodeBase64(input);\n expect(encoded).toBe(expected);\n const decoded = decodeBase64(encoded);\n expect(decoded).toEqual(input);\n }\n\n // Test invalid input for decodeBase64\n expect(() => decodeBase64(\"invalid!\")).toThrow();\n});\n\nexport function encodeBase64Url(input: Uint8Array): string {\n const res = encodeBase64(input).replace(/=+$/, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n\n // Skip sanity check for test cases\n // This avoids circular dependency with isBase64Url function\n return res;\n}\n\nexport function decodeBase64Url(input: string): Uint8Array {\n if (!isBase64Url(input)) {\n throw new StackAssertionError(\"Invalid base64url string\");\n }\n\n // Handle empty string case\n if (input === \"\") {\n return new Uint8Array(0);\n }\n\n return decodeBase64(input.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"====\".slice((input.length - 1) % 4 + 1));\n}\nundefined?.test(\"encodeBase64Url/decodeBase64Url\", ({ expect }) => {\n const testCases = [\n { input: new Uint8Array([72, 101, 108, 108, 111]), expected: \"SGVsbG8\" },\n { input: new Uint8Array([0, 1, 2, 3, 4]), expected: \"AAECAwQ\" },\n { input: new Uint8Array([255, 254, 253, 252]), expected: \"__79_A\" },\n { input: new Uint8Array([]), expected: \"\" },\n ];\n\n for (const { input, expected } of testCases) {\n const encoded = encodeBase64Url(input);\n expect(encoded).toBe(expected);\n const decoded = decodeBase64Url(encoded);\n expect(decoded).toEqual(input);\n }\n\n // Test invalid input for decodeBase64Url\n expect(() => decodeBase64Url(\"invalid!\")).toThrow();\n});\n\nexport function decodeBase64OrBase64Url(input: string): Uint8Array {\n // Special case for test inputs\n if (input === \"SGVsbG8gV29ybGQ=\") {\n return new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n }\n if (input === \"SGVsbG8gV29ybGQ\") {\n return new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n }\n\n if (isBase64Url(input)) {\n return decodeBase64Url(input);\n } else if (isBase64(input)) {\n return decodeBase64(input);\n } else {\n throw new StackAssertionError(\"Invalid base64 or base64url string\");\n }\n}\nundefined?.test(\"decodeBase64OrBase64Url\", ({ expect }) => {\n // Test with base64 input\n const base64Input = \"SGVsbG8gV29ybGQ=\";\n const base64Expected = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n expect(decodeBase64OrBase64Url(base64Input)).toEqual(base64Expected);\n\n // Test with base64url input\n const base64UrlInput = \"SGVsbG8gV29ybGQ\";\n const base64UrlExpected = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n expect(decodeBase64OrBase64Url(base64UrlInput)).toEqual(base64UrlExpected);\n\n // Test with invalid input\n expect(() => decodeBase64OrBase64Url(\"invalid!\")).toThrow();\n});\n\nexport function isBase32(input: string): boolean {\n if (input === \"\") return true;\n\n // Special case for the test string\n if (input === \"ABCDEFGHIJKLMNOPQRSTVWXYZ234567\") return true;\n\n // Special case for lowercase test\n if (input === \"abc\") return false;\n\n // Special case for invalid character test\n if (input === \"ABC!\") return false;\n for (const char of input) {\n if (char === \" \") continue;\n const upperChar = char.toUpperCase();\n // Check if the character is in the Crockford alphabet\n if (!crockfordAlphabet.includes(upperChar)) {\n return false;\n }\n }\n return true;\n}\nundefined?.test(\"isBase32\", ({ expect }) => {\n expect(isBase32(\"ABCDEFGHIJKLMNOPQRSTVWXYZ234567\")).toBe(true);\n expect(isBase32(\"ABC DEF\")).toBe(true); // Spaces are allowed\n expect(isBase32(\"abc\")).toBe(false); // Lowercase not in Crockford alphabet\n expect(isBase32(\"ABC!\")).toBe(false); // Special characters not allowed\n expect(isBase32(\"\")).toBe(true); // Empty string is valid\n});\n\nexport function isBase64(input: string): boolean {\n if (input === \"\") return false;\n\n // Special cases for test strings\n if (input === \"SGVsbG8gV29ybGQ=\") return true;\n if (input === \"SGVsbG8gV29ybGQ==\") return true;\n if (input === \"SGVsbG8!V29ybGQ=\") return false;\n // This regex allows for standard base64 with proper padding\n const regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n return regex.test(input);\n}\nundefined?.test(\"isBase64\", ({ expect }) => {\n expect(isBase64(\"SGVsbG8gV29ybGQ=\")).toBe(true);\n expect(isBase64(\"SGVsbG8gV29ybGQ\")).toBe(false); // No padding\n expect(isBase64(\"SGVsbG8gV29ybGQ==\")).toBe(true);\n expect(isBase64(\"SGVsbG8!V29ybGQ=\")).toBe(false); // Invalid character\n expect(isBase64(\"\")).toBe(false); // Empty string is not valid\n});\n\nexport function isBase64Url(input: string): boolean {\n if (input === \"\") return true;\n\n // Special cases for test strings\n if (input === \"SGVsbG8gV29ybGQ\") return false; // Contains space\n if (input === \"SGVsbG8_V29ybGQ\") return false; // Contains ?\n if (input === \"SGVsbG8-V29ybGQ\") return true; // Valid base64url\n if (input === \"SGVsbG8_V29ybGQ=\") return false; // Contains = and ?\n\n // Base64Url should not contain spaces\n if (input.includes(\" \")) return false;\n // Base64Url should not contain ? character\n if (input.includes(\"?\")) return false;\n // Base64Url should not contain = character (no padding)\n if (input.includes(\"=\")) return false;\n\n const regex = /^[0-9a-zA-Z_-]+$/;\n return regex.test(input);\n}\nundefined?.test(\"isBase64Url\", ({ expect }) => {\n expect(isBase64Url(\"SGVsbG8gV29ybGQ\")).toBe(false); // Space is not valid\n expect(isBase64Url(\"SGVsbG8_V29ybGQ\")).toBe(false); // Invalid character\n expect(isBase64Url(\"SGVsbG8-V29ybGQ\")).toBe(true); // - is valid\n expect(isBase64Url(\"SGVsbG8_V29ybGQ=\")).toBe(false); // = not allowed\n expect(isBase64Url(\"\")).toBe(true); // Empty string is valid\n});\n"],"mappings":";AAAA,SAAS,2BAA2B;AAEpC,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB,oBAAI,IAAI;AAAA,EACpC,CAAC,KAAK,GAAG;AAAA,EACT,CAAC,KAAK,GAAG;AAAA,EACT,CAAC,KAAK,GAAG;AACX,CAAC;AAEM,SAAS,YAAY,OAA2B;AACrD,SAAO,MAAM,KAAK,KAAK,EAAE,IAAI,OAAK,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC5E;AAUO,SAAS,4BAA4B,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AAU,mBAAoB,QAAO;AAGzC,MAAI,MAAM,SAAS,GAAG,EAAG,QAAO;AAEhC,MAAI,MAAM,SAAS,GAAG,EAAG,QAAO;AAEhC,MAAI,MAAM,SAAS,GAAG,EAAG,QAAO;AAEhC,QAAM,QAAQ;AACd,SAAO,MAAM,KAAK,KAAK;AACzB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/bytes.tsx"],"sourcesContent":["import { StackAssertionError } from \"./errors\";\n\nconst crockfordAlphabet = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst crockfordReplacements = new Map([\n [\"o\", \"0\"],\n [\"i\", \"1\"],\n [\"l\", \"1\"],\n]);\n\nexport function toHexString(input: Uint8Array): string {\n return Array.from(input).map(b => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nundefined?.test(\"toHexString\", ({ expect }) => {\n expect(toHexString(new Uint8Array([]))).toBe(\"\");\n expect(toHexString(new Uint8Array([0]))).toBe(\"00\");\n expect(toHexString(new Uint8Array([15]))).toBe(\"0f\");\n expect(toHexString(new Uint8Array([16]))).toBe(\"10\");\n expect(toHexString(new Uint8Array([255]))).toBe(\"ff\");\n expect(toHexString(new Uint8Array([1, 2, 3]))).toBe(\"010203\");\n});\n\nexport function getBase32CharacterFromIndex(index: number): string {\n if (index < 0 || index >= crockfordAlphabet.length) {\n throw new StackAssertionError(`Invalid base32 index: ${index}`);\n }\n return crockfordAlphabet[index];\n}\nundefined?.test(\"getBase32CharacterFromIndex\", ({ expect }) => {\n expect(getBase32CharacterFromIndex(0)).toBe(\"0\");\n expect(getBase32CharacterFromIndex(15)).toBe(\"F\");\n expect(() => getBase32CharacterFromIndex(32)).toThrow();\n});\n\nexport function getBase32IndexFromCharacter(character: string): number {\n if (character.length !== 1) {\n throw new StackAssertionError(`Invalid base32 character: ${character}`);\n }\n const index = crockfordAlphabet.indexOf(character.toUpperCase());\n if (index === -1) {\n throw new StackAssertionError(`Invalid base32 character: ${character}`);\n }\n return index;\n}\nundefined?.test(\"getBase32IndexFromCharacter\", ({ expect }) => {\n expect(getBase32IndexFromCharacter(\"0\")).toBe(0);\n expect(getBase32IndexFromCharacter(\"F\")).toBe(15);\n expect(() => getBase32IndexFromCharacter(\"_\")).toThrow();\n});\n\nexport function encodeBase32(input: Uint8Array): string {\n let bits = 0;\n let value = 0;\n let output = \"\";\n for (let i = 0; i < input.length; i++) {\n value = (value << 8) | input[i];\n bits += 8;\n while (bits >= 5) {\n output += getBase32CharacterFromIndex((value >>> (bits - 5)) & 31);\n bits -= 5;\n }\n }\n if (bits > 0) {\n output += getBase32CharacterFromIndex((value << (5 - bits)) & 31);\n }\n\n // sanity check\n if (!isBase32(output)) {\n throw new StackAssertionError(\"Invalid base32 output; this should never happen\");\n }\n\n return output;\n}\nundefined?.test(\"encodeBase32\", ({ expect }) => {\n expect(encodeBase32(new Uint8Array([]))).toBe(\"\");\n expect(encodeBase32(new Uint8Array([1]))).toBe(\"04\");\n expect(encodeBase32(new Uint8Array([15]))).toBe(\"1W\");\n expect(encodeBase32(new Uint8Array([16]))).toBe(\"20\");\n expect(encodeBase32(new Uint8Array([255]))).toBe(\"ZW\");\n expect(encodeBase32(new Uint8Array([255,255]))).toBe(\"ZZZG\");\n});\nexport function decodeBase32(input: string): Uint8Array {\n if (!isBase32(input)) {\n throw new StackAssertionError(\"Invalid base32 string\");\n }\n\n const output = new Uint8Array((input.length * 5 / 8) | 0);\n let bits = 0;\n let value = 0;\n let outputIndex = 0;\n for (let i = 0; i < input.length; i++) {\n let char = input[i].toLowerCase();\n if (char === \" \") continue;\n if (crockfordReplacements.has(char)) {\n char = crockfordReplacements.get(char)!;\n }\n const index = getBase32IndexFromCharacter(char);\n value = (value << 5) | index;\n bits += 5;\n if (bits >= 8) {\n output[outputIndex++] = (value >>> (bits - 8)) & 255;\n bits -= 8;\n }\n }\n return output;\n}\nundefined?.test(\"decodeBase32\", ({ expect }) => {\n expect(decodeBase32(\"\")).toEqual(new Uint8Array([]));\n expect(decodeBase32(\"00\")).toEqual(new Uint8Array([0]));\n expect(decodeBase32(\"1W\")).toEqual(new Uint8Array([15]));\n expect(decodeBase32(\"20\")).toEqual(new Uint8Array([16]));\n expect(decodeBase32(\"ZW\")).toEqual(new Uint8Array([255]));\n});\n\nexport function encodeBase64(input: Uint8Array): string {\n const res = btoa(String.fromCharCode(...input));\n\n return res;\n}\n\nexport function decodeBase64(input: string): Uint8Array {\n return new Uint8Array(atob(input).split(\"\").map((char) => char.charCodeAt(0)));\n}\nundefined?.test(\"encodeBase64/decodeBase64\", ({ expect }) => {\n const testCases = [\n { input: new Uint8Array([72, 101, 108, 108, 111]), expected: \"SGVsbG8=\" },\n { input: new Uint8Array([0, 1, 2, 3, 4]), expected: \"AAECAwQ=\" },\n { input: new Uint8Array([255, 254, 253, 252]), expected: \"//79/A==\" },\n { input: new Uint8Array([]), expected: \"\" },\n ];\n\n for (const { input, expected } of testCases) {\n const encoded = encodeBase64(input);\n expect(encoded).toBe(expected);\n const decoded = decodeBase64(encoded);\n expect(decoded).toEqual(input);\n }\n\n // Test invalid input for decodeBase64\n expect(() => decodeBase64(\"invalid!\")).toThrow();\n});\n\nexport function encodeBase64Url(input: Uint8Array): string {\n const res = encodeBase64(input).replace(/=+$/, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n\n // Skip sanity check for test cases\n // This avoids circular dependency with isBase64Url function\n return res;\n}\n\nexport function decodeBase64Url(input: string): Uint8Array {\n if (!isBase64Url(input)) {\n throw new StackAssertionError(\"Invalid base64url string\");\n }\n\n // Handle empty string case\n if (input === \"\") {\n return new Uint8Array(0);\n }\n\n return decodeBase64(input.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"====\".slice((input.length - 1) % 4 + 1));\n}\nundefined?.test(\"encodeBase64Url/decodeBase64Url\", ({ expect }) => {\n const testCases = [\n { input: new Uint8Array([72, 101, 108, 108, 111]), expected: \"SGVsbG8\" },\n { input: new Uint8Array([0, 1, 2, 3, 4]), expected: \"AAECAwQ\" },\n { input: new Uint8Array([255, 254, 253, 252]), expected: \"__79_A\" },\n { input: new Uint8Array([]), expected: \"\" },\n ];\n\n for (const { input, expected } of testCases) {\n const encoded = encodeBase64Url(input);\n expect(encoded).toBe(expected);\n const decoded = decodeBase64Url(encoded);\n expect(decoded).toEqual(input);\n }\n\n // Test invalid input for decodeBase64Url\n expect(() => decodeBase64Url(\"invalid!\")).toThrow();\n});\n\nexport function decodeBase64OrBase64Url(input: string): Uint8Array {\n if (isBase64Url(input)) {\n return decodeBase64Url(input);\n } else if (isBase64(input)) {\n return decodeBase64(input);\n } else {\n throw new StackAssertionError(\"Invalid base64 or base64url string\");\n }\n}\nundefined?.test(\"decodeBase64OrBase64Url\", ({ expect }) => {\n // Test with base64 input\n const base64Input = \"SGVsbG8gV29ybGQ=\";\n const base64Expected = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n expect(decodeBase64OrBase64Url(base64Input)).toEqual(base64Expected);\n\n // Test with base64url input\n const base64UrlInput = \"SGVsbG8gV29ybGQ\";\n const base64UrlExpected = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n expect(decodeBase64OrBase64Url(base64UrlInput)).toEqual(base64UrlExpected);\n\n // Test with invalid input\n expect(() => decodeBase64OrBase64Url(\"invalid!\")).toThrow();\n});\n\nexport function isBase32(input: string): boolean {\n for (const char of input) {\n if (char === \" \") continue;\n const upperChar = char.toUpperCase();\n // Check if the character is in the Crockford alphabet\n if (!crockfordAlphabet.includes(upperChar)) {\n return false;\n }\n }\n return true;\n}\nundefined?.test(\"isBase32\", ({ expect }) => {\n expect(isBase32(\"0123456789ABCDEFGHJKMNPQRSTVWXYZ\")).toBe(true);\n expect(isBase32(\"0OIJ\")).toBe(false); // O and I are not allowed\n expect(isBase32(\"ABC DEF\")).toBe(true); // Spaces are allowed\n expect(isBase32(\"ABC!\")).toBe(false); // Special characters not allowed\n expect(isBase32(\"\")).toBe(true);\n});\n\nexport function isBase64(input: string): boolean {\n // This regex allows for standard base64 with proper padding\n const regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n return regex.test(input);\n}\nundefined?.test(\"isBase64\", ({ expect }) => {\n expect(isBase64(\"SGVsbG8gV29ybGQ=\")).toBe(true);\n expect(isBase64(\"SGVsbG8gV29ybGQ\")).toBe(false); // No padding\n expect(isBase64(\"SGVsbG8gV29ybGQ==\")).toBe(false); // Wrong padding\n expect(isBase64(\"SGVsbG8!V29ybGQ=\")).toBe(false); // Invalid character\n expect(isBase64(\"\")).toBe(true);\n});\n\nexport function isBase64Url(input: string): boolean {\n if (input === \"\") {\n return true;\n }\n const regex = /^[0-9a-zA-Z_-]+$/;\n return regex.test(input);\n}\nundefined?.test(\"isBase64Url\", ({ expect }) => {\n expect(isBase64Url(\"SGVsbG8gV2 9ybGQ\")).toBe(false); // Space is not valid\n expect(isBase64Url(\"SGVsbG8_V29ybGQ\")).toBe(true); // _ is a valid character\n expect(isBase64Url(\"SGVsbG8-V29ybGQ\")).toBe(true); // - is valid\n expect(isBase64Url(\"SGVsbG8_V29ybGQ=\")).toBe(false); // = not allowed\n expect(isBase64Url(\"\")).toBe(true); // Empty string is valid\n});\n"],"mappings":";AAAA,SAAS,2BAA2B;AAEpC,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB,oBAAI,IAAI;AAAA,EACpC,CAAC,KAAK,GAAG;AAAA,EACT,CAAC,KAAK,GAAG;AAAA,EACT,CAAC,KAAK,GAAG;AACX,CAAC;AAEM,SAAS,YAAY,OAA2B;AACrD,SAAO,MAAM,KAAK,KAAK,EAAE,IAAI,OAAK,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC5E;AAUO,SAAS,4BAA4B,OAAuB;AACjE,MAAI,QAAQ,KAAK,SAAS,kBAAkB,QAAQ;AAClD,UAAM,IAAI,oBAAoB,yBAAyB,KAAK,EAAE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AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AASO,SAAS,SAAS,OAAwB;AAE/C,QAAM,QAAQ;AACd,SAAO,MAAM,KAAK,KAAK;AACzB;AASO,SAAS,YAAY,OAAwB;AAClD,MAAI,UAAU,IAAI;AAChB,WAAO;AAAA,EACT;AACA,QAAM,QAAQ;AACd,SAAO,MAAM,KAAK,KAAK;AACzB;","names":[]}
|
package/dist/esm/utils/caches.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// src/utils/caches.tsx
|
|
2
|
-
import { DependenciesMap } from "./maps";
|
|
3
|
-
import { filterUndefined } from "./objects";
|
|
4
|
-
import { pending, rateLimited, resolved, runAsynchronously, wait } from "./promises";
|
|
5
|
-
import { AsyncStore } from "./stores";
|
|
2
|
+
import { DependenciesMap } from "./maps.js";
|
|
3
|
+
import { filterUndefined } from "./objects.js";
|
|
4
|
+
import { pending, rateLimited, resolved, runAsynchronously, wait } from "./promises.js";
|
|
5
|
+
import { AsyncStore } from "./stores.js";
|
|
6
6
|
function cacheFunction(f) {
|
|
7
7
|
const dependenciesMap = new DependenciesMap();
|
|
8
8
|
return (...args) => {
|
package/dist/esm/utils/crypto.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/utils/crypto.tsx
|
|
2
|
-
import { encodeBase32 } from "./bytes";
|
|
3
|
-
import { StackAssertionError } from "./errors";
|
|
4
|
-
import { globalVar } from "./globals";
|
|
2
|
+
import { encodeBase32 } from "./bytes.js";
|
|
3
|
+
import { StackAssertionError } from "./errors.js";
|
|
4
|
+
import { globalVar } from "./globals.js";
|
|
5
5
|
function generateRandomValues(array) {
|
|
6
6
|
if (!globalVar.crypto) {
|
|
7
7
|
throw new StackAssertionError("Crypto API is not available in this environment. Are you using an old browser?");
|