@octap/browser-sdk 0.1.1 → 0.2.0
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 +34 -0
- package/README.md +32 -19
- package/dist/auth.d.ts +38 -25
- package/dist/auth.js +107 -98
- package/dist/auth.js.map +1 -1
- package/dist/errors.d.ts +5 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/session-store.d.ts +3 -3
- package/dist/session-store.js +2 -2
- package/dist/session-store.js.map +1 -1
- package/dist/sign-in-popup.d.ts +21 -0
- package/dist/sign-in-popup.js +75 -0
- package/dist/sign-in-popup.js.map +1 -0
- package/dist/zklogin-signer.d.ts +6 -14
- package/dist/zklogin-signer.js +5 -64
- package/dist/zklogin-signer.js.map +1 -1
- package/package.json +4 -2
- package/dist/client.d.ts +0 -48
- package/dist/client.js +0 -110
- package/dist/client.js.map +0 -1
- package/dist/google-provider.d.ts +0 -13
- package/dist/google-provider.js +0 -104
- package/dist/google-provider.js.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
Breaking. Upgrade together with `@octap/sdk` 0.4, whose `verifyCustomer` takes the new customer
|
|
6
|
+
token, and against a Core with OCT-394.
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
|
|
10
|
+
- Customers sign in on OctaP's own page, in a popup (OCT-394). Your page no longer loads Google's
|
|
11
|
+
script and never sees Google's token.
|
|
12
|
+
- `createOctapAuth({ organizationId })`: `googleClientId` is gone, and `apiBaseUrl` is optional
|
|
13
|
+
(default `https://api.octap.biz`).
|
|
14
|
+
- Call `signIn()` from a click handler, or use `renderSignInButton()`: browsers block a popup opened
|
|
15
|
+
any other way.
|
|
16
|
+
- `getIdToken()` returns a customer token signed by OctaP for your organization only, valid up to an
|
|
17
|
+
hour. Check it on your backend with `@octap/sdk`'s `verifyCustomer`.
|
|
18
|
+
- Sessions saved by 0.1 are not restored: customers sign in again once after the upgrade.
|
|
19
|
+
- Error codes: `popup-blocked` is new, `nonce-mismatch` is gone.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- `DEFAULT_API_BASE_URL`.
|
|
24
|
+
- `signIn({ signal })` can be aborted.
|
|
25
|
+
|
|
26
|
+
### Setup
|
|
27
|
+
|
|
28
|
+
- Add your site's origin to your organization's sign-in origins in the console (`https://` only,
|
|
29
|
+
plus `http://localhost` while developing). OctaP delivers a sign-in to no other page.
|
|
30
|
+
|
|
31
|
+
## 0.1.1
|
|
32
|
+
|
|
33
|
+
First published version. Google sign-in ran on the merchant's page, with the merchant's
|
|
34
|
+
`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({
|
|
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
|
-
|
|
24
|
+
auth.renderSignInButton(document.getElementById('sign-in'), {
|
|
25
25
|
onError: (error) => showMessage(error.message),
|
|
26
26
|
});
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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`.
|
|
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
|
|
93
|
-
| `
|
|
94
|
-
| `provider-unavailable` |
|
|
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` |
|
|
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
|
-
|
|
108
|
-
|
|
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
|
|
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
|
-
##
|
|
132
|
+
## Why sign-in happens on OctaP's page
|
|
123
133
|
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
8
|
+
/** Defaults to `https://api.octap.biz`. */
|
|
9
|
+
apiBaseUrl?: string;
|
|
8
10
|
/**
|
|
9
|
-
* Where the signing key, proof and
|
|
10
|
-
* default) survives a reload in this tab; `memory` does not. Any script running on your page
|
|
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
|
|
20
|
+
/** Sign-in failures, including a customer closing the sign-in window. */
|
|
19
21
|
onError?: (error: OctapAuthError) => void;
|
|
20
|
-
/**
|
|
21
|
-
|
|
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 {
|
|
@@ -51,20 +55,25 @@ export interface FinalizedClaim {
|
|
|
51
55
|
blockchainDigest: string;
|
|
52
56
|
}
|
|
53
57
|
export type AuthStateListener = (user: OctapUser | null) => void;
|
|
58
|
+
/**
|
|
59
|
+
* Customer sign-in and signing for one organization. Sign-in happens on OctaP's own page, in a
|
|
60
|
+
* popup: Google's token never reaches this page or your backend. What comes back is the customer, a
|
|
61
|
+
* proof for a signing key that never leaves this page, and a customer token your backend checks with
|
|
62
|
+
* `@octap/sdk`'s `verifyCustomer`. That token is valid for this organization only.
|
|
63
|
+
*
|
|
64
|
+
* Your page's origin must be one of the organization's sign-in origins (console, Developer settings).
|
|
65
|
+
*/
|
|
54
66
|
export declare class OctapAuth {
|
|
55
67
|
private readonly api;
|
|
68
|
+
private readonly apiBaseUrl;
|
|
56
69
|
private readonly store;
|
|
57
70
|
private readonly organizationId;
|
|
58
|
-
private readonly googleClientId;
|
|
59
71
|
private readonly listeners;
|
|
60
72
|
private session;
|
|
61
|
-
private provider?;
|
|
62
73
|
private button?;
|
|
63
|
-
private signingIn
|
|
74
|
+
private signingIn?;
|
|
64
75
|
/** Changes when the session ends, so a sign-in still running cannot bring it back. */
|
|
65
76
|
private signInGeneration;
|
|
66
|
-
/** Changes on each new button, so only the latest nonce can be rendered or used. */
|
|
67
|
-
private armGeneration;
|
|
68
77
|
private expiryTimer?;
|
|
69
78
|
constructor(options: OctapAuthOptions);
|
|
70
79
|
/** The signed-in customer, restored synchronously after a reload. Null once the session expires. */
|
|
@@ -72,13 +81,21 @@ export declare class OctapAuth {
|
|
|
72
81
|
/** Calls `listener` with the current customer soon after subscribing, then on every change. */
|
|
73
82
|
onAuthStateChanged(listener: AuthStateListener): () => void;
|
|
74
83
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
84
|
+
* Opens OctaP's sign-in window and resolves with the customer once they have signed in. Call it
|
|
85
|
+
* from a click handler: browsers block a window opened any other way. Signing in the first time
|
|
86
|
+
* joins this organization's loyalty program. A call while a sign-in is open returns that sign-in.
|
|
77
87
|
*/
|
|
78
|
-
|
|
88
|
+
signIn(options?: {
|
|
89
|
+
signal?: AbortSignal;
|
|
90
|
+
}): Promise<OctapUser>;
|
|
79
91
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
92
|
+
* Renders a button into `element` that calls `signIn()`, reporting failures through `onError`.
|
|
93
|
+
* While a customer is signed in it renders nothing, and appears again once they sign out or expire.
|
|
94
|
+
*/
|
|
95
|
+
renderSignInButton(element: HTMLElement, options?: RenderOptions): void;
|
|
96
|
+
/**
|
|
97
|
+
* The customer token for your backend to check with `@octap/sdk`'s `verifyCustomer`. It lasts up
|
|
98
|
+
* to an hour; once it has expired the customer is signed out, so the button returns.
|
|
82
99
|
*/
|
|
83
100
|
getIdToken(): Promise<string>;
|
|
84
101
|
/** Lower-level signing: returns the zkLogin signature over base64 transaction bytes. */
|
|
@@ -98,10 +115,9 @@ export declare class OctapAuth {
|
|
|
98
115
|
*/
|
|
99
116
|
signAndFinalizeVoucherUse(use: SignableVoucherUse, options?: RequestOptions): Promise<FinalizedVoucherUse>;
|
|
100
117
|
private submitSigned;
|
|
101
|
-
/**
|
|
118
|
+
/** Ends the session on this page. */
|
|
102
119
|
signOut(): Promise<void>;
|
|
103
120
|
private requireSession;
|
|
104
|
-
private expireSession;
|
|
105
121
|
private endSession;
|
|
106
122
|
/** Lets an open page notice expiry without waiting for a call to fail. Only runs in a browser. */
|
|
107
123
|
private scheduleExpiry;
|
|
@@ -109,10 +125,7 @@ export declare class OctapAuth {
|
|
|
109
125
|
/** One merchant listener's bug must not undo a sign-in, or stop the other listeners. */
|
|
110
126
|
private call;
|
|
111
127
|
private reportError;
|
|
112
|
-
/**
|
|
113
|
-
private
|
|
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;
|
|
128
|
+
/** Shows the sign-in button while nobody is signed in, and nothing while someone is. */
|
|
129
|
+
private renderButton;
|
|
117
130
|
}
|
|
118
131
|
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 {
|
|
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
|
|
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.
|
|
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:
|
|
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
|
-
*
|
|
60
|
-
*
|
|
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
|
-
|
|
127
|
+
renderSignInButton(element, options = {}) {
|
|
63
128
|
this.button = { element, options };
|
|
64
|
-
this.
|
|
65
|
-
if (!this.currentUser)
|
|
66
|
-
await this.arm();
|
|
129
|
+
this.renderButton();
|
|
67
130
|
}
|
|
68
131
|
/**
|
|
69
|
-
* The
|
|
70
|
-
*
|
|
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 {
|
|
74
|
-
const expiry =
|
|
136
|
+
const { token } = this.requireSession();
|
|
137
|
+
const expiry = tokenExpiry(token);
|
|
75
138
|
if (expiry !== undefined && Date.now() >= expiry * 1000) {
|
|
76
|
-
this.
|
|
77
|
-
throw new OctapAuthError('token-expired', 'The sign-in
|
|
139
|
+
this.endSession();
|
|
140
|
+
throw new OctapAuthError('token-expired', 'The sign-in expired. Sign in again.');
|
|
78
141
|
}
|
|
79
|
-
return
|
|
142
|
+
return token;
|
|
80
143
|
}
|
|
81
144
|
/** Lower-level signing: returns the zkLogin signature over base64 transaction bytes. */
|
|
82
145
|
async signTransaction(transactionBytes) {
|
|
@@ -120,34 +183,27 @@ export class OctapAuth {
|
|
|
120
183
|
: 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
184
|
}
|
|
122
185
|
}
|
|
123
|
-
/**
|
|
186
|
+
/** Ends the session on this page. */
|
|
124
187
|
async signOut() {
|
|
125
|
-
this.provider?.signOut();
|
|
126
188
|
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
189
|
}
|
|
130
190
|
requireSession() {
|
|
131
191
|
if (!this.session) {
|
|
132
192
|
throw new OctapAuthError('not-signed-in', 'No customer is signed in.');
|
|
133
193
|
}
|
|
134
194
|
if (Date.now() >= this.session.signer.expiresAt) {
|
|
135
|
-
this.
|
|
195
|
+
this.endSession();
|
|
136
196
|
throw new OctapAuthError('session-expired', 'The signing session expired. Sign in again.');
|
|
137
197
|
}
|
|
138
198
|
return this.session;
|
|
139
199
|
}
|
|
140
|
-
expireSession() {
|
|
141
|
-
this.endSession();
|
|
142
|
-
void this.rearm();
|
|
143
|
-
}
|
|
144
200
|
endSession() {
|
|
145
201
|
const hadSession = this.session !== null;
|
|
146
202
|
this.signInGeneration++;
|
|
147
|
-
this.signingIn = false;
|
|
148
203
|
this.store.clear();
|
|
149
204
|
this.session = null;
|
|
150
205
|
this.scheduleExpiry();
|
|
206
|
+
this.renderButton();
|
|
151
207
|
if (hadSession)
|
|
152
208
|
this.notify();
|
|
153
209
|
}
|
|
@@ -161,7 +217,7 @@ export class OctapAuth {
|
|
|
161
217
|
const remaining = this.session.signer.expiresAt - Date.now();
|
|
162
218
|
this.expiryTimer = window.setTimeout(() => {
|
|
163
219
|
if (this.session && Date.now() >= this.session.signer.expiresAt)
|
|
164
|
-
this.
|
|
220
|
+
this.endSession();
|
|
165
221
|
else
|
|
166
222
|
this.scheduleExpiry();
|
|
167
223
|
}, Math.min(Math.max(remaining, 0), MAX_TIMER_MS));
|
|
@@ -182,7 +238,7 @@ export class OctapAuth {
|
|
|
182
238
|
reportError(err) {
|
|
183
239
|
const error = err instanceof OctapAuthError
|
|
184
240
|
? err
|
|
185
|
-
: new OctapAuthError('
|
|
241
|
+
: new OctapAuthError('api-error', err instanceof Error ? err.message : String(err));
|
|
186
242
|
try {
|
|
187
243
|
this.button?.options.onError?.(error);
|
|
188
244
|
}
|
|
@@ -190,71 +246,24 @@ export class OctapAuth {
|
|
|
190
246
|
console.error('The onError handler threw:', handlerError);
|
|
191
247
|
}
|
|
192
248
|
}
|
|
193
|
-
/**
|
|
194
|
-
|
|
195
|
-
if (!this.button)
|
|
249
|
+
/** Shows the sign-in button while nobody is signed in, and nothing while someone is. */
|
|
250
|
+
renderButton() {
|
|
251
|
+
if (!this.button || typeof document === 'undefined')
|
|
196
252
|
return;
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
async arm() {
|
|
201
|
-
const generation = ++this.armGeneration;
|
|
202
|
-
const pending = await PendingSignIn.start(this.api);
|
|
203
|
-
if (generation !== this.armGeneration)
|
|
253
|
+
const { element, options } = this.button;
|
|
254
|
+
if (this.currentUser) {
|
|
255
|
+
element.replaceChildren();
|
|
204
256
|
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
257
|
}
|
|
258
|
+
const button = document.createElement('button');
|
|
259
|
+
button.type = 'button';
|
|
260
|
+
button.textContent = options.label ?? 'Sign in with Google';
|
|
261
|
+
if (options.className)
|
|
262
|
+
button.className = options.className;
|
|
263
|
+
button.addEventListener('click', () => {
|
|
264
|
+
this.signIn().catch((err) => this.reportError(err));
|
|
265
|
+
});
|
|
266
|
+
element.replaceChildren(button);
|
|
258
267
|
}
|
|
259
268
|
}
|
|
260
269
|
export function createOctapAuth(options) {
|
package/dist/auth.js.map
CHANGED
|
@@ -1 +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,
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"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AAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAChD,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;QACvB,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC,KAAK,IAAI,qBAAqB,CAAC;QAC5D,IAAI,OAAO,CAAC,SAAS;YAAE,MAAM,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QAC5D,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;YACpC,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;QAC/D,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAED,MAAM,UAAU,eAAe,CAAC,OAAyB;IACvD,OAAO,IAAI,SAAS,CAAC,OAAO,CAAC,CAAC;AAChC,CAAC"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
export type OctapAuthErrorCode =
|
|
2
|
-
/** The customer closed
|
|
2
|
+
/** The customer closed the sign-in window. */
|
|
3
3
|
'sign-in-canceled'
|
|
4
|
-
/**
|
|
5
|
-
| '
|
|
6
|
-
/**
|
|
4
|
+
/** The browser blocked the sign-in window: call `signIn()` from a click handler. */
|
|
5
|
+
| 'popup-blocked'
|
|
6
|
+
/** The SDK ran outside a browser. */
|
|
7
7
|
| 'provider-unavailable'
|
|
8
8
|
/** No customer is signed in. */
|
|
9
9
|
| 'not-signed-in'
|
|
10
10
|
/** The signing session passed its `maxEpoch`, so the customer must sign in again. */
|
|
11
11
|
| 'session-expired'
|
|
12
|
-
/**
|
|
12
|
+
/** The customer token expired, so the backend would refuse it. The customer must sign in again. */
|
|
13
13
|
| 'token-expired'
|
|
14
14
|
/** The transaction is for a different address than the signed-in customer's. */
|
|
15
15
|
| 'wrong-account'
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { OctapAuth, createOctapAuth, type AuthStateListener, type FinalizedClaim, type FinalizedVoucherUse, type OctapAuthOptions, type RenderOptions, type SignableClaim, type SignableVoucherUse, } from './auth.js';
|
|
1
|
+
export { DEFAULT_API_BASE_URL, OctapAuth, createOctapAuth, type AuthStateListener, type FinalizedClaim, type FinalizedVoucherUse, type OctapAuthOptions, type RenderOptions, type SignableClaim, type SignableVoucherUse, } from './auth.js';
|
|
2
2
|
export type { RequestOptions } from './core-api.js';
|
|
3
3
|
export { OctapAuthError, type OctapAuthErrorCode } from './errors.js';
|
|
4
4
|
export type { OctapUser, Persistence } from './session-store.js';
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,eAAe,GAQhB,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,cAAc,EAA2B,MAAM,aAAa,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,SAAS,EACT,eAAe,GAQhB,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,cAAc,EAA2B,MAAM,aAAa,CAAC"}
|
package/dist/session-store.d.ts
CHANGED
|
@@ -7,7 +7,8 @@ export interface OctapUser {
|
|
|
7
7
|
}
|
|
8
8
|
export interface StoredSession {
|
|
9
9
|
user: OctapUser;
|
|
10
|
-
|
|
10
|
+
/** The customer token Core signed for this organization, for the merchant's backend. */
|
|
11
|
+
token: string;
|
|
11
12
|
signer: SignerState;
|
|
12
13
|
}
|
|
13
14
|
export type Persistence = 'session' | 'memory';
|
|
@@ -16,10 +17,9 @@ export interface SessionStore {
|
|
|
16
17
|
save(session: StoredSession): void;
|
|
17
18
|
clear(): void;
|
|
18
19
|
}
|
|
19
|
-
/** A session belongs to one configuration: another API or
|
|
20
|
+
/** A session belongs to one configuration: another API or organization must not restore it. */
|
|
20
21
|
export interface SessionScope {
|
|
21
22
|
apiBaseUrl: string;
|
|
22
|
-
googleClientId: string;
|
|
23
23
|
organizationId: string;
|
|
24
24
|
}
|
|
25
25
|
export declare function createSessionStore(persistence: Persistence, scope: SessionScope): SessionStore;
|
package/dist/session-store.js
CHANGED
|
@@ -16,7 +16,7 @@ function isStoredSession(value) {
|
|
|
16
16
|
return (typeof session?.user?.endUserId === 'string' &&
|
|
17
17
|
typeof session.user.memberId === 'string' &&
|
|
18
18
|
typeof session.user.suiAddress === 'string' &&
|
|
19
|
-
typeof session.
|
|
19
|
+
typeof session.token === 'string' &&
|
|
20
20
|
typeof session.signer?.secretKey === 'string' &&
|
|
21
21
|
typeof session.signer.maxEpoch === 'number' &&
|
|
22
22
|
typeof session.signer.expiresAt === 'number' &&
|
|
@@ -73,7 +73,7 @@ export function createSessionStore(persistence, scope) {
|
|
|
73
73
|
catch {
|
|
74
74
|
storage = undefined;
|
|
75
75
|
}
|
|
76
|
-
const key = `octap.auth.${JSON.stringify([scope.apiBaseUrl, scope.
|
|
76
|
+
const key = `octap.auth.${JSON.stringify([scope.apiBaseUrl, scope.organizationId])}`;
|
|
77
77
|
return storage ? browserStore(storage, key) : memoryStore();
|
|
78
78
|
}
|
|
79
79
|
//# sourceMappingURL=session-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-store.js","sourceRoot":"","sources":["../src/session-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"session-store.js","sourceRoot":"","sources":["../src/session-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,qBAAqB,CAAC;AAwBlE,SAAS,WAAW;IAClB,IAAI,IAAI,GAAyB,IAAI,CAAC;IACtC,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MAAM,CAAC;gBACP,uDAAuD;YACzD,CAAC;YACD,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;QACvB,CAAC;QACD,IAAI,CAAC,OAAO;YACV,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACrB,IAAI,CAAC;gBACH,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;YAChD,CAAC;YAAC,MAAM,CAAC;gBACP,uDAAuD;YACzD,CAAC;QACH,CAAC;QACD,KAAK;YACH,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,IAAI,CAAC;gBACH,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YAC1B,CAAC;YAAC,MAAM,CAAC;gBACP,0CAA0C;YAC5C,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAQD,MAAM,UAAU,kBAAkB,CAAC,WAAwB,EAAE,KAAmB;IAC9E,IAAI,WAAW,KAAK,QAAQ;QAAE,OAAO,WAAW,EAAE,CAAC;IACnD,IAAI,OAA4B,CAAC;IACjC,IAAI,CAAC;QACH,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC;IACtC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,SAAS,CAAC;IACtB,CAAC;IACD,MAAM,GAAG,GAAG,cAAc,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC;IACrF,OAAO,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';
|
|
2
|
+
/** What Core's sign-in page posts back. Mirrors `CustomerSignInResult` in `@octap/contracts`. */
|
|
3
|
+
export interface SignInResult {
|
|
4
|
+
customerToken: string;
|
|
5
|
+
user: {
|
|
6
|
+
endUserId: string;
|
|
7
|
+
memberId: string;
|
|
8
|
+
suiAddress: string;
|
|
9
|
+
};
|
|
10
|
+
signer: {
|
|
11
|
+
proof: ZkLoginSignatureInputs;
|
|
12
|
+
maxEpoch: number;
|
|
13
|
+
expiresAt: number;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Opens Core's sign-in page and waits for its result. The page posts only to the origin the
|
|
18
|
+
* organization allowed; here, a message counts only when it comes from that window and from Core's
|
|
19
|
+
* origin. Must run in a click handler, or the browser blocks the window.
|
|
20
|
+
*/
|
|
21
|
+
export declare function openSignInPopup(url: URL, signal?: AbortSignal): Promise<unknown>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { OctapAuthError } from './errors.js';
|
|
2
|
+
/** The message type Core's sign-in page posts with. */
|
|
3
|
+
const MESSAGE_TYPE = 'octap:sign-in';
|
|
4
|
+
const WINDOW_FEATURES = 'popup,width=480,height=640';
|
|
5
|
+
/** Core keeps a started sign-in this long. */
|
|
6
|
+
const SIGN_IN_TIMEOUT_MS = 10 * 60_000;
|
|
7
|
+
const CLOSED_POLL_MS = 500;
|
|
8
|
+
/** The result is posted just before the window closes itself, so wait a moment before calling it canceled. */
|
|
9
|
+
const CLOSED_GRACE_MS = 1_000;
|
|
10
|
+
/**
|
|
11
|
+
* Opens Core's sign-in page and waits for its result. The page posts only to the origin the
|
|
12
|
+
* organization allowed; here, a message counts only when it comes from that window and from Core's
|
|
13
|
+
* origin. Must run in a click handler, or the browser blocks the window.
|
|
14
|
+
*/
|
|
15
|
+
export function openSignInPopup(url, signal) {
|
|
16
|
+
if (typeof window === 'undefined' || typeof window.open !== 'function') {
|
|
17
|
+
return Promise.reject(new OctapAuthError('provider-unavailable', 'Sign-in needs a browser.'));
|
|
18
|
+
}
|
|
19
|
+
const popup = window.open(url.toString(), 'octap-sign-in', WINDOW_FEATURES);
|
|
20
|
+
if (!popup) {
|
|
21
|
+
return Promise.reject(new OctapAuthError('popup-blocked', 'The browser blocked the sign-in window. Sign in from a button click.'));
|
|
22
|
+
}
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
let closedSince;
|
|
25
|
+
const finish = (outcome) => {
|
|
26
|
+
window.removeEventListener('message', onMessage);
|
|
27
|
+
window.clearInterval(poll);
|
|
28
|
+
window.clearTimeout(timeout);
|
|
29
|
+
signal?.removeEventListener('abort', onAbort);
|
|
30
|
+
outcome();
|
|
31
|
+
};
|
|
32
|
+
const close = () => {
|
|
33
|
+
try {
|
|
34
|
+
popup.close();
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// Already gone.
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const onMessage = (event) => {
|
|
41
|
+
if (event.source !== popup || event.origin !== url.origin)
|
|
42
|
+
return;
|
|
43
|
+
const data = event.data;
|
|
44
|
+
if (data?.type !== MESSAGE_TYPE)
|
|
45
|
+
return;
|
|
46
|
+
if (data.error) {
|
|
47
|
+
close();
|
|
48
|
+
const status = typeof data.error.status === 'number' ? data.error.status : undefined;
|
|
49
|
+
const message = typeof data.error.message === 'string' ? data.error.message : 'Sign-in failed.';
|
|
50
|
+
finish(() => reject(new OctapAuthError('api-error', message, { status, body: data.error })));
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
finish(() => resolve(data.result));
|
|
54
|
+
};
|
|
55
|
+
const onAbort = () => {
|
|
56
|
+
close();
|
|
57
|
+
finish(() => reject(new OctapAuthError('aborted', 'Sign-in was aborted.')));
|
|
58
|
+
};
|
|
59
|
+
const poll = window.setInterval(() => {
|
|
60
|
+
if (!popup.closed)
|
|
61
|
+
return;
|
|
62
|
+
closedSince ??= Date.now();
|
|
63
|
+
if (Date.now() - closedSince >= CLOSED_GRACE_MS) {
|
|
64
|
+
finish(() => reject(new OctapAuthError('sign-in-canceled', 'The sign-in window was closed.')));
|
|
65
|
+
}
|
|
66
|
+
}, CLOSED_POLL_MS);
|
|
67
|
+
const timeout = window.setTimeout(() => {
|
|
68
|
+
close();
|
|
69
|
+
finish(() => reject(new OctapAuthError('timeout', 'Sign-in took too long. Sign in again.')));
|
|
70
|
+
}, SIGN_IN_TIMEOUT_MS);
|
|
71
|
+
window.addEventListener('message', onMessage);
|
|
72
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=sign-in-popup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-in-popup.js","sourceRoot":"","sources":["../src/sign-in-popup.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAS7C,uDAAuD;AACvD,MAAM,YAAY,GAAG,eAAe,CAAC;AACrC,MAAM,eAAe,GAAG,4BAA4B,CAAC;AACrD,8CAA8C;AAC9C,MAAM,kBAAkB,GAAG,EAAE,GAAG,MAAM,CAAC;AACvC,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,8GAA8G;AAC9G,MAAM,eAAe,GAAG,KAAK,CAAC;AAE9B;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,GAAQ,EAAE,MAAoB;IAC5D,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QACvE,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC,sBAAsB,EAAE,0BAA0B,CAAC,CAAC,CAAC;IAChG,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC;IAC5E,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,OAAO,CAAC,MAAM,CACnB,IAAI,cAAc,CAAC,eAAe,EAAE,sEAAsE,CAAC,CAC5G,CAAC;IACJ,CAAC;IAED,OA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IAC7D,CAAC,CAAC,CAAC;AACL,CAAC"}
|
package/dist/zklogin-signer.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { type ZkLoginSignatureInputs } from '@mysten/sui/zklogin';
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* The zkLogin signer: the ephemeral key and the proof Core built for it. The private key stays on
|
|
4
|
+
* this device: only its public half is ever sent, to open Core's sign-in page.
|
|
5
|
+
*/
|
|
3
6
|
export interface SignerState {
|
|
4
7
|
secretKey: string;
|
|
5
8
|
maxEpoch: number;
|
|
@@ -8,18 +11,7 @@ export interface SignerState {
|
|
|
8
11
|
proof: ZkLoginSignatureInputs;
|
|
9
12
|
}
|
|
10
13
|
export declare function isZkProof(value: unknown): value is ZkLoginSignatureInputs;
|
|
11
|
-
/**
|
|
12
|
-
export declare
|
|
13
|
-
private readonly keypair;
|
|
14
|
-
private readonly params;
|
|
15
|
-
private constructor();
|
|
16
|
-
static start(api: CoreApi): Promise<PendingSignIn>;
|
|
17
|
-
get nonce(): string;
|
|
18
|
-
/** A flow check, not token validation: Enoki validates the token's signature. */
|
|
19
|
-
assertIssuedForThisAttempt(idToken: string): void;
|
|
20
|
-
prove(api: CoreApi, idToken: string): Promise<SignerState>;
|
|
21
|
-
}
|
|
22
|
-
/** Seconds since the epoch at which an id_token stops being valid, or undefined if unreadable. */
|
|
23
|
-
export declare function idTokenExpiry(idToken: string): number | undefined;
|
|
14
|
+
/** Seconds since the epoch at which a token stops being valid, or undefined if unreadable. */
|
|
15
|
+
export declare function tokenExpiry(token: string): number | undefined;
|
|
24
16
|
/** Signs for the signed-in customer, refusing bytes that name a different sender. */
|
|
25
17
|
export declare function signWithZkLogin(state: SignerState, suiAddress: string, transactionBytes: string): Promise<string>;
|
package/dist/zklogin-signer.js
CHANGED
|
@@ -12,74 +12,15 @@ export function isZkProof(value) {
|
|
|
12
12
|
Array.isArray(proof.proofPoints.b) &&
|
|
13
13
|
Array.isArray(proof.proofPoints.c));
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
keypair;
|
|
18
|
-
params;
|
|
19
|
-
constructor(keypair, params) {
|
|
20
|
-
this.keypair = keypair;
|
|
21
|
-
this.params = params;
|
|
22
|
-
}
|
|
23
|
-
static async start(api) {
|
|
24
|
-
const keypair = new Ed25519Keypair();
|
|
25
|
-
const params = await api.post('/v1/identity/zklogin/nonce', {
|
|
26
|
-
ephemeralPublicKey: keypair.getPublicKey().toSuiPublicKey(),
|
|
27
|
-
});
|
|
28
|
-
if (typeof params.nonce !== 'string' ||
|
|
29
|
-
!params.nonce ||
|
|
30
|
-
typeof params.randomness !== 'string' ||
|
|
31
|
-
!Number.isFinite(params.maxEpoch) ||
|
|
32
|
-
!Number.isFinite(params.estimatedExpiration)) {
|
|
33
|
-
throw new OctapAuthError('invalid-response', 'OctaP returned an invalid sign-in nonce.', { body: params });
|
|
34
|
-
}
|
|
35
|
-
return new PendingSignIn(keypair, params);
|
|
36
|
-
}
|
|
37
|
-
get nonce() {
|
|
38
|
-
return this.params.nonce;
|
|
39
|
-
}
|
|
40
|
-
/** A flow check, not token validation: Enoki validates the token's signature. */
|
|
41
|
-
assertIssuedForThisAttempt(idToken) {
|
|
42
|
-
if (Date.now() >= this.params.estimatedExpiration) {
|
|
43
|
-
throw new OctapAuthError('session-expired', 'This sign-in attempt expired. Sign in again.');
|
|
44
|
-
}
|
|
45
|
-
let nonce;
|
|
46
|
-
try {
|
|
47
|
-
nonce = decodePayload(idToken).nonce;
|
|
48
|
-
}
|
|
49
|
-
catch {
|
|
50
|
-
throw new OctapAuthError('nonce-mismatch', 'Google returned an unreadable token. Sign in again.');
|
|
51
|
-
}
|
|
52
|
-
if (nonce !== this.params.nonce) {
|
|
53
|
-
throw new OctapAuthError('nonce-mismatch', 'Google sign-in did not match this attempt. Sign in again.');
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
async prove(api, idToken) {
|
|
57
|
-
const proof = await api.post('/v1/identity/zklogin/proof', {
|
|
58
|
-
idToken,
|
|
59
|
-
ephemeralPublicKey: this.keypair.getPublicKey().toSuiPublicKey(),
|
|
60
|
-
randomness: this.params.randomness,
|
|
61
|
-
maxEpoch: this.params.maxEpoch,
|
|
62
|
-
});
|
|
63
|
-
if (!isZkProof(proof)) {
|
|
64
|
-
throw new OctapAuthError('invalid-response', 'OctaP returned an invalid signing proof.', { body: proof });
|
|
65
|
-
}
|
|
66
|
-
return {
|
|
67
|
-
secretKey: this.keypair.getSecretKey(),
|
|
68
|
-
maxEpoch: this.params.maxEpoch,
|
|
69
|
-
expiresAt: this.params.estimatedExpiration,
|
|
70
|
-
proof,
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
function decodePayload(idToken) {
|
|
75
|
-
const payload = idToken.split('.')[1];
|
|
15
|
+
function decodePayload(token) {
|
|
16
|
+
const payload = token.split('.')[1];
|
|
76
17
|
const bytes = Uint8Array.from(atob(payload.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
|
|
77
18
|
return JSON.parse(new TextDecoder().decode(bytes));
|
|
78
19
|
}
|
|
79
|
-
/** Seconds since the epoch at which
|
|
80
|
-
export function
|
|
20
|
+
/** Seconds since the epoch at which a token stops being valid, or undefined if unreadable. */
|
|
21
|
+
export function tokenExpiry(token) {
|
|
81
22
|
try {
|
|
82
|
-
const { exp } = decodePayload(
|
|
23
|
+
const { exp } = decodePayload(token);
|
|
83
24
|
return typeof exp === 'number' ? exp : undefined;
|
|
84
25
|
}
|
|
85
26
|
catch {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zklogin-signer.js","sourceRoot":"","sources":["../src/zklogin-signer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/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Ac,CAAC,iBAAiB,EAAE,oDAAoD,CAAC,CAAC;IACpG,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@octap/browser-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Firebase-style customer sign-in and transaction signing for OctaP loyalty programs.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
"types": "./dist/index.d.ts",
|
|
15
15
|
"scripts": {
|
|
16
16
|
"build": "tsc -p tsconfig.json",
|
|
17
|
+
"prepack": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && npm run build",
|
|
17
18
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
18
19
|
},
|
|
19
20
|
"dependencies": {
|
|
@@ -24,6 +25,7 @@
|
|
|
24
25
|
},
|
|
25
26
|
"files": [
|
|
26
27
|
"dist",
|
|
27
|
-
"README.md"
|
|
28
|
+
"README.md",
|
|
29
|
+
"CHANGELOG.md"
|
|
28
30
|
]
|
|
29
31
|
}
|
package/dist/client.d.ts
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
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;
|
package/dist/client.js
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
export class OctaBrowserClient {
|
|
2
|
-
apiBaseUrl;
|
|
3
|
-
defaultOrganizationId;
|
|
4
|
-
getAuthToken;
|
|
5
|
-
constructor(options) {
|
|
6
|
-
this.apiBaseUrl = options.apiBaseUrl.replace(/\/+$/, '');
|
|
7
|
-
this.defaultOrganizationId = options.organizationId;
|
|
8
|
-
this.getAuthToken = options.getAuthToken;
|
|
9
|
-
}
|
|
10
|
-
async request(path, method = 'GET', body, orgId) {
|
|
11
|
-
const url = `${this.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
|
12
|
-
const headers = {
|
|
13
|
-
accept: 'application/json',
|
|
14
|
-
};
|
|
15
|
-
if (body !== undefined) {
|
|
16
|
-
headers['content-type'] = 'application/json';
|
|
17
|
-
}
|
|
18
|
-
const organizationId = orgId ?? this.defaultOrganizationId;
|
|
19
|
-
if (organizationId) {
|
|
20
|
-
headers['x-organization-id'] = organizationId;
|
|
21
|
-
}
|
|
22
|
-
if (this.getAuthToken) {
|
|
23
|
-
const token = await this.getAuthToken();
|
|
24
|
-
if (token) {
|
|
25
|
-
headers['authorization'] = `Bearer ${token}`;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
const response = await fetch(url, {
|
|
29
|
-
method,
|
|
30
|
-
headers,
|
|
31
|
-
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
32
|
-
});
|
|
33
|
-
if (!response.ok) {
|
|
34
|
-
let errorBody = null;
|
|
35
|
-
try {
|
|
36
|
-
errorBody = await response.json();
|
|
37
|
-
}
|
|
38
|
-
catch {
|
|
39
|
-
errorBody = await response.text();
|
|
40
|
-
}
|
|
41
|
-
throw new Error(typeof errorBody === 'object' && errorBody !== null && 'message' in errorBody
|
|
42
|
-
? String(errorBody.message)
|
|
43
|
-
: `Octa Browser SDK request failed: ${response.status} ${response.statusText}`);
|
|
44
|
-
}
|
|
45
|
-
return response.json();
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Get credit balance for a member.
|
|
49
|
-
*/
|
|
50
|
-
async getBalance(memberId) {
|
|
51
|
-
return this.request(`/v1/credits/members/${memberId}/balance`, 'GET');
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* List loyalty transactions for a member.
|
|
55
|
-
*/
|
|
56
|
-
async listTransactions(memberId, limit = 50) {
|
|
57
|
-
return this.request(`/v1/credits/members/${memberId}/transactions?limit=${limit}`, 'GET');
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* List active vouchers in the organization.
|
|
61
|
-
*/
|
|
62
|
-
async listVouchers(organizationId) {
|
|
63
|
-
return this.request('/v1/rewards/vouchers', 'GET', undefined, organizationId);
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Get details of a specific voucher.
|
|
67
|
-
*/
|
|
68
|
-
async getVoucher(voucherId) {
|
|
69
|
-
return this.request(`/v1/rewards/vouchers/${voucherId}`, 'GET');
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Claim a voucher using loyalty points.
|
|
73
|
-
*/
|
|
74
|
-
async claimVoucher(voucherId, organizationEndUserId, idempotencyKey, organizationId) {
|
|
75
|
-
return this.request(`/v1/rewards/vouchers/${voucherId}/claim`, 'POST', {
|
|
76
|
-
organizationEndUserId,
|
|
77
|
-
idempotencyKey: idempotencyKey ?? `claim-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
|
|
78
|
-
}, organizationId);
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* List all vouchers claimed/owned by a member.
|
|
82
|
-
*/
|
|
83
|
-
async listMemberVouchers(memberId) {
|
|
84
|
-
return this.request(`/v1/rewards/members/${memberId}/vouchers`, 'GET');
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Resolves a Google id_token (obtained from the host app's own Google Sign-In; this SDK does
|
|
88
|
-
* not render a sign-in button) to a zkLogin Sui address and a global end-user identity.
|
|
89
|
-
*/
|
|
90
|
-
async loginWithGoogle(idToken) {
|
|
91
|
-
return this.request('/v1/identity/google-login', 'POST', { idToken });
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Enrolls an already-logged-in end user into one organization's loyalty program.
|
|
95
|
-
*/
|
|
96
|
-
async enroll(endUserId, organizationId, externalMemberId) {
|
|
97
|
-
const orgId = organizationId ?? this.defaultOrganizationId;
|
|
98
|
-
if (!orgId) {
|
|
99
|
-
throw new Error('organizationId is required (pass it or set BrowserClientOptions.organizationId)');
|
|
100
|
-
}
|
|
101
|
-
return this.request(`/v1/identity/organizations/${orgId}/enroll`, 'POST', {
|
|
102
|
-
endUserId,
|
|
103
|
-
externalMemberId,
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
export function createBrowserClient(options) {
|
|
108
|
-
return new OctaBrowserClient(options);
|
|
109
|
-
}
|
|
110
|
-
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAiBA,MAAM,OAAO,iBAAiB;IACX,UAAU,CAAS;IACnB,qBAAqB,CAAU;IAC/B,YAAY,CAAgD;IAE7E,YAAY,OAA6B;QACvC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,qBAAqB,GAAG,OAAO,CAAC,cAAc,CAAC;QACpD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAEO,KAAK,CAAC,OAAO,CAAI,IAAY,EAAE,SAAyB,KAAK,EAAE,IAAc,EAAE,KAAc;QACnG,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,EAAE,CAAC;QAC5E,MAAM,OAAO,GAA2B;YACtC,MAAM,EAAE,kBAAkB;SAC3B,CAAC;QAEF,IAAI,IAAI,KAAK,SAAS,EA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,CAAsB,2BAA2B,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;IAC7F,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,MAAM,CAAC,SAAiB,EAAE,cAAuB,EAAE,gBAAyB;QAChF,MAAM,KAAK,GAAG,cAAc,IAAI,IAAI,CAAC,qBAAqB,CAAC;QAC3D,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CAAC,iFAAiF,CAAC,CAAC;QACrG,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAuB,8BAA8B,KAAK,SAAS,EAAE,MAAM,EAAE;YAC9F,SAAS;YACT,gBAAgB;SACjB,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,UAAU,mBAAmB,CAAC,OAA6B;IAC/D,OAAO,IAAI,iBAAiB,CAAC,OAAO,CAAC,CAAC;AACxC,CAAC"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Provider sign-in: turns a click into an id_token bound to a nonce. Nothing outside this file knows
|
|
3
|
-
* it is Google, which keeps a later provider a change here, not in the public API.
|
|
4
|
-
*/
|
|
5
|
-
export interface SignInHandlers {
|
|
6
|
-
onIdToken(idToken: string): void;
|
|
7
|
-
onCanceled(): void;
|
|
8
|
-
}
|
|
9
|
-
export interface IdTokenProvider {
|
|
10
|
-
render(element: HTMLElement, nonce: string, handlers: SignInHandlers): Promise<void>;
|
|
11
|
-
signOut(): void;
|
|
12
|
-
}
|
|
13
|
-
export declare function createGoogleProvider(clientId: string, buttonOptions?: Record<string, unknown>): IdTokenProvider;
|
package/dist/google-provider.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import { OctapAuthError } from './errors.js';
|
|
2
|
-
const SCRIPT_URL = 'https://accounts.google.com/gsi/client';
|
|
3
|
-
const SCRIPT_TIMEOUT_MS = 20_000;
|
|
4
|
-
/** A credential can arrive just after the popup closes, so wait before calling it a cancellation. */
|
|
5
|
-
const CANCEL_GRACE_MS = 1_500;
|
|
6
|
-
const CANCEL_POLL_MS = 250;
|
|
7
|
-
const CANCEL_WATCH_LIMIT_MS = 5 * 60_000;
|
|
8
|
-
let loading;
|
|
9
|
-
function loadGoogleIdentity() {
|
|
10
|
-
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
|
11
|
-
return Promise.reject(new OctapAuthError('provider-unavailable', 'Google sign-in needs a browser.'));
|
|
12
|
-
}
|
|
13
|
-
const loaded = window.google?.accounts?.id;
|
|
14
|
-
if (loaded)
|
|
15
|
-
return Promise.resolve(loaded);
|
|
16
|
-
if (loading)
|
|
17
|
-
return loading;
|
|
18
|
-
loading = new Promise((resolve, reject) => {
|
|
19
|
-
const script = document.createElement('script');
|
|
20
|
-
script.src = SCRIPT_URL;
|
|
21
|
-
script.async = true;
|
|
22
|
-
const fail = () => {
|
|
23
|
-
window.clearTimeout(timer);
|
|
24
|
-
script.remove();
|
|
25
|
-
loading = undefined;
|
|
26
|
-
reject(new OctapAuthError('provider-unavailable', 'Google sign-in could not load.'));
|
|
27
|
-
};
|
|
28
|
-
const timer = window.setTimeout(fail, SCRIPT_TIMEOUT_MS);
|
|
29
|
-
script.onerror = fail;
|
|
30
|
-
script.onload = () => {
|
|
31
|
-
const google = window.google?.accounts?.id;
|
|
32
|
-
if (!google) {
|
|
33
|
-
fail();
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
window.clearTimeout(timer);
|
|
37
|
-
resolve(google);
|
|
38
|
-
};
|
|
39
|
-
document.head.appendChild(script);
|
|
40
|
-
});
|
|
41
|
-
return loading;
|
|
42
|
-
}
|
|
43
|
-
export function createGoogleProvider(clientId, buttonOptions = {}) {
|
|
44
|
-
let google;
|
|
45
|
-
let stopWatching;
|
|
46
|
-
return {
|
|
47
|
-
async render(element, nonce, handlers) {
|
|
48
|
-
google = await loadGoogleIdentity();
|
|
49
|
-
google.initialize({
|
|
50
|
-
client_id: clientId,
|
|
51
|
-
auto_select: false,
|
|
52
|
-
nonce,
|
|
53
|
-
callback: ({ credential }) => {
|
|
54
|
-
stopWatching?.();
|
|
55
|
-
handlers.onIdToken(credential);
|
|
56
|
-
},
|
|
57
|
-
});
|
|
58
|
-
google.renderButton(element, {
|
|
59
|
-
theme: 'outline',
|
|
60
|
-
size: 'large',
|
|
61
|
-
...buttonOptions,
|
|
62
|
-
click_listener: () => {
|
|
63
|
-
stopWatching?.();
|
|
64
|
-
stopWatching = watchForCancel(handlers.onCanceled);
|
|
65
|
-
},
|
|
66
|
-
});
|
|
67
|
-
},
|
|
68
|
-
signOut() {
|
|
69
|
-
stopWatching?.();
|
|
70
|
-
google?.disableAutoSelect();
|
|
71
|
-
},
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Google's button reports no cancellation. Its popup takes focus from this document and gives it back
|
|
76
|
-
* when it closes, so focus returning with no credential after a short wait means it was closed. This
|
|
77
|
-
* polls because Google's button is a cross-origin iframe, which makes `blur` and `focus` events on the
|
|
78
|
-
* window fire unreliably. A customer who clicks back while the popup is open also looks like this,
|
|
79
|
-
* and a credential arriving afterwards still completes the sign-in.
|
|
80
|
-
*/
|
|
81
|
-
function watchForCancel(onCanceled) {
|
|
82
|
-
const startedAt = Date.now();
|
|
83
|
-
let popupSeen = false;
|
|
84
|
-
let focusedSince;
|
|
85
|
-
const timer = window.setInterval(() => {
|
|
86
|
-
if (Date.now() - startedAt >= CANCEL_WATCH_LIMIT_MS) {
|
|
87
|
-
stop();
|
|
88
|
-
}
|
|
89
|
-
else if (!document.hasFocus()) {
|
|
90
|
-
popupSeen = true;
|
|
91
|
-
focusedSince = undefined;
|
|
92
|
-
}
|
|
93
|
-
else if (popupSeen) {
|
|
94
|
-
focusedSince ??= Date.now();
|
|
95
|
-
if (Date.now() - focusedSince >= CANCEL_GRACE_MS) {
|
|
96
|
-
stop();
|
|
97
|
-
onCanceled();
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
}, CANCEL_POLL_MS);
|
|
101
|
-
const stop = () => window.clearInterval(timer);
|
|
102
|
-
return stop;
|
|
103
|
-
}
|
|
104
|
-
//# sourceMappingURL=google-provider.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"google-provider.js","sourceRoot":"","sources":["../src/google-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AA6B7C,MAAM,UAAU,GAAG,wCAAwC,CAAC;AAC5D,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,qGAAqG;AACrG,MAAM,eAAe,GAAG,KAAK,CAAC;AAC9B,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,qBAAqB,GAAG,CAAC,GAAG,MAAM,CAAC;AAEzC,IAAI,OAA4C,CAAC;AAEjD,SAAS,kBAAkB;IACzB,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;QACrE,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC,sBAAsB,EAAE,iCAAiC,CAAC,CAAC,CAAC;IACvG,CAAC;IACD,MAAM,MAAM,GAAI,MAAuB,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC;IAC7D,IAAI,MAAM;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3C,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC;IAE5B,OAAO,GAAG,IAAI,OAAO,CAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACxD,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAChD,MAAM,CAAC,GAAG,GAAG,UAAU,CAAC;QACxB,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC;QACpB,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;YAC3B,MAAM,CAAC,MAAM,EA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