@takeal/cusfront-sdk 0.6.1 → 0.6.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/CHANGELOG.md +28 -0
- package/README.md +55 -0
- package/dist/{cards-qfHz6xZY.d.cts → cards-DU2DdhYO.d.cts} +10 -0
- package/dist/{cards-CF3-He2x.d.ts → cards-DzhPVA9N.d.ts} +10 -0
- package/dist/{deposits-ZjT_btgi.d.cts → deposits-BEkNeE-v.d.cts} +1 -1
- package/dist/{deposits-B2LBe2k1.d.ts → deposits-Dt6A76MB.d.ts} +1 -1
- package/dist/index.cjs +95 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -8
- package/dist/index.d.ts +16 -8
- package/dist/index.js +95 -7
- package/dist/index.js.map +1 -1
- package/dist/react/index.d.cts +4 -2
- package/dist/react/index.d.ts +4 -2
- package/dist/resources/auth.cjs +25 -4
- package/dist/resources/auth.cjs.map +1 -1
- package/dist/resources/auth.d.cts +40 -5
- package/dist/resources/auth.d.ts +40 -5
- package/dist/resources/auth.js +25 -4
- package/dist/resources/auth.js.map +1 -1
- package/dist/resources/cards.cjs +2 -0
- package/dist/resources/cards.cjs.map +1 -1
- package/dist/resources/cards.d.cts +2 -1
- package/dist/resources/cards.d.ts +2 -1
- package/dist/resources/cards.js +2 -0
- package/dist/resources/cards.js.map +1 -1
- package/dist/resources/consents.cjs +91 -0
- package/dist/resources/consents.cjs.map +1 -0
- package/dist/resources/consents.d.cts +83 -0
- package/dist/resources/consents.d.ts +83 -0
- package/dist/resources/consents.js +89 -0
- package/dist/resources/consents.js.map +1 -0
- package/dist/resources/deposits.cjs +2 -0
- package/dist/resources/deposits.cjs.map +1 -1
- package/dist/resources/deposits.d.cts +3 -2
- package/dist/resources/deposits.d.ts +3 -2
- package/dist/resources/deposits.js +2 -0
- package/dist/resources/deposits.js.map +1 -1
- package/dist/resources/funding-options.d.cts +3 -2
- package/dist/resources/funding-options.d.ts +3 -2
- package/dist/resources/me.d.cts +1 -0
- package/dist/resources/me.d.ts +1 -0
- package/dist/resources/receipts.cjs +22 -0
- package/dist/resources/receipts.cjs.map +1 -0
- package/dist/resources/receipts.d.cts +51 -0
- package/dist/resources/receipts.d.ts +51 -0
- package/dist/resources/receipts.js +20 -0
- package/dist/resources/receipts.js.map +1 -0
- package/dist/telegram.cjs +133 -7
- package/dist/telegram.cjs.map +1 -1
- package/dist/telegram.d.cts +4 -2
- package/dist/telegram.d.ts +4 -2
- package/dist/telegram.js +133 -7
- package/dist/telegram.js.map +1 -1
- package/package.json +11 -1
package/dist/react/index.d.cts
CHANGED
|
@@ -2,8 +2,8 @@ import * as react from 'react';
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { CusfrontClient } from '../index.cjs';
|
|
4
4
|
import { User } from '../resources/auth.cjs';
|
|
5
|
-
import { D as Deposit } from '../deposits-
|
|
6
|
-
import { C as CardProduct, a as Card } from '../cards-
|
|
5
|
+
import { D as Deposit } from '../deposits-BEkNeE-v.cjs';
|
|
6
|
+
import { C as CardProduct, a as Card } from '../cards-DU2DdhYO.cjs';
|
|
7
7
|
import { Balance } from '../resources/balance.cjs';
|
|
8
8
|
import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.cjs';
|
|
9
9
|
import '../http-DeANAoTs.cjs';
|
|
@@ -22,6 +22,8 @@ import '../resources/me.cjs';
|
|
|
22
22
|
import '../devices-a5Z45Mx_.cjs';
|
|
23
23
|
import '../resources/attribution.cjs';
|
|
24
24
|
import '../resources/history.cjs';
|
|
25
|
+
import '../resources/consents.cjs';
|
|
26
|
+
import '../resources/receipts.cjs';
|
|
25
27
|
import '../analytics.cjs';
|
|
26
28
|
|
|
27
29
|
interface ClientProviderProps {
|
package/dist/react/index.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import * as react from 'react';
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { CusfrontClient } from '../index.js';
|
|
4
4
|
import { User } from '../resources/auth.js';
|
|
5
|
-
import { D as Deposit } from '../deposits-
|
|
6
|
-
import { C as CardProduct, a as Card } from '../cards-
|
|
5
|
+
import { D as Deposit } from '../deposits-Dt6A76MB.js';
|
|
6
|
+
import { C as CardProduct, a as Card } from '../cards-DzhPVA9N.js';
|
|
7
7
|
import { Balance } from '../resources/balance.js';
|
|
8
8
|
import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.js';
|
|
9
9
|
import '../http-DeANAoTs.js';
|
|
@@ -22,6 +22,8 @@ import '../resources/me.js';
|
|
|
22
22
|
import '../devices-B_YveTl9.js';
|
|
23
23
|
import '../resources/attribution.js';
|
|
24
24
|
import '../resources/history.js';
|
|
25
|
+
import '../resources/consents.js';
|
|
26
|
+
import '../resources/receipts.js';
|
|
25
27
|
import '../analytics.js';
|
|
26
28
|
|
|
27
29
|
interface ClientProviderProps {
|
package/dist/resources/auth.cjs
CHANGED
|
@@ -100,7 +100,8 @@ var AuthResource = class {
|
|
|
100
100
|
* `wallet_currency` must be one the deployment offers; omit it to take
|
|
101
101
|
* the deployment default (it can be switched later via `client.wallet`
|
|
102
102
|
* while the wallet is empty).
|
|
103
|
-
* Errors: 400 `validation` / `currency_not_allowed
|
|
103
|
+
* Errors: 400 `validation` / `currency_not_allowed` / `consents_required`
|
|
104
|
+
* / `unknown_consent`, 409 email taken. */
|
|
104
105
|
async register(input) {
|
|
105
106
|
const resp = await this.http.post("/auth/register", {
|
|
106
107
|
body: withRemember(input),
|
|
@@ -145,6 +146,8 @@ var AuthResource = class {
|
|
|
145
146
|
if (input.provision !== void 0) body.provision = input.provision;
|
|
146
147
|
if (input.attribution !== void 0) body.attribution = input.attribution;
|
|
147
148
|
if (input.code !== void 0) body.code = input.code;
|
|
149
|
+
if (input.consents !== void 0) body.consents = input.consents;
|
|
150
|
+
if (input.consentChannel !== void 0) body.consent_channel = input.consentChannel;
|
|
148
151
|
let resp;
|
|
149
152
|
try {
|
|
150
153
|
resp = await this.http.post("/auth/telegram/exchange", {
|
|
@@ -179,12 +182,30 @@ var AuthResource = class {
|
|
|
179
182
|
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
180
183
|
return resp;
|
|
181
184
|
}
|
|
182
|
-
/** Attach
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
+
/** Attach the first real email to a Telegram-made account (and clear
|
|
186
|
+
* `email_pending`). 409 if taken. An account that already has a real
|
|
187
|
+
* address gets 409 `email_change_needs_code`: change it with
|
|
188
|
+
* {@link requestEmailChange} and {@link confirmEmailChange}. */
|
|
185
189
|
async linkEmail(input) {
|
|
186
190
|
return this.http.post("/me/email", { body: { email: input.email } });
|
|
187
191
|
}
|
|
192
|
+
/** Step one of an email change: a six-digit code goes to the new address
|
|
193
|
+
* and works for 5 minutes. Nothing changes yet.
|
|
194
|
+
* Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`
|
|
195
|
+
* (five codes an hour). */
|
|
196
|
+
async requestEmailChange(input) {
|
|
197
|
+
return this.http.post("/me/email/change", {
|
|
198
|
+
body: { email: input.email }
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/** Step two: the code from the e-mail changes the address; the old one
|
|
202
|
+
* gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new
|
|
203
|
+
* request is needed), 409 the address was taken meanwhile. */
|
|
204
|
+
async confirmEmailChange(input) {
|
|
205
|
+
return this.http.post("/me/email/change/confirm", {
|
|
206
|
+
body: { challenge_id: input.challengeId, code: input.code }
|
|
207
|
+
});
|
|
208
|
+
}
|
|
188
209
|
/** Current user — fails 401 when the stored JWT is expired or
|
|
189
210
|
* missing. Useful as a "do I have a session" probe on app boot. */
|
|
190
211
|
async me() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/error.ts","../../src/resources/auth.ts"],"names":[],"mappings":";;;AA2CO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA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,WAAA,EAAa,EAAE,IAAA,EAAM,EAAE,KAAA,EAAO,KAAA,CAAM,KAAA,EAAM,EAAG,CAAA;AAAA,EAC3E;AAAA;AAAA;AAAA,EAIA,MAAM,EAAA,GAAoB;AACxB,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAU,UAAU,CAAA;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,UAAA,GAAa,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,GAAA,EAAK,CAAA,GAAI,IAAA;AAClF,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,cAAA,EAAgB;AAAA,QACzC,MAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,QAAA,KAAa,EAAC;AAAA,QACjD,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,IAAA,CAAK,YAAY,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,EACpE;AACF","file":"auth.cjs","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport type { SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n if (input.attribution !== undefined) body.attribution = input.attribution;\n if (input.code !== undefined) body.code = input.code;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach a real email to the current user (and clear `email_pending`).\n * Used after a Telegram exchange to satisfy the email requirement; also\n * works for a password user changing their address. 409 if taken. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/error.ts","../../src/resources/auth.ts"],"names":[],"mappings":";;;AA2CO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,IAAS,EAA+B,UAAA,KAAe,IAAA;AAC/F;;;AC6KA,SAAS,aACP,KAAA,EACiD;AACjD,EAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,EAAA,OAAO,WAAW,EAAE,GAAG,IAAA,EAAM,WAAA,EAAa,MAAK,GAAI,IAAA;AACrD;AAEO,IAAM,eAAN,MAAmB;AAAA,EACxB,WAAA,CACmB,IAAA,EACA,MAAA,EACA,UAAA,EACjB;AAHiB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAEjB,IAAA,IAAI,UAAA,EAAY,IAAA,CAAK,YAAA,CAAa,MAAM,IAAA,CAAK,KAAA,EAAM,CAAE,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,MAAM,CAAC,CAAA;AAAA,EACrF;AAAA;AAAA,EAGA,MAAc,KAAK,IAAA,EAAwE;AACzF,IAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA,CAAK,OAAO,GAAA,CAAI,IAAA,CAAK,YAAY,CAAC,CAAA;AACxD,IAAA,IAAI,IAAA,CAAK,cAAA,IAAkB,IAAA,CAAK,UAAA,EAAY;AAC1C,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA,CAAK,W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EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,UAAA,GAAa,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,GAAA,EAAK,CAAA,GAAI,IAAA;AAClF,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,cAAA,EAAgB;AAAA,QACzC,MAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,QAAA,KAAa,EAAC;AAAA,QACjD,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,IAAA,CAAK,YAAY,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,EACpE;AACF","file":"auth.cjs","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport type { SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n /** Consents for a new account, as in `register`. Sent as `consents`;\n * ignored for an account that already exists. */\n consents?: ConsentKind[];\n /** Sent as `consent_channel`; the server takes `miniapp` when omitted. */\n consentChannel?: ConsentChannel;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n /** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),\n * `personal_data`, `marketing`. A deployment can require the first two\n * (400 `consents_required` without them). */\n consents?: ConsentKind[];\n /** Where they were ticked. Read from the client header when omitted. */\n consent_channel?: ConsentChannel;\n}\n\n/** What `requestEmailChange` returns: send `challenge_id` back with the code. */\nexport interface EmailChangeRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed` / `consents_required`\n * / `unknown_consent`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n consents?: ConsentKind[];\n consent_channel?: ConsentChannel;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n if (input.attribution !== undefined) body.attribution = input.attribution;\n if (input.code !== undefined) body.code = input.code;\n if (input.consents !== undefined) body.consents = input.consents;\n if (input.consentChannel !== undefined) body.consent_channel = input.consentChannel;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the first real email to a Telegram-made account (and clear\n * `email_pending`). 409 if taken. An account that already has a real\n * address gets 409 `email_change_needs_code`: change it with\n * {@link requestEmailChange} and {@link confirmEmailChange}. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Step one of an email change: a six-digit code goes to the new address\n * and works for 5 minutes. Nothing changes yet.\n * Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`\n * (five codes an hour). */\n async requestEmailChange(input: { email: string }): Promise<EmailChangeRequested> {\n return this.http.post<EmailChangeRequested>(\"/me/email/change\", {\n body: { email: input.email },\n });\n }\n\n /** Step two: the code from the e-mail changes the address; the old one\n * gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new\n * request is needed), 409 the address was taken meanwhile. */\n async confirmEmailChange(input: { challengeId: string; code: string }): Promise<User> {\n return this.http.post<User>(\"/me/email/change/confirm\", {\n body: { challenge_id: input.challengeId, code: input.code },\n });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ConsentKind, ConsentChannel } from './consents.cjs';
|
|
1
2
|
import { H as HttpClient, T as TokenStore } from '../http-DeANAoTs.cjs';
|
|
2
3
|
import { SignupAttribution } from './attribution.cjs';
|
|
3
4
|
import { CodeResult } from './codes.cjs';
|
|
@@ -58,6 +59,11 @@ interface ExchangeTelegramInput {
|
|
|
58
59
|
* reads the `startapp` of the link the Mini App was opened with, when
|
|
59
60
|
* that is a code. The result comes back as `code_result`. */
|
|
60
61
|
code?: string;
|
|
62
|
+
/** Consents for a new account, as in `register`. Sent as `consents`;
|
|
63
|
+
* ignored for an account that already exists. */
|
|
64
|
+
consents?: ConsentKind[];
|
|
65
|
+
/** Sent as `consent_channel`; the server takes `miniapp` when omitted. */
|
|
66
|
+
consentChannel?: ConsentChannel;
|
|
61
67
|
}
|
|
62
68
|
/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has
|
|
63
69
|
* signed in with yet. No account was created and no JWT was stored. */
|
|
@@ -151,6 +157,19 @@ interface RegisterInput {
|
|
|
151
157
|
* sign-up: the account is created and `code_result` says why the code
|
|
152
158
|
* was not applied, so the app can show it. */
|
|
153
159
|
code?: string;
|
|
160
|
+
/** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),
|
|
161
|
+
* `personal_data`, `marketing`. A deployment can require the first two
|
|
162
|
+
* (400 `consents_required` without them). */
|
|
163
|
+
consents?: ConsentKind[];
|
|
164
|
+
/** Where they were ticked. Read from the client header when omitted. */
|
|
165
|
+
consent_channel?: ConsentChannel;
|
|
166
|
+
}
|
|
167
|
+
/** What `requestEmailChange` returns: send `challenge_id` back with the code. */
|
|
168
|
+
interface EmailChangeRequested {
|
|
169
|
+
challenge_id: string;
|
|
170
|
+
/** Where the code went, partly hidden: `al***@example.com`. */
|
|
171
|
+
destination_hint: string;
|
|
172
|
+
expires_at: string;
|
|
154
173
|
}
|
|
155
174
|
/** A signed-in session without the login `stage` marker — what
|
|
156
175
|
* `register` returns. With a `code`, `code_result` is set. */
|
|
@@ -202,7 +221,8 @@ declare class AuthResource {
|
|
|
202
221
|
* `wallet_currency` must be one the deployment offers; omit it to take
|
|
203
222
|
* the deployment default (it can be switched later via `client.wallet`
|
|
204
223
|
* while the wallet is empty).
|
|
205
|
-
* Errors: 400 `validation` / `currency_not_allowed
|
|
224
|
+
* Errors: 400 `validation` / `currency_not_allowed` / `consents_required`
|
|
225
|
+
* / `unknown_consent`, 409 email taken. */
|
|
206
226
|
register(input: RegisterInput): Promise<Session>;
|
|
207
227
|
/** Finish a `totp_setup_required` login: send the first code from the
|
|
208
228
|
* authenticator app. The JWT is stored. The response carries ten
|
|
@@ -252,12 +272,27 @@ declare class AuthResource {
|
|
|
252
272
|
* Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
|
|
253
273
|
* another account); 503 `telegram_not_configured`. */
|
|
254
274
|
linkTelegram(input: LinkTelegramInput): Promise<JwtIssued>;
|
|
255
|
-
/** Attach
|
|
256
|
-
*
|
|
257
|
-
*
|
|
275
|
+
/** Attach the first real email to a Telegram-made account (and clear
|
|
276
|
+
* `email_pending`). 409 if taken. An account that already has a real
|
|
277
|
+
* address gets 409 `email_change_needs_code`: change it with
|
|
278
|
+
* {@link requestEmailChange} and {@link confirmEmailChange}. */
|
|
258
279
|
linkEmail(input: {
|
|
259
280
|
email: string;
|
|
260
281
|
}): Promise<User>;
|
|
282
|
+
/** Step one of an email change: a six-digit code goes to the new address
|
|
283
|
+
* and works for 5 minutes. Nothing changes yet.
|
|
284
|
+
* Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`
|
|
285
|
+
* (five codes an hour). */
|
|
286
|
+
requestEmailChange(input: {
|
|
287
|
+
email: string;
|
|
288
|
+
}): Promise<EmailChangeRequested>;
|
|
289
|
+
/** Step two: the code from the e-mail changes the address; the old one
|
|
290
|
+
* gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new
|
|
291
|
+
* request is needed), 409 the address was taken meanwhile. */
|
|
292
|
+
confirmEmailChange(input: {
|
|
293
|
+
challengeId: string;
|
|
294
|
+
code: string;
|
|
295
|
+
}): Promise<User>;
|
|
261
296
|
/** Current user — fails 401 when the stored JWT is expired or
|
|
262
297
|
* missing. Useful as a "do I have a session" probe on app boot. */
|
|
263
298
|
me(): Promise<User>;
|
|
@@ -267,4 +302,4 @@ declare class AuthResource {
|
|
|
267
302
|
signOut(): Promise<void>;
|
|
268
303
|
}
|
|
269
304
|
|
|
270
|
-
export { AuthResource, type AvailableMethod, type ChangePasswordInput, type ExchangeTelegramInput, type JwtIssued, type LinkTelegramInput, type LoginInput, type LoginResponse, type OtpSentResponse, type OtpVerifyInput, type RegisterInput, type Session, type SwitchMethodInput, type TelegramLink, type TelegramUnknown, type TotpRequired, type TotpSetupComplete, type TotpSetupRequired, type TotpVerifyInput, type User };
|
|
305
|
+
export { AuthResource, type AvailableMethod, type ChangePasswordInput, type EmailChangeRequested, type ExchangeTelegramInput, type JwtIssued, type LinkTelegramInput, type LoginInput, type LoginResponse, type OtpSentResponse, type OtpVerifyInput, type RegisterInput, type Session, type SwitchMethodInput, type TelegramLink, type TelegramUnknown, type TotpRequired, type TotpSetupComplete, type TotpSetupRequired, type TotpVerifyInput, type User };
|
package/dist/resources/auth.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ConsentKind, ConsentChannel } from './consents.js';
|
|
1
2
|
import { H as HttpClient, T as TokenStore } from '../http-DeANAoTs.js';
|
|
2
3
|
import { SignupAttribution } from './attribution.js';
|
|
3
4
|
import { CodeResult } from './codes.js';
|
|
@@ -58,6 +59,11 @@ interface ExchangeTelegramInput {
|
|
|
58
59
|
* reads the `startapp` of the link the Mini App was opened with, when
|
|
59
60
|
* that is a code. The result comes back as `code_result`. */
|
|
60
61
|
code?: string;
|
|
62
|
+
/** Consents for a new account, as in `register`. Sent as `consents`;
|
|
63
|
+
* ignored for an account that already exists. */
|
|
64
|
+
consents?: ConsentKind[];
|
|
65
|
+
/** Sent as `consent_channel`; the server takes `miniapp` when omitted. */
|
|
66
|
+
consentChannel?: ConsentChannel;
|
|
61
67
|
}
|
|
62
68
|
/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has
|
|
63
69
|
* signed in with yet. No account was created and no JWT was stored. */
|
|
@@ -151,6 +157,19 @@ interface RegisterInput {
|
|
|
151
157
|
* sign-up: the account is created and `code_result` says why the code
|
|
152
158
|
* was not applied, so the app can show it. */
|
|
153
159
|
code?: string;
|
|
160
|
+
/** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),
|
|
161
|
+
* `personal_data`, `marketing`. A deployment can require the first two
|
|
162
|
+
* (400 `consents_required` without them). */
|
|
163
|
+
consents?: ConsentKind[];
|
|
164
|
+
/** Where they were ticked. Read from the client header when omitted. */
|
|
165
|
+
consent_channel?: ConsentChannel;
|
|
166
|
+
}
|
|
167
|
+
/** What `requestEmailChange` returns: send `challenge_id` back with the code. */
|
|
168
|
+
interface EmailChangeRequested {
|
|
169
|
+
challenge_id: string;
|
|
170
|
+
/** Where the code went, partly hidden: `al***@example.com`. */
|
|
171
|
+
destination_hint: string;
|
|
172
|
+
expires_at: string;
|
|
154
173
|
}
|
|
155
174
|
/** A signed-in session without the login `stage` marker — what
|
|
156
175
|
* `register` returns. With a `code`, `code_result` is set. */
|
|
@@ -202,7 +221,8 @@ declare class AuthResource {
|
|
|
202
221
|
* `wallet_currency` must be one the deployment offers; omit it to take
|
|
203
222
|
* the deployment default (it can be switched later via `client.wallet`
|
|
204
223
|
* while the wallet is empty).
|
|
205
|
-
* Errors: 400 `validation` / `currency_not_allowed
|
|
224
|
+
* Errors: 400 `validation` / `currency_not_allowed` / `consents_required`
|
|
225
|
+
* / `unknown_consent`, 409 email taken. */
|
|
206
226
|
register(input: RegisterInput): Promise<Session>;
|
|
207
227
|
/** Finish a `totp_setup_required` login: send the first code from the
|
|
208
228
|
* authenticator app. The JWT is stored. The response carries ten
|
|
@@ -252,12 +272,27 @@ declare class AuthResource {
|
|
|
252
272
|
* Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
|
|
253
273
|
* another account); 503 `telegram_not_configured`. */
|
|
254
274
|
linkTelegram(input: LinkTelegramInput): Promise<JwtIssued>;
|
|
255
|
-
/** Attach
|
|
256
|
-
*
|
|
257
|
-
*
|
|
275
|
+
/** Attach the first real email to a Telegram-made account (and clear
|
|
276
|
+
* `email_pending`). 409 if taken. An account that already has a real
|
|
277
|
+
* address gets 409 `email_change_needs_code`: change it with
|
|
278
|
+
* {@link requestEmailChange} and {@link confirmEmailChange}. */
|
|
258
279
|
linkEmail(input: {
|
|
259
280
|
email: string;
|
|
260
281
|
}): Promise<User>;
|
|
282
|
+
/** Step one of an email change: a six-digit code goes to the new address
|
|
283
|
+
* and works for 5 minutes. Nothing changes yet.
|
|
284
|
+
* Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`
|
|
285
|
+
* (five codes an hour). */
|
|
286
|
+
requestEmailChange(input: {
|
|
287
|
+
email: string;
|
|
288
|
+
}): Promise<EmailChangeRequested>;
|
|
289
|
+
/** Step two: the code from the e-mail changes the address; the old one
|
|
290
|
+
* gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new
|
|
291
|
+
* request is needed), 409 the address was taken meanwhile. */
|
|
292
|
+
confirmEmailChange(input: {
|
|
293
|
+
challengeId: string;
|
|
294
|
+
code: string;
|
|
295
|
+
}): Promise<User>;
|
|
261
296
|
/** Current user — fails 401 when the stored JWT is expired or
|
|
262
297
|
* missing. Useful as a "do I have a session" probe on app boot. */
|
|
263
298
|
me(): Promise<User>;
|
|
@@ -267,4 +302,4 @@ declare class AuthResource {
|
|
|
267
302
|
signOut(): Promise<void>;
|
|
268
303
|
}
|
|
269
304
|
|
|
270
|
-
export { AuthResource, type AvailableMethod, type ChangePasswordInput, type ExchangeTelegramInput, type JwtIssued, type LinkTelegramInput, type LoginInput, type LoginResponse, type OtpSentResponse, type OtpVerifyInput, type RegisterInput, type Session, type SwitchMethodInput, type TelegramLink, type TelegramUnknown, type TotpRequired, type TotpSetupComplete, type TotpSetupRequired, type TotpVerifyInput, type User };
|
|
305
|
+
export { AuthResource, type AvailableMethod, type ChangePasswordInput, type EmailChangeRequested, type ExchangeTelegramInput, type JwtIssued, type LinkTelegramInput, type LoginInput, type LoginResponse, type OtpSentResponse, type OtpVerifyInput, type RegisterInput, type Session, type SwitchMethodInput, type TelegramLink, type TelegramUnknown, type TotpRequired, type TotpSetupComplete, type TotpSetupRequired, type TotpVerifyInput, type User };
|
package/dist/resources/auth.js
CHANGED
|
@@ -98,7 +98,8 @@ var AuthResource = class {
|
|
|
98
98
|
* `wallet_currency` must be one the deployment offers; omit it to take
|
|
99
99
|
* the deployment default (it can be switched later via `client.wallet`
|
|
100
100
|
* while the wallet is empty).
|
|
101
|
-
* Errors: 400 `validation` / `currency_not_allowed
|
|
101
|
+
* Errors: 400 `validation` / `currency_not_allowed` / `consents_required`
|
|
102
|
+
* / `unknown_consent`, 409 email taken. */
|
|
102
103
|
async register(input) {
|
|
103
104
|
const resp = await this.http.post("/auth/register", {
|
|
104
105
|
body: withRemember(input),
|
|
@@ -143,6 +144,8 @@ var AuthResource = class {
|
|
|
143
144
|
if (input.provision !== void 0) body.provision = input.provision;
|
|
144
145
|
if (input.attribution !== void 0) body.attribution = input.attribution;
|
|
145
146
|
if (input.code !== void 0) body.code = input.code;
|
|
147
|
+
if (input.consents !== void 0) body.consents = input.consents;
|
|
148
|
+
if (input.consentChannel !== void 0) body.consent_channel = input.consentChannel;
|
|
146
149
|
let resp;
|
|
147
150
|
try {
|
|
148
151
|
resp = await this.http.post("/auth/telegram/exchange", {
|
|
@@ -177,12 +180,30 @@ var AuthResource = class {
|
|
|
177
180
|
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
178
181
|
return resp;
|
|
179
182
|
}
|
|
180
|
-
/** Attach
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
+
/** Attach the first real email to a Telegram-made account (and clear
|
|
184
|
+
* `email_pending`). 409 if taken. An account that already has a real
|
|
185
|
+
* address gets 409 `email_change_needs_code`: change it with
|
|
186
|
+
* {@link requestEmailChange} and {@link confirmEmailChange}. */
|
|
183
187
|
async linkEmail(input) {
|
|
184
188
|
return this.http.post("/me/email", { body: { email: input.email } });
|
|
185
189
|
}
|
|
190
|
+
/** Step one of an email change: a six-digit code goes to the new address
|
|
191
|
+
* and works for 5 minutes. Nothing changes yet.
|
|
192
|
+
* Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`
|
|
193
|
+
* (five codes an hour). */
|
|
194
|
+
async requestEmailChange(input) {
|
|
195
|
+
return this.http.post("/me/email/change", {
|
|
196
|
+
body: { email: input.email }
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
/** Step two: the code from the e-mail changes the address; the old one
|
|
200
|
+
* gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new
|
|
201
|
+
* request is needed), 409 the address was taken meanwhile. */
|
|
202
|
+
async confirmEmailChange(input) {
|
|
203
|
+
return this.http.post("/me/email/change/confirm", {
|
|
204
|
+
body: { challenge_id: input.challengeId, code: input.code }
|
|
205
|
+
});
|
|
206
|
+
}
|
|
186
207
|
/** Current user — fails 401 when the stored JWT is expired or
|
|
187
208
|
* missing. Useful as a "do I have a session" probe on app boot. */
|
|
188
209
|
async me() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/error.ts","../../src/resources/auth.ts"],"names":[],"mappings":";AA2CO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,IAAS,EAA+B,UAAA,KAAe,IAAA;AAC/F;;;ACyJA,SAAS,aACP,KAAA,EACiD;AACjD,EAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,EAAA,OAAO,WAAW,EAAE,GAAG,IAAA,EAAM,WAAA,EAAa,MAAK,GAAI,IAAA;AACrD;AAEO,IAAM,eAAN,MAAmB;AAAA,EACxB,WAAA,CACmB,IAAA,EACA,MAAA,EACA,UAAA,EACjB;AAHiB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAEjB,IAAA,IAAI,UAAA,EAAY,IA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AAA,CAAW,cAAA,EAAgB;AAAA,QACzC,MAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,QAAA,KAAa,EAAC;AAAA,QACjD,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,IAAA,CAAK,YAAY,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,EACpE;AACF","file":"auth.js","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport type { SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n if (input.attribution !== undefined) body.attribution = input.attribution;\n if (input.code !== undefined) body.code = input.code;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach a real email to the current user (and clear `email_pending`).\n * Used after a Telegram exchange to satisfy the email requirement; also\n * works for a password user changing their address. 409 if taken. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/error.ts","../../src/resources/auth.ts"],"names":[],"mappings":";AA2CO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,IAAS,EAA+B,UAAA,KAAe,IAAA;AAC/F;;;AC6KA,SAAS,aACP,KAAA,EACiD;AACjD,EAAA,MAAM,EAAE,QAAA,EAAU,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AA,CAAK,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,IAAA,CAAK,YAAY,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,EACpE;AACF","file":"auth.js","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport type { SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n /** Consents for a new account, as in `register`. Sent as `consents`;\n * ignored for an account that already exists. */\n consents?: ConsentKind[];\n /** Sent as `consent_channel`; the server takes `miniapp` when omitted. */\n consentChannel?: ConsentChannel;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n /** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),\n * `personal_data`, `marketing`. A deployment can require the first two\n * (400 `consents_required` without them). */\n consents?: ConsentKind[];\n /** Where they were ticked. Read from the client header when omitted. */\n consent_channel?: ConsentChannel;\n}\n\n/** What `requestEmailChange` returns: send `challenge_id` back with the code. */\nexport interface EmailChangeRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed` / `consents_required`\n * / `unknown_consent`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n consents?: ConsentKind[];\n consent_channel?: ConsentChannel;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n if (input.attribution !== undefined) body.attribution = input.attribution;\n if (input.code !== undefined) body.code = input.code;\n if (input.consents !== undefined) body.consents = input.consents;\n if (input.consentChannel !== undefined) body.consent_channel = input.consentChannel;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the first real email to a Telegram-made account (and clear\n * `email_pending`). 409 if taken. An account that already has a real\n * address gets 409 `email_change_needs_code`: change it with\n * {@link requestEmailChange} and {@link confirmEmailChange}. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Step one of an email change: a six-digit code goes to the new address\n * and works for 5 minutes. Nothing changes yet.\n * Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`\n * (five codes an hour). */\n async requestEmailChange(input: { email: string }): Promise<EmailChangeRequested> {\n return this.http.post<EmailChangeRequested>(\"/me/email/change\", {\n body: { email: input.email },\n });\n }\n\n /** Step two: the code from the e-mail changes the address; the old one\n * gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new\n * request is needed), 409 the address was taken meanwhile. */\n async confirmEmailChange(input: { challengeId: string; code: string }): Promise<User> {\n return this.http.post<User>(\"/me/email/change/confirm\", {\n body: { challenge_id: input.challengeId, code: input.code },\n });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}
|
package/dist/resources/cards.cjs
CHANGED
|
@@ -9,6 +9,7 @@ function cardRequestBody(input) {
|
|
|
9
9
|
useBonus,
|
|
10
10
|
bonusAmount,
|
|
11
11
|
promoCode,
|
|
12
|
+
consentChannel,
|
|
12
13
|
initial_amount: _ignored,
|
|
13
14
|
...rest
|
|
14
15
|
} = input;
|
|
@@ -19,6 +20,7 @@ function cardRequestBody(input) {
|
|
|
19
20
|
if (useBonus !== void 0) body["use_bonus"] = useBonus;
|
|
20
21
|
if (bonusAmount !== void 0) body["bonus_amount"] = bonusAmount;
|
|
21
22
|
if (promoCode !== void 0) body["promo_code"] = promoCode;
|
|
23
|
+
if (consentChannel !== void 0) body["consent_channel"] = consentChannel;
|
|
22
24
|
return body;
|
|
23
25
|
}
|
|
24
26
|
var CardsResource = class {
|