@shakibdshy/signet-auth-client 0.0.0-stage → 1.0.0-beta.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shakibdshy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,189 @@
1
- # Temporary Holding Version
1
+ # Signet TypeScript client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The frontend client for [Signet](https://github.com/shakibdshy/signet-auth), an authentication library written in Go.**
4
+
5
+ Signet runs on the server, inside a Go application. This package is the frontend half: a
6
+ typed TypeScript client for the HTTP API that Signet serves from your backend. Use it from
7
+ a browser or Node.js to sign Users up and in, read and end Sessions, and reach Signet's
8
+ password reset, passwordless, Passkey, OAuth, SSO, organization, API key and admin features.
9
+ It attaches cookies and the CSRF token, so your frontend never builds those requests by hand.
10
+
11
+ | Part of Signet | Runs in | Written in | Package |
12
+ | --- | --- | --- | --- |
13
+ | The auth logic: passwords, Sessions, OAuth, mail, security checks | Your backend | Go | `github.com/shakibdshy/signet-auth` |
14
+ | **Calls that backend from a frontend** | Browser, Node.js | TypeScript, JavaScript | **`@shakibdshy/signet-auth-client`** (this package) |
15
+ | Shares the Session with React components and guards routes (optional) | Browser | TypeScript, React | `@shakibdshy/signet-auth-react` |
16
+
17
+ Current version: **`1.0.0-beta.2`**, a pre-1.0 release, so the API may still change before
18
+ `v1.0.0`. The Go module (`v1.0.0-beta.2`) and both npm packages (`1.0.0-beta.2`) are released
19
+ together at the same version.
20
+
21
+ > **This package does not implement authentication.** Every request goes to the Signet
22
+ > handler in your Go backend, so it has nothing to call without one. To set that backend up,
23
+ > start with the [Signet README for Go](https://github.com/shakibdshy/signet-auth).
24
+
25
+ ## Which package do you need?
26
+
27
+ - **Any TypeScript or JavaScript frontend**, including React, Vue, Svelte, Next.js and
28
+ TanStack Start: use this package.
29
+ - **React, when you want your components to share one Session state:** add
30
+ [`@shakibdshy/signet-auth-react`](https://github.com/shakibdshy/signet-auth/tree/main/client/react).
31
+ It installs this client for you and adds `SignetProvider`, `useSession()` and
32
+ `sessionGuard` on top.
33
+
34
+ Signet is an embeddable Go library, not a hosted auth service. Your backend imports it,
35
+ mounts its handler under a path prefix such as `/auth`, and keeps its own database. There is
36
+ no separate auth server to install.
37
+
38
+ ## Requirements
39
+
40
+ - **Node.js 20 or newer.**
41
+ - **A backend that runs Signet.**
42
+ - **Same origin.** Signet keeps Sessions in cookies and requires same-origin requests for
43
+ CSRF protection, so a cross-origin fetch cannot use a cookie Session. Serve your frontend
44
+ and the Go handler from one origin, or route requests through a same-origin proxy.
45
+
46
+ ## Install
47
+
48
+ ```sh
49
+ npm install @shakibdshy/signet-auth-client@1.0.0-beta.2
50
+ ```
51
+
52
+ To use a change that is not published yet, install from a checkout of the repository:
53
+
54
+ ```sh
55
+ cd /path/to/signet-auth/client/ts
56
+ npm install
57
+ npm run build
58
+
59
+ cd /path/to/your-frontend
60
+ npm install /path/to/signet-auth/client/ts
61
+ ```
62
+
63
+ ## Quick start
64
+
65
+ ```ts
66
+ import { createSignetClient, SignetApiError } from "@shakibdshy/signet-auth-client";
67
+
68
+ export const auth = createSignetClient({
69
+ // Your backend's origin, plus the prefix where it mounts Signet.
70
+ // If the Go server mounts the handler at /auth, this must end with /auth.
71
+ baseURL: "https://api.example.com/auth",
72
+ });
73
+
74
+ // Create an account. name is required.
75
+ await auth.signUp({
76
+ email: "user@example.com",
77
+ password: "correct horse battery staple",
78
+ name: "Ada",
79
+ });
80
+
81
+ // Sign in. The Go backend sets the Session cookie; you never handle it.
82
+ await auth.signIn({ email: "user@example.com", password: "correct horse battery staple" });
83
+
84
+ // Read the signed-in User. The profile carries the verification state,
85
+ // the Username (empty when there is none) and the timestamps.
86
+ const user = await auth.me();
87
+
88
+ // Sign out.
89
+ await auth.signOut({});
90
+ ```
91
+
92
+ Each call sends cookies and throws a `SignetApiError` when the backend returns an error
93
+ response.
94
+
95
+ ```ts
96
+ try {
97
+ await auth.signIn({ email: "user@example.com", password: "wrong" });
98
+ } catch (err) {
99
+ if (err instanceof SignetApiError && err.code === "invalid_credentials") {
100
+ // Show a generic sign-in error.
101
+ }
102
+ }
103
+ ```
104
+
105
+ A `SignetApiError` carries the backend's `code` (for example `invalid_credentials`,
106
+ `rate_limited` or `two_factor_required`), its `message`, and the HTTP `status`. All codes
107
+ are listed in the [error reference](https://shakibdshy.github.io/signet-auth/docs/errors).
108
+
109
+ > **Most common mistake:** using only `https://api.example.com` as `baseURL` when the
110
+ > backend mounts Signet at `/auth`. This client calls `/signup`, so without the prefix every
111
+ > request goes to `https://api.example.com/signup` and returns 404.
112
+
113
+ ### Options
114
+
115
+ | Option | Required | What it does |
116
+ | --- | --- | --- |
117
+ | `baseURL` | Yes | Your backend's origin plus the prefix where it mounts Signet, for example `https://api.example.com/auth`. |
118
+ | `fetch` | No | A custom `fetch` implementation, mainly for tests. |
119
+ | `csrfToken` | No | A CSRF token you already have. Without it, the client fetches one from `GET /csrf-token` the first time it is needed. |
120
+
121
+ ### What the client handles for you
122
+
123
+ - **Cookies.** Every request sends cookies (`credentials: "include"`), so the Session cookie
124
+ that the Go backend sets is used on later calls.
125
+ - **CSRF.** The client fetches a token from `GET /csrf-token`, or reuses the one returned by
126
+ sign-in, and sends it as `X-CSRF-Token` on the calls that require it.
127
+
128
+ ## What you can call
129
+
130
+ The client has a typed method for most of Signet's HTTP API. The main methods by area:
131
+
132
+ | Area | Main methods |
133
+ | --- | --- |
134
+ | Sign-up, sign-in and sign-out | `signUp`, `signIn`, `signOut`, `me`, `lastSignInMethod` |
135
+ | JWT Access and Refresh tokens, when the backend enables them | `exchangeToken` |
136
+ | Sessions | `listSessions`, `revokeSession`, `revokeAllSessions` — each listed Session carries `user_agent`, the raw browser header it was started from |
137
+ | Email verification and passwords | `sendVerification`, `verifyEmail`, `sendPasswordReset`, `resetPassword`, `changePassword`, `changeEmail`, `verifyChangeEmail` |
138
+ | Linked provider accounts | `listAccounts`, `unlinkAccount` |
139
+ | Second factor | `enableTwoFactor`, `verifyTwoFactor`, `disableTwoFactor`, `regenerateBackupCodes` |
140
+ | Account deletion | `requestAccountDeletion`, `confirmAccountDeletion` |
141
+ | Passwordless sign-in | `sendMagicLink`, `verifyMagicLink`, `sendOtp`, `verifyOtp` |
142
+ | Passkeys | `beginPasskeyRegistration`, `finishPasskeyRegistration`, `beginPasskeySignIn`, `finishPasskeySignIn`, `listPasskeys`, `deletePasskey` |
143
+ | OAuth sign-in with Google, GitHub or a generic OIDC provider | `oauthStart` |
144
+ | Authorization server and device authorization | `oauthAuthorize`, `oauthToken`, `beginDeviceAuthorization`, `approveDeviceAuthorization`, `deviceToken` |
145
+ | Organization SSO and SAML | `startSSOSignIn`, `completeSSOSignIn`, `listSSOConnections`, `createSSOConnection`, `deleteSSOConnection`, `startSAMLSignIn` |
146
+ | Organizations | `createOrganization`, `listOrganizations`, `listOrganizationMembers`, `addOrganizationMember`, `removeOrganizationMember`, `setOrganizationMemberRole`, `setActiveOrganization`, `activeOrganization`, `clearActiveOrganization` |
147
+ | API keys | `createApiKey`, `listApiKeys`, `verifyApiKey`, `revokeApiKey` |
148
+ | Admin actions and impersonation | `adminListUsers`, `adminSetUserRole`, `adminBanUser`, `adminUnbanUser`, `adminListUserSessions`, `adminRevokeUserSession`, `impersonate`, `stopImpersonating` |
149
+
150
+ **One endpoint is intentionally not wrapped:** `POST /saml/acs` receives the SAML assertion
151
+ posted by the identity provider's browser redirect, so your frontend never calls it.
152
+
153
+ ## How it stays in sync with the Go API
154
+
155
+ Signet's HTTP API is defined once, in the Go source. Signet generates an OpenAPI document
156
+ from that definition, and this package generates its request and response types from the
157
+ document. CI in the Go repository fails if the three drift apart. So when the Go API
158
+ changes, the types here change with it, and your build fails at the affected call instead of
159
+ at runtime.
160
+
161
+ ## Learn more
162
+
163
+ - [Frontend client guide](https://shakibdshy.github.io/signet-auth/docs/frontend-client): every
164
+ method, with examples for sign-in forms, passwordless sign-in, OAuth, Passkeys and more.
165
+ - [React session hooks guide](https://shakibdshy.github.io/signet-auth/docs/react-hooks) and
166
+ the [React package README](https://github.com/shakibdshy/signet-auth/tree/main/client/react).
167
+ - [HTTP API reference](https://shakibdshy.github.io/signet-auth/docs/openapi): every endpoint.
168
+ - [Signet README for Go](https://github.com/shakibdshy/signet-auth): features, quickstart and
169
+ backend setup.
170
+
171
+ ## Development
172
+
173
+ The client lives in
174
+ [`client/ts`](https://github.com/shakibdshy/signet-auth/tree/main/client/ts) in the Signet
175
+ repository.
176
+
177
+ ```sh
178
+ npm install
179
+ npm run generate # regenerate src/schema.d.ts from ../../api/signet.openapi.json
180
+ npm run typecheck # compile-time contract checks, including src/type-contracts.ts
181
+ npm run build # emit dist/ for publishing
182
+ ```
183
+
184
+ The HTTP contract lives in `internal/httpapi/contract.go`. `make generate-check` at the
185
+ repository root verifies that the published spec and the generated types match it.
186
+
187
+ ## License
188
+
189
+ [MIT](https://github.com/shakibdshy/signet-auth/blob/main/LICENSE)
@@ -0,0 +1,107 @@
1
+ import type { components, paths } from "./schema";
2
+ /** Error codes the server can return, derived from the published contract. */
3
+ export type SignetErrorCode = components["schemas"]["ApiError"]["error"];
4
+ /** An error response decoded into a typed exception. */
5
+ export declare class SignetApiError extends Error {
6
+ readonly code: SignetErrorCode;
7
+ readonly status: number;
8
+ constructor(code: SignetErrorCode, message: string, status: number);
9
+ }
10
+ type RequestBody<P extends keyof paths, M extends keyof paths[P]> = paths[P][M] extends {
11
+ requestBody: {
12
+ content: {
13
+ "application/json": infer B;
14
+ };
15
+ };
16
+ } ? B : never;
17
+ type SuccessBody<P extends keyof paths, M extends keyof paths[P], S extends number> = paths[P][M] extends {
18
+ responses: Record<S, infer R>;
19
+ } ? R extends {
20
+ content: {
21
+ "application/json": infer B;
22
+ };
23
+ } ? B : void : void;
24
+ export interface SignetClientOptions {
25
+ /** Backend origin, e.g. https://api.example.com */
26
+ baseURL: string;
27
+ /** Optional custom fetch implementation (useful for tests). */
28
+ fetch?: (input: Request) => Promise<Response>;
29
+ /** Pre-obtained CSRF token; otherwise fetched lazily from /csrf-token. */
30
+ csrfToken?: string;
31
+ }
32
+ /** A type-safe client for Signet's HTTP endpoints. */
33
+ export declare function createSignetClient(options: SignetClientOptions): {
34
+ /** Force a fresh CSRF token on the next state-changing request. */
35
+ clearCsrfToken: () => void;
36
+ signUp(body: RequestBody<"/signup", "post">): Promise<SuccessBody<"/signup", "post", 201>>;
37
+ signIn(body: RequestBody<"/signin", "post">): Promise<SuccessBody<"/signin", "post", 200>>;
38
+ sendMagicLink(body: RequestBody<"/send-magic-link", "post">): Promise<SuccessBody<"/send-magic-link", "post", 200>>;
39
+ verifyMagicLink(params: paths["/verify-magic-link"]["get"]["parameters"]["query"]): Promise<SuccessBody<"/verify-magic-link", "get", 200>>;
40
+ sendOtp(body: RequestBody<"/send-otp", "post">): Promise<SuccessBody<"/send-otp", "post", 200>>;
41
+ verifyOtp(body: RequestBody<"/verify-otp", "post">): Promise<SuccessBody<"/verify-otp", "post", 200>>;
42
+ signOut(body: RequestBody<"/signout", "post">): Promise<SuccessBody<"/signout", "post", 204>>;
43
+ me(): Promise<SuccessBody<"/me", "get", 200>>;
44
+ listSessions(): Promise<SuccessBody<"/sessions", "get", 200>>;
45
+ revokeAllSessions(): Promise<SuccessBody<"/sessions", "delete", 204>>;
46
+ revokeSession(): Promise<SuccessBody<"/session", "delete", 204>>;
47
+ exchangeToken(body: RequestBody<"/token", "post">): Promise<SuccessBody<"/token", "post", 200>>;
48
+ sendVerification(body: RequestBody<"/send-verification", "post">): Promise<SuccessBody<"/send-verification", "post", 200>>;
49
+ verifyEmail(body: RequestBody<"/verify-email", "post">): Promise<SuccessBody<"/verify-email", "post", 200>>;
50
+ sendPasswordReset(body: RequestBody<"/send-password-reset", "post">): Promise<SuccessBody<"/send-password-reset", "post", 200>>;
51
+ resetPassword(body: RequestBody<"/reset-password", "post">): Promise<SuccessBody<"/reset-password", "post", 200>>;
52
+ changePassword(body: RequestBody<"/change-password", "post">): Promise<SuccessBody<"/change-password", "post", 200>>;
53
+ changeEmail(body: RequestBody<"/change-email", "post">): Promise<SuccessBody<"/change-email", "post", 200>>;
54
+ verifyChangeEmail(body: RequestBody<"/verify-change-email", "post">): Promise<SuccessBody<"/verify-change-email", "post", 200>>;
55
+ listAccounts(): Promise<SuccessBody<"/accounts", "get", 200>>;
56
+ unlinkAccount(body: RequestBody<"/unlink-account", "post">): Promise<SuccessBody<"/unlink-account", "post", 200>>;
57
+ enableTwoFactor(body: RequestBody<"/enable-two-factor", "post">): Promise<SuccessBody<"/enable-two-factor", "post", 200>>;
58
+ verifyTwoFactor(body: RequestBody<"/verify-two-factor", "post">): Promise<SuccessBody<"/verify-two-factor", "post", 200>>;
59
+ disableTwoFactor(body: RequestBody<"/disable-two-factor", "post">): Promise<SuccessBody<"/disable-two-factor", "post", 200>>;
60
+ regenerateBackupCodes(body: RequestBody<"/regenerate-backup-codes", "post">): Promise<SuccessBody<"/regenerate-backup-codes", "post", 200>>;
61
+ requestAccountDeletion(): Promise<SuccessBody<"/request-account-deletion", "post", 200>>;
62
+ confirmAccountDeletion(body: RequestBody<"/confirm-account-deletion", "post">): Promise<SuccessBody<"/confirm-account-deletion", "post", 200>>;
63
+ oauthStart(body: RequestBody<"/oauth/start", "post">): Promise<SuccessBody<"/oauth/start", "post", 200>>;
64
+ oauthCallback(code: string, state: string): Promise<SuccessBody<"/oauth/callback", "get", 302>>;
65
+ csrfToken(): Promise<SuccessBody<"/csrf-token", "get", 200>>;
66
+ lastSignInMethod(): Promise<SuccessBody<"/last-sign-in-method", "get", 200>>;
67
+ beginPasskeyRegistration(body: RequestBody<"/passkeys/register-begin", "post">): Promise<SuccessBody<"/passkeys/register-begin", "post", 200>>;
68
+ finishPasskeyRegistration(body: RequestBody<"/passkeys/register-finish", "post">): Promise<SuccessBody<"/passkeys/register-finish", "post", 200>>;
69
+ beginPasskeySignIn(): Promise<SuccessBody<"/passkeys/signin-begin", "post", 200>>;
70
+ finishPasskeySignIn(body: RequestBody<"/passkeys/signin-finish", "post">): Promise<SuccessBody<"/passkeys/signin-finish", "post", 200>>;
71
+ listPasskeys(): Promise<SuccessBody<"/passkeys", "get", 200>>;
72
+ oauthAuthorize(body: RequestBody<"/oauth/authorize", "post">): Promise<SuccessBody<"/oauth/authorize", "post", 200>>;
73
+ oauthToken(body: RequestBody<"/oauth/token", "post">): Promise<SuccessBody<"/oauth/token", "post", 200>>;
74
+ beginDeviceAuthorization(body: RequestBody<"/oauth/device/authorize", "post">): Promise<SuccessBody<"/oauth/device/authorize", "post", 200>>;
75
+ startSAMLSignIn(body: RequestBody<"/saml/start", "post">): Promise<SuccessBody<"/saml/start", "post", 200>>;
76
+ startSSOSignIn(body: RequestBody<"/sso/start", "post">): Promise<SuccessBody<"/sso/start", "post", 200>>;
77
+ completeSSOSignIn(state: string, code: string): Promise<SuccessBody<"/sso/callback", "get", 200>>;
78
+ listSSOConnections(): Promise<SuccessBody<"/sso/connections", "get", 200>>;
79
+ createSSOConnection(body: RequestBody<"/sso/connections", "post">): Promise<SuccessBody<"/sso/connections", "post", 201>>;
80
+ deleteSSOConnection(id: string): Promise<SuccessBody<"/sso/connections", "delete", 200>>;
81
+ deviceToken(body: RequestBody<"/oauth/device/token", "post">): Promise<SuccessBody<"/oauth/device/token", "post", 200>>;
82
+ approveDeviceAuthorization(body: RequestBody<"/oauth/device/approve", "post">): Promise<SuccessBody<"/oauth/device/approve", "post", 200>>;
83
+ deletePasskey(body: RequestBody<"/passkeys/delete", "post">): Promise<SuccessBody<"/passkeys/delete", "post", 200>>;
84
+ createApiKey(body: RequestBody<"/api-keys", "post">): Promise<SuccessBody<"/api-keys", "post", 201>>;
85
+ listApiKeys(): Promise<SuccessBody<"/api-keys", "get", 200>>;
86
+ verifyApiKey(key: string): Promise<SuccessBody<"/verify-api-key", "post", 200>>;
87
+ revokeApiKey(body: RequestBody<"/revoke-api-key", "post">): Promise<SuccessBody<"/revoke-api-key", "post", 200>>;
88
+ createOrganization(body: RequestBody<"/organizations", "post">): Promise<SuccessBody<"/organizations", "post", 201>>;
89
+ listOrganizations(): Promise<SuccessBody<"/organizations", "get", 200>>;
90
+ listOrganizationMembers(organizationId: string): Promise<SuccessBody<"/organization-members", "get", 200>>;
91
+ addOrganizationMember(body: RequestBody<"/organization-members/add", "post">): Promise<SuccessBody<"/organization-members/add", "post", 200>>;
92
+ removeOrganizationMember(body: RequestBody<"/organization-members/remove", "post">): Promise<SuccessBody<"/organization-members/remove", "post", 200>>;
93
+ setOrganizationMemberRole(body: RequestBody<"/organization-members/role", "post">): Promise<SuccessBody<"/organization-members/role", "post", 200>>;
94
+ setActiveOrganization(body: RequestBody<"/set-active-organization", "post">): Promise<SuccessBody<"/set-active-organization", "post", 200>>;
95
+ activeOrganization(): Promise<SuccessBody<"/active-organization", "get", 200>>;
96
+ clearActiveOrganization(): Promise<SuccessBody<"/clear-active-organization", "post", 200>>;
97
+ adminListUsers(): Promise<SuccessBody<"/admin-users", "get", 200>>;
98
+ adminSetUserRole(body: RequestBody<"/admin-users/role", "post">): Promise<SuccessBody<"/admin-users/role", "post", 200>>;
99
+ adminBanUser(body: RequestBody<"/admin-users/ban", "post">): Promise<SuccessBody<"/admin-users/ban", "post", 200>>;
100
+ adminUnbanUser(body: RequestBody<"/admin-users/unban", "post">): Promise<SuccessBody<"/admin-users/unban", "post", 200>>;
101
+ adminListUserSessions(userId: string): Promise<SuccessBody<"/admin-user-sessions", "get", 200>>;
102
+ adminRevokeUserSession(body: RequestBody<"/admin-user-sessions/revoke", "post">): Promise<SuccessBody<"/admin-user-sessions/revoke", "post", 200>>;
103
+ impersonate(body: RequestBody<"/impersonate", "post">): Promise<SuccessBody<"/impersonate", "post", 200>>;
104
+ stopImpersonating(token: string): Promise<SuccessBody<"/stop-impersonating", "post", 200>>;
105
+ };
106
+ export type SignetClient = ReturnType<typeof createSignetClient>;
107
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,282 @@
1
+ import createClient from "openapi-fetch";
2
+ /** An error response decoded into a typed exception. */
3
+ export class SignetApiError extends Error {
4
+ code;
5
+ status;
6
+ constructor(code, message, status) {
7
+ super(message);
8
+ this.code = code;
9
+ this.status = status;
10
+ this.name = "SignetApiError";
11
+ }
12
+ }
13
+ async function unwrap(result) {
14
+ if (result.error) {
15
+ throw new SignetApiError(result.error.error, result.error.message, result.response.status);
16
+ }
17
+ if (result.data === undefined) {
18
+ return undefined;
19
+ }
20
+ return result.data;
21
+ }
22
+ /** A type-safe client for Signet's HTTP endpoints. */
23
+ export function createSignetClient(options) {
24
+ const api = createClient({
25
+ baseUrl: options.baseURL,
26
+ credentials: "include",
27
+ fetch: options.fetch,
28
+ });
29
+ let csrfToken = options.csrfToken;
30
+ async function csrfHeaders() {
31
+ if (!csrfToken) {
32
+ const result = await api.GET("/csrf-token");
33
+ if (result.error || !result.data) {
34
+ const code = result.error?.error ?? "internal_error";
35
+ const message = result.error?.message ?? "could not obtain CSRF token";
36
+ throw new SignetApiError(code, message, result.response.status);
37
+ }
38
+ csrfToken = result.data.token;
39
+ }
40
+ return { "X-CSRF-Token": csrfToken };
41
+ }
42
+ function clearCsrfToken() {
43
+ csrfToken = undefined;
44
+ }
45
+ return {
46
+ /** Force a fresh CSRF token on the next state-changing request. */
47
+ clearCsrfToken,
48
+ async signUp(body) {
49
+ return unwrap(await api.POST("/signup", { body, headers: await csrfHeaders() }));
50
+ },
51
+ async signIn(body) {
52
+ const result = await api.POST("/signin", { body, headers: await csrfHeaders() });
53
+ const data = await unwrap(result);
54
+ csrfToken = data.csrf_token;
55
+ return data;
56
+ },
57
+ async sendMagicLink(body) {
58
+ return unwrap(await api.POST("/send-magic-link", { body }));
59
+ },
60
+ async verifyMagicLink(params) {
61
+ return unwrap(await api.GET("/verify-magic-link", { params: { query: params } }));
62
+ },
63
+ async sendOtp(body) {
64
+ return unwrap(await api.POST("/send-otp", { body }));
65
+ },
66
+ async verifyOtp(body) {
67
+ return unwrap(await api.POST("/verify-otp", { body }));
68
+ },
69
+ async signOut(body) {
70
+ return unwrap(await api.POST("/signout", { body, headers: await csrfHeaders() }));
71
+ },
72
+ async me() {
73
+ return unwrap(await api.GET("/me"));
74
+ },
75
+ async listSessions() {
76
+ return unwrap(await api.GET("/sessions"));
77
+ },
78
+ async revokeAllSessions() {
79
+ return unwrap(await api.DELETE("/sessions", { headers: await csrfHeaders() }));
80
+ },
81
+ async revokeSession() {
82
+ return unwrap(await api.DELETE("/session", { headers: await csrfHeaders() }));
83
+ },
84
+ async exchangeToken(body) {
85
+ return unwrap(await api.POST("/token", { body, headers: await csrfHeaders() }));
86
+ },
87
+ async sendVerification(body) {
88
+ return unwrap(await api.POST("/send-verification", { body, headers: await csrfHeaders() }));
89
+ },
90
+ async verifyEmail(body) {
91
+ return unwrap(await api.POST("/verify-email", { body, headers: await csrfHeaders() }));
92
+ },
93
+ async sendPasswordReset(body) {
94
+ return unwrap(await api.POST("/send-password-reset", { body, headers: await csrfHeaders() }));
95
+ },
96
+ async resetPassword(body) {
97
+ return unwrap(await api.POST("/reset-password", { body, headers: await csrfHeaders() }));
98
+ },
99
+ async changePassword(body) {
100
+ return unwrap(await api.POST("/change-password", { body, headers: await csrfHeaders() }));
101
+ },
102
+ async changeEmail(body) {
103
+ return unwrap(await api.POST("/change-email", { body, headers: await csrfHeaders() }));
104
+ },
105
+ async verifyChangeEmail(body) {
106
+ return unwrap(await api.POST("/verify-change-email", { body, headers: await csrfHeaders() }));
107
+ },
108
+ // --- Linked accounts ---
109
+ async listAccounts() {
110
+ return unwrap(await api.GET("/accounts"));
111
+ },
112
+ async unlinkAccount(body) {
113
+ return unwrap(await api.POST("/unlink-account", { body, headers: await csrfHeaders() }));
114
+ },
115
+ // --- Second factor ---
116
+ async enableTwoFactor(body) {
117
+ return unwrap(await api.POST("/enable-two-factor", { body, headers: await csrfHeaders() }));
118
+ },
119
+ async verifyTwoFactor(body) {
120
+ // No CSRF header: this completes a sign-in, so the contract marks it anonymous and exempt.
121
+ return unwrap(await api.POST("/verify-two-factor", { body }));
122
+ },
123
+ async disableTwoFactor(body) {
124
+ return unwrap(await api.POST("/disable-two-factor", { body, headers: await csrfHeaders() }));
125
+ },
126
+ async regenerateBackupCodes(body) {
127
+ return unwrap(await api.POST("/regenerate-backup-codes", { body, headers: await csrfHeaders() }));
128
+ },
129
+ // --- Account deletion ---
130
+ async requestAccountDeletion() {
131
+ return unwrap(await api.POST("/request-account-deletion", { headers: await csrfHeaders() }));
132
+ },
133
+ async confirmAccountDeletion(body) {
134
+ return unwrap(await api.POST("/confirm-account-deletion", { body, headers: await csrfHeaders() }));
135
+ },
136
+ async oauthStart(body) {
137
+ return unwrap(await api.POST("/oauth/start", { body, headers: await csrfHeaders() }));
138
+ },
139
+ async oauthCallback(code, state) {
140
+ return unwrap(await api.GET("/oauth/callback", { params: { query: { code, state } } }));
141
+ },
142
+ async csrfToken() {
143
+ return unwrap(await api.GET("/csrf-token"));
144
+ },
145
+ async lastSignInMethod() {
146
+ return unwrap(await api.GET("/last-sign-in-method"));
147
+ },
148
+ // --- Passkeys ---
149
+ async beginPasskeyRegistration(body) {
150
+ return unwrap(await api.POST("/passkeys/register-begin", { body, headers: await csrfHeaders() }));
151
+ },
152
+ async finishPasskeyRegistration(body) {
153
+ return unwrap(await api.POST("/passkeys/register-finish", { body, headers: await csrfHeaders() }));
154
+ },
155
+ async beginPasskeySignIn() {
156
+ return unwrap(await api.POST("/passkeys/signin-begin"));
157
+ },
158
+ async finishPasskeySignIn(body) {
159
+ const result = await unwrap(await api.POST("/passkeys/signin-finish", { body }));
160
+ clearCsrfToken();
161
+ return result;
162
+ },
163
+ async listPasskeys() {
164
+ return unwrap(await api.GET("/passkeys"));
165
+ },
166
+ async oauthAuthorize(body) {
167
+ return unwrap(await api.POST("/oauth/authorize", { body, headers: await csrfHeaders() }));
168
+ },
169
+ async oauthToken(body) {
170
+ return unwrap(await api.POST("/oauth/token", { body }));
171
+ },
172
+ async beginDeviceAuthorization(body) {
173
+ return unwrap(await api.POST("/oauth/device/authorize", { body }));
174
+ },
175
+ async startSAMLSignIn(body) {
176
+ return unwrap(await api.POST("/saml/start", { body }));
177
+ },
178
+ async startSSOSignIn(body) {
179
+ return unwrap(await api.POST("/sso/start", { body }));
180
+ },
181
+ async completeSSOSignIn(state, code) {
182
+ return unwrap(await api.GET("/sso/callback", { params: { query: { state, code } } }));
183
+ },
184
+ async listSSOConnections() {
185
+ return unwrap(await api.GET("/sso/connections"));
186
+ },
187
+ async createSSOConnection(body) {
188
+ return unwrap(await api.POST("/sso/connections", { body, headers: await csrfHeaders() }));
189
+ },
190
+ async deleteSSOConnection(id) {
191
+ return unwrap(await api.DELETE("/sso/connections", { body: { id }, headers: await csrfHeaders() }));
192
+ },
193
+ async deviceToken(body) {
194
+ return unwrap(await api.POST("/oauth/device/token", { body }));
195
+ },
196
+ async approveDeviceAuthorization(body) {
197
+ return unwrap(await api.POST("/oauth/device/approve", { body, headers: await csrfHeaders() }));
198
+ },
199
+ async deletePasskey(body) {
200
+ return unwrap(await api.POST("/passkeys/delete", { body, headers: await csrfHeaders() }));
201
+ },
202
+ // --- API keys ---
203
+ async createApiKey(body) {
204
+ return unwrap(await api.POST("/api-keys", { body, headers: await csrfHeaders() }));
205
+ },
206
+ async listApiKeys() {
207
+ return unwrap(await api.GET("/api-keys"));
208
+ },
209
+ async verifyApiKey(key) {
210
+ return unwrap(await api.POST("/verify-api-key", {
211
+ params: { header: { "X-API-Key": key } },
212
+ }));
213
+ },
214
+ async revokeApiKey(body) {
215
+ return unwrap(await api.POST("/revoke-api-key", { body, headers: await csrfHeaders() }));
216
+ },
217
+ // --- Organizations ---
218
+ async createOrganization(body) {
219
+ return unwrap(await api.POST("/organizations", { body, headers: await csrfHeaders() }));
220
+ },
221
+ async listOrganizations() {
222
+ return unwrap(await api.GET("/organizations"));
223
+ },
224
+ async listOrganizationMembers(organizationId) {
225
+ return unwrap(await api.GET("/organization-members", {
226
+ params: { query: { organization_id: organizationId } },
227
+ }));
228
+ },
229
+ async addOrganizationMember(body) {
230
+ return unwrap(await api.POST("/organization-members/add", { body, headers: await csrfHeaders() }));
231
+ },
232
+ async removeOrganizationMember(body) {
233
+ return unwrap(await api.POST("/organization-members/remove", { body, headers: await csrfHeaders() }));
234
+ },
235
+ async setOrganizationMemberRole(body) {
236
+ return unwrap(await api.POST("/organization-members/role", { body, headers: await csrfHeaders() }));
237
+ },
238
+ async setActiveOrganization(body) {
239
+ return unwrap(await api.POST("/set-active-organization", { body, headers: await csrfHeaders() }));
240
+ },
241
+ async activeOrganization() {
242
+ return unwrap(await api.GET("/active-organization"));
243
+ },
244
+ async clearActiveOrganization() {
245
+ return unwrap(await api.POST("/clear-active-organization", { headers: await csrfHeaders() }));
246
+ },
247
+ // --- Admin management ---
248
+ async adminListUsers() {
249
+ return unwrap(await api.GET("/admin-users"));
250
+ },
251
+ async adminSetUserRole(body) {
252
+ return unwrap(await api.POST("/admin-users/role", { body, headers: await csrfHeaders() }));
253
+ },
254
+ async adminBanUser(body) {
255
+ return unwrap(await api.POST("/admin-users/ban", { body, headers: await csrfHeaders() }));
256
+ },
257
+ async adminUnbanUser(body) {
258
+ return unwrap(await api.POST("/admin-users/unban", { body, headers: await csrfHeaders() }));
259
+ },
260
+ async adminListUserSessions(userId) {
261
+ return unwrap(await api.GET("/admin-user-sessions", {
262
+ params: { query: { user_id: userId } },
263
+ }));
264
+ },
265
+ async adminRevokeUserSession(body) {
266
+ return unwrap(await api.POST("/admin-user-sessions/revoke", { body, headers: await csrfHeaders() }));
267
+ },
268
+ async impersonate(body) {
269
+ const data = await unwrap(await api.POST("/impersonate", { body, headers: await csrfHeaders() }));
270
+ clearCsrfToken();
271
+ return data;
272
+ },
273
+ async stopImpersonating(token) {
274
+ const data = await unwrap(await api.POST("/stop-impersonating", {
275
+ body: { token },
276
+ headers: await csrfHeaders(),
277
+ }));
278
+ clearCsrfToken();
279
+ return data;
280
+ },
281
+ };
282
+ }