@octap/browser-sdk 0.1.1 → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ ## 0.2.1
4
+
5
+ Additive only: types for a use of several vouchers; nothing that worked before changes.
6
+
7
+ ### Added
8
+
9
+ - Several vouchers with one signature (OCT-218): `signAndFinalizeVoucherUse` still signs one set of
10
+ bytes; for a use of several vouchers, `signAndFinalizeVoucherUse<FinalizedVoucherUses>()` returns
11
+ `vouchers`, `blockchainDigest` and `orderReference`. `FinalizedVoucherUse` gains `vouchers` and
12
+ `orderReference` and keeps every field it had. `FinalizedVoucher` and `FinalizedVoucherUses` are
13
+ exported.
14
+
15
+ ## 0.2.0
16
+
17
+ Breaking. Upgrade together with `@octap/sdk` 0.4, whose `verifyCustomer` takes the new customer
18
+ token, and against a Core with OCT-394.
19
+
20
+ ### Changed
21
+
22
+ - Customers sign in on OctaP's own page, in a popup (OCT-394). Your page no longer loads Google's
23
+ script and never sees Google's token.
24
+ - `createOctapAuth({ organizationId })`: `googleClientId` is gone, and `apiBaseUrl` is optional
25
+ (default `https://api.octap.biz`).
26
+ - Call `signIn()` from a click handler, or use `renderSignInButton()`: browsers block a popup opened
27
+ any other way.
28
+ - `getIdToken()` returns a customer token signed by OctaP for your organization only, valid up to an
29
+ hour. Check it on your backend with `@octap/sdk`'s `verifyCustomer`.
30
+ - Sessions saved by 0.1 are not restored: customers sign in again once after the upgrade.
31
+ - Error codes: `popup-blocked` is new, `nonce-mismatch` is gone.
32
+
33
+ ### Added
34
+
35
+ - `DEFAULT_API_BASE_URL`.
36
+ - `signIn({ signal })` can be aborted.
37
+
38
+ ### Setup
39
+
40
+ - Add your site's origin to your organization's sign-in origins in the console (`https://` only,
41
+ plus `http://localhost` while developing). OctaP delivers a sign-in to no other page.
42
+
43
+ ## 0.1.1
44
+
45
+ First published version. Google sign-in ran on the merchant's page, with the merchant's
46
+ `googleClientId`.
package/README.md CHANGED
@@ -15,26 +15,36 @@ npm install @octap/browser-sdk
15
15
  ```ts
16
16
  import { createOctapAuth } from '@octap/browser-sdk';
17
17
 
18
- const auth = createOctapAuth({ apiBaseUrl, organizationId, googleClientId });
18
+ const auth = createOctapAuth({ organizationId });
19
19
 
20
20
  auth.onAuthStateChanged((user) => {
21
21
  // { endUserId, memberId, suiAddress } or null. Also called once on load, after a reload restores.
22
22
  });
23
23
 
24
- await auth.renderGoogleButton(document.getElementById('sign-in'), {
24
+ auth.renderSignInButton(document.getElementById('sign-in'), {
25
25
  onError: (error) => showMessage(error.message),
26
26
  });
27
27
  ```
28
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.
29
+ The customer signs in with Google on OctaP's own page, in a popup. Signing in also enrolls them in
30
+ your organization. Google's token never reaches your page or your backend: your page gets the
31
+ customer, a signing key it keeps, and a customer token for your backend.
32
+
33
+ Before the first sign-in, add your site's origin (`https://shop.example`, and `http://localhost:3000`
34
+ while developing) to your organization's sign-in origins in the console. OctaP refuses to deliver a
35
+ sign-in to any other page. There is no Google client ID to configure.
36
+
37
+ To use your own button, call `auth.signIn()` from its click handler: browsers block a popup opened
38
+ any other way. The rendered button shows nothing while a customer is signed in, and returns after
39
+ they sign out or their session expires. `apiBaseUrl` defaults to `https://api.octap.biz`; set it only
40
+ for a Core running elsewhere, such as locally.
33
41
 
34
42
  ## Prove the customer to your backend
35
43
 
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.
44
+ Send the customer token to your backend, and check it there with `verifyCustomer` from `@octap/sdk`.
45
+ Never trust a member ID your frontend sends on its own. The token is valid for your organization
46
+ only and lasts up to an hour: when `getIdToken` finds it expired, the customer is signed out, so
47
+ listeners get `null` and the button returns.
38
48
 
39
49
  ```ts
40
50
  const response = await fetch('/api/claim', {
@@ -89,12 +99,12 @@ Every failure is an `OctapAuthError` with a `code`. API errors also have `status
89
99
 
90
100
  | Code | Meaning | What to do |
91
101
  | ---------------------- | ------------------------------------------------------- | -------------------------------- |
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 |
102
+ | `sign-in-canceled` | The customer closed the sign-in window | Nothing; the button still works |
103
+ | `popup-blocked` | The browser blocked the sign-in window | Call `signIn()` from a click |
104
+ | `provider-unavailable` | The SDK ran outside a browser | Sign in from the browser |
95
105
  | `not-signed-in` | No customer is signed in | Show the button |
96
106
  | `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 |
107
+ | `token-expired` | The customer token expired (after up to an hour) | Ask them to sign in again |
98
108
  | `wrong-account` | The transaction belongs to a different customer | Ask them to use that account |
99
109
  | `invalid-claim` | The claim has nothing to sign, or its bytes are invalid | Check the claim's status |
100
110
  | `outcome-unknown` | Finalize may have reached the chain | Read the claim; do not re-create |
@@ -104,13 +114,13 @@ Every failure is an `OctapAuthError` with a `code`. API errors also have `status
104
114
  | `aborted` | Your `AbortSignal` fired | Nothing |
105
115
  | `invalid-response` | OctaP's response could not be read | Report it |
106
116
 
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.
117
+ A sign-in that OctaP refuses, such as from an origin that is not in your sign-in origins, is an
118
+ `api-error` with the status and message OctaP's page showed.
110
119
 
111
120
  ## Security
112
121
 
113
- The session holds the ephemeral signing key, the proof and the id_token until `maxEpoch` or sign-out.
122
+ The session holds the ephemeral signing key, the proof and the customer token until they expire or
123
+ sign-out.
114
124
 
115
125
  - By default these are in `sessionStorage`, so they survive a reload in this tab. Any script on your
116
126
  page can read them, so an XSS flaw lets an attacker sign as this customer until the session
@@ -119,10 +129,13 @@ The session holds the ephemeral signing key, the proof and the id_token until `m
119
129
  out.
120
130
  - The private key is never sent anywhere. Only its public half reaches OctaP.
121
131
 
122
- ## Google client ID
132
+ ## Why sign-in happens on OctaP's page
123
133
 
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.
134
+ Every customer's wallet address comes from OctaP's one Google client, so all merchants share it.
135
+ Signing in on OctaP's page keeps Google's token there: what your backend gets is a token OctaP signed
136
+ for your organization alone. A token a customer showed another merchant is refused here, and yours
137
+ is refused there. If your site sends `Cross-Origin-Opener-Policy: same-origin`, use
138
+ `same-origin-allow-popups`, or the sign-in window cannot report back.
126
139
 
127
140
  ## Local example
128
141
 
package/dist/auth.d.ts CHANGED
@@ -1,24 +1,28 @@
1
1
  import { type RequestOptions } from './core-api.js';
2
2
  import { OctapAuthError } from './errors.js';
3
3
  import { type OctapUser, type Persistence } from './session-store.js';
4
+ /** OctaP's API. Set `apiBaseUrl` only to reach another Core, such as one running locally. */
5
+ export declare const DEFAULT_API_BASE_URL = "https://api.octap.biz";
4
6
  export interface OctapAuthOptions {
5
- apiBaseUrl: string;
6
7
  organizationId: string;
7
- googleClientId: string;
8
+ /** Defaults to `https://api.octap.biz`. */
9
+ apiBaseUrl?: string;
8
10
  /**
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.
11
+ * Where the signing key, proof and customer token are kept until they expire or sign-out. `session`
12
+ * (the default) survives a reload in this tab; `memory` does not. Any script running on your page
13
+ * can read a `session` value, so an XSS flaw exposes it until it expires.
12
14
  */
13
15
  persistence?: Persistence;
14
16
  timeoutMs?: number;
15
17
  fetch?: typeof fetch;
16
18
  }
17
19
  export interface RenderOptions {
18
- /** Sign-in failures, including a customer closing Google's window. */
20
+ /** Sign-in failures, including a customer closing the sign-in window. */
19
21
  onError?: (error: OctapAuthError) => void;
20
- /** Passed through to Google's button, such as `theme`, `size`, `text` or `shape`. */
21
- button?: Record<string, unknown>;
22
+ /** The button's text. Defaults to "Sign in with Google". */
23
+ label?: string;
24
+ /** A class for the button, to style it like the rest of your page. */
25
+ className?: string;
22
26
  }
23
27
  /** The merchant backend's claim result, as `@octap/sdk`'s `claimVoucher` returns it. */
24
28
  export interface SignableClaim {
@@ -31,7 +35,8 @@ export interface SignableVoucherUse {
31
35
  digest?: string | null;
32
36
  transactionBytes?: string | null;
33
37
  }
34
- export interface FinalizedVoucherUse {
38
+ /** One voucher the chain marked used. */
39
+ export interface FinalizedVoucher {
35
40
  voucherOwnershipId: string;
36
41
  voucherId: string;
37
42
  serialCode: string;
@@ -42,6 +47,15 @@ export interface FinalizedVoucherUse {
42
47
  discountValue?: string | null;
43
48
  blockchainDigest: string;
44
49
  }
50
+ /** A use of several vouchers, signed once: every voucher of it, in `serialCode` order. */
51
+ export interface FinalizedVoucherUses {
52
+ vouchers: FinalizedVoucher[];
53
+ blockchainDigest: string;
54
+ orderReference: string | null;
55
+ }
56
+ /** A use of one voucher: its fields at the top level too. */
57
+ export interface FinalizedVoucherUse extends FinalizedVoucher, FinalizedVoucherUses {
58
+ }
45
59
  export interface FinalizedClaim {
46
60
  transactionId: string;
47
61
  organizationEndUserId: string;
@@ -51,20 +65,25 @@ export interface FinalizedClaim {
51
65
  blockchainDigest: string;
52
66
  }
53
67
  export type AuthStateListener = (user: OctapUser | null) => void;
68
+ /**
69
+ * Customer sign-in and signing for one organization. Sign-in happens on OctaP's own page, in a
70
+ * popup: Google's token never reaches this page or your backend. What comes back is the customer, a
71
+ * proof for a signing key that never leaves this page, and a customer token your backend checks with
72
+ * `@octap/sdk`'s `verifyCustomer`. That token is valid for this organization only.
73
+ *
74
+ * Your page's origin must be one of the organization's sign-in origins (console, Developer settings).
75
+ */
54
76
  export declare class OctapAuth {
55
77
  private readonly api;
78
+ private readonly apiBaseUrl;
56
79
  private readonly store;
57
80
  private readonly organizationId;
58
- private readonly googleClientId;
59
81
  private readonly listeners;
60
82
  private session;
61
- private provider?;
62
83
  private button?;
63
- private signingIn;
84
+ private signingIn?;
64
85
  /** Changes when the session ends, so a sign-in still running cannot bring it back. */
65
86
  private signInGeneration;
66
- /** Changes on each new button, so only the latest nonce can be rendered or used. */
67
- private armGeneration;
68
87
  private expiryTimer?;
69
88
  constructor(options: OctapAuthOptions);
70
89
  /** The signed-in customer, restored synchronously after a reload. Null once the session expires. */
@@ -72,13 +91,21 @@ export declare class OctapAuth {
72
91
  /** Calls `listener` with the current customer soon after subscribing, then on every change. */
73
92
  onAuthStateChanged(listener: AuthStateListener): () => void;
74
93
  /**
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.
94
+ * Opens OctaP's sign-in window and resolves with the customer once they have signed in. Call it
95
+ * from a click handler: browsers block a window opened any other way. Signing in the first time
96
+ * joins this organization's loyalty program. A call while a sign-in is open returns that sign-in.
97
+ */
98
+ signIn(options?: {
99
+ signal?: AbortSignal;
100
+ }): Promise<OctapUser>;
101
+ /**
102
+ * Renders a button into `element` that calls `signIn()`, reporting failures through `onError`.
103
+ * While a customer is signed in it renders nothing, and appears again once they sign out or expire.
77
104
  */
78
- renderGoogleButton(element: HTMLElement, options?: RenderOptions): Promise<void>;
105
+ renderSignInButton(element: HTMLElement, options?: RenderOptions): void;
79
106
  /**
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.
107
+ * The customer token for your backend to check with `@octap/sdk`'s `verifyCustomer`. It lasts up
108
+ * to an hour; once it has expired the customer is signed out, so the button returns.
82
109
  */
83
110
  getIdToken(): Promise<string>;
84
111
  /** Lower-level signing: returns the zkLogin signature over base64 transaction bytes. */
@@ -92,16 +119,16 @@ export declare class OctapAuth {
92
119
  */
93
120
  signAndFinalize(claim: SignableClaim, options?: RequestOptions): Promise<FinalizedClaim>;
94
121
  /**
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.
122
+ * Signs the customer's use of a voucher, or of several at once, and finalizes it. Show the customer
123
+ * what they are using first: this one signature is the only thing that can mark their vouchers used.
124
+ * Never retried automatically; on `outcome-unknown`, read the vouchers from your backend. A use of
125
+ * several vouchers answers `FinalizedVoucherUses`: pass it as the type argument.
98
126
  */
99
- signAndFinalizeVoucherUse(use: SignableVoucherUse, options?: RequestOptions): Promise<FinalizedVoucherUse>;
127
+ signAndFinalizeVoucherUse<T extends FinalizedVoucherUses = FinalizedVoucherUse>(use: SignableVoucherUse, options?: RequestOptions): Promise<T>;
100
128
  private submitSigned;
101
- /** Always ends the session. A button that cannot return is reported through `onError`. */
129
+ /** Ends the session on this page. */
102
130
  signOut(): Promise<void>;
103
131
  private requireSession;
104
- private expireSession;
105
132
  private endSession;
106
133
  /** Lets an open page notice expiry without waiting for a call to fail. Only runs in a browser. */
107
134
  private scheduleExpiry;
@@ -109,10 +136,7 @@ export declare class OctapAuth {
109
136
  /** One merchant listener's bug must not undo a sign-in, or stop the other listeners. */
110
137
  private call;
111
138
  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;
139
+ /** Shows the sign-in button while nobody is signed in, and nothing while someone is. */
140
+ private renderButton;
117
141
  }
118
142
  export declare function createOctapAuth(options: OctapAuthOptions): OctapAuth;
package/dist/auth.js CHANGED
@@ -1,36 +1,55 @@
1
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
1
2
  import { CoreApi, normalizeBaseUrl } from './core-api.js';
2
3
  import { OctapAuthError } from './errors.js';
3
- import { createGoogleProvider } from './google-provider.js';
4
4
  import { createSessionStore, } from './session-store.js';
5
- import { PendingSignIn, idTokenExpiry, signWithZkLogin } from './zklogin-signer.js';
5
+ import { openSignInPopup } from './sign-in-popup.js';
6
+ import { isZkProof, signWithZkLogin, tokenExpiry } from './zklogin-signer.js';
7
+ /** OctaP's API. Set `apiBaseUrl` only to reach another Core, such as one running locally. */
8
+ export const DEFAULT_API_BASE_URL = 'https://api.octap.biz';
6
9
  const DEFAULT_TIMEOUT_MS = 35_000;
7
10
  /** Finalize waits for the chain's verdict, so it gets longer than an ordinary request. */
8
11
  const FINALIZE_TIMEOUT_MS = 90_000;
9
12
  /** Browsers run a longer `setTimeout` immediately. */
10
13
  const MAX_TIMER_MS = 2_147_483_647;
14
+ function isSignInResult(value) {
15
+ const result = value;
16
+ return (typeof result?.customerToken === 'string' &&
17
+ typeof result.user?.endUserId === 'string' &&
18
+ typeof result.user.memberId === 'string' &&
19
+ typeof result.user.suiAddress === 'string' &&
20
+ isZkProof(result.signer?.proof) &&
21
+ Number.isFinite(result.signer.maxEpoch) &&
22
+ Number.isFinite(result.signer.expiresAt));
23
+ }
24
+ /**
25
+ * Customer sign-in and signing for one organization. Sign-in happens on OctaP's own page, in a
26
+ * popup: Google's token never reaches this page or your backend. What comes back is the customer, a
27
+ * proof for a signing key that never leaves this page, and a customer token your backend checks with
28
+ * `@octap/sdk`'s `verifyCustomer`. That token is valid for this organization only.
29
+ *
30
+ * Your page's origin must be one of the organization's sign-in origins (console, Developer settings).
31
+ */
11
32
  export class OctapAuth {
12
33
  api;
34
+ apiBaseUrl;
13
35
  store;
14
36
  organizationId;
15
- googleClientId;
16
37
  listeners = new Set();
17
38
  session;
18
- provider;
19
39
  button;
20
- signingIn = false;
40
+ signingIn;
21
41
  /** Changes when the session ends, so a sign-in still running cannot bring it back. */
22
42
  signInGeneration = 0;
23
- /** Changes on each new button, so only the latest nonce can be rendered or used. */
24
- armGeneration = 0;
25
43
  expiryTimer;
26
44
  constructor(options) {
45
+ if (!options?.organizationId)
46
+ throw new TypeError('OctapAuth needs an organizationId.');
27
47
  const fetchFn = options.fetch ?? ((...args) => globalThis.fetch(...args));
28
- this.api = new CoreApi(options.apiBaseUrl, fetchFn, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
48
+ this.apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl ?? DEFAULT_API_BASE_URL);
49
+ this.api = new CoreApi(this.apiBaseUrl, fetchFn, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
29
50
  this.organizationId = options.organizationId;
30
- this.googleClientId = options.googleClientId;
31
51
  this.store = createSessionStore(options.persistence ?? 'session', {
32
- apiBaseUrl: normalizeBaseUrl(options.apiBaseUrl),
33
- googleClientId: options.googleClientId,
52
+ apiBaseUrl: this.apiBaseUrl,
34
53
  organizationId: options.organizationId,
35
54
  });
36
55
  this.session = this.store.load();
@@ -56,27 +75,71 @@ export class OctapAuth {
56
75
  };
57
76
  }
58
77
  /**
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.
78
+ * Opens OctaP's sign-in window and resolves with the customer once they have signed in. Call it
79
+ * from a click handler: browsers block a window opened any other way. Signing in the first time
80
+ * joins this organization's loyalty program. A call while a sign-in is open returns that sign-in.
81
+ */
82
+ signIn(options = {}) {
83
+ if (this.signingIn)
84
+ return this.signingIn;
85
+ const generation = this.signInGeneration;
86
+ const keypair = new Ed25519Keypair();
87
+ const url = new URL(`${this.apiBaseUrl}/v1/identity/sign-in`);
88
+ url.searchParams.set('organizationId', this.organizationId);
89
+ url.searchParams.set('origin', typeof location === 'undefined' ? '' : location.origin);
90
+ url.searchParams.set('ephemeralPublicKey', keypair.getPublicKey().toSuiPublicKey());
91
+ const attempt = openSignInPopup(url, options.signal)
92
+ .then((result) => {
93
+ if (!isSignInResult(result)) {
94
+ throw new OctapAuthError('invalid-response', 'OctaP returned an incomplete sign-in.', { body: result });
95
+ }
96
+ if (generation !== this.signInGeneration) {
97
+ throw new OctapAuthError('sign-in-canceled', 'The customer signed out while signing in.');
98
+ }
99
+ const session = {
100
+ user: { ...result.user },
101
+ token: result.customerToken,
102
+ signer: {
103
+ secretKey: keypair.getSecretKey(),
104
+ maxEpoch: result.signer.maxEpoch,
105
+ expiresAt: result.signer.expiresAt,
106
+ proof: result.signer.proof,
107
+ },
108
+ };
109
+ this.session = session;
110
+ this.store.save(session);
111
+ this.scheduleExpiry();
112
+ this.renderButton();
113
+ this.notify();
114
+ return session.user;
115
+ })
116
+ .finally(() => {
117
+ if (this.signingIn === attempt)
118
+ this.signingIn = undefined;
119
+ });
120
+ this.signingIn = attempt;
121
+ return attempt;
122
+ }
123
+ /**
124
+ * Renders a button into `element` that calls `signIn()`, reporting failures through `onError`.
125
+ * While a customer is signed in it renders nothing, and appears again once they sign out or expire.
61
126
  */
62
- async renderGoogleButton(element, options = {}) {
127
+ renderSignInButton(element, options = {}) {
63
128
  this.button = { element, options };
64
- this.provider = createGoogleProvider(this.googleClientId, options.button);
65
- if (!this.currentUser)
66
- await this.arm();
129
+ this.renderButton();
67
130
  }
68
131
  /**
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.
132
+ * The customer token for your backend to check with `@octap/sdk`'s `verifyCustomer`. It lasts up
133
+ * to an hour; once it has expired the customer is signed out, so the button returns.
71
134
  */
72
135
  async getIdToken() {
73
- const { idToken } = this.requireSession();
74
- const expiry = idTokenExpiry(idToken);
136
+ const { token } = this.requireSession();
137
+ const expiry = tokenExpiry(token);
75
138
  if (expiry !== undefined && Date.now() >= expiry * 1000) {
76
- this.expireSession();
77
- throw new OctapAuthError('token-expired', 'The sign-in token expired. Sign in again.');
139
+ this.endSession();
140
+ throw new OctapAuthError('token-expired', 'The sign-in expired. Sign in again.');
78
141
  }
79
- return idToken;
142
+ return token;
80
143
  }
81
144
  /** Lower-level signing: returns the zkLogin signature over base64 transaction bytes. */
82
145
  async signTransaction(transactionBytes) {
@@ -97,9 +160,10 @@ export class OctapAuth {
97
160
  return this.submitSigned('/v1/credits/redeem/finalize', claim.digest, claim.transactionBytes, options);
98
161
  }
99
162
  /**
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.
163
+ * Signs the customer's use of a voucher, or of several at once, and finalizes it. Show the customer
164
+ * what they are using first: this one signature is the only thing that can mark their vouchers used.
165
+ * Never retried automatically; on `outcome-unknown`, read the vouchers from your backend. A use of
166
+ * several vouchers answers `FinalizedVoucherUses`: pass it as the type argument.
103
167
  */
104
168
  async signAndFinalizeVoucherUse(use, options = {}) {
105
169
  if (!use.digest || !use.transactionBytes) {
@@ -120,34 +184,27 @@ export class OctapAuth {
120
184
  : 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
185
  }
122
186
  }
123
- /** Always ends the session. A button that cannot return is reported through `onError`. */
187
+ /** Ends the session on this page. */
124
188
  async signOut() {
125
- this.provider?.signOut();
126
189
  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
190
  }
130
191
  requireSession() {
131
192
  if (!this.session) {
132
193
  throw new OctapAuthError('not-signed-in', 'No customer is signed in.');
133
194
  }
134
195
  if (Date.now() >= this.session.signer.expiresAt) {
135
- this.expireSession();
196
+ this.endSession();
136
197
  throw new OctapAuthError('session-expired', 'The signing session expired. Sign in again.');
137
198
  }
138
199
  return this.session;
139
200
  }
140
- expireSession() {
141
- this.endSession();
142
- void this.rearm();
143
- }
144
201
  endSession() {
145
202
  const hadSession = this.session !== null;
146
203
  this.signInGeneration++;
147
- this.signingIn = false;
148
204
  this.store.clear();
149
205
  this.session = null;
150
206
  this.scheduleExpiry();
207
+ this.renderButton();
151
208
  if (hadSession)
152
209
  this.notify();
153
210
  }
@@ -161,7 +218,7 @@ export class OctapAuth {
161
218
  const remaining = this.session.signer.expiresAt - Date.now();
162
219
  this.expiryTimer = window.setTimeout(() => {
163
220
  if (this.session && Date.now() >= this.session.signer.expiresAt)
164
- this.expireSession();
221
+ this.endSession();
165
222
  else
166
223
  this.scheduleExpiry();
167
224
  }, Math.min(Math.max(remaining, 0), MAX_TIMER_MS));
@@ -182,7 +239,7 @@ export class OctapAuth {
182
239
  reportError(err) {
183
240
  const error = err instanceof OctapAuthError
184
241
  ? err
185
- : new OctapAuthError('provider-unavailable', err instanceof Error ? err.message : String(err));
242
+ : new OctapAuthError('api-error', err instanceof Error ? err.message : String(err));
186
243
  try {
187
244
  this.button?.options.onError?.(error);
188
245
  }
@@ -190,71 +247,24 @@ export class OctapAuth {
190
247
  console.error('The onError handler threw:', handlerError);
191
248
  }
192
249
  }
193
- /** Puts a usable button back, if one was rendered, reporting rather than throwing a failure. */
194
- async rearm() {
195
- if (!this.button)
250
+ /** Shows the sign-in button while nobody is signed in, and nothing while someone is. */
251
+ renderButton() {
252
+ if (!this.button || typeof document === 'undefined')
196
253
  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)
254
+ const { element, options } = this.button;
255
+ if (this.currentUser) {
256
+ element.replaceChildren();
204
257
  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
+ const button = document.createElement('button');
260
+ button.type = 'button';
261
+ button.textContent = options.label ?? 'Sign in with Google';
262
+ if (options.className)
263
+ button.className = options.className;
264
+ button.addEventListener('click', () => {
265
+ this.signIn().catch((err) => this.reportError(err));
266
+ });
267
+ element.replaceChildren(button);
258
268
  }
259
269
  }
260
270
  export function createOctapAuth(options) {