@octap/browser-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OctaPointees
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
1
+ # @octap/browser-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Customer sign-in and transaction signing for a merchant's website, added the way you would add
4
+ Firebase Auth. You never handle OAuth nonces, ephemeral keys, ZK proofs or Enoki.
5
+
6
+ This package holds no merchant credential. Balance, history, voucher lists and claims need your API
7
+ key, so they stay on your backend through `@octap/sdk`.
8
+
9
+ ```bash
10
+ npm install @octap/browser-sdk
11
+ ```
12
+
13
+ ## Sign a customer in
14
+
15
+ ```ts
16
+ import { createOctapAuth } from '@octap/browser-sdk';
17
+
18
+ const auth = createOctapAuth({ apiBaseUrl, organizationId, googleClientId });
19
+
20
+ auth.onAuthStateChanged((user) => {
21
+ // { endUserId, memberId, suiAddress } or null. Also called once on load, after a reload restores.
22
+ });
23
+
24
+ await auth.renderGoogleButton(document.getElementById('sign-in'), {
25
+ onError: (error) => showMessage(error.message),
26
+ });
27
+ ```
28
+
29
+ Signing in also enrolls the customer in your organization. The button renders nothing while a
30
+ customer is signed in, and returns after they sign out or their session expires. Google's token
31
+ lasts about an hour: when `getIdToken` finds it expired, the customer is signed out, so listeners get
32
+ `null` and the button returns.
33
+
34
+ ## Prove the customer to your backend
35
+
36
+ Send the token to your backend, and check it there with `verifyCustomer` from `@octap/sdk`. Never
37
+ trust a member ID your frontend sends on its own.
38
+
39
+ ```ts
40
+ const response = await fetch('/api/claim', {
41
+ method: 'POST',
42
+ headers: { authorization: `Bearer ${await auth.getIdToken()}` },
43
+ body: JSON.stringify({ voucherId }),
44
+ });
45
+ ```
46
+
47
+ ## Claim a paid voucher
48
+
49
+ Your backend calls `claimVoucher` and returns the result. The customer's device then signs it:
50
+
51
+ ```ts
52
+ const claim = await response.json();
53
+ if (claim.status === 'RESERVED') {
54
+ await auth.signAndFinalize(claim);
55
+ }
56
+ ```
57
+
58
+ Follow these rules, whatever your interface looks like:
59
+
60
+ - A RESERVED voucher is not owned yet. Show it as pending until finalize succeeds.
61
+ - `signAndFinalize` never retries by itself. On `outcome-unknown`, the transaction may have failed
62
+ or may still land. Read the claim from your backend, or claim again with the **same** idempotency
63
+ key. `status` and `body` carry what the server answered, if anything.
64
+ - Use a new idempotency key only after the claim is CANCELLED.
65
+
66
+ ## Use a voucher
67
+
68
+ Your backend calls `prepareVoucherUse` from `@octap/sdk` and returns the result. Show the customer
69
+ which voucher they are using, then have their device sign it:
70
+
71
+ ```ts
72
+ const use = await response.json();
73
+ const used = await auth.signAndFinalizeVoucherUse(use);
74
+ // used.status is REDEEMED; deliver the benefit on the voucher.redeemed webhook.
75
+ ```
76
+
77
+ The signature is the only thing that can mark a customer's voucher used: your API key cannot.
78
+ `signAndFinalizeVoucherUse` never retries by itself. On `outcome-unknown`, read the voucher from your
79
+ backend before you try again.
80
+
81
+ ## Lower-level signing
82
+
83
+ `auth.signTransaction(transactionBytes)` is the lower-level call: it returns the zkLogin signature
84
+ and sends nothing. It refuses bytes whose sender is not the signed-in customer.
85
+
86
+ ## Errors
87
+
88
+ Every failure is an `OctapAuthError` with a `code`. API errors also have `status` and `body`.
89
+
90
+ | Code | Meaning | What to do |
91
+ | ---------------------- | ------------------------------------------------------- | -------------------------------- |
92
+ | `sign-in-canceled` | The customer closed Google's window | Nothing; the button still works |
93
+ | `nonce-mismatch` | Google's token was not issued for this attempt | Ask them to sign in again |
94
+ | `provider-unavailable` | Google's script could not load | Check for blocked scripts |
95
+ | `not-signed-in` | No customer is signed in | Show the button |
96
+ | `session-expired` | The signing session passed `maxEpoch` | Ask them to sign in again |
97
+ | `token-expired` | Google's token expired (after about an hour) | Ask them to sign in again |
98
+ | `wrong-account` | The transaction belongs to a different customer | Ask them to use that account |
99
+ | `invalid-claim` | The claim has nothing to sign, or its bytes are invalid | Check the claim's status |
100
+ | `outcome-unknown` | Finalize may have reached the chain | Read the claim; do not re-create |
101
+ | `api-error` | OctaP answered with an error | See `status` and `message` |
102
+ | `network-error` | OctaP could not be reached | Retry later |
103
+ | `timeout` | The request took too long | Retry later |
104
+ | `aborted` | Your `AbortSignal` fired | Nothing |
105
+ | `invalid-response` | OctaP's response could not be read | Report it |
106
+
107
+ `sign-in-canceled` is a best guess from the page regaining focus, because Google's button reports no
108
+ cancellation itself. It can fire while the popup is still open if the customer clicks back to the
109
+ page, and may not fire at all. Use it only to show a message.
110
+
111
+ ## Security
112
+
113
+ The session holds the ephemeral signing key, the proof and the id_token until `maxEpoch` or sign-out.
114
+
115
+ - By default these are in `sessionStorage`, so they survive a reload in this tab. Any script on your
116
+ page can read them, so an XSS flaw lets an attacker sign as this customer until the session
117
+ expires. Use a strict Content Security Policy, and avoid third-party scripts on these pages.
118
+ - Pass `persistence: 'memory'` to keep them out of browser storage. A reload then signs the customer
119
+ out.
120
+ - The private key is never sent anywhere. Only its public half reaches OctaP.
121
+
122
+ ## Google client ID
123
+
124
+ Use the Google client ID OctaP gives you, and ask OctaP to add your site's origin to it. All merchants
125
+ share this client for now, so moving to per-merchant clients later would change customer wallets.
126
+
127
+ ## Local example
128
+
129
+ See [the browser auth example](https://github.com/OctaPointees/octap-core/tree/dev/ts-sdks/examples/browser-auth)
130
+ in the octap-core repository for a runnable page.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,118 @@
1
+ import { type RequestOptions } from './core-api.js';
2
+ import { OctapAuthError } from './errors.js';
3
+ import { type OctapUser, type Persistence } from './session-store.js';
4
+ export interface OctapAuthOptions {
5
+ apiBaseUrl: string;
6
+ organizationId: string;
7
+ googleClientId: string;
8
+ /**
9
+ * Where the signing key, proof and id_token are kept until `maxEpoch` or sign-out. `session` (the
10
+ * default) survives a reload in this tab; `memory` does not. Any script running on your page can
11
+ * read a `session` value, so an XSS flaw exposes it until it expires.
12
+ */
13
+ persistence?: Persistence;
14
+ timeoutMs?: number;
15
+ fetch?: typeof fetch;
16
+ }
17
+ export interface RenderOptions {
18
+ /** Sign-in failures, including a customer closing Google's window. */
19
+ onError?: (error: OctapAuthError) => void;
20
+ /** Passed through to Google's button, such as `theme`, `size`, `text` or `shape`. */
21
+ button?: Record<string, unknown>;
22
+ }
23
+ /** The merchant backend's claim result, as `@octap/sdk`'s `claimVoucher` returns it. */
24
+ export interface SignableClaim {
25
+ status: string;
26
+ digest?: string | null;
27
+ transactionBytes?: string | null;
28
+ }
29
+ /** What `prepareVoucherUse` returned on the merchant's server. */
30
+ export interface SignableVoucherUse {
31
+ digest?: string | null;
32
+ transactionBytes?: string | null;
33
+ }
34
+ export interface FinalizedVoucherUse {
35
+ voucherOwnershipId: string;
36
+ voucherId: string;
37
+ serialCode: string;
38
+ status: string;
39
+ redeemedAt: string;
40
+ voucherTitle: string;
41
+ discountType?: string | null;
42
+ discountValue?: string | null;
43
+ blockchainDigest: string;
44
+ }
45
+ export interface FinalizedClaim {
46
+ transactionId: string;
47
+ organizationEndUserId: string;
48
+ pointsRedeemed: number;
49
+ newBalance: number;
50
+ status: string;
51
+ blockchainDigest: string;
52
+ }
53
+ export type AuthStateListener = (user: OctapUser | null) => void;
54
+ export declare class OctapAuth {
55
+ private readonly api;
56
+ private readonly store;
57
+ private readonly organizationId;
58
+ private readonly googleClientId;
59
+ private readonly listeners;
60
+ private session;
61
+ private provider?;
62
+ private button?;
63
+ private signingIn;
64
+ /** Changes when the session ends, so a sign-in still running cannot bring it back. */
65
+ private signInGeneration;
66
+ /** Changes on each new button, so only the latest nonce can be rendered or used. */
67
+ private armGeneration;
68
+ private expiryTimer?;
69
+ constructor(options: OctapAuthOptions);
70
+ /** The signed-in customer, restored synchronously after a reload. Null once the session expires. */
71
+ get currentUser(): OctapUser | null;
72
+ /** Calls `listener` with the current customer soon after subscribing, then on every change. */
73
+ onAuthStateChanged(listener: AuthStateListener): () => void;
74
+ /**
75
+ * Renders Google's button. Key, nonce, enrollment and proof are handled when the customer uses it.
76
+ * While a customer is signed in it renders nothing, and appears once they sign out or expire.
77
+ */
78
+ renderGoogleButton(element: HTMLElement, options?: RenderOptions): Promise<void>;
79
+ /**
80
+ * The id_token for your backend to check with `@octap/sdk`'s `verifyCustomer`. Google's token lasts
81
+ * about an hour. When it has expired the customer is signed out, so the button returns for a new one.
82
+ */
83
+ getIdToken(): Promise<string>;
84
+ /** Lower-level signing: returns the zkLogin signature over base64 transaction bytes. */
85
+ signTransaction(transactionBytes: string): Promise<string>;
86
+ /**
87
+ * Signs a RESERVED claim and finalizes it. The voucher is not owned until this resolves.
88
+ *
89
+ * Never retried automatically. On `outcome-unknown` the transaction may have failed or may still
90
+ * land, so read the claim from your backend, or retry the claim with the same idempotency key. Use
91
+ * a new key only after the claim is CANCELLED.
92
+ */
93
+ signAndFinalize(claim: SignableClaim, options?: RequestOptions): Promise<FinalizedClaim>;
94
+ /**
95
+ * Signs the customer's use of a voucher and finalizes it. Show the customer what they are using
96
+ * first: this signature is the only thing that can mark their voucher used. Never retried
97
+ * automatically; on `outcome-unknown`, read the voucher from your backend.
98
+ */
99
+ signAndFinalizeVoucherUse(use: SignableVoucherUse, options?: RequestOptions): Promise<FinalizedVoucherUse>;
100
+ private submitSigned;
101
+ /** Always ends the session. A button that cannot return is reported through `onError`. */
102
+ signOut(): Promise<void>;
103
+ private requireSession;
104
+ private expireSession;
105
+ private endSession;
106
+ /** Lets an open page notice expiry without waiting for a call to fail. Only runs in a browser. */
107
+ private scheduleExpiry;
108
+ private notify;
109
+ /** One merchant listener's bug must not undo a sign-in, or stop the other listeners. */
110
+ private call;
111
+ private reportError;
112
+ /** Puts a usable button back, if one was rendered, reporting rather than throwing a failure. */
113
+ private rearm;
114
+ /** Prepares a key and nonce and renders the button with them. A newer call replaces an older one. */
115
+ private arm;
116
+ private completeSignIn;
117
+ }
118
+ export declare function createOctapAuth(options: OctapAuthOptions): OctapAuth;
package/dist/auth.js ADDED
@@ -0,0 +1,263 @@
1
+ import { CoreApi, normalizeBaseUrl } from './core-api.js';
2
+ import { OctapAuthError } from './errors.js';
3
+ import { createGoogleProvider } from './google-provider.js';
4
+ import { createSessionStore, } from './session-store.js';
5
+ import { PendingSignIn, idTokenExpiry, signWithZkLogin } from './zklogin-signer.js';
6
+ const DEFAULT_TIMEOUT_MS = 35_000;
7
+ /** Finalize waits for the chain's verdict, so it gets longer than an ordinary request. */
8
+ const FINALIZE_TIMEOUT_MS = 90_000;
9
+ /** Browsers run a longer `setTimeout` immediately. */
10
+ const MAX_TIMER_MS = 2_147_483_647;
11
+ export class OctapAuth {
12
+ api;
13
+ store;
14
+ organizationId;
15
+ googleClientId;
16
+ listeners = new Set();
17
+ session;
18
+ provider;
19
+ button;
20
+ signingIn = false;
21
+ /** Changes when the session ends, so a sign-in still running cannot bring it back. */
22
+ signInGeneration = 0;
23
+ /** Changes on each new button, so only the latest nonce can be rendered or used. */
24
+ armGeneration = 0;
25
+ expiryTimer;
26
+ constructor(options) {
27
+ const fetchFn = options.fetch ?? ((...args) => globalThis.fetch(...args));
28
+ this.api = new CoreApi(options.apiBaseUrl, fetchFn, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
29
+ this.organizationId = options.organizationId;
30
+ this.googleClientId = options.googleClientId;
31
+ this.store = createSessionStore(options.persistence ?? 'session', {
32
+ apiBaseUrl: normalizeBaseUrl(options.apiBaseUrl),
33
+ googleClientId: options.googleClientId,
34
+ organizationId: options.organizationId,
35
+ });
36
+ this.session = this.store.load();
37
+ if (this.session && Date.now() >= this.session.signer.expiresAt) {
38
+ this.store.clear();
39
+ this.session = null;
40
+ }
41
+ this.scheduleExpiry();
42
+ }
43
+ /** The signed-in customer, restored synchronously after a reload. Null once the session expires. */
44
+ get currentUser() {
45
+ return this.session && Date.now() < this.session.signer.expiresAt ? this.session.user : null;
46
+ }
47
+ /** Calls `listener` with the current customer soon after subscribing, then on every change. */
48
+ onAuthStateChanged(listener) {
49
+ this.listeners.add(listener);
50
+ queueMicrotask(() => {
51
+ if (this.listeners.has(listener))
52
+ this.call(listener);
53
+ });
54
+ return () => {
55
+ this.listeners.delete(listener);
56
+ };
57
+ }
58
+ /**
59
+ * Renders Google's button. Key, nonce, enrollment and proof are handled when the customer uses it.
60
+ * While a customer is signed in it renders nothing, and appears once they sign out or expire.
61
+ */
62
+ async renderGoogleButton(element, options = {}) {
63
+ this.button = { element, options };
64
+ this.provider = createGoogleProvider(this.googleClientId, options.button);
65
+ if (!this.currentUser)
66
+ await this.arm();
67
+ }
68
+ /**
69
+ * The id_token for your backend to check with `@octap/sdk`'s `verifyCustomer`. Google's token lasts
70
+ * about an hour. When it has expired the customer is signed out, so the button returns for a new one.
71
+ */
72
+ async getIdToken() {
73
+ const { idToken } = this.requireSession();
74
+ const expiry = idTokenExpiry(idToken);
75
+ if (expiry !== undefined && Date.now() >= expiry * 1000) {
76
+ this.expireSession();
77
+ throw new OctapAuthError('token-expired', 'The sign-in token expired. Sign in again.');
78
+ }
79
+ return idToken;
80
+ }
81
+ /** Lower-level signing: returns the zkLogin signature over base64 transaction bytes. */
82
+ async signTransaction(transactionBytes) {
83
+ const session = this.requireSession();
84
+ return signWithZkLogin(session.signer, session.user.suiAddress, transactionBytes);
85
+ }
86
+ /**
87
+ * Signs a RESERVED claim and finalizes it. The voucher is not owned until this resolves.
88
+ *
89
+ * Never retried automatically. On `outcome-unknown` the transaction may have failed or may still
90
+ * land, so read the claim from your backend, or retry the claim with the same idempotency key. Use
91
+ * a new key only after the claim is CANCELLED.
92
+ */
93
+ async signAndFinalize(claim, options = {}) {
94
+ if (claim.status !== 'RESERVED' || !claim.digest || !claim.transactionBytes) {
95
+ throw new OctapAuthError('invalid-claim', 'Only a RESERVED claim with transaction bytes can be signed.');
96
+ }
97
+ return this.submitSigned('/v1/credits/redeem/finalize', claim.digest, claim.transactionBytes, options);
98
+ }
99
+ /**
100
+ * Signs the customer's use of a voucher and finalizes it. Show the customer what they are using
101
+ * first: this signature is the only thing that can mark their voucher used. Never retried
102
+ * automatically; on `outcome-unknown`, read the voucher from your backend.
103
+ */
104
+ async signAndFinalizeVoucherUse(use, options = {}) {
105
+ if (!use.digest || !use.transactionBytes) {
106
+ throw new OctapAuthError('invalid-claim', 'Only a voucher use with transaction bytes can be signed.');
107
+ }
108
+ return this.submitSigned('/v1/rewards/vouchers/use/finalize', use.digest, use.transactionBytes, options);
109
+ }
110
+ async submitSigned(path, digest, transactionBytes, options) {
111
+ const signature = await this.signTransaction(transactionBytes);
112
+ try {
113
+ return await this.api.post(path, { digest, signature }, { ...options, timeoutMs: options.timeoutMs ?? FINALIZE_TIMEOUT_MS });
114
+ }
115
+ catch (err) {
116
+ // Core answers 400 for a bad signature and for an Enoki failure after sending alike, and 404 for
117
+ // a repeat of a finalize that already succeeded. Only a rate limit proves nothing was attempted.
118
+ throw err instanceof OctapAuthError && err.status === 429
119
+ ? err
120
+ : new OctapAuthError('outcome-unknown', 'The result of this transaction is not known yet. Check the claim before trying again.', err instanceof OctapAuthError ? { status: err.status, body: err.body } : {});
121
+ }
122
+ }
123
+ /** Always ends the session. A button that cannot return is reported through `onError`. */
124
+ async signOut() {
125
+ this.provider?.signOut();
126
+ this.endSession();
127
+ // The button's nonce belongs to a key this session may have used, so issue a fresh one.
128
+ await this.rearm();
129
+ }
130
+ requireSession() {
131
+ if (!this.session) {
132
+ throw new OctapAuthError('not-signed-in', 'No customer is signed in.');
133
+ }
134
+ if (Date.now() >= this.session.signer.expiresAt) {
135
+ this.expireSession();
136
+ throw new OctapAuthError('session-expired', 'The signing session expired. Sign in again.');
137
+ }
138
+ return this.session;
139
+ }
140
+ expireSession() {
141
+ this.endSession();
142
+ void this.rearm();
143
+ }
144
+ endSession() {
145
+ const hadSession = this.session !== null;
146
+ this.signInGeneration++;
147
+ this.signingIn = false;
148
+ this.store.clear();
149
+ this.session = null;
150
+ this.scheduleExpiry();
151
+ if (hadSession)
152
+ this.notify();
153
+ }
154
+ /** Lets an open page notice expiry without waiting for a call to fail. Only runs in a browser. */
155
+ scheduleExpiry() {
156
+ if (typeof window === 'undefined')
157
+ return;
158
+ window.clearTimeout(this.expiryTimer);
159
+ if (!this.session)
160
+ return;
161
+ const remaining = this.session.signer.expiresAt - Date.now();
162
+ this.expiryTimer = window.setTimeout(() => {
163
+ if (this.session && Date.now() >= this.session.signer.expiresAt)
164
+ this.expireSession();
165
+ else
166
+ this.scheduleExpiry();
167
+ }, Math.min(Math.max(remaining, 0), MAX_TIMER_MS));
168
+ }
169
+ notify() {
170
+ for (const listener of this.listeners)
171
+ this.call(listener);
172
+ }
173
+ /** One merchant listener's bug must not undo a sign-in, or stop the other listeners. */
174
+ call(listener) {
175
+ try {
176
+ listener(this.currentUser);
177
+ }
178
+ catch (err) {
179
+ console.error('An onAuthStateChanged listener threw:', err);
180
+ }
181
+ }
182
+ reportError(err) {
183
+ const error = err instanceof OctapAuthError
184
+ ? err
185
+ : new OctapAuthError('provider-unavailable', err instanceof Error ? err.message : String(err));
186
+ try {
187
+ this.button?.options.onError?.(error);
188
+ }
189
+ catch (handlerError) {
190
+ console.error('The onError handler threw:', handlerError);
191
+ }
192
+ }
193
+ /** Puts a usable button back, if one was rendered, reporting rather than throwing a failure. */
194
+ async rearm() {
195
+ if (!this.button)
196
+ return;
197
+ await this.arm().catch((err) => this.reportError(err));
198
+ }
199
+ /** Prepares a key and nonce and renders the button with them. A newer call replaces an older one. */
200
+ async arm() {
201
+ const generation = ++this.armGeneration;
202
+ const pending = await PendingSignIn.start(this.api);
203
+ if (generation !== this.armGeneration)
204
+ return;
205
+ await this.provider.render(this.button.element, pending.nonce, {
206
+ onIdToken: (idToken) => {
207
+ if (generation === this.armGeneration)
208
+ void this.completeSignIn(pending, idToken);
209
+ },
210
+ onCanceled: () => {
211
+ if (generation === this.armGeneration) {
212
+ this.reportError(new OctapAuthError('sign-in-canceled', 'Google sign-in was canceled.'));
213
+ }
214
+ },
215
+ });
216
+ }
217
+ async completeSignIn(pending, idToken) {
218
+ if (this.signingIn)
219
+ return;
220
+ this.signingIn = true;
221
+ const generation = this.signInGeneration;
222
+ const superseded = () => generation !== this.signInGeneration;
223
+ try {
224
+ pending.assertIssuedForThisAttempt(idToken);
225
+ const { suiAddress } = await this.api.post('/v1/identity/google-login', { idToken });
226
+ if (superseded())
227
+ return;
228
+ const { endUserId, organizationEndUserId } = await this.api.post(`/v1/identity/organizations/${encodeURIComponent(this.organizationId)}/enroll`, { idToken });
229
+ if (superseded())
230
+ return;
231
+ if (typeof suiAddress !== 'string' ||
232
+ typeof endUserId !== 'string' ||
233
+ typeof organizationEndUserId !== 'string') {
234
+ throw new OctapAuthError('invalid-response', 'OctaP returned an incomplete customer.');
235
+ }
236
+ const signer = await pending.prove(this.api, idToken);
237
+ if (superseded())
238
+ return;
239
+ this.session = { user: { endUserId, memberId: organizationEndUserId, suiAddress }, idToken, signer };
240
+ this.store.save(this.session);
241
+ this.scheduleExpiry();
242
+ // A button armed for another attempt must not outlive this session's sign-in.
243
+ this.armGeneration++;
244
+ this.button?.element.replaceChildren();
245
+ this.notify();
246
+ }
247
+ catch (err) {
248
+ if (superseded())
249
+ return;
250
+ this.reportError(err);
251
+ // A nonce is good for one attempt, so a failure must leave a usable button behind.
252
+ await this.rearm();
253
+ }
254
+ finally {
255
+ if (!superseded())
256
+ this.signingIn = false;
257
+ }
258
+ }
259
+ }
260
+ export function createOctapAuth(options) {
261
+ return new OctapAuth(options);
262
+ }
263
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAwB,MAAM,sBAAsB,CAAC;AAClF,OAAO,EACL,kBAAkB,GAKnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AA2DpF,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,0FAA0F;AAC1F,MAAM,mBAAmB,GAAG,MAAM,CAAC;AACnC,sDAAsD;AACtD,MAAM,YAAY,GAAG,aAAa,CAAC;AAEnC,MAAM,OAAO,SAAS;IACH,GAAG,CAAU;IACb,KAAK,CAAe;IACpB,cAAc,CAAS;IACvB,cAAc,CAAS;IACvB,SAAS,GAAG,IAAI,GAAG,EAAqB,CAAC;IAClD,OAAO,CAAuB;IAC9B,QAAQ,CAAmB;IAC3B,MAAM,CAAoD;IAC1D,SAAS,GAAG,KAAK,CAAC;IAC1B,sFAAsF;IAC9E,gBAAgB,GAAG,CAAC,CAAC;IAC7B,oFAAoF;IAC5E,aAAa,GA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;YAEzB,IAAI,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,EAAE,SAAS,EAAE,QAAQ,EAAE,qBAAqB,EAAE,UAAU,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;YACrG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAC9B,IAAI,CAAC,cAAc,EAAE,CAAC;YACtB,8EAA8E;YAC9E,IAAI,CAAC,aAAa,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,eAAe,EAAE,CAAC;YACvC,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACtB,IAAI,UAAU,EAAE;gBAAE,OAAO;YACzB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;YACtB,mFAAmF;YACnF,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,UAAU,EAAE;gBAAE,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QAC5C,CAAC;IACH,CAAC;CACF;AAED,MAAM,UAAU,eAAe,CAAC,OAAyB;IACvD,OAAO,IAAI,SAAS,CAAC,OAAO,CAAC,CAAC;AAChC,CAAC"}
@@ -0,0 +1,48 @@
1
+ import type { CreditBalanceSnapshot, LoyaltyTransactionDto, VoucherDto, ClaimVoucherResponse, VoucherOwnershipDto, GoogleLoginResponse, EnrollMemberResponse } from '@octap/contracts';
2
+ export interface BrowserClientOptions {
3
+ apiBaseUrl: string;
4
+ googleClientId?: string;
5
+ organizationId?: string;
6
+ getAuthToken?: () => Promise<string | null> | string | null;
7
+ }
8
+ export declare class OctaBrowserClient {
9
+ private readonly apiBaseUrl;
10
+ private readonly defaultOrganizationId?;
11
+ private readonly getAuthToken?;
12
+ constructor(options: BrowserClientOptions);
13
+ private request;
14
+ /**
15
+ * Get credit balance for a member.
16
+ */
17
+ getBalance(memberId: string): Promise<CreditBalanceSnapshot>;
18
+ /**
19
+ * List loyalty transactions for a member.
20
+ */
21
+ listTransactions(memberId: string, limit?: number): Promise<LoyaltyTransactionDto[]>;
22
+ /**
23
+ * List active vouchers in the organization.
24
+ */
25
+ listVouchers(organizationId?: string): Promise<VoucherDto[]>;
26
+ /**
27
+ * Get details of a specific voucher.
28
+ */
29
+ getVoucher(voucherId: string): Promise<VoucherDto>;
30
+ /**
31
+ * Claim a voucher using loyalty points.
32
+ */
33
+ claimVoucher(voucherId: string, organizationEndUserId: string, idempotencyKey?: string, organizationId?: string): Promise<ClaimVoucherResponse>;
34
+ /**
35
+ * List all vouchers claimed/owned by a member.
36
+ */
37
+ listMemberVouchers(memberId: string): Promise<VoucherOwnershipDto[]>;
38
+ /**
39
+ * Resolves a Google id_token (obtained from the host app's own Google Sign-In; this SDK does
40
+ * not render a sign-in button) to a zkLogin Sui address and a global end-user identity.
41
+ */
42
+ loginWithGoogle(idToken: string): Promise<GoogleLoginResponse>;
43
+ /**
44
+ * Enrolls an already-logged-in end user into one organization's loyalty program.
45
+ */
46
+ enroll(endUserId: string, organizationId?: string, externalMemberId?: string): Promise<EnrollMemberResponse>;
47
+ }
48
+ export declare function createBrowserClient(options: BrowserClientOptions): OctaBrowserClient;