@stackframe/js 2.8.49 → 2.8.52
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 +30 -0
- package/dist/esm/lib/cookie.js +2 -2
- package/dist/esm/lib/cookie.js.map +1 -1
- package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js +7 -0
- package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -1
- package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js +51 -32
- package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -1
- package/dist/esm/lib/stack-app/apps/implementations/common.js +1 -1
- package/dist/esm/lib/stack-app/apps/implementations/common.js.map +1 -1
- package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js +40 -1
- package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -1
- package/dist/esm/lib/stack-app/apps/interfaces/client-app.js.map +1 -1
- package/dist/esm/lib/stack-app/common.js.map +1 -1
- package/dist/esm/lib/stack-app/users/index.js.map +1 -1
- package/dist/index.d.mts +92 -79
- package/dist/index.d.ts +92 -79
- package/dist/lib/cookie.js +2 -2
- package/dist/lib/cookie.js.map +1 -1
- package/dist/lib/stack-app/apps/implementations/admin-app-impl.js +7 -0
- package/dist/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -1
- package/dist/lib/stack-app/apps/implementations/client-app-impl.js +51 -32
- package/dist/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -1
- package/dist/lib/stack-app/apps/implementations/common.js +1 -1
- package/dist/lib/stack-app/apps/implementations/common.js.map +1 -1
- package/dist/lib/stack-app/apps/implementations/server-app-impl.js +49 -0
- package/dist/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -1
- package/dist/lib/stack-app/apps/interfaces/client-app.js.map +1 -1
- package/dist/lib/stack-app/common.js.map +1 -1
- package/dist/lib/stack-app/users/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/lib/stack-app/users/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { KnownErrors } from \"@stackframe/stack-shared\";\nimport { CurrentUserCrud } from \"@stackframe/stack-shared/dist/interface/crud/current-user\";\nimport { UsersCrud } from \"@stackframe/stack-shared/dist/interface/crud/users\";\nimport { InternalSession } from \"@stackframe/stack-shared/dist/sessions\";\nimport { encodeBase64 } from \"@stackframe/stack-shared/dist/utils/bytes\";\nimport { GeoInfo } from \"@stackframe/stack-shared/dist/utils/geo\";\nimport { ReadonlyJson } from \"@stackframe/stack-shared/dist/utils/json\";\nimport { ProviderType } from \"@stackframe/stack-shared/dist/utils/oauth\";\nimport { Result } from \"@stackframe/stack-shared/dist/utils/results\";\nimport { ApiKeyCreationOptions, UserApiKey, UserApiKeyFirstView } from \"../api-keys\";\nimport { AsyncStoreProperty } from \"../common\";\nimport { OAuthConnection } from \"../connected-accounts\";\nimport { ContactChannel, ContactChannelCreateOptions, ServerContactChannel, ServerContactChannelCreateOptions } from \"../contact-channels\";\nimport { Customer } from \"../customers\";\nimport { NotificationCategory } from \"../notification-categories\";\nimport { AdminTeamPermission, TeamPermission } from \"../permissions\";\nimport { AdminOwnedProject, AdminProjectCreateOptions } from \"../projects\";\nimport { EditableTeamMemberProfile, ServerTeam, ServerTeamCreateOptions, Team, TeamCreateOptions } from \"../teams\";\n\nconst userGetterErrorMessage = \"Stack Auth: useUser() already returns the user object. Use `const user = useUser()` (or `const user = await app.getUser()`) instead of destructuring it like `const { user } = ...`.\";\n\nexport function attachUserDestructureGuard(target: object): void {\n const descriptor = Object.getOwnPropertyDescriptor(target, \"user\");\n if (descriptor?.get === guardGetter) {\n return;\n }\n\n Object.defineProperty(target, \"user\", {\n get: guardGetter,\n configurable: false,\n enumerable: false,\n });\n}\n\nfunction guardGetter(): never {\n throw new Error(userGetterErrorMessage);\n}\n\nexport type OAuthProvider = {\n readonly id: string,\n readonly type: string,\n readonly userId: string,\n readonly accountId?: string,\n readonly email?: string,\n readonly allowSignIn: boolean,\n readonly allowConnectedAccounts: boolean,\n update(data: { allowSignIn?: boolean, allowConnectedAccounts?: boolean }): Promise<Result<void,\n InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>\n >>,\n delete(): Promise<void>,\n};\n\nexport type ServerOAuthProvider = {\n readonly id: string,\n readonly type: string,\n readonly userId: string,\n readonly accountId: string,\n readonly email?: string,\n readonly allowSignIn: boolean,\n readonly allowConnectedAccounts: boolean,\n update(data: { accountId?: string, email?: string, allowSignIn?: boolean, allowConnectedAccounts?: boolean }): Promise<Result<void,\n InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>\n >>,\n delete(): Promise<void>,\n};\n\n\nexport type Session = {\n getTokens(): Promise<{ accessToken: string | null, refreshToken: string | null }>,\n};\n\n/**\n * Contains everything related to the current user session.\n */\nexport type Auth = {\n readonly _internalSession: InternalSession,\n readonly currentSession: Session,\n signOut(options?: { redirectUrl?: URL | string }): Promise<void>,\n\n /**\n * Returns headers for sending authenticated HTTP requests to external servers. Most commonly used in cross-origin\n * requests. Similar to `getAuthJson`, but specifically for HTTP requests.\n *\n * If you are using `tokenStore: \"cookie\"`, you don't need this for same-origin requests. However, most\n * browsers now disable third-party cookies by default, so we must pass authentication tokens by header instead\n * if the client and server are on different origins.\n *\n * This function returns a header object that can be used with `fetch` or other HTTP request libraries to send\n * authenticated requests.\n *\n * On the server, you can then pass in the `Request` object to the `tokenStore` option\n * of your Stack app. Please note that CORS does not allow most headers by default, so you\n * must include `x-stack-auth` in the [`Access-Control-Allow-Headers` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers)\n * of the CORS preflight response.\n *\n * If you are not using HTTP (and hence cannot set headers), you will need to use the `getAuthJson()` function\n * instead.\n *\n * Example:\n *\n * ```ts\n * // client\n * const res = await fetch(\"https://api.example.com\", {\n * headers: {\n * ...await stackApp.getAuthHeaders()\n * // you can also add your own headers here\n * },\n * });\n *\n * // server\n * function handleRequest(req: Request) {\n * const user = await stackServerApp.getUser({ tokenStore: req });\n * return new Response(\"Welcome, \" + user.displayName);\n * }\n * ```\n */\n getAuthHeaders(): Promise<{ \"x-stack-auth\": string }>,\n\n /**\n * Creates a JSON-serializable object containing the information to authenticate a user on an external server.\n * Similar to `getAuthHeaders`, but returns an object that can be sent over any protocol instead of just\n * HTTP headers.\n *\n * While `getAuthHeaders` is the recommended way to send authentication tokens over HTTP, your app may use\n * a different protocol, for example WebSockets or gRPC. This function returns a token object that can be JSON-serialized and sent to the server in any way you like.\n *\n * On the server, you can pass in this token object into the `tokenStore` option to fetch user details.\n *\n * Example:\n *\n * ```ts\n * // client\n * const res = await rpcCall(rpcEndpoint, {\n * data: {\n * auth: await stackApp.getAuthJson(),\n * },\n * });\n *\n * // server\n * function handleRequest(data) {\n * const user = await stackServerApp.getUser({ tokenStore: data.auth });\n * return new Response(\"Welcome, \" + user.displayName);\n * }\n * ```\n */\n getAuthJson(): Promise<{ accessToken: string | null, refreshToken: string | null }>,\n registerPasskey(options?: { hostname?: string }): Promise<Result<undefined, KnownErrors[\"PasskeyRegistrationFailed\"] | KnownErrors[\"PasskeyWebAuthnError\"]>>,\n};\n\n/**\n * ```\n * +----------+-------------+-------------------+\n * | \\ | !Server | Server |\n * +----------+-------------+-------------------+\n * | !Session | User | ServerUser |\n * | Session | CurrentUser | CurrentServerUser |\n * +----------+-------------+-------------------+\n * ```\n *\n * The fields on each of these types are available iff:\n * BaseUser: true\n * Auth: Session\n * ServerBaseUser: Server\n * UserExtra: Session OR Server\n *\n * The types are defined as follows (in the typescript manner):\n * User = BaseUser\n * CurrentUser = BaseUser & Auth & UserExtra\n * ServerUser = BaseUser & ServerBaseUser & UserExtra\n * CurrentServerUser = BaseUser & ServerBaseUser & Auth & UserExtra\n **/\n\nexport type BaseUser = {\n readonly id: string,\n\n readonly displayName: string | null,\n\n /**\n * The user's email address.\n *\n * Note: This might NOT be unique across multiple users, so always use `id` for unique identification.\n */\n readonly primaryEmail: string | null,\n readonly primaryEmailVerified: boolean,\n readonly profileImageUrl: string | null,\n\n readonly signedUpAt: Date,\n\n readonly clientMetadata: any,\n readonly clientReadOnlyMetadata: any,\n\n /**\n * Whether the user has a password set.\n */\n readonly hasPassword: boolean,\n readonly otpAuthEnabled: boolean,\n readonly passkeyAuthEnabled: boolean,\n\n readonly isMultiFactorRequired: boolean,\n readonly isAnonymous: boolean,\n toClientJson(): CurrentUserCrud[\"Client\"][\"Read\"],\n\n /**\n * @deprecated, use contact channel's usedForAuth instead\n */\n readonly emailAuthEnabled: boolean,\n /**\n * @deprecated\n */\n readonly oauthProviders: readonly { id: string }[],\n}\n\nexport type UserExtra = {\n setDisplayName(displayName: string): Promise<void>,\n /** @deprecated Use contact channel's sendVerificationEmail instead */\n sendVerificationEmail(): Promise<KnownErrors[\"EmailAlreadyVerified\"] | void>,\n setClientMetadata(metadata: any): Promise<void>,\n updatePassword(options: { oldPassword: string, newPassword: string}): Promise<KnownErrors[\"PasswordConfirmationMismatch\"] | KnownErrors[\"PasswordRequirementsNotMet\"] | void>,\n setPassword(options: { password: string }): Promise<KnownErrors[\"PasswordRequirementsNotMet\"] | void>,\n\n /**\n * A shorthand method to update multiple fields of the user at once.\n */\n update(update: UserUpdateOptions): Promise<void>,\n\n listContactChannels(): Promise<ContactChannel[]>,\n createContactChannel(data: ContactChannelCreateOptions): Promise<ContactChannel>,\n\n listNotificationCategories(): Promise<NotificationCategory[]>,\n\n delete(): Promise<void>,\n\n getConnectedAccount(id: ProviderType, options: { or: 'redirect', scopes?: string[] }): Promise<OAuthConnection>,\n getConnectedAccount(id: ProviderType, options?: { or?: 'redirect' | 'throw' | 'return-null', scopes?: string[] }): Promise<OAuthConnection | null>,\n\n\n hasPermission(scope: Team, permissionId: string): Promise<boolean>,\n hasPermission(permissionId: string): Promise<boolean>,\n\n getPermission(scope: Team, permissionId: string): Promise<TeamPermission | null>,\n getPermission(permissionId: string): Promise<TeamPermission | null>,\n\n listPermissions(scope: Team, options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n listPermissions(options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n\n\n readonly selectedTeam: Team | null,\n setSelectedTeam(team: Team | null): Promise<void>,\n createTeam(data: TeamCreateOptions): Promise<Team>,\n leaveTeam(team: Team): Promise<void>,\n\n getActiveSessions(): Promise<ActiveSession[]>,\n revokeSession(sessionId: string): Promise<void>,\n getTeamProfile(team: Team): Promise<EditableTeamMemberProfile>,\n\n createApiKey(options: ApiKeyCreationOptions<\"user\">): Promise<UserApiKeyFirstView>,\n\n listOAuthProviders(): Promise<OAuthProvider[]>,\n\n getOAuthProvider(id: string): Promise<OAuthProvider | null>,\n}\n& AsyncStoreProperty<\"apiKeys\", [], UserApiKey[], true>\n& AsyncStoreProperty<\"team\", [id: string], Team | null, false>\n& AsyncStoreProperty<\"teams\", [], Team[], true>\n& AsyncStoreProperty<\"permission\", [scope: Team, permissionId: string, options?: { recursive?: boolean }], TeamPermission | null, false>\n& AsyncStoreProperty<\"permissions\", [scope: Team, options?: { recursive?: boolean }], TeamPermission[], true>;\n\nexport type InternalUserExtra =\n & {\n createProject(newProject: AdminProjectCreateOptions): Promise<AdminOwnedProject>,\n transferProject(projectIdToTransfer: string, newTeamId: string): Promise<void>,\n }\n & AsyncStoreProperty<\"ownedProjects\", [], AdminOwnedProject[], true>\n\nexport type User = BaseUser;\n\nexport type CurrentUser = BaseUser & Auth & UserExtra & Customer;\n\nexport type CurrentInternalUser = CurrentUser & InternalUserExtra;\n\nexport type ProjectCurrentUser<ProjectId> = ProjectId extends \"internal\" ? CurrentInternalUser : CurrentUser;\n\nexport type TokenPartialUser = Pick<\n User,\n | \"id\"\n | \"displayName\"\n | \"primaryEmail\"\n | \"primaryEmailVerified\"\n | \"isAnonymous\"\n>\n\nexport type SyncedPartialUser = TokenPartialUser & Pick<\n User,\n | \"id\"\n | \"displayName\"\n | \"primaryEmail\"\n | \"primaryEmailVerified\"\n | \"profileImageUrl\"\n | \"signedUpAt\"\n | \"clientMetadata\"\n | \"clientReadOnlyMetadata\"\n | \"isAnonymous\"\n | \"hasPassword\"\n>;\n\n\nexport type ActiveSession = {\n id: string,\n userId: string,\n createdAt: Date,\n isImpersonation: boolean,\n lastUsedAt: Date | undefined,\n isCurrentSession: boolean,\n geoInfo?: GeoInfo,\n};\n\nexport type UserUpdateOptions = {\n displayName?: string,\n clientMetadata?: ReadonlyJson,\n selectedTeamId?: string | null,\n totpMultiFactorSecret?: Uint8Array | null,\n profileImageUrl?: string | null,\n otpAuthEnabled?: boolean,\n passkeyAuthEnabled?:boolean,\n}\nexport function userUpdateOptionsToCrud(options: UserUpdateOptions): CurrentUserCrud[\"Client\"][\"Update\"] {\n return {\n display_name: options.displayName,\n client_metadata: options.clientMetadata,\n selected_team_id: options.selectedTeamId,\n totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,\n profile_image_url: options.profileImageUrl,\n otp_auth_enabled: options.otpAuthEnabled,\n passkey_auth_enabled: options.passkeyAuthEnabled,\n };\n}\n\n\nexport type ServerBaseUser = {\n setPrimaryEmail(email: string | null, options?: { verified?: boolean | undefined }): Promise<void>,\n\n readonly lastActiveAt: Date,\n\n readonly serverMetadata: any,\n setServerMetadata(metadata: any): Promise<void>,\n setClientReadOnlyMetadata(metadata: any): Promise<void>,\n\n createTeam(data: Omit<ServerTeamCreateOptions, \"creatorUserId\">): Promise<ServerTeam>,\n\n listContactChannels(): Promise<ServerContactChannel[]>,\n createContactChannel(data: ServerContactChannelCreateOptions): Promise<ServerContactChannel>,\n\n update(user: ServerUserUpdateOptions): Promise<void>,\n\n grantPermission(scope: Team, permissionId: string): Promise<void>,\n grantPermission(permissionId: string): Promise<void>,\n\n revokePermission(scope: Team, permissionId: string): Promise<void>,\n revokePermission(permissionId: string): Promise<void>,\n\n getPermission(scope: Team, permissionId: string): Promise<TeamPermission | null>,\n getPermission(permissionId: string): Promise<TeamPermission | null>,\n\n hasPermission(scope: Team, permissionId: string): Promise<boolean>,\n hasPermission(permissionId: string): Promise<boolean>,\n\n listPermissions(scope: Team, options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n listPermissions(options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n\n\n listOAuthProviders(): Promise<ServerOAuthProvider[]>,\n\n getOAuthProvider(id: string): Promise<ServerOAuthProvider | null>,\n\n /**\n * Creates a new session object with a refresh token for this user. Can be used to impersonate them.\n */\n createSession(options?: { expiresInMillis?: number, isImpersonation?: boolean }): Promise<Session>,\n}\n& AsyncStoreProperty<\"team\", [id: string], ServerTeam | null, false>\n& AsyncStoreProperty<\"teams\", [], ServerTeam[], true>\n& AsyncStoreProperty<\"permission\", [scope: Team, permissionId: string, options?: { direct?: boolean }], AdminTeamPermission | null, false>\n& AsyncStoreProperty<\"permissions\", [scope: Team, options?: { direct?: boolean }], AdminTeamPermission[], true>;\n\n/**\n * A user including sensitive fields that should only be used on the server, never sent to the client\n * (such as sensitive information and serverMetadata).\n */\nexport type ServerUser = ServerBaseUser & BaseUser & UserExtra & Customer<true>;\n\nexport type CurrentServerUser = Auth & ServerUser;\n\nexport type CurrentInternalServerUser = CurrentServerUser & InternalUserExtra;\n\nexport type ProjectCurrentServerUser<ProjectId> = ProjectId extends \"internal\" ? CurrentInternalServerUser : CurrentServerUser;\n\nexport type SyncedPartialServerUser = SyncedPartialUser & Pick<\n ServerUser,\n | \"serverMetadata\"\n>;\n\nexport type ServerUserUpdateOptions = {\n primaryEmail?: string | null,\n primaryEmailVerified?: boolean,\n primaryEmailAuthEnabled?: boolean,\n clientReadOnlyMetadata?: ReadonlyJson,\n serverMetadata?: ReadonlyJson,\n password?: string,\n} & UserUpdateOptions;\nexport function serverUserUpdateOptionsToCrud(options: ServerUserUpdateOptions): CurrentUserCrud[\"Server\"][\"Update\"] {\n return {\n display_name: options.displayName,\n primary_email: options.primaryEmail,\n client_metadata: options.clientMetadata,\n client_read_only_metadata: options.clientReadOnlyMetadata,\n server_metadata: options.serverMetadata,\n selected_team_id: options.selectedTeamId,\n primary_email_auth_enabled: options.primaryEmailAuthEnabled,\n primary_email_verified: options.primaryEmailVerified,\n password: options.password,\n profile_image_url: options.profileImageUrl,\n totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,\n };\n}\n\n\nexport type ServerUserCreateOptions = {\n primaryEmail?: string | null,\n primaryEmailAuthEnabled?: boolean,\n password?: string,\n otpAuthEnabled?: boolean,\n displayName?: string,\n primaryEmailVerified?: boolean,\n clientMetadata?: any,\n clientReadOnlyMetadata?: any,\n serverMetadata?: any,\n}\nexport function serverUserCreateOptionsToCrud(options: ServerUserCreateOptions): UsersCrud[\"Server\"][\"Create\"] {\n return {\n primary_email: options.primaryEmail,\n password: options.password,\n otp_auth_enabled: options.otpAuthEnabled,\n primary_email_auth_enabled: options.primaryEmailAuthEnabled,\n display_name: options.displayName,\n primary_email_verified: options.primaryEmailVerified,\n client_metadata: options.clientMetadata,\n client_read_only_metadata: options.clientReadOnlyMetadata,\n server_metadata: options.serverMetadata,\n };\n}\n"],"mappings":";AAQA,SAAS,oBAAoB;AAe7B,IAAM,yBAAyB;AAExB,SAAS,2BAA2B,QAAsB;AAC/D,QAAM,aAAa,OAAO,yBAAyB,QAAQ,MAAM;AACjE,MAAI,YAAY,QAAQ,aAAa;AACnC;AAAA,EACF;AAEA,SAAO,eAAe,QAAQ,QAAQ;AAAA,IACpC,KAAK;AAAA,IACL,cAAc;AAAA,IACd,YAAY;AAAA,EACd,CAAC;AACH;AAEA,SAAS,cAAqB;AAC5B,QAAM,IAAI,MAAM,sBAAsB;AACxC;AAiSO,SAAS,wBAAwB,SAAiE;AACvG,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,iBAAiB,QAAQ;AAAA,IACzB,kBAAkB,QAAQ;AAAA,IAC1B,oBAAoB,QAAQ,yBAAyB,OAAO,aAAa,QAAQ,qBAAqB,IAAI,QAAQ;AAAA,IAClH,mBAAmB,QAAQ;AAAA,IAC3B,kBAAkB,QAAQ;AAAA,IAC1B,sBAAsB,QAAQ;AAAA,EAChC;AACF;AA0EO,SAAS,8BAA8B,SAAuE;AACnH,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,eAAe,QAAQ;AAAA,IACvB,iBAAiB,QAAQ;AAAA,IACzB,2BAA2B,QAAQ;AAAA,IACnC,iBAAiB,QAAQ;AAAA,IACzB,kBAAkB,QAAQ;AAAA,IAC1B,4BAA4B,QAAQ;AAAA,IACpC,wBAAwB,QAAQ;AAAA,IAChC,UAAU,QAAQ;AAAA,IAClB,mBAAmB,QAAQ;AAAA,IAC3B,oBAAoB,QAAQ,yBAAyB,OAAO,aAAa,QAAQ,qBAAqB,IAAI,QAAQ;AAAA,EACpH;AACF;AAcO,SAAS,8BAA8B,SAAiE;AAC7G,SAAO;AAAA,IACL,eAAe,QAAQ;AAAA,IACvB,UAAU,QAAQ;AAAA,IAClB,kBAAkB,QAAQ;AAAA,IAC1B,4BAA4B,QAAQ;AAAA,IACpC,cAAc,QAAQ;AAAA,IACtB,wBAAwB,QAAQ;AAAA,IAChC,iBAAiB,QAAQ;AAAA,IACzB,2BAA2B,QAAQ;AAAA,IACnC,iBAAiB,QAAQ;AAAA,EAC3B;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/lib/stack-app/users/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { KnownErrors } from \"@stackframe/stack-shared\";\nimport { CurrentUserCrud } from \"@stackframe/stack-shared/dist/interface/crud/current-user\";\nimport { UsersCrud } from \"@stackframe/stack-shared/dist/interface/crud/users\";\nimport { InternalSession } from \"@stackframe/stack-shared/dist/sessions\";\nimport { encodeBase64 } from \"@stackframe/stack-shared/dist/utils/bytes\";\nimport { GeoInfo } from \"@stackframe/stack-shared/dist/utils/geo\";\nimport { ReadonlyJson } from \"@stackframe/stack-shared/dist/utils/json\";\nimport { ProviderType } from \"@stackframe/stack-shared/dist/utils/oauth\";\nimport { Result } from \"@stackframe/stack-shared/dist/utils/results\";\nimport { ApiKeyCreationOptions, UserApiKey, UserApiKeyFirstView } from \"../api-keys\";\nimport { AsyncStoreProperty, AuthLike } from \"../common\";\nimport { OAuthConnection } from \"../connected-accounts\";\nimport { ContactChannel, ContactChannelCreateOptions, ServerContactChannel, ServerContactChannelCreateOptions } from \"../contact-channels\";\nimport { Customer } from \"../customers\";\nimport { NotificationCategory } from \"../notification-categories\";\nimport { AdminTeamPermission, TeamPermission } from \"../permissions\";\nimport { AdminOwnedProject, AdminProjectCreateOptions } from \"../projects\";\nimport { EditableTeamMemberProfile, ServerTeam, ServerTeamCreateOptions, Team, TeamCreateOptions } from \"../teams\";\n\nconst userGetterErrorMessage = \"Stack Auth: useUser() already returns the user object. Use `const user = useUser()` (or `const user = await app.getUser()`) instead of destructuring it like `const { user } = ...`.\";\n\nexport function attachUserDestructureGuard(target: object): void {\n const descriptor = Object.getOwnPropertyDescriptor(target, \"user\");\n if (descriptor?.get === guardGetter) {\n return;\n }\n\n Object.defineProperty(target, \"user\", {\n get: guardGetter,\n configurable: false,\n enumerable: false,\n });\n}\n\nfunction guardGetter(): never {\n throw new Error(userGetterErrorMessage);\n}\n\nexport type OAuthProvider = {\n readonly id: string,\n readonly type: string,\n readonly userId: string,\n readonly accountId?: string,\n readonly email?: string,\n readonly allowSignIn: boolean,\n readonly allowConnectedAccounts: boolean,\n update(data: { allowSignIn?: boolean, allowConnectedAccounts?: boolean }): Promise<Result<void,\n InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>\n >>,\n delete(): Promise<void>,\n};\n\nexport type ServerOAuthProvider = {\n readonly id: string,\n readonly type: string,\n readonly userId: string,\n readonly accountId: string,\n readonly email?: string,\n readonly allowSignIn: boolean,\n readonly allowConnectedAccounts: boolean,\n update(data: { accountId?: string, email?: string, allowSignIn?: boolean, allowConnectedAccounts?: boolean }): Promise<Result<void,\n InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>\n >>,\n delete(): Promise<void>,\n};\n\n\nexport type Session = {\n getTokens(): Promise<{ accessToken: string | null, refreshToken: string | null }>,\n};\n\n/**\n * Contains everything related to the current user session.\n */\nexport type Auth = AuthLike<{}> & {\n readonly _internalSession: InternalSession,\n readonly currentSession: Session,\n};\n\n/**\n * ```\n * +----------+-------------+-------------------+\n * | \\ | !Server | Server |\n * +----------+-------------+-------------------+\n * | !Session | User | ServerUser |\n * | Session | CurrentUser | CurrentServerUser |\n * +----------+-------------+-------------------+\n * ```\n *\n * The fields on each of these types are available iff:\n * BaseUser: true\n * Auth: Session\n * ServerBaseUser: Server\n * UserExtra: Session OR Server\n *\n * The types are defined as follows (in the typescript manner):\n * User = BaseUser\n * CurrentUser = BaseUser & Auth & UserExtra\n * ServerUser = BaseUser & ServerBaseUser & UserExtra\n * CurrentServerUser = BaseUser & ServerBaseUser & Auth & UserExtra\n **/\n\nexport type BaseUser = {\n readonly id: string,\n\n readonly displayName: string | null,\n\n /**\n * The user's email address.\n *\n * Note: This might NOT be unique across multiple users, so always use `id` for unique identification.\n */\n readonly primaryEmail: string | null,\n readonly primaryEmailVerified: boolean,\n readonly profileImageUrl: string | null,\n\n readonly signedUpAt: Date,\n\n readonly clientMetadata: any,\n readonly clientReadOnlyMetadata: any,\n\n /**\n * Whether the user has a password set.\n */\n readonly hasPassword: boolean,\n readonly otpAuthEnabled: boolean,\n readonly passkeyAuthEnabled: boolean,\n\n readonly isMultiFactorRequired: boolean,\n readonly isAnonymous: boolean,\n toClientJson(): CurrentUserCrud[\"Client\"][\"Read\"],\n\n /**\n * @deprecated, use contact channel's usedForAuth instead\n */\n readonly emailAuthEnabled: boolean,\n /**\n * @deprecated\n */\n readonly oauthProviders: readonly { id: string }[],\n}\n\nexport type UserExtra = {\n setDisplayName(displayName: string): Promise<void>,\n /** @deprecated Use contact channel's sendVerificationEmail instead */\n sendVerificationEmail(): Promise<KnownErrors[\"EmailAlreadyVerified\"] | void>,\n setClientMetadata(metadata: any): Promise<void>,\n updatePassword(options: { oldPassword: string, newPassword: string}): Promise<KnownErrors[\"PasswordConfirmationMismatch\"] | KnownErrors[\"PasswordRequirementsNotMet\"] | void>,\n setPassword(options: { password: string }): Promise<KnownErrors[\"PasswordRequirementsNotMet\"] | void>,\n\n /**\n * A shorthand method to update multiple fields of the user at once.\n */\n update(update: UserUpdateOptions): Promise<void>,\n\n listContactChannels(): Promise<ContactChannel[]>,\n createContactChannel(data: ContactChannelCreateOptions): Promise<ContactChannel>,\n\n listNotificationCategories(): Promise<NotificationCategory[]>,\n\n delete(): Promise<void>,\n\n getConnectedAccount(id: ProviderType, options: { or: 'redirect', scopes?: string[] }): Promise<OAuthConnection>,\n getConnectedAccount(id: ProviderType, options?: { or?: 'redirect' | 'throw' | 'return-null', scopes?: string[] }): Promise<OAuthConnection | null>,\n\n\n hasPermission(scope: Team, permissionId: string): Promise<boolean>,\n hasPermission(permissionId: string): Promise<boolean>,\n\n getPermission(scope: Team, permissionId: string): Promise<TeamPermission | null>,\n getPermission(permissionId: string): Promise<TeamPermission | null>,\n\n listPermissions(scope: Team, options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n listPermissions(options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n\n\n readonly selectedTeam: Team | null,\n setSelectedTeam(team: Team | null): Promise<void>,\n createTeam(data: TeamCreateOptions): Promise<Team>,\n leaveTeam(team: Team): Promise<void>,\n\n getActiveSessions(): Promise<ActiveSession[]>,\n revokeSession(sessionId: string): Promise<void>,\n getTeamProfile(team: Team): Promise<EditableTeamMemberProfile>,\n\n createApiKey(options: ApiKeyCreationOptions<\"user\">): Promise<UserApiKeyFirstView>,\n\n listOAuthProviders(): Promise<OAuthProvider[]>,\n\n getOAuthProvider(id: string): Promise<OAuthProvider | null>,\n\n registerPasskey(options?: { hostname?: string }): Promise<Result<undefined, KnownErrors[\"PasskeyRegistrationFailed\"] | KnownErrors[\"PasskeyWebAuthnError\"]>>,\n}\n& AsyncStoreProperty<\"apiKeys\", [], UserApiKey[], true>\n& AsyncStoreProperty<\"team\", [id: string], Team | null, false>\n& AsyncStoreProperty<\"teams\", [], Team[], true>\n& AsyncStoreProperty<\"permission\", [scope: Team, permissionId: string, options?: { recursive?: boolean }], TeamPermission | null, false>\n& AsyncStoreProperty<\"permissions\", [scope: Team, options?: { recursive?: boolean }], TeamPermission[], true>;\n\nexport type InternalUserExtra =\n & {\n createProject(newProject: AdminProjectCreateOptions): Promise<AdminOwnedProject>,\n transferProject(projectIdToTransfer: string, newTeamId: string): Promise<void>,\n }\n & AsyncStoreProperty<\"ownedProjects\", [], AdminOwnedProject[], true>\n\nexport type User = BaseUser;\n\nexport type CurrentUser = BaseUser & Auth & UserExtra & Customer;\n\nexport type CurrentInternalUser = CurrentUser & InternalUserExtra;\n\nexport type ProjectCurrentUser<ProjectId> = ProjectId extends \"internal\" ? CurrentInternalUser : CurrentUser;\n\nexport type TokenPartialUser = Pick<\n User,\n | \"id\"\n | \"displayName\"\n | \"primaryEmail\"\n | \"primaryEmailVerified\"\n | \"isAnonymous\"\n>\n\nexport type SyncedPartialUser = TokenPartialUser & Pick<\n User,\n | \"id\"\n | \"displayName\"\n | \"primaryEmail\"\n | \"primaryEmailVerified\"\n | \"profileImageUrl\"\n | \"signedUpAt\"\n | \"clientMetadata\"\n | \"clientReadOnlyMetadata\"\n | \"isAnonymous\"\n | \"hasPassword\"\n>;\n\n\nexport type ActiveSession = {\n id: string,\n userId: string,\n createdAt: Date,\n isImpersonation: boolean,\n lastUsedAt: Date | undefined,\n isCurrentSession: boolean,\n geoInfo?: GeoInfo,\n};\n\nexport type UserUpdateOptions = {\n displayName?: string,\n clientMetadata?: ReadonlyJson,\n selectedTeamId?: string | null,\n totpMultiFactorSecret?: Uint8Array | null,\n profileImageUrl?: string | null,\n otpAuthEnabled?: boolean,\n passkeyAuthEnabled?:boolean,\n}\nexport function userUpdateOptionsToCrud(options: UserUpdateOptions): CurrentUserCrud[\"Client\"][\"Update\"] {\n return {\n display_name: options.displayName,\n client_metadata: options.clientMetadata,\n selected_team_id: options.selectedTeamId,\n totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,\n profile_image_url: options.profileImageUrl,\n otp_auth_enabled: options.otpAuthEnabled,\n passkey_auth_enabled: options.passkeyAuthEnabled,\n };\n}\n\n\nexport type ServerBaseUser = {\n setPrimaryEmail(email: string | null, options?: { verified?: boolean | undefined }): Promise<void>,\n\n readonly lastActiveAt: Date,\n\n readonly serverMetadata: any,\n setServerMetadata(metadata: any): Promise<void>,\n setClientReadOnlyMetadata(metadata: any): Promise<void>,\n\n createTeam(data: Omit<ServerTeamCreateOptions, \"creatorUserId\">): Promise<ServerTeam>,\n\n listContactChannels(): Promise<ServerContactChannel[]>,\n createContactChannel(data: ServerContactChannelCreateOptions): Promise<ServerContactChannel>,\n\n update(user: ServerUserUpdateOptions): Promise<void>,\n\n grantPermission(scope: Team, permissionId: string): Promise<void>,\n grantPermission(permissionId: string): Promise<void>,\n\n revokePermission(scope: Team, permissionId: string): Promise<void>,\n revokePermission(permissionId: string): Promise<void>,\n\n getPermission(scope: Team, permissionId: string): Promise<TeamPermission | null>,\n getPermission(permissionId: string): Promise<TeamPermission | null>,\n\n hasPermission(scope: Team, permissionId: string): Promise<boolean>,\n hasPermission(permissionId: string): Promise<boolean>,\n\n listPermissions(scope: Team, options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n listPermissions(options?: { recursive?: boolean }): Promise<TeamPermission[]>,\n\n\n listOAuthProviders(): Promise<ServerOAuthProvider[]>,\n\n getOAuthProvider(id: string): Promise<ServerOAuthProvider | null>,\n\n /**\n * Creates a new session object with a refresh token for this user. Can be used to impersonate them.\n */\n createSession(options?: { expiresInMillis?: number, isImpersonation?: boolean }): Promise<Session>,\n}\n& AsyncStoreProperty<\"team\", [id: string], ServerTeam | null, false>\n& AsyncStoreProperty<\"teams\", [], ServerTeam[], true>\n& AsyncStoreProperty<\"permission\", [scope: Team, permissionId: string, options?: { direct?: boolean }], AdminTeamPermission | null, false>\n& AsyncStoreProperty<\"permissions\", [scope: Team, options?: { direct?: boolean }], AdminTeamPermission[], true>;\n\n/**\n * A user including sensitive fields that should only be used on the server, never sent to the client\n * (such as sensitive information and serverMetadata).\n */\nexport type ServerUser = ServerBaseUser & BaseUser & UserExtra & Customer<true>;\n\nexport type CurrentServerUser = Auth & ServerUser;\n\nexport type CurrentInternalServerUser = CurrentServerUser & InternalUserExtra;\n\nexport type ProjectCurrentServerUser<ProjectId> = ProjectId extends \"internal\" ? CurrentInternalServerUser : CurrentServerUser;\n\nexport type SyncedPartialServerUser = SyncedPartialUser & Pick<\n ServerUser,\n | \"serverMetadata\"\n>;\n\nexport type ServerUserUpdateOptions = {\n primaryEmail?: string | null,\n primaryEmailVerified?: boolean,\n primaryEmailAuthEnabled?: boolean,\n clientReadOnlyMetadata?: ReadonlyJson,\n serverMetadata?: ReadonlyJson,\n password?: string,\n} & UserUpdateOptions;\nexport function serverUserUpdateOptionsToCrud(options: ServerUserUpdateOptions): CurrentUserCrud[\"Server\"][\"Update\"] {\n return {\n display_name: options.displayName,\n primary_email: options.primaryEmail,\n client_metadata: options.clientMetadata,\n client_read_only_metadata: options.clientReadOnlyMetadata,\n server_metadata: options.serverMetadata,\n selected_team_id: options.selectedTeamId,\n primary_email_auth_enabled: options.primaryEmailAuthEnabled,\n primary_email_verified: options.primaryEmailVerified,\n password: options.password,\n profile_image_url: options.profileImageUrl,\n totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,\n };\n}\n\n\nexport type ServerUserCreateOptions = {\n primaryEmail?: string | null,\n primaryEmailAuthEnabled?: boolean,\n password?: string,\n otpAuthEnabled?: boolean,\n displayName?: string,\n primaryEmailVerified?: boolean,\n clientMetadata?: any,\n clientReadOnlyMetadata?: any,\n serverMetadata?: any,\n}\nexport function serverUserCreateOptionsToCrud(options: ServerUserCreateOptions): UsersCrud[\"Server\"][\"Create\"] {\n return {\n primary_email: options.primaryEmail,\n password: options.password,\n otp_auth_enabled: options.otpAuthEnabled,\n primary_email_auth_enabled: options.primaryEmailAuthEnabled,\n display_name: options.displayName,\n primary_email_verified: options.primaryEmailVerified,\n client_metadata: options.clientMetadata,\n client_read_only_metadata: options.clientReadOnlyMetadata,\n server_metadata: options.serverMetadata,\n };\n}\n"],"mappings":";AAQA,SAAS,oBAAoB;AAe7B,IAAM,yBAAyB;AAExB,SAAS,2BAA2B,QAAsB;AAC/D,QAAM,aAAa,OAAO,yBAAyB,QAAQ,MAAM;AACjE,MAAI,YAAY,QAAQ,aAAa;AACnC;AAAA,EACF;AAEA,SAAO,eAAe,QAAQ,QAAQ;AAAA,IACpC,KAAK;AAAA,IACL,cAAc;AAAA,IACd,YAAY;AAAA,EACd,CAAC;AACH;AAEA,SAAS,cAAqB;AAC5B,QAAM,IAAI,MAAM,sBAAsB;AACxC;AA6NO,SAAS,wBAAwB,SAAiE;AACvG,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,iBAAiB,QAAQ;AAAA,IACzB,kBAAkB,QAAQ;AAAA,IAC1B,oBAAoB,QAAQ,yBAAyB,OAAO,aAAa,QAAQ,qBAAqB,IAAI,QAAQ;AAAA,IAClH,mBAAmB,QAAQ;AAAA,IAC3B,kBAAkB,QAAQ;AAAA,IAC1B,sBAAsB,QAAQ;AAAA,EAChC;AACF;AA0EO,SAAS,8BAA8B,SAAuE;AACnH,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,eAAe,QAAQ;AAAA,IACvB,iBAAiB,QAAQ;AAAA,IACzB,2BAA2B,QAAQ;AAAA,IACnC,iBAAiB,QAAQ;AAAA,IACzB,kBAAkB,QAAQ;AAAA,IAC1B,4BAA4B,QAAQ;AAAA,IACpC,wBAAwB,QAAQ;AAAA,IAChC,UAAU,QAAQ;AAAA,IAClB,mBAAmB,QAAQ;AAAA,IAC3B,oBAAoB,QAAQ,yBAAyB,OAAO,aAAa,QAAQ,qBAAqB,IAAI,QAAQ;AAAA,EACpH;AACF;AAcO,SAAS,8BAA8B,SAAiE;AAC7G,SAAO;AAAA,IACL,eAAe,QAAQ;AAAA,IACvB,UAAU,QAAQ;AAAA,IAClB,kBAAkB,QAAQ;AAAA,IAC1B,4BAA4B,QAAQ;AAAA,IACpC,cAAc,QAAQ;AAAA,IACtB,wBAAwB,QAAQ;AAAA,IAChC,iBAAiB,QAAQ;AAAA,IACzB,2BAA2B,QAAQ;AAAA,IACnC,iBAAiB,QAAQ;AAAA,EAC3B;AACF;","names":[]}
|
package/dist/index.d.mts
CHANGED
|
@@ -87,6 +87,89 @@ type HandlerUrls = {
|
|
|
87
87
|
type OAuthScopesOnSignIn = {
|
|
88
88
|
[key in ProviderType]: string[];
|
|
89
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* Contains the authentication methods without session-related fields.
|
|
92
|
+
* Used for apps that have token storage capabilities.
|
|
93
|
+
*/
|
|
94
|
+
type AuthLike<ExtraOptions = {}> = {
|
|
95
|
+
signOut(options?: {
|
|
96
|
+
redirectUrl?: URL | string;
|
|
97
|
+
} & ExtraOptions): Promise<void>;
|
|
98
|
+
signOut(options?: {
|
|
99
|
+
redirectUrl?: URL | string;
|
|
100
|
+
}): Promise<void>;
|
|
101
|
+
/**
|
|
102
|
+
* Returns headers for sending authenticated HTTP requests to external servers. Most commonly used in cross-origin
|
|
103
|
+
* requests. Similar to `getAuthJson`, but specifically for HTTP requests.
|
|
104
|
+
*
|
|
105
|
+
* If you are using `tokenStore: "cookie"`, you don't need this for same-origin requests. However, most
|
|
106
|
+
* browsers now disable third-party cookies by default, so we must pass authentication tokens by header instead
|
|
107
|
+
* if the client and server are on different origins.
|
|
108
|
+
*
|
|
109
|
+
* This function returns a header object that can be used with `fetch` or other HTTP request libraries to send
|
|
110
|
+
* authenticated requests.
|
|
111
|
+
*
|
|
112
|
+
* On the server, you can then pass in the `Request` object to the `tokenStore` option
|
|
113
|
+
* of your Stack app. Please note that CORS does not allow most headers by default, so you
|
|
114
|
+
* must include `x-stack-auth` in the [`Access-Control-Allow-Headers` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers)
|
|
115
|
+
* of the CORS preflight response.
|
|
116
|
+
*
|
|
117
|
+
* If you are not using HTTP (and hence cannot set headers), you will need to use the `getAuthJson()` function
|
|
118
|
+
* instead.
|
|
119
|
+
*
|
|
120
|
+
* Example:
|
|
121
|
+
*
|
|
122
|
+
* ```ts
|
|
123
|
+
* // client
|
|
124
|
+
* const res = await fetch("https://api.example.com", {
|
|
125
|
+
* headers: {
|
|
126
|
+
* ...await stackApp.getAuthHeaders()
|
|
127
|
+
* // you can also add your own headers here
|
|
128
|
+
* },
|
|
129
|
+
* });
|
|
130
|
+
*
|
|
131
|
+
* // server
|
|
132
|
+
* function handleRequest(req: Request) {
|
|
133
|
+
* const user = await stackServerApp.getUser({ tokenStore: req });
|
|
134
|
+
* return new Response("Welcome, " + user.displayName);
|
|
135
|
+
* }
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
getAuthHeaders(options?: {} & ExtraOptions): Promise<{
|
|
139
|
+
"x-stack-auth": string;
|
|
140
|
+
}>;
|
|
141
|
+
/**
|
|
142
|
+
* Creates a JSON-serializable object containing the information to authenticate a user on an external server.
|
|
143
|
+
* Similar to `getAuthHeaders`, but returns an object that can be sent over any protocol instead of just
|
|
144
|
+
* HTTP headers.
|
|
145
|
+
*
|
|
146
|
+
* While `getAuthHeaders` is the recommended way to send authentication tokens over HTTP, your app may use
|
|
147
|
+
* a different protocol, for example WebSockets or gRPC. This function returns a token object that can be JSON-serialized and sent to the server in any way you like.
|
|
148
|
+
*
|
|
149
|
+
* On the server, you can pass in this token object into the `tokenStore` option to fetch user details.
|
|
150
|
+
*
|
|
151
|
+
* Example:
|
|
152
|
+
*
|
|
153
|
+
* ```ts
|
|
154
|
+
* // client
|
|
155
|
+
* const res = await rpcCall(rpcEndpoint, {
|
|
156
|
+
* data: {
|
|
157
|
+
* auth: await stackApp.getAuthJson(),
|
|
158
|
+
* },
|
|
159
|
+
* });
|
|
160
|
+
*
|
|
161
|
+
* // server
|
|
162
|
+
* function handleRequest(data) {
|
|
163
|
+
* const user = await stackServerApp.getUser({ tokenStore: data.auth });
|
|
164
|
+
* return new Response("Welcome, " + user.displayName);
|
|
165
|
+
* }
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
getAuthJson(options?: {} & ExtraOptions): Promise<{
|
|
169
|
+
accessToken: string | null;
|
|
170
|
+
refreshToken: string | null;
|
|
171
|
+
}>;
|
|
172
|
+
};
|
|
90
173
|
/** @internal */
|
|
91
174
|
declare const stackAppInternalsSymbol: unique symbol;
|
|
92
175
|
|
|
@@ -402,86 +485,9 @@ type Session = {
|
|
|
402
485
|
/**
|
|
403
486
|
* Contains everything related to the current user session.
|
|
404
487
|
*/
|
|
405
|
-
type Auth = {
|
|
488
|
+
type Auth = AuthLike<{}> & {
|
|
406
489
|
readonly _internalSession: InternalSession;
|
|
407
490
|
readonly currentSession: Session;
|
|
408
|
-
signOut(options?: {
|
|
409
|
-
redirectUrl?: URL | string;
|
|
410
|
-
}): Promise<void>;
|
|
411
|
-
/**
|
|
412
|
-
* Returns headers for sending authenticated HTTP requests to external servers. Most commonly used in cross-origin
|
|
413
|
-
* requests. Similar to `getAuthJson`, but specifically for HTTP requests.
|
|
414
|
-
*
|
|
415
|
-
* If you are using `tokenStore: "cookie"`, you don't need this for same-origin requests. However, most
|
|
416
|
-
* browsers now disable third-party cookies by default, so we must pass authentication tokens by header instead
|
|
417
|
-
* if the client and server are on different origins.
|
|
418
|
-
*
|
|
419
|
-
* This function returns a header object that can be used with `fetch` or other HTTP request libraries to send
|
|
420
|
-
* authenticated requests.
|
|
421
|
-
*
|
|
422
|
-
* On the server, you can then pass in the `Request` object to the `tokenStore` option
|
|
423
|
-
* of your Stack app. Please note that CORS does not allow most headers by default, so you
|
|
424
|
-
* must include `x-stack-auth` in the [`Access-Control-Allow-Headers` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers)
|
|
425
|
-
* of the CORS preflight response.
|
|
426
|
-
*
|
|
427
|
-
* If you are not using HTTP (and hence cannot set headers), you will need to use the `getAuthJson()` function
|
|
428
|
-
* instead.
|
|
429
|
-
*
|
|
430
|
-
* Example:
|
|
431
|
-
*
|
|
432
|
-
* ```ts
|
|
433
|
-
* // client
|
|
434
|
-
* const res = await fetch("https://api.example.com", {
|
|
435
|
-
* headers: {
|
|
436
|
-
* ...await stackApp.getAuthHeaders()
|
|
437
|
-
* // you can also add your own headers here
|
|
438
|
-
* },
|
|
439
|
-
* });
|
|
440
|
-
*
|
|
441
|
-
* // server
|
|
442
|
-
* function handleRequest(req: Request) {
|
|
443
|
-
* const user = await stackServerApp.getUser({ tokenStore: req });
|
|
444
|
-
* return new Response("Welcome, " + user.displayName);
|
|
445
|
-
* }
|
|
446
|
-
* ```
|
|
447
|
-
*/
|
|
448
|
-
getAuthHeaders(): Promise<{
|
|
449
|
-
"x-stack-auth": string;
|
|
450
|
-
}>;
|
|
451
|
-
/**
|
|
452
|
-
* Creates a JSON-serializable object containing the information to authenticate a user on an external server.
|
|
453
|
-
* Similar to `getAuthHeaders`, but returns an object that can be sent over any protocol instead of just
|
|
454
|
-
* HTTP headers.
|
|
455
|
-
*
|
|
456
|
-
* While `getAuthHeaders` is the recommended way to send authentication tokens over HTTP, your app may use
|
|
457
|
-
* a different protocol, for example WebSockets or gRPC. This function returns a token object that can be JSON-serialized and sent to the server in any way you like.
|
|
458
|
-
*
|
|
459
|
-
* On the server, you can pass in this token object into the `tokenStore` option to fetch user details.
|
|
460
|
-
*
|
|
461
|
-
* Example:
|
|
462
|
-
*
|
|
463
|
-
* ```ts
|
|
464
|
-
* // client
|
|
465
|
-
* const res = await rpcCall(rpcEndpoint, {
|
|
466
|
-
* data: {
|
|
467
|
-
* auth: await stackApp.getAuthJson(),
|
|
468
|
-
* },
|
|
469
|
-
* });
|
|
470
|
-
*
|
|
471
|
-
* // server
|
|
472
|
-
* function handleRequest(data) {
|
|
473
|
-
* const user = await stackServerApp.getUser({ tokenStore: data.auth });
|
|
474
|
-
* return new Response("Welcome, " + user.displayName);
|
|
475
|
-
* }
|
|
476
|
-
* ```
|
|
477
|
-
*/
|
|
478
|
-
getAuthJson(): Promise<{
|
|
479
|
-
accessToken: string | null;
|
|
480
|
-
refreshToken: string | null;
|
|
481
|
-
}>;
|
|
482
|
-
registerPasskey(options?: {
|
|
483
|
-
hostname?: string;
|
|
484
|
-
}): Promise<Result<undefined, KnownErrors["PasskeyRegistrationFailed"] | KnownErrors["PasskeyWebAuthnError"]>>;
|
|
485
491
|
};
|
|
486
492
|
/**
|
|
487
493
|
* ```
|
|
@@ -587,6 +593,9 @@ type UserExtra = {
|
|
|
587
593
|
createApiKey(options: ApiKeyCreationOptions<"user">): Promise<UserApiKeyFirstView>;
|
|
588
594
|
listOAuthProviders(): Promise<OAuthProvider[]>;
|
|
589
595
|
getOAuthProvider(id: string): Promise<OAuthProvider | null>;
|
|
596
|
+
registerPasskey(options?: {
|
|
597
|
+
hostname?: string;
|
|
598
|
+
}): Promise<Result<undefined, KnownErrors["PasskeyRegistrationFailed"] | KnownErrors["PasskeyWebAuthnError"]>>;
|
|
590
599
|
} & AsyncStoreProperty<"apiKeys", [], UserApiKey[], true> & AsyncStoreProperty<"team", [id: string], Team | null, false> & AsyncStoreProperty<"teams", [], Team[], true> & AsyncStoreProperty<"permission", [scope: Team, permissionId: string, options?: {
|
|
591
600
|
recursive?: boolean;
|
|
592
601
|
}], TeamPermission | null, false> & AsyncStoreProperty<"permissions", [scope: Team, options?: {
|
|
@@ -1247,7 +1256,11 @@ type StackClientApp<HasTokenStore extends boolean = boolean, ProjectId extends s
|
|
|
1247
1256
|
options: CustomerProductsRequestOptions
|
|
1248
1257
|
], CustomerProductsList, true> & {
|
|
1249
1258
|
[K in `redirectTo${Capitalize<keyof Omit<HandlerUrls, 'handler' | 'oauthCallback'>>}`]: (options?: RedirectToOptions) => Promise<void>;
|
|
1250
|
-
}
|
|
1259
|
+
} & AuthLike<HasTokenStore extends false ? {
|
|
1260
|
+
tokenStore: TokenStoreInit;
|
|
1261
|
+
} : {
|
|
1262
|
+
tokenStore?: TokenStoreInit;
|
|
1263
|
+
}>);
|
|
1251
1264
|
declare const StackClientApp: StackClientAppConstructor;
|
|
1252
1265
|
|
|
1253
1266
|
declare function getConvexProvidersConfig(options: {
|
package/dist/index.d.ts
CHANGED
|
@@ -87,6 +87,89 @@ type HandlerUrls = {
|
|
|
87
87
|
type OAuthScopesOnSignIn = {
|
|
88
88
|
[key in ProviderType]: string[];
|
|
89
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* Contains the authentication methods without session-related fields.
|
|
92
|
+
* Used for apps that have token storage capabilities.
|
|
93
|
+
*/
|
|
94
|
+
type AuthLike<ExtraOptions = {}> = {
|
|
95
|
+
signOut(options?: {
|
|
96
|
+
redirectUrl?: URL | string;
|
|
97
|
+
} & ExtraOptions): Promise<void>;
|
|
98
|
+
signOut(options?: {
|
|
99
|
+
redirectUrl?: URL | string;
|
|
100
|
+
}): Promise<void>;
|
|
101
|
+
/**
|
|
102
|
+
* Returns headers for sending authenticated HTTP requests to external servers. Most commonly used in cross-origin
|
|
103
|
+
* requests. Similar to `getAuthJson`, but specifically for HTTP requests.
|
|
104
|
+
*
|
|
105
|
+
* If you are using `tokenStore: "cookie"`, you don't need this for same-origin requests. However, most
|
|
106
|
+
* browsers now disable third-party cookies by default, so we must pass authentication tokens by header instead
|
|
107
|
+
* if the client and server are on different origins.
|
|
108
|
+
*
|
|
109
|
+
* This function returns a header object that can be used with `fetch` or other HTTP request libraries to send
|
|
110
|
+
* authenticated requests.
|
|
111
|
+
*
|
|
112
|
+
* On the server, you can then pass in the `Request` object to the `tokenStore` option
|
|
113
|
+
* of your Stack app. Please note that CORS does not allow most headers by default, so you
|
|
114
|
+
* must include `x-stack-auth` in the [`Access-Control-Allow-Headers` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers)
|
|
115
|
+
* of the CORS preflight response.
|
|
116
|
+
*
|
|
117
|
+
* If you are not using HTTP (and hence cannot set headers), you will need to use the `getAuthJson()` function
|
|
118
|
+
* instead.
|
|
119
|
+
*
|
|
120
|
+
* Example:
|
|
121
|
+
*
|
|
122
|
+
* ```ts
|
|
123
|
+
* // client
|
|
124
|
+
* const res = await fetch("https://api.example.com", {
|
|
125
|
+
* headers: {
|
|
126
|
+
* ...await stackApp.getAuthHeaders()
|
|
127
|
+
* // you can also add your own headers here
|
|
128
|
+
* },
|
|
129
|
+
* });
|
|
130
|
+
*
|
|
131
|
+
* // server
|
|
132
|
+
* function handleRequest(req: Request) {
|
|
133
|
+
* const user = await stackServerApp.getUser({ tokenStore: req });
|
|
134
|
+
* return new Response("Welcome, " + user.displayName);
|
|
135
|
+
* }
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
getAuthHeaders(options?: {} & ExtraOptions): Promise<{
|
|
139
|
+
"x-stack-auth": string;
|
|
140
|
+
}>;
|
|
141
|
+
/**
|
|
142
|
+
* Creates a JSON-serializable object containing the information to authenticate a user on an external server.
|
|
143
|
+
* Similar to `getAuthHeaders`, but returns an object that can be sent over any protocol instead of just
|
|
144
|
+
* HTTP headers.
|
|
145
|
+
*
|
|
146
|
+
* While `getAuthHeaders` is the recommended way to send authentication tokens over HTTP, your app may use
|
|
147
|
+
* a different protocol, for example WebSockets or gRPC. This function returns a token object that can be JSON-serialized and sent to the server in any way you like.
|
|
148
|
+
*
|
|
149
|
+
* On the server, you can pass in this token object into the `tokenStore` option to fetch user details.
|
|
150
|
+
*
|
|
151
|
+
* Example:
|
|
152
|
+
*
|
|
153
|
+
* ```ts
|
|
154
|
+
* // client
|
|
155
|
+
* const res = await rpcCall(rpcEndpoint, {
|
|
156
|
+
* data: {
|
|
157
|
+
* auth: await stackApp.getAuthJson(),
|
|
158
|
+
* },
|
|
159
|
+
* });
|
|
160
|
+
*
|
|
161
|
+
* // server
|
|
162
|
+
* function handleRequest(data) {
|
|
163
|
+
* const user = await stackServerApp.getUser({ tokenStore: data.auth });
|
|
164
|
+
* return new Response("Welcome, " + user.displayName);
|
|
165
|
+
* }
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
getAuthJson(options?: {} & ExtraOptions): Promise<{
|
|
169
|
+
accessToken: string | null;
|
|
170
|
+
refreshToken: string | null;
|
|
171
|
+
}>;
|
|
172
|
+
};
|
|
90
173
|
/** @internal */
|
|
91
174
|
declare const stackAppInternalsSymbol: unique symbol;
|
|
92
175
|
|
|
@@ -402,86 +485,9 @@ type Session = {
|
|
|
402
485
|
/**
|
|
403
486
|
* Contains everything related to the current user session.
|
|
404
487
|
*/
|
|
405
|
-
type Auth = {
|
|
488
|
+
type Auth = AuthLike<{}> & {
|
|
406
489
|
readonly _internalSession: InternalSession;
|
|
407
490
|
readonly currentSession: Session;
|
|
408
|
-
signOut(options?: {
|
|
409
|
-
redirectUrl?: URL | string;
|
|
410
|
-
}): Promise<void>;
|
|
411
|
-
/**
|
|
412
|
-
* Returns headers for sending authenticated HTTP requests to external servers. Most commonly used in cross-origin
|
|
413
|
-
* requests. Similar to `getAuthJson`, but specifically for HTTP requests.
|
|
414
|
-
*
|
|
415
|
-
* If you are using `tokenStore: "cookie"`, you don't need this for same-origin requests. However, most
|
|
416
|
-
* browsers now disable third-party cookies by default, so we must pass authentication tokens by header instead
|
|
417
|
-
* if the client and server are on different origins.
|
|
418
|
-
*
|
|
419
|
-
* This function returns a header object that can be used with `fetch` or other HTTP request libraries to send
|
|
420
|
-
* authenticated requests.
|
|
421
|
-
*
|
|
422
|
-
* On the server, you can then pass in the `Request` object to the `tokenStore` option
|
|
423
|
-
* of your Stack app. Please note that CORS does not allow most headers by default, so you
|
|
424
|
-
* must include `x-stack-auth` in the [`Access-Control-Allow-Headers` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers)
|
|
425
|
-
* of the CORS preflight response.
|
|
426
|
-
*
|
|
427
|
-
* If you are not using HTTP (and hence cannot set headers), you will need to use the `getAuthJson()` function
|
|
428
|
-
* instead.
|
|
429
|
-
*
|
|
430
|
-
* Example:
|
|
431
|
-
*
|
|
432
|
-
* ```ts
|
|
433
|
-
* // client
|
|
434
|
-
* const res = await fetch("https://api.example.com", {
|
|
435
|
-
* headers: {
|
|
436
|
-
* ...await stackApp.getAuthHeaders()
|
|
437
|
-
* // you can also add your own headers here
|
|
438
|
-
* },
|
|
439
|
-
* });
|
|
440
|
-
*
|
|
441
|
-
* // server
|
|
442
|
-
* function handleRequest(req: Request) {
|
|
443
|
-
* const user = await stackServerApp.getUser({ tokenStore: req });
|
|
444
|
-
* return new Response("Welcome, " + user.displayName);
|
|
445
|
-
* }
|
|
446
|
-
* ```
|
|
447
|
-
*/
|
|
448
|
-
getAuthHeaders(): Promise<{
|
|
449
|
-
"x-stack-auth": string;
|
|
450
|
-
}>;
|
|
451
|
-
/**
|
|
452
|
-
* Creates a JSON-serializable object containing the information to authenticate a user on an external server.
|
|
453
|
-
* Similar to `getAuthHeaders`, but returns an object that can be sent over any protocol instead of just
|
|
454
|
-
* HTTP headers.
|
|
455
|
-
*
|
|
456
|
-
* While `getAuthHeaders` is the recommended way to send authentication tokens over HTTP, your app may use
|
|
457
|
-
* a different protocol, for example WebSockets or gRPC. This function returns a token object that can be JSON-serialized and sent to the server in any way you like.
|
|
458
|
-
*
|
|
459
|
-
* On the server, you can pass in this token object into the `tokenStore` option to fetch user details.
|
|
460
|
-
*
|
|
461
|
-
* Example:
|
|
462
|
-
*
|
|
463
|
-
* ```ts
|
|
464
|
-
* // client
|
|
465
|
-
* const res = await rpcCall(rpcEndpoint, {
|
|
466
|
-
* data: {
|
|
467
|
-
* auth: await stackApp.getAuthJson(),
|
|
468
|
-
* },
|
|
469
|
-
* });
|
|
470
|
-
*
|
|
471
|
-
* // server
|
|
472
|
-
* function handleRequest(data) {
|
|
473
|
-
* const user = await stackServerApp.getUser({ tokenStore: data.auth });
|
|
474
|
-
* return new Response("Welcome, " + user.displayName);
|
|
475
|
-
* }
|
|
476
|
-
* ```
|
|
477
|
-
*/
|
|
478
|
-
getAuthJson(): Promise<{
|
|
479
|
-
accessToken: string | null;
|
|
480
|
-
refreshToken: string | null;
|
|
481
|
-
}>;
|
|
482
|
-
registerPasskey(options?: {
|
|
483
|
-
hostname?: string;
|
|
484
|
-
}): Promise<Result<undefined, KnownErrors["PasskeyRegistrationFailed"] | KnownErrors["PasskeyWebAuthnError"]>>;
|
|
485
491
|
};
|
|
486
492
|
/**
|
|
487
493
|
* ```
|
|
@@ -587,6 +593,9 @@ type UserExtra = {
|
|
|
587
593
|
createApiKey(options: ApiKeyCreationOptions<"user">): Promise<UserApiKeyFirstView>;
|
|
588
594
|
listOAuthProviders(): Promise<OAuthProvider[]>;
|
|
589
595
|
getOAuthProvider(id: string): Promise<OAuthProvider | null>;
|
|
596
|
+
registerPasskey(options?: {
|
|
597
|
+
hostname?: string;
|
|
598
|
+
}): Promise<Result<undefined, KnownErrors["PasskeyRegistrationFailed"] | KnownErrors["PasskeyWebAuthnError"]>>;
|
|
590
599
|
} & AsyncStoreProperty<"apiKeys", [], UserApiKey[], true> & AsyncStoreProperty<"team", [id: string], Team | null, false> & AsyncStoreProperty<"teams", [], Team[], true> & AsyncStoreProperty<"permission", [scope: Team, permissionId: string, options?: {
|
|
591
600
|
recursive?: boolean;
|
|
592
601
|
}], TeamPermission | null, false> & AsyncStoreProperty<"permissions", [scope: Team, options?: {
|
|
@@ -1247,7 +1256,11 @@ type StackClientApp<HasTokenStore extends boolean = boolean, ProjectId extends s
|
|
|
1247
1256
|
options: CustomerProductsRequestOptions
|
|
1248
1257
|
], CustomerProductsList, true> & {
|
|
1249
1258
|
[K in `redirectTo${Capitalize<keyof Omit<HandlerUrls, 'handler' | 'oauthCallback'>>}`]: (options?: RedirectToOptions) => Promise<void>;
|
|
1250
|
-
}
|
|
1259
|
+
} & AuthLike<HasTokenStore extends false ? {
|
|
1260
|
+
tokenStore: TokenStoreInit;
|
|
1261
|
+
} : {
|
|
1262
|
+
tokenStore?: TokenStoreInit;
|
|
1263
|
+
}>);
|
|
1251
1264
|
declare const StackClientApp: StackClientAppConstructor;
|
|
1252
1265
|
|
|
1253
1266
|
declare function getConvexProvidersConfig(options: {
|
package/dist/lib/cookie.js
CHANGED
|
@@ -116,9 +116,9 @@ function setCookieClientInternal(name, value, options = {}) {
|
|
|
116
116
|
}
|
|
117
117
|
function deleteCookieClientInternal(name, options = {}) {
|
|
118
118
|
if (options.domain !== void 0) {
|
|
119
|
-
import_js_cookie.default.remove(name, { domain: options.domain });
|
|
119
|
+
import_js_cookie.default.remove(name, { domain: options.domain, secure: determineSecureFromClientContext() });
|
|
120
120
|
}
|
|
121
|
-
import_js_cookie.default.remove(name);
|
|
121
|
+
import_js_cookie.default.remove(name, { secure: determineSecureFromClientContext() });
|
|
122
122
|
}
|
|
123
123
|
function setOrDeleteCookieClient(name, value, options = {}) {
|
|
124
124
|
ensureClient();
|
package/dist/lib/cookie.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/lib/cookie.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { isBrowserLike } from '@stackframe/stack-shared/dist/utils/env';\nimport { StackAssertionError } from '@stackframe/stack-shared/dist/utils/errors';\nimport Cookies from \"js-cookie\";\nimport { calculatePKCECodeChallenge, generateRandomCodeVerifier, generateRandomState } from \"oauth4webapi\";\n\ntype SetCookieOptions = { maxAge?: number, noOpIfServerComponent?: boolean, domain?: string, secure?: boolean };\ntype DeleteCookieOptions = { noOpIfServerComponent?: boolean, domain?: string };\n\nfunction ensureClient() {\n if (!isBrowserLike()) {\n throw new Error(\"cookieClient functions can only be called in a browser environment, yet window is undefined\");\n }\n}\n\nexport type CookieHelper = {\n get: (name: string) => string | null,\n getAll: () => Record<string, string>,\n set: (name: string, value: string, options: SetCookieOptions) => void,\n setOrDelete: (name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) => void,\n delete: (name: string, options: DeleteCookieOptions) => void,\n};\n\nconst placeholderCookieHelperIdentity = { \"placeholder cookie helper identity\": true };\nexport async function createPlaceholderCookieHelper(): Promise<CookieHelper> {\n function throwError(): never {\n throw new StackAssertionError(\"Throwing cookie helper is just a placeholder. This should never be called\");\n }\n return {\n get: throwError,\n getAll: throwError,\n set: throwError,\n setOrDelete: throwError,\n delete: throwError,\n };\n}\n\nexport async function createCookieHelper(): Promise<CookieHelper> {\n if (isBrowserLike()) {\n return createBrowserCookieHelper();\n } else {\n return await createPlaceholderCookieHelper();\n }\n}\n\nexport function createBrowserCookieHelper(): CookieHelper {\n return {\n get: getCookieClient,\n getAll: getAllCookiesClient,\n set: setCookieClient,\n setOrDelete: setOrDeleteCookieClient,\n delete: deleteCookieClient,\n };\n}\n\nfunction handleCookieError(e: unknown, options: DeleteCookieOptions | SetCookieOptions) {\n if (e instanceof Error && e.message.includes(\"Cookies can only be modified in\")) {\n if (options.noOpIfServerComponent) {\n // ignore\n } else {\n throw new StackAssertionError(\"Attempted to set cookie in server component. Pass { noOpIfServerComponent: true } in the options of Stack's cookie functions if this is intentional and you want to ignore this error. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options\");\n }\n } else {\n throw e;\n }\n}\n\n\nexport function getCookieClient(name: string): string | null {\n const all = getAllCookiesClient();\n return all[name] ?? null;\n}\n\nexport function getAllCookiesClient(): Record<string, string> {\n ensureClient();\n // set a helper cookie, see comment in `NextCookieHelper.set` above\n Cookies.set(\"stack-is-https\", \"true\", { secure: true });\n return Cookies.get();\n}\n\nexport async function getCookie(name: string): Promise<string | null> {\n const cookieHelper = await createCookieHelper();\n return cookieHelper.get(name);\n}\n\nexport async function isSecure(): Promise<boolean> {\n if (isBrowserLike()) {\n return determineSecureFromClientContext();\n }\n return false;\n}\n\nfunction determineSecureFromClientContext(): boolean {\n return typeof window !== \"undefined\" && window.location.protocol === \"https:\";\n}\n\nfunction setCookieClientInternal(name: string, value: string, options: SetCookieOptions = {}) {\n const secure = options.secure ?? determineSecureFromClientContext();\n Cookies.set(name, value, {\n expires: options.maxAge === undefined ? undefined : new Date(Date.now() + (options.maxAge) * 1000),\n domain: options.domain,\n secure,\n });\n}\n\nfunction deleteCookieClientInternal(name: string, options: DeleteCookieOptions = {}) {\n if (options.domain !== undefined) {\n Cookies.remove(name, { domain: options.domain });\n }\n Cookies.remove(name);\n}\n\nexport function setOrDeleteCookieClient(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions = {}) {\n ensureClient();\n if (value === null) {\n deleteCookieClientInternal(name, options);\n } else {\n setCookieClientInternal(name, value, options);\n }\n}\n\nexport async function setOrDeleteCookie(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions = {}) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.setOrDelete(name, value, options);\n}\n\nexport function deleteCookieClient(name: string, options: DeleteCookieOptions = {}) {\n ensureClient();\n deleteCookieClientInternal(name, options);\n}\n\nexport async function deleteCookie(name: string, options: DeleteCookieOptions = {}) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.delete(name, options);\n}\n\nexport function setCookieClient(name: string, value: string, options: SetCookieOptions = {}) {\n ensureClient();\n setCookieClientInternal(name, value, options);\n}\n\nexport async function setCookie(name: string, value: string, options: SetCookieOptions = {}) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.set(name, value, options);\n}\n\nexport async function saveVerifierAndState() {\n const codeVerifier = generateRandomCodeVerifier();\n const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);\n const state = generateRandomState();\n\n await setCookie(\"stack-oauth-outer-\" + state, codeVerifier, { maxAge: 60 * 60 });\n\n return {\n codeChallenge,\n state,\n };\n}\n\nexport function consumeVerifierAndStateCookie(state: string) {\n ensureClient();\n const cookieName = \"stack-oauth-outer-\" + state;\n const codeVerifier = getCookieClient(cookieName);\n if (!codeVerifier) {\n return null;\n }\n deleteCookieClient(cookieName);\n return {\n codeVerifier,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,iBAA8B;AAC9B,oBAAoC;AACpC,uBAAoB;AACpB,0BAA4F;AAK5F,SAAS,eAAe;AACtB,MAAI,KAAC,0BAAc,GAAG;AACpB,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACF;AAWA,eAAsB,gCAAuD;AAC3E,WAAS,aAAoB;AAC3B,UAAM,IAAI,kCAAoB,2EAA2E;AAAA,EAC3G;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAEA,eAAsB,qBAA4C;AAChE,UAAI,0BAAc,GAAG;AACnB,WAAO,0BAA0B;AAAA,EACnC,OAAO;AACL,WAAO,MAAM,8BAA8B;AAAA,EAC7C;AACF;AAEO,SAAS,4BAA0C;AACxD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAeO,SAAS,gBAAgB,MAA6B;AAC3D,QAAM,MAAM,oBAAoB;AAChC,SAAO,IAAI,IAAI,KAAK;AACtB;AAEO,SAAS,sBAA8C;AAC5D,eAAa;AAEb,mBAAAA,QAAQ,IAAI,kBAAkB,QAAQ,EAAE,QAAQ,KAAK,CAAC;AACtD,SAAO,iBAAAA,QAAQ,IAAI;AACrB;AAEA,eAAsB,UAAU,MAAsC;AACpE,QAAM,eAAe,MAAM,mBAAmB;AAC9C,SAAO,aAAa,IAAI,IAAI;AAC9B;AAEA,eAAsB,WAA6B;AACjD,UAAI,0BAAc,GAAG;AACnB,WAAO,iCAAiC;AAAA,EAC1C;AACA,SAAO;AACT;AAEA,SAAS,mCAA4C;AACnD,SAAO,OAAO,WAAW,eAAe,OAAO,SAAS,aAAa;AACvE;AAEA,SAAS,wBAAwB,MAAc,OAAe,UAA4B,CAAC,GAAG;AAC5F,QAAM,SAAS,QAAQ,UAAU,iCAAiC;AAClE,mBAAAA,QAAQ,IAAI,MAAM,OAAO;AAAA,IACvB,SAAS,QAAQ,WAAW,SAAY,SAAY,IAAI,KAAK,KAAK,IAAI,IAAK,QAAQ,SAAU,GAAI;AAAA,IACjG,QAAQ,QAAQ;AAAA,IAChB;AAAA,EACF,CAAC;AACH;AAEA,SAAS,2BAA2B,MAAc,UAA+B,CAAC,GAAG;AACnF,MAAI,QAAQ,WAAW,QAAW;AAChC,qBAAAA,QAAQ,OAAO,MAAM,EAAE,QAAQ,QAAQ,
|
|
1
|
+
{"version":3,"sources":["../../src/lib/cookie.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { isBrowserLike } from '@stackframe/stack-shared/dist/utils/env';\nimport { StackAssertionError } from '@stackframe/stack-shared/dist/utils/errors';\nimport Cookies from \"js-cookie\";\nimport { calculatePKCECodeChallenge, generateRandomCodeVerifier, generateRandomState } from \"oauth4webapi\";\n\ntype SetCookieOptions = { maxAge?: number, noOpIfServerComponent?: boolean, domain?: string, secure?: boolean };\ntype DeleteCookieOptions = { noOpIfServerComponent?: boolean, domain?: string };\n\nfunction ensureClient() {\n if (!isBrowserLike()) {\n throw new Error(\"cookieClient functions can only be called in a browser environment, yet window is undefined\");\n }\n}\n\nexport type CookieHelper = {\n get: (name: string) => string | null,\n getAll: () => Record<string, string>,\n set: (name: string, value: string, options: SetCookieOptions) => void,\n setOrDelete: (name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) => void,\n delete: (name: string, options: DeleteCookieOptions) => void,\n};\n\nconst placeholderCookieHelperIdentity = { \"placeholder cookie helper identity\": true };\nexport async function createPlaceholderCookieHelper(): Promise<CookieHelper> {\n function throwError(): never {\n throw new StackAssertionError(\"Throwing cookie helper is just a placeholder. This should never be called\");\n }\n return {\n get: throwError,\n getAll: throwError,\n set: throwError,\n setOrDelete: throwError,\n delete: throwError,\n };\n}\n\nexport async function createCookieHelper(): Promise<CookieHelper> {\n if (isBrowserLike()) {\n return createBrowserCookieHelper();\n } else {\n return await createPlaceholderCookieHelper();\n }\n}\n\nexport function createBrowserCookieHelper(): CookieHelper {\n return {\n get: getCookieClient,\n getAll: getAllCookiesClient,\n set: setCookieClient,\n setOrDelete: setOrDeleteCookieClient,\n delete: deleteCookieClient,\n };\n}\n\nfunction handleCookieError(e: unknown, options: DeleteCookieOptions | SetCookieOptions) {\n if (e instanceof Error && e.message.includes(\"Cookies can only be modified in\")) {\n if (options.noOpIfServerComponent) {\n // ignore\n } else {\n throw new StackAssertionError(\"Attempted to set cookie in server component. Pass { noOpIfServerComponent: true } in the options of Stack's cookie functions if this is intentional and you want to ignore this error. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options\");\n }\n } else {\n throw e;\n }\n}\n\n\nexport function getCookieClient(name: string): string | null {\n const all = getAllCookiesClient();\n return all[name] ?? null;\n}\n\nexport function getAllCookiesClient(): Record<string, string> {\n ensureClient();\n // set a helper cookie, see comment in `NextCookieHelper.set` above\n Cookies.set(\"stack-is-https\", \"true\", { secure: true });\n return Cookies.get();\n}\n\nexport async function getCookie(name: string): Promise<string | null> {\n const cookieHelper = await createCookieHelper();\n return cookieHelper.get(name);\n}\n\nexport async function isSecure(): Promise<boolean> {\n if (isBrowserLike()) {\n return determineSecureFromClientContext();\n }\n return false;\n}\n\nfunction determineSecureFromClientContext(): boolean {\n return typeof window !== \"undefined\" && window.location.protocol === \"https:\";\n}\n\nfunction setCookieClientInternal(name: string, value: string, options: SetCookieOptions = {}) {\n const secure = options.secure ?? determineSecureFromClientContext();\n Cookies.set(name, value, {\n expires: options.maxAge === undefined ? undefined : new Date(Date.now() + (options.maxAge) * 1000),\n domain: options.domain,\n secure,\n });\n}\n\nfunction deleteCookieClientInternal(name: string, options: DeleteCookieOptions = {}) {\n if (options.domain !== undefined) {\n Cookies.remove(name, { domain: options.domain, secure: determineSecureFromClientContext() });\n }\n Cookies.remove(name, { secure: determineSecureFromClientContext() });\n}\n\nexport function setOrDeleteCookieClient(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions = {}) {\n ensureClient();\n if (value === null) {\n deleteCookieClientInternal(name, options);\n } else {\n setCookieClientInternal(name, value, options);\n }\n}\n\nexport async function setOrDeleteCookie(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions = {}) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.setOrDelete(name, value, options);\n}\n\nexport function deleteCookieClient(name: string, options: DeleteCookieOptions = {}) {\n ensureClient();\n deleteCookieClientInternal(name, options);\n}\n\nexport async function deleteCookie(name: string, options: DeleteCookieOptions = {}) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.delete(name, options);\n}\n\nexport function setCookieClient(name: string, value: string, options: SetCookieOptions = {}) {\n ensureClient();\n setCookieClientInternal(name, value, options);\n}\n\nexport async function setCookie(name: string, value: string, options: SetCookieOptions = {}) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.set(name, value, options);\n}\n\nexport async function saveVerifierAndState() {\n const codeVerifier = generateRandomCodeVerifier();\n const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);\n const state = generateRandomState();\n\n await setCookie(\"stack-oauth-outer-\" + state, codeVerifier, { maxAge: 60 * 60 });\n\n return {\n codeChallenge,\n state,\n };\n}\n\nexport function consumeVerifierAndStateCookie(state: string) {\n ensureClient();\n const cookieName = \"stack-oauth-outer-\" + state;\n const codeVerifier = getCookieClient(cookieName);\n if (!codeVerifier) {\n return null;\n }\n deleteCookieClient(cookieName);\n return {\n codeVerifier,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,iBAA8B;AAC9B,oBAAoC;AACpC,uBAAoB;AACpB,0BAA4F;AAK5F,SAAS,eAAe;AACtB,MAAI,KAAC,0BAAc,GAAG;AACpB,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACF;AAWA,eAAsB,gCAAuD;AAC3E,WAAS,aAAoB;AAC3B,UAAM,IAAI,kCAAoB,2EAA2E;AAAA,EAC3G;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAEA,eAAsB,qBAA4C;AAChE,UAAI,0BAAc,GAAG;AACnB,WAAO,0BAA0B;AAAA,EACnC,OAAO;AACL,WAAO,MAAM,8BAA8B;AAAA,EAC7C;AACF;AAEO,SAAS,4BAA0C;AACxD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAeO,SAAS,gBAAgB,MAA6B;AAC3D,QAAM,MAAM,oBAAoB;AAChC,SAAO,IAAI,IAAI,KAAK;AACtB;AAEO,SAAS,sBAA8C;AAC5D,eAAa;AAEb,mBAAAA,QAAQ,IAAI,kBAAkB,QAAQ,EAAE,QAAQ,KAAK,CAAC;AACtD,SAAO,iBAAAA,QAAQ,IAAI;AACrB;AAEA,eAAsB,UAAU,MAAsC;AACpE,QAAM,eAAe,MAAM,mBAAmB;AAC9C,SAAO,aAAa,IAAI,IAAI;AAC9B;AAEA,eAAsB,WAA6B;AACjD,UAAI,0BAAc,GAAG;AACnB,WAAO,iCAAiC;AAAA,EAC1C;AACA,SAAO;AACT;AAEA,SAAS,mCAA4C;AACnD,SAAO,OAAO,WAAW,eAAe,OAAO,SAAS,aAAa;AACvE;AAEA,SAAS,wBAAwB,MAAc,OAAe,UAA4B,CAAC,GAAG;AAC5F,QAAM,SAAS,QAAQ,UAAU,iCAAiC;AAClE,mBAAAA,QAAQ,IAAI,MAAM,OAAO;AAAA,IACvB,SAAS,QAAQ,WAAW,SAAY,SAAY,IAAI,KAAK,KAAK,IAAI,IAAK,QAAQ,SAAU,GAAI;AAAA,IACjG,QAAQ,QAAQ;AAAA,IAChB;AAAA,EACF,CAAC;AACH;AAEA,SAAS,2BAA2B,MAAc,UAA+B,CAAC,GAAG;AACnF,MAAI,QAAQ,WAAW,QAAW;AAChC,qBAAAA,QAAQ,OAAO,MAAM,EAAE,QAAQ,QAAQ,QAAQ,QAAQ,iCAAiC,EAAE,CAAC;AAAA,EAC7F;AACA,mBAAAA,QAAQ,OAAO,MAAM,EAAE,QAAQ,iCAAiC,EAAE,CAAC;AACrE;AAEO,SAAS,wBAAwB,MAAc,OAAsB,UAAkD,CAAC,GAAG;AAChI,eAAa;AACb,MAAI,UAAU,MAAM;AAClB,+BAA2B,MAAM,OAAO;AAAA,EAC1C,OAAO;AACL,4BAAwB,MAAM,OAAO,OAAO;AAAA,EAC9C;AACF;AAEA,eAAsB,kBAAkB,MAAc,OAAsB,UAAkD,CAAC,GAAG;AAChI,QAAM,eAAe,MAAM,mBAAmB;AAC9C,eAAa,YAAY,MAAM,OAAO,OAAO;AAC/C;AAEO,SAAS,mBAAmB,MAAc,UAA+B,CAAC,GAAG;AAClF,eAAa;AACb,6BAA2B,MAAM,OAAO;AAC1C;AAEA,eAAsB,aAAa,MAAc,UAA+B,CAAC,GAAG;AAClF,QAAM,eAAe,MAAM,mBAAmB;AAC9C,eAAa,OAAO,MAAM,OAAO;AACnC;AAEO,SAAS,gBAAgB,MAAc,OAAe,UAA4B,CAAC,GAAG;AAC3F,eAAa;AACb,0BAAwB,MAAM,OAAO,OAAO;AAC9C;AAEA,eAAsB,UAAU,MAAc,OAAe,UAA4B,CAAC,GAAG;AAC3F,QAAM,eAAe,MAAM,mBAAmB;AAC9C,eAAa,IAAI,MAAM,OAAO,OAAO;AACvC;AAEA,eAAsB,uBAAuB;AAC3C,QAAM,mBAAe,gDAA2B;AAChD,QAAM,gBAAgB,UAAM,gDAA2B,YAAY;AACnE,QAAM,YAAQ,yCAAoB;AAElC,QAAM,UAAU,uBAAuB,OAAO,cAAc,EAAE,QAAQ,KAAK,GAAG,CAAC;AAE/E,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,8BAA8B,OAAe;AAC3D,eAAa;AACb,QAAM,aAAa,uBAAuB;AAC1C,QAAM,eAAe,gBAAgB,UAAU;AAC/C,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AACA,qBAAmB,UAAU;AAC7B,SAAO;AAAA,IACL;AAAA,EACF;AACF;","names":["Cookies"]}
|
|
@@ -324,6 +324,13 @@ var _StackAdminAppImplIncomplete = class extends import_server_app_impl._StackSe
|
|
|
324
324
|
async _refreshInternalApiKeys() {
|
|
325
325
|
await this._internalApiKeysCache.refresh([]);
|
|
326
326
|
}
|
|
327
|
+
async _refreshUsers() {
|
|
328
|
+
await Promise.all([
|
|
329
|
+
super._refreshUsers(),
|
|
330
|
+
this._metricsCache.refresh([false]),
|
|
331
|
+
this._metricsCache.refresh([true])
|
|
332
|
+
]);
|
|
333
|
+
}
|
|
327
334
|
get [import_common.stackAppInternalsSymbol]() {
|
|
328
335
|
return {
|
|
329
336
|
...super[import_common.stackAppInternalsSymbol]
|