@openkey/sdk 0.1.0 → 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/README.md +95 -107
- package/dist/index.d.mts +22 -12
- package/dist/index.d.ts +22 -12
- package/dist/index.js +46 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +46 -20
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,7 +9,8 @@ OpenKey provides secure cryptographic key management using passkeys (WebAuthn).
|
|
|
9
9
|
**Key features:**
|
|
10
10
|
- **Passkey-secured keys** - Keys are protected by WebAuthn, not passwords
|
|
11
11
|
- **No seed phrases** - Never worry about losing or exposing recovery phrases
|
|
12
|
-
- **
|
|
12
|
+
- **Iframe modal signing** - Clean inline UX with auto-fallback to popup
|
|
13
|
+
- **External wallet support** - Link and sign with MetaMask, Rainbow, etc.
|
|
13
14
|
- **EIP-1193 compatible** - Works with ethers.js, viem, and other web3 libraries
|
|
14
15
|
|
|
15
16
|
## Installation
|
|
@@ -25,164 +26,151 @@ bun add @openkey/sdk
|
|
|
25
26
|
## Quick Start
|
|
26
27
|
|
|
27
28
|
```typescript
|
|
28
|
-
import { OpenKey } from '@openkey/sdk';
|
|
29
|
+
import { OpenKey, OpenKeyEIP1193Provider } from '@openkey/sdk';
|
|
29
30
|
|
|
30
|
-
// Initialize the SDK
|
|
31
|
+
// Initialize the SDK (iframe modal by default)
|
|
31
32
|
const openkey = new OpenKey({
|
|
32
|
-
host: 'https://openkey.so',
|
|
33
|
-
// host: 'http://localhost:5173', // Development
|
|
33
|
+
host: 'https://openkey.so',
|
|
34
34
|
});
|
|
35
35
|
|
|
36
|
-
// Connect
|
|
37
|
-
const
|
|
38
|
-
console.log('Connected:', address);
|
|
36
|
+
// Connect (opens iframe modal for passkey auth + key selection)
|
|
37
|
+
const authResult = await openkey.connect();
|
|
38
|
+
console.log('Connected:', authResult.address, authResult.keyType);
|
|
39
39
|
|
|
40
|
-
// Sign a message (opens
|
|
41
|
-
const signature = await openkey.signMessage({
|
|
40
|
+
// Sign a message (opens iframe modal for user approval)
|
|
41
|
+
const { signature } = await openkey.signMessage({
|
|
42
42
|
message: 'Hello, OpenKey!',
|
|
43
|
-
keyId,
|
|
43
|
+
keyId: authResult.keyId,
|
|
44
44
|
});
|
|
45
|
-
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## UI Modes
|
|
48
|
+
|
|
49
|
+
The SDK supports three UI modes for auth and signing flows:
|
|
50
|
+
|
|
51
|
+
| Mode | Description |
|
|
52
|
+
|------|-------------|
|
|
53
|
+
| `'iframe'` (default) | Inline modal overlay. No popup blockers. Responsive (card on desktop, bottom sheet on mobile). |
|
|
54
|
+
| `'popup'` | Separate browser window. Classic approach. May be blocked by browsers. |
|
|
55
|
+
| `'redirect'` | Full page navigation to OpenKey. User returns after completion. |
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
// Set default mode in constructor
|
|
59
|
+
const openkey = new OpenKey({ mode: 'iframe' });
|
|
60
|
+
|
|
61
|
+
// Override per operation
|
|
62
|
+
await openkey.connect({ mode: 'popup' });
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Auto-fallback
|
|
66
|
+
|
|
67
|
+
When using `'iframe'` mode, the SDK automatically falls back to `'popup'` if the iframe is blocked by the app's CSP. A brief toast notification ("Opening in new window...") is shown. To avoid the fallback, add to your CSP:
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
frame-src https://openkey.so;
|
|
46
71
|
```
|
|
47
72
|
|
|
48
73
|
## API Reference
|
|
49
74
|
|
|
50
75
|
### `new OpenKey(options)`
|
|
51
76
|
|
|
52
|
-
Create a new OpenKey instance.
|
|
53
|
-
|
|
54
77
|
```typescript
|
|
55
78
|
const openkey = new OpenKey({
|
|
56
|
-
host: 'https://openkey.so',
|
|
79
|
+
host: 'https://openkey.so', // OpenKey server URL
|
|
80
|
+
appName: 'My App', // Display name in auth UI
|
|
81
|
+
mode: 'iframe', // 'iframe' | 'popup' | 'redirect'
|
|
82
|
+
externalProvider: provider, // Optional: app-provided wallet for external key signing
|
|
57
83
|
});
|
|
58
84
|
```
|
|
59
85
|
|
|
60
|
-
|
|
61
|
-
- `host` (string): The OpenKey server URL. Use `https://openkey.so` for production.
|
|
86
|
+
### `openkey.connect(opts?)`
|
|
62
87
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
Opens the OpenKey popup for the user to authenticate and select a key.
|
|
88
|
+
Authenticate and select a key.
|
|
66
89
|
|
|
67
90
|
```typescript
|
|
68
|
-
const { address, keyId } = await openkey.connect();
|
|
91
|
+
const { address, keyId, keyType } = await openkey.connect();
|
|
92
|
+
// keyType: 'MANAGED' (TEE-secured) or 'EXTERNAL' (linked wallet)
|
|
69
93
|
```
|
|
70
94
|
|
|
71
|
-
|
|
72
|
-
- `address` (string): The Ethereum address of the selected key
|
|
73
|
-
- `keyId` (string): The unique identifier for the key (used in signing operations)
|
|
74
|
-
|
|
75
|
-
### `openkey.signMessage(params)`
|
|
95
|
+
### `openkey.signMessage(request, opts?)`
|
|
76
96
|
|
|
77
|
-
Sign a message
|
|
97
|
+
Sign a message. External keys route directly to the user's wallet.
|
|
78
98
|
|
|
79
99
|
```typescript
|
|
80
|
-
const signature = await openkey.signMessage({
|
|
100
|
+
const { signature, address } = await openkey.signMessage({
|
|
81
101
|
message: 'Hello, World!',
|
|
82
102
|
keyId: 'key-id-from-connect',
|
|
83
103
|
});
|
|
84
104
|
```
|
|
85
105
|
|
|
86
|
-
|
|
87
|
-
- `message` (string): The message to sign
|
|
88
|
-
- `keyId` (string): The key ID from `connect()`
|
|
106
|
+
### `openkey.signTypedData(request, opts?)`
|
|
89
107
|
|
|
90
|
-
|
|
91
|
-
- `signature` (string): The hex-encoded signature
|
|
92
|
-
|
|
93
|
-
### `openkey.signTypedData(params)`
|
|
94
|
-
|
|
95
|
-
Sign EIP-712 typed data with the user's key.
|
|
108
|
+
Sign EIP-712 typed data.
|
|
96
109
|
|
|
97
110
|
```typescript
|
|
98
|
-
const signature = await openkey.signTypedData({
|
|
99
|
-
domain: {
|
|
100
|
-
|
|
101
|
-
version: '1',
|
|
102
|
-
chainId: 1,
|
|
103
|
-
},
|
|
104
|
-
types: {
|
|
105
|
-
Message: [{ name: 'content', type: 'string' }],
|
|
106
|
-
},
|
|
111
|
+
const { signature } = await openkey.signTypedData({
|
|
112
|
+
domain: { name: 'My App', version: '1', chainId: 1 },
|
|
113
|
+
types: { Message: [{ name: 'content', type: 'string' }] },
|
|
107
114
|
primaryType: 'Message',
|
|
108
|
-
message: {
|
|
109
|
-
content: 'Hello!',
|
|
110
|
-
},
|
|
115
|
+
message: { content: 'Hello!' },
|
|
111
116
|
keyId: 'key-id-from-connect',
|
|
112
117
|
});
|
|
113
118
|
```
|
|
114
119
|
|
|
115
|
-
|
|
120
|
+
### `openkey.linkWallet(opts?)`
|
|
116
121
|
|
|
117
|
-
|
|
122
|
+
Link an external wallet to the user's OpenKey account.
|
|
118
123
|
|
|
119
124
|
```typescript
|
|
120
|
-
|
|
125
|
+
const { address, keyId } = await openkey.linkWallet();
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### `OpenKeyEIP1193Provider`
|
|
129
|
+
|
|
130
|
+
A drop-in EIP-1193 provider that routes signing through OpenKey. Handles both managed and external keys transparently.
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
import { OpenKey, OpenKeyEIP1193Provider } from '@openkey/sdk';
|
|
134
|
+
|
|
135
|
+
const openkey = new OpenKey({ host: 'https://openkey.so' });
|
|
136
|
+
const authResult = await openkey.connect();
|
|
137
|
+
|
|
138
|
+
// Create provider that works with ethers.js, viem, etc.
|
|
139
|
+
const provider = new OpenKeyEIP1193Provider(openkey, authResult);
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Integration with ethers.js
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
import { OpenKey, OpenKeyEIP1193Provider } from '@openkey/sdk';
|
|
121
146
|
import { BrowserProvider } from 'ethers';
|
|
122
147
|
|
|
123
|
-
// Create OpenKey instance
|
|
124
148
|
const openkey = new OpenKey({ host: 'https://openkey.so' });
|
|
149
|
+
const authResult = await openkey.connect();
|
|
150
|
+
const provider = new OpenKeyEIP1193Provider(openkey, authResult);
|
|
125
151
|
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
// Create an EIP-1193 compatible provider
|
|
130
|
-
const eip1193Provider = {
|
|
131
|
-
async request({ method, params }: { method: string; params?: any[] }) {
|
|
132
|
-
switch (method) {
|
|
133
|
-
case 'eth_accounts':
|
|
134
|
-
case 'eth_requestAccounts':
|
|
135
|
-
return [address];
|
|
136
|
-
case 'eth_chainId':
|
|
137
|
-
return '0x1'; // Mainnet
|
|
138
|
-
case 'personal_sign': {
|
|
139
|
-
const message = hexToString(params![0]);
|
|
140
|
-
const result = await openkey.signMessage({ message, keyId });
|
|
141
|
-
return result.signature;
|
|
142
|
-
}
|
|
143
|
-
default:
|
|
144
|
-
throw new Error(`Unsupported method: ${method}`);
|
|
145
|
-
}
|
|
146
|
-
},
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
// Use with ethers
|
|
150
|
-
const provider = new BrowserProvider(eip1193Provider);
|
|
151
|
-
const signer = await provider.getSigner();
|
|
152
|
+
const ethersProvider = new BrowserProvider(provider);
|
|
153
|
+
const signer = await ethersProvider.getSigner();
|
|
152
154
|
```
|
|
153
155
|
|
|
154
156
|
## Integration with TinyCloud
|
|
155
157
|
|
|
156
|
-
OpenKey works seamlessly with [TinyCloud](https://tinycloud.xyz) for decentralized storage:
|
|
157
|
-
|
|
158
158
|
```typescript
|
|
159
|
-
import { OpenKey } from '@openkey/sdk';
|
|
159
|
+
import { OpenKey, OpenKeyEIP1193Provider } from '@openkey/sdk';
|
|
160
160
|
import { TinyCloudWeb } from '@tinycloud/web-sdk';
|
|
161
|
-
import {
|
|
161
|
+
import { providers } from 'ethers';
|
|
162
162
|
|
|
163
|
-
// Setup OpenKey
|
|
164
163
|
const openkey = new OpenKey({ host: 'https://openkey.so' });
|
|
165
|
-
const
|
|
164
|
+
const authResult = await openkey.connect();
|
|
165
|
+
const eip1193Provider = new OpenKeyEIP1193Provider(openkey, authResult);
|
|
166
|
+
const web3Provider = new providers.Web3Provider(eip1193Provider);
|
|
166
167
|
|
|
167
|
-
// Create EIP-1193 provider (see above)
|
|
168
|
-
const eip1193Provider = createOpenKeyProvider(openkey, address, keyId);
|
|
169
|
-
const ethersProvider = new BrowserProvider(eip1193Provider);
|
|
170
|
-
|
|
171
|
-
// Initialize TinyCloud with OpenKey as the signer
|
|
172
168
|
const tcw = new TinyCloudWeb({
|
|
173
|
-
providers: {
|
|
174
|
-
web3: {
|
|
175
|
-
driver: ethersProvider,
|
|
176
|
-
},
|
|
177
|
-
},
|
|
169
|
+
providers: { web3: { driver: web3Provider } },
|
|
178
170
|
});
|
|
179
171
|
|
|
180
|
-
// Sign in to TinyCloud (uses OpenKey for SIWE signature)
|
|
181
172
|
await tcw.signIn();
|
|
182
|
-
|
|
183
|
-
// Now you can use TinyCloud storage
|
|
184
173
|
await tcw.kv.put('hello', 'world');
|
|
185
|
-
const result = await tcw.kv.get('hello');
|
|
186
174
|
```
|
|
187
175
|
|
|
188
176
|
## Development
|
|
@@ -195,12 +183,6 @@ const openkey = new OpenKey({
|
|
|
195
183
|
});
|
|
196
184
|
```
|
|
197
185
|
|
|
198
|
-
You can also enable dev mode in your app to use local OpenKey:
|
|
199
|
-
|
|
200
|
-
```javascript
|
|
201
|
-
localStorage.setItem('__DEV_MODE__', 'true');
|
|
202
|
-
```
|
|
203
|
-
|
|
204
186
|
## Browser Support
|
|
205
187
|
|
|
206
188
|
OpenKey requires WebAuthn support:
|
|
@@ -209,17 +191,23 @@ OpenKey requires WebAuthn support:
|
|
|
209
191
|
- Safari 13+
|
|
210
192
|
- Edge 79+
|
|
211
193
|
|
|
194
|
+
Iframe mode requires cross-origin WebAuthn support:
|
|
195
|
+
- Chrome 84+
|
|
196
|
+
- Firefox 84+
|
|
197
|
+
- Safari 14.5+
|
|
198
|
+
|
|
212
199
|
## Security
|
|
213
200
|
|
|
214
201
|
- Keys never leave the OpenKey TEE (Trusted Execution Environment)
|
|
215
202
|
- All signing operations require explicit user approval via passkey
|
|
216
203
|
- No seed phrases or private keys to manage or lose
|
|
204
|
+
- Iframe communicates via `postMessage` with origin validation
|
|
205
|
+
- Auto-fallback to popup ensures signing always works
|
|
217
206
|
|
|
218
207
|
## Links
|
|
219
208
|
|
|
220
209
|
- [OpenKey Website](https://openkey.so)
|
|
221
|
-
- [
|
|
222
|
-
- [GitHub](https://github.com/AstroX11/openkey)
|
|
210
|
+
- [GitHub](https://github.com/TinyCloudLabs/openkey)
|
|
223
211
|
- [TinyCloud Integration](https://tinycloud.xyz)
|
|
224
212
|
|
|
225
213
|
## License
|
package/dist/index.d.mts
CHANGED
|
@@ -4,13 +4,14 @@ interface EIP1193Provider {
|
|
|
4
4
|
params?: any[];
|
|
5
5
|
}): Promise<any>;
|
|
6
6
|
}
|
|
7
|
+
type OpenKeyMode = 'iframe' | 'popup' | 'redirect';
|
|
7
8
|
interface OpenKeyConfig {
|
|
8
9
|
/** OpenKey host URL (default: https://openkey.so) */
|
|
9
10
|
host?: string;
|
|
10
11
|
/** App identifier for display */
|
|
11
12
|
appName?: string;
|
|
12
|
-
/**
|
|
13
|
-
|
|
13
|
+
/** UI mode: 'iframe' (default), 'popup', or 'redirect' */
|
|
14
|
+
mode?: OpenKeyMode;
|
|
14
15
|
/** App-provided wallet provider for external key signing */
|
|
15
16
|
externalProvider?: EIP1193Provider;
|
|
16
17
|
}
|
|
@@ -74,10 +75,9 @@ interface OAuthTokenResponse {
|
|
|
74
75
|
declare class OpenKey {
|
|
75
76
|
private host;
|
|
76
77
|
private appName;
|
|
77
|
-
private
|
|
78
|
+
private mode;
|
|
78
79
|
private config;
|
|
79
80
|
private popup;
|
|
80
|
-
private iframe;
|
|
81
81
|
private lastAuth;
|
|
82
82
|
private discoveredProviders;
|
|
83
83
|
constructor(config?: OpenKeyConfig);
|
|
@@ -85,12 +85,16 @@ declare class OpenKey {
|
|
|
85
85
|
* Connect to OpenKey and get user's wallet address
|
|
86
86
|
* Opens auth flow for user to select/create a key
|
|
87
87
|
*/
|
|
88
|
-
connect(
|
|
88
|
+
connect(opts?: {
|
|
89
|
+
mode?: OpenKeyMode;
|
|
90
|
+
}): Promise<AuthResult>;
|
|
89
91
|
/**
|
|
90
92
|
* Link an external wallet to the user's OpenKey account
|
|
91
93
|
* Opens link-wallet widget flow
|
|
92
94
|
*/
|
|
93
|
-
linkWallet(
|
|
95
|
+
linkWallet(opts?: {
|
|
96
|
+
mode?: OpenKeyMode;
|
|
97
|
+
}): Promise<{
|
|
94
98
|
address: string;
|
|
95
99
|
keyId: string;
|
|
96
100
|
}>;
|
|
@@ -98,12 +102,16 @@ declare class OpenKey {
|
|
|
98
102
|
* Sign a message with the user's OpenKey wallet
|
|
99
103
|
* For external keys, routes directly to the user's wallet provider
|
|
100
104
|
*/
|
|
101
|
-
signMessage(request: SignMessageRequest
|
|
105
|
+
signMessage(request: SignMessageRequest, opts?: {
|
|
106
|
+
mode?: OpenKeyMode;
|
|
107
|
+
}): Promise<SignResult>;
|
|
102
108
|
/**
|
|
103
109
|
* Sign typed data (EIP-712) with the user's OpenKey wallet
|
|
104
110
|
* For external keys, routes directly to the user's wallet provider
|
|
105
111
|
*/
|
|
106
|
-
signTypedData(request: SignTypedDataRequest
|
|
112
|
+
signTypedData(request: SignTypedDataRequest, opts?: {
|
|
113
|
+
mode?: OpenKeyMode;
|
|
114
|
+
}): Promise<SignResult>;
|
|
107
115
|
/**
|
|
108
116
|
* Find a wallet provider that controls the given address.
|
|
109
117
|
* Checks: 1) app-provided externalProvider, 2) EIP-6963 discovered wallets, 3) window.ethereum
|
|
@@ -111,8 +119,8 @@ declare class OpenKey {
|
|
|
111
119
|
findWalletProvider(targetAddress: string): Promise<EIP1193Provider>;
|
|
112
120
|
private signWithExternalWallet;
|
|
113
121
|
private signTypedDataWithExternalWallet;
|
|
114
|
-
private
|
|
115
|
-
private
|
|
122
|
+
private signWithOpenKey;
|
|
123
|
+
private signTypedDataWithOpenKey;
|
|
116
124
|
private toHex;
|
|
117
125
|
/**
|
|
118
126
|
* Check if user is already authenticated
|
|
@@ -159,9 +167,11 @@ declare class OpenKey {
|
|
|
159
167
|
};
|
|
160
168
|
private openOAuthFlow;
|
|
161
169
|
private openOAuthPopup;
|
|
170
|
+
private resolveMode;
|
|
162
171
|
private openFlow;
|
|
172
|
+
private openIframeModal;
|
|
173
|
+
private handleWalletLinkDelegation;
|
|
163
174
|
private openPopup;
|
|
164
|
-
private openIframe;
|
|
165
175
|
/**
|
|
166
176
|
* Disconnect and close any open flows
|
|
167
177
|
*/
|
|
@@ -187,4 +197,4 @@ declare class OpenKeyEIP1193Provider implements EIP1193Provider {
|
|
|
187
197
|
|
|
188
198
|
declare function getOpenKey(config?: OpenKeyConfig): OpenKey;
|
|
189
199
|
|
|
190
|
-
export { type AuthResult, type EIP1193Provider, type OAuthConfig, type OAuthResult, type OAuthTokenResponse, OpenKey, type OpenKeyConfig, OpenKeyEIP1193Provider, type OpenKeyError, type SignMessageRequest, type SignResult, type SignTypedDataRequest, OpenKey as default, getOpenKey };
|
|
200
|
+
export { type AuthResult, type EIP1193Provider, type OAuthConfig, type OAuthResult, type OAuthTokenResponse, OpenKey, type OpenKeyConfig, OpenKeyEIP1193Provider, type OpenKeyError, type OpenKeyMode, type SignMessageRequest, type SignResult, type SignTypedDataRequest, OpenKey as default, getOpenKey };
|
package/dist/index.d.ts
CHANGED
|
@@ -4,13 +4,14 @@ interface EIP1193Provider {
|
|
|
4
4
|
params?: any[];
|
|
5
5
|
}): Promise<any>;
|
|
6
6
|
}
|
|
7
|
+
type OpenKeyMode = 'iframe' | 'popup' | 'redirect';
|
|
7
8
|
interface OpenKeyConfig {
|
|
8
9
|
/** OpenKey host URL (default: https://openkey.so) */
|
|
9
10
|
host?: string;
|
|
10
11
|
/** App identifier for display */
|
|
11
12
|
appName?: string;
|
|
12
|
-
/**
|
|
13
|
-
|
|
13
|
+
/** UI mode: 'iframe' (default), 'popup', or 'redirect' */
|
|
14
|
+
mode?: OpenKeyMode;
|
|
14
15
|
/** App-provided wallet provider for external key signing */
|
|
15
16
|
externalProvider?: EIP1193Provider;
|
|
16
17
|
}
|
|
@@ -74,10 +75,9 @@ interface OAuthTokenResponse {
|
|
|
74
75
|
declare class OpenKey {
|
|
75
76
|
private host;
|
|
76
77
|
private appName;
|
|
77
|
-
private
|
|
78
|
+
private mode;
|
|
78
79
|
private config;
|
|
79
80
|
private popup;
|
|
80
|
-
private iframe;
|
|
81
81
|
private lastAuth;
|
|
82
82
|
private discoveredProviders;
|
|
83
83
|
constructor(config?: OpenKeyConfig);
|
|
@@ -85,12 +85,16 @@ declare class OpenKey {
|
|
|
85
85
|
* Connect to OpenKey and get user's wallet address
|
|
86
86
|
* Opens auth flow for user to select/create a key
|
|
87
87
|
*/
|
|
88
|
-
connect(
|
|
88
|
+
connect(opts?: {
|
|
89
|
+
mode?: OpenKeyMode;
|
|
90
|
+
}): Promise<AuthResult>;
|
|
89
91
|
/**
|
|
90
92
|
* Link an external wallet to the user's OpenKey account
|
|
91
93
|
* Opens link-wallet widget flow
|
|
92
94
|
*/
|
|
93
|
-
linkWallet(
|
|
95
|
+
linkWallet(opts?: {
|
|
96
|
+
mode?: OpenKeyMode;
|
|
97
|
+
}): Promise<{
|
|
94
98
|
address: string;
|
|
95
99
|
keyId: string;
|
|
96
100
|
}>;
|
|
@@ -98,12 +102,16 @@ declare class OpenKey {
|
|
|
98
102
|
* Sign a message with the user's OpenKey wallet
|
|
99
103
|
* For external keys, routes directly to the user's wallet provider
|
|
100
104
|
*/
|
|
101
|
-
signMessage(request: SignMessageRequest
|
|
105
|
+
signMessage(request: SignMessageRequest, opts?: {
|
|
106
|
+
mode?: OpenKeyMode;
|
|
107
|
+
}): Promise<SignResult>;
|
|
102
108
|
/**
|
|
103
109
|
* Sign typed data (EIP-712) with the user's OpenKey wallet
|
|
104
110
|
* For external keys, routes directly to the user's wallet provider
|
|
105
111
|
*/
|
|
106
|
-
signTypedData(request: SignTypedDataRequest
|
|
112
|
+
signTypedData(request: SignTypedDataRequest, opts?: {
|
|
113
|
+
mode?: OpenKeyMode;
|
|
114
|
+
}): Promise<SignResult>;
|
|
107
115
|
/**
|
|
108
116
|
* Find a wallet provider that controls the given address.
|
|
109
117
|
* Checks: 1) app-provided externalProvider, 2) EIP-6963 discovered wallets, 3) window.ethereum
|
|
@@ -111,8 +119,8 @@ declare class OpenKey {
|
|
|
111
119
|
findWalletProvider(targetAddress: string): Promise<EIP1193Provider>;
|
|
112
120
|
private signWithExternalWallet;
|
|
113
121
|
private signTypedDataWithExternalWallet;
|
|
114
|
-
private
|
|
115
|
-
private
|
|
122
|
+
private signWithOpenKey;
|
|
123
|
+
private signTypedDataWithOpenKey;
|
|
116
124
|
private toHex;
|
|
117
125
|
/**
|
|
118
126
|
* Check if user is already authenticated
|
|
@@ -159,9 +167,11 @@ declare class OpenKey {
|
|
|
159
167
|
};
|
|
160
168
|
private openOAuthFlow;
|
|
161
169
|
private openOAuthPopup;
|
|
170
|
+
private resolveMode;
|
|
162
171
|
private openFlow;
|
|
172
|
+
private openIframeModal;
|
|
173
|
+
private handleWalletLinkDelegation;
|
|
163
174
|
private openPopup;
|
|
164
|
-
private openIframe;
|
|
165
175
|
/**
|
|
166
176
|
* Disconnect and close any open flows
|
|
167
177
|
*/
|
|
@@ -187,4 +197,4 @@ declare class OpenKeyEIP1193Provider implements EIP1193Provider {
|
|
|
187
197
|
|
|
188
198
|
declare function getOpenKey(config?: OpenKeyConfig): OpenKey;
|
|
189
199
|
|
|
190
|
-
export { type AuthResult, type EIP1193Provider, type OAuthConfig, type OAuthResult, type OAuthTokenResponse, OpenKey, type OpenKeyConfig, OpenKeyEIP1193Provider, type OpenKeyError, type SignMessageRequest, type SignResult, type SignTypedDataRequest, OpenKey as default, getOpenKey };
|
|
200
|
+
export { type AuthResult, type EIP1193Provider, type OAuthConfig, type OAuthResult, type OAuthTokenResponse, OpenKey, type OpenKeyConfig, OpenKeyEIP1193Provider, type OpenKeyError, type OpenKeyMode, type SignMessageRequest, type SignResult, type SignTypedDataRequest, OpenKey as default, getOpenKey };
|
package/dist/index.js
CHANGED
|
@@ -1,21 +1,47 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
|
|
3
|
-
inset:
|
|
4
|
-
background: rgba(0,
|
|
5
|
-
display:
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
1
|
+
"use strict";var w=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var I=(a,e)=>{for(var t in e)w(a,t,{get:e[t],enumerable:!0})},A=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of b(e))!O.call(a,r)&&r!==t&&w(a,r,{get:()=>e[r],enumerable:!(s=P(e,r))||s.enumerable});return a};var C=a=>A(w({},"__esModule",{value:!0}),a);var L={};I(L,{OpenKey:()=>m,OpenKeyEIP1193Provider:()=>T,default:()=>D,getOpenKey:()=>N});module.exports=C(L);var M="https://openkey.so";var f="openkey_oauth",v=class{root;shadow;iframe;onClose;onMessage;messageHandler;host;constructor(e){this.host=e.host,this.onClose=e.onClose,this.onMessage=e.onMessage;let t=window.matchMedia("(max-width: 639px)").matches;this.root=document.createElement("div"),this.shadow=this.root.attachShadow({mode:"closed"});let s=document.createElement("style");s.textContent=`
|
|
2
|
+
:host{all:initial}
|
|
3
|
+
.ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:999999;display:flex;align-items:${t?"flex-end":"center"};justify-content:center;animation:ok-fade-in 150ms ease-out}
|
|
4
|
+
.ok-card{position:relative;background:#fff;width:${t?"100%":"400px"};border-radius:${t?"16px 16px 0 0":"16px"};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;animation:${t?"ok-slide-up 250ms ease-out":"ok-scale-in 200ms ease-out"};${t?"max-height:85vh;":""}}
|
|
5
|
+
.ok-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;background:transparent;color:#6b7280;font-size:18px;cursor:pointer;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:4px}
|
|
6
|
+
.ok-close:hover{color:#111827}
|
|
7
|
+
.ok-handle{width:40px;height:4px;background:#d1d5db;border-radius:2px;margin:8px auto 0}
|
|
8
|
+
iframe{border:none;width:100%;height:400px;display:block;transition:height 200ms ease}
|
|
9
|
+
.ok-backdrop.ok-exit{animation:ok-fade-out 150ms ease-in}
|
|
10
|
+
.ok-backdrop.ok-exit .ok-card{animation:${t?"ok-slide-down 200ms ease-in":"ok-scale-out 150ms ease-in"}}
|
|
11
|
+
@keyframes ok-fade-in{from{opacity:0}to{opacity:1}}
|
|
12
|
+
@keyframes ok-fade-out{from{opacity:1}to{opacity:0}}
|
|
13
|
+
@keyframes ok-scale-in{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}
|
|
14
|
+
@keyframes ok-scale-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.95)}}
|
|
15
|
+
@keyframes ok-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}
|
|
16
|
+
@keyframes ok-slide-down{from{transform:translateY(0)}to{transform:translateY(100%)}}
|
|
17
|
+
@media(prefers-color-scheme:dark){
|
|
18
|
+
.ok-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}
|
|
19
|
+
.ok-close{color:#9ca3af}
|
|
20
|
+
.ok-close:hover{color:#f3f4f6}
|
|
21
|
+
.ok-handle{background:#4b5563}
|
|
22
|
+
}
|
|
23
|
+
`;let r=document.createElement("div");r.className="ok-backdrop",r.addEventListener("click",n=>{n.target===r&&this.close()});let o=document.createElement("div");if(o.className="ok-card",t){let n=document.createElement("div");n.className="ok-handle",o.appendChild(n)}let d=document.createElement("button");d.className="ok-close",d.textContent="\xD7",d.addEventListener("click",()=>this.close()),o.appendChild(d),this.iframe=document.createElement("iframe"),this.iframe.src=e.url,this.iframe.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *"),this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),o.appendChild(this.iframe),r.appendChild(o),this.shadow.appendChild(s),this.shadow.appendChild(r),this.messageHandler=n=>{if(n.origin!==this.host)return;let l=n.data;if(l.type==="openkey:resize"){let u=Math.min(l.height,Math.floor(window.innerHeight*.9),700);this.iframe.style.height=`${u}px`;return}this.onMessage(l)},window.addEventListener("message",this.messageHandler),document.body.appendChild(this.root)}postMessage(e){this.iframe.contentWindow?.postMessage(e,this.host)}destroy(){window.removeEventListener("message",this.messageHandler),this.root.remove()}close(){let e=this.shadow.querySelector(".ok-backdrop");e?(e.classList.add("ok-exit"),setTimeout(()=>{this.destroy(),this.onClose()},200)):(this.destroy(),this.onClose())}},E=class{root;shadow;constructor(e){this.root=document.createElement("div"),this.shadow=this.root.attachShadow({mode:"closed"});let t=document.createElement("style");t.textContent=`
|
|
24
|
+
:host{all:initial}
|
|
25
|
+
.wp-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:1000000;display:flex;align-items:center;justify-content:center;animation:wp-fade 150ms ease-out}
|
|
26
|
+
.wp-card{background:#fff;width:340px;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);padding:20px;animation:wp-scale 200ms ease-out}
|
|
27
|
+
.wp-title{font:600 16px/1.3 system-ui,sans-serif;color:#111;margin:0 0 12px}
|
|
28
|
+
.wp-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
|
|
29
|
+
.wp-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:10px;background:transparent;cursor:pointer;font:14px/1.3 system-ui,sans-serif;color:#111;width:100%;text-align:left;transition:border-color 150ms}
|
|
30
|
+
.wp-item:hover{border-color:#6366f1}
|
|
31
|
+
.wp-icon{width:28px;height:28px;border-radius:6px}
|
|
32
|
+
.wp-empty{font:14px/1.4 system-ui,sans-serif;color:#6b7280;text-align:center;padding:16px 0}
|
|
33
|
+
.wp-cancel{display:block;width:100%;margin-top:12px;padding:8px;border:none;background:transparent;color:#6b7280;font:14px/1.3 system-ui,sans-serif;cursor:pointer;border-radius:8px}
|
|
34
|
+
.wp-cancel:hover{background:#f3f4f6;color:#111}
|
|
35
|
+
@keyframes wp-fade{from{opacity:0}to{opacity:1}}
|
|
36
|
+
@keyframes wp-scale{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}
|
|
37
|
+
@media(prefers-color-scheme:dark){
|
|
38
|
+
.wp-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}
|
|
39
|
+
.wp-title{color:#f3f4f6}
|
|
40
|
+
.wp-item{border-color:#374151;color:#f3f4f6}
|
|
41
|
+
.wp-item:hover{border-color:#818cf8}
|
|
42
|
+
.wp-empty{color:#9ca3af}
|
|
43
|
+
.wp-cancel{color:#9ca3af}
|
|
44
|
+
.wp-cancel:hover{background:#262626;color:#f3f4f6}
|
|
45
|
+
}
|
|
46
|
+
`;let s=document.createElement("div");s.className="wp-backdrop",s.addEventListener("click",n=>{n.target===s&&(this.destroy(),e.onCancel())});let r=document.createElement("div");r.className="wp-card";let o=document.createElement("h2");if(o.className="wp-title",o.textContent="Select a wallet",r.appendChild(o),e.providers.length===0){let n=document.createElement("div");n.className="wp-empty",n.textContent="No wallets detected",r.appendChild(n)}else{let n=document.createElement("ul");n.className="wp-list";for(let{info:l,provider:u}of e.providers){let c=document.createElement("button");if(c.className="wp-item",l.icon){let i=document.createElement("img");i.className="wp-icon",i.src=l.icon,i.alt=l.name,c.appendChild(i)}let h=document.createElement("span");h.textContent=l.name,c.appendChild(h),c.addEventListener("click",()=>{this.destroy(),e.onSelect(u)}),n.appendChild(c)}r.appendChild(n)}let d=document.createElement("button");d.className="wp-cancel",d.textContent="Cancel",d.addEventListener("click",()=>{this.destroy(),e.onCancel()}),r.appendChild(d),s.appendChild(r),this.shadow.appendChild(t),this.shadow.appendChild(s),document.body.appendChild(this.root)}destroy(){this.root.remove()}};function S(){let a=document.createElement("div"),e=a.attachShadow({mode:"closed"});e.innerHTML='<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:#1f2937;color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class="ok-toast">Opening in new window\u2026</div>',document.body.appendChild(a),setTimeout(()=>a.remove(),3e3)}function x(a){return btoa(String.fromCharCode(...a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function U(){let a=new Uint8Array(32);return crypto.getRandomValues(a),x(a)}async function _(a){let t=new TextEncoder().encode(a),s=await crypto.subtle.digest("SHA-256",t);return x(new Uint8Array(s))}function R(){let a=new Uint8Array(16);return crypto.getRandomValues(a),x(a)}var m=class{host;appName;mode;config;popup=null;lastAuth=null;discoveredProviders=[];constructor(e={}){this.config=e,this.host=e.host||M,this.appName=e.appName||window.location.hostname,this.mode=e.mode??"iframe",typeof window<"u"&&(this.discoveredProviders=[],window.addEventListener("eip6963:announceProvider",t=>{this.discoveredProviders.push(t.detail)}),window.dispatchEvent(new Event("eip6963:requestProvider")))}async connect(e){let t=await this.openFlow("connect",{type:"openkey:auth:request",appName:this.appName},e?.mode);return this.lastAuth=t,t}async linkWallet(e){return this.openFlow("link-wallet",{type:"openkey:link-wallet:request"},e?.mode)}async signMessage(e,t){return this.lastAuth?.keyType==="EXTERNAL"?this.signWithExternalWallet(e):this.signWithOpenKey(e,t?.mode)}async signTypedData(e,t){return this.lastAuth?.keyType==="EXTERNAL"?this.signTypedDataWithExternalWallet(e):this.signTypedDataWithOpenKey(e,t?.mode)}async findWalletProvider(e){if(this.config.externalProvider)return this.config.externalProvider;for(let{provider:t}of this.discoveredProviders)try{if((await t.request({method:"eth_requestAccounts"})).some(r=>r.toLowerCase()===e.toLowerCase()))return t}catch{}if(typeof window<"u"&&window.ethereum){let t=window.ethereum;try{if((await t.request({method:"eth_requestAccounts"})).some(r=>r.toLowerCase()===e.toLowerCase()))return t}catch{}return t}throw new Error("No wallet provider found for external key. Connect your wallet.")}async signWithExternalWallet(e){let t=await this.findWalletProvider(this.lastAuth.address),s=this.toHex(e.message);return{signature:await t.request({method:"personal_sign",params:[s,this.lastAuth.address]}),address:this.lastAuth.address}}async signTypedDataWithExternalWallet(e){return{signature:await(await this.findWalletProvider(this.lastAuth.address)).request({method:"eth_signTypedData_v4",params:[this.lastAuth.address,JSON.stringify(e)]}),address:this.lastAuth.address}}signWithOpenKey(e,t){return this.openFlow("sign",{type:"openkey:sign:request",message:e.message,keyId:e.keyId},t)}signTypedDataWithOpenKey(e,t){return this.openFlow("sign-typed-data",{type:"openkey:signTypedData:request",data:e},t)}toHex(e){return"0x"+Array.from(new TextEncoder().encode(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async isConnected(){try{let e=await fetch(`${this.host}/api/auth/session`,{credentials:"include"});return e.ok?!!(await e.json()).user:!1}catch{return!1}}oauth={connect:async e=>{let t=await U(),s=await _(t),r=e.state||R();sessionStorage.setItem(f,JSON.stringify({verifier:t,state:r}));let o=new URL(`${this.host}/api/auth/oauth2/authorize`);return o.searchParams.set("client_id",e.clientId),o.searchParams.set("redirect_uri",e.redirectUri),o.searchParams.set("response_type","code"),o.searchParams.set("scope","openid"),o.searchParams.set("state",r),o.searchParams.set("code_challenge",s),o.searchParams.set("code_challenge_method","S256"),this.openOAuthFlow(o.toString(),r,e.redirectUri)},exchangeCode:async(e,t)=>{let s=sessionStorage.getItem(f);if(!s)throw new Error("No PKCE verifier found. Start a new OAuth flow.");let{verifier:r}=JSON.parse(s),o=await fetch(`${this.host}/api/auth/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:t.redirectUri,client_id:t.clientId,code_verifier:r})});if(sessionStorage.removeItem(f),!o.ok){let d=await o.json();throw new Error(d.error_description||"Token exchange failed")}return o.json()},verifyState:e=>{let t=sessionStorage.getItem(f);if(!t)return!1;let{state:s}=JSON.parse(t);return s===e},parseCallback:e=>{let t=new URL(e||window.location.href),s=t.searchParams.get("error");if(s)return{error:s,errorDescription:t.searchParams.get("error_description")||void 0};let r=t.searchParams.get("code"),o=t.searchParams.get("state");return!r||!o?{error:"missing_params",errorDescription:"Missing code or state parameter"}:{code:r,state:o}}};openOAuthFlow(e,t,s){return new Promise((r,o)=>{this.mode!=="redirect"?this.openOAuthPopup(e,t,s,r,o):window.location.href=e})}openOAuthPopup(e,t,s,r,o){let d=window.screenX+(window.outerWidth-400)/2,n=window.screenY+(window.outerHeight-600)/2;if(this.popup=window.open(e,"openkey-oauth",`width=400,height=600,left=${d},top=${n},popup=true`),!this.popup){o({code:"POPUP_BLOCKED",message:"Popup was blocked. Please allow popups or use redirect mode."});return}let l=new URL(s).origin,u=setInterval(()=>{try{if(this.popup?.closed){clearInterval(u),clearTimeout(c),o({code:"USER_CANCELLED",message:"User closed the popup"});return}let h=this.popup?.location?.href;if(h&&h.startsWith(l)){clearInterval(u),clearTimeout(c);let i=new URL(h),y=i.searchParams.get("code"),p=i.searchParams.get("state"),g=i.searchParams.get("error");if(this.popup?.close(),g){o({code:"UNAUTHORIZED",message:i.searchParams.get("error_description")||g});return}if(p!==t){o({code:"STATE_MISMATCH",message:"State mismatch - possible CSRF attack"});return}y?r({code:y,state:p}):o({code:"UNAUTHORIZED",message:"Authorization failed - no code returned"})}}catch{}},100),c=setTimeout(()=>{clearInterval(u),this.popup?.close(),o({code:"TIMEOUT",message:"OAuth flow timed out"})},3e5)}resolveMode(e){return e??this.mode}async openFlow(e,t,s){let r=this.resolveMode(s),o=encodeURIComponent(window.location.origin);if(r==="popup"){let n=`${this.host}/widget/${e}?origin=${o}`;return new Promise((l,u)=>this.openPopup(n,t,l,u))}if(r==="redirect"){let n=`${this.host}/widget/${e}?origin=${o}`;return window.location.href=n,new Promise(()=>{})}let d=`${this.host}/widget/embed/${e}?origin=${o}`;return this.openIframeModal(d,e,t,o)}openIframeModal(e,t,s,r){return new Promise((o,d)=>{let n=!1,l=!1,u=null,c=p=>{l||(l=!0,p())},h=()=>{clearTimeout(i),clearTimeout(y),u?.destroy(),u=null};u=new v({url:e,host:this.host,onClose:()=>{c(()=>{clearTimeout(i),clearTimeout(y),u=null,d({code:"USER_CANCELLED",message:"User cancelled the request"})})},onMessage:p=>{if(p.type==="openkey:ready"){n=!0,u?.postMessage(s);return}if(p.type==="openkey:close"){c(()=>{h(),d({code:"USER_CANCELLED",message:"User cancelled the request"})});return}if(p.type==="openkey:link-wallet:delegate"){this.handleWalletLinkDelegation(u);return}(p.type==="openkey:auth:response"||p.type==="openkey:sign:response"||p.type==="openkey:signTypedData:response"||p.type==="openkey:link-wallet:response")&&c(()=>{h(),p.success?p.type==="openkey:auth:response"?o({address:p.address,keyId:p.keyId,keyType:p.keyType||"MANAGED"}):p.type==="openkey:link-wallet:response"?o({address:p.address,keyId:p.keyId}):o({signature:p.signature,address:p.address}):d(p.error)})}});let i=setTimeout(()=>{if(n||l)return;h(),console.warn("OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP."),S();let p=`${this.host}/widget/${t}?origin=${r}`;this.openPopup(p,s,g=>c(()=>o(g)),g=>c(()=>d(g)))},3e3),y=setTimeout(()=>{c(()=>{h(),d({code:"TIMEOUT",message:"Request timed out"})})},3e5)})}handleWalletLinkDelegation(e){let t=s=>e.postMessage(s);new E({providers:this.discoveredProviders,onCancel:()=>{t({type:"openkey:link-wallet:result",success:!1,error:{code:"USER_CANCELLED",message:"Wallet linking cancelled"}})},onSelect:async s=>{try{let o=(await s.request({method:"eth_requestAccounts"}))[0];if(!o)throw new Error("No account returned");let d=await fetch(`${this.host}/api/keys/link/challenge`,{method:"POST",credentials:"include"});if(!d.ok)throw new Error("Failed to get challenge");let{message:n}=await d.json(),l=this.toHex(n),u=await s.request({method:"personal_sign",params:[l,o]}),c=await fetch(`${this.host}/api/keys/link`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({address:o,signature:u,message:n})});if(!c.ok){let i=await c.json();throw new Error(i.error||"Failed to link wallet")}let{key:h}=await c.json();t({type:"openkey:link-wallet:result",success:!0,address:h.address,keyId:h.id})}catch(r){t({type:"openkey:link-wallet:result",success:!1,error:{code:"UNKNOWN",message:r.message||"Wallet linking failed"}})}}})}openPopup(e,t,s,r){let o=window.screenX+(window.outerWidth-400)/2,d=window.screenY+(window.outerHeight-600)/2;if(this.popup=window.open(e,"openkey",`width=400,height=600,left=${o},top=${d},popup=true`),!this.popup){r({code:"POPUP_BLOCKED",message:"Popup was blocked. Please allow popups for this site."});return}let n=()=>{window.removeEventListener("message",c),clearInterval(l),clearTimeout(u)},l=setInterval(()=>{this.popup?.closed&&(n(),r({code:"USER_CANCELLED",message:"User closed the popup"}))},500),u=setTimeout(()=>{n(),this.popup?.close(),r({code:"TIMEOUT",message:"Request timed out"})},3e5),c=h=>{if(h.origin!==this.host)return;let i=h.data;if(i.type==="openkey:ready"){this.popup?.postMessage(t,this.host);return}if(i.type==="openkey:close"){n(),this.popup?.close(),r({code:"USER_CANCELLED",message:"User cancelled the request"});return}(i.type==="openkey:auth:response"||i.type==="openkey:sign:response"||i.type==="openkey:signTypedData:response"||i.type==="openkey:link-wallet:response")&&(n(),this.popup?.close(),i.success?i.type==="openkey:auth:response"?s({address:i.address,keyId:i.keyId,keyType:i.keyType||"MANAGED"}):i.type==="openkey:link-wallet:response"?s({address:i.address,keyId:i.keyId}):s({signature:i.signature,address:i.address}):r(i.error))};window.addEventListener("message",c)}disconnect(){this.popup?.close(),this.popup=null}},T=class{openkey;address;keyId;keyType;constructor(e,t){this.openkey=e,this.address=t.address,this.keyId=t.keyId,this.keyType=t.keyType}async request({method:e,params:t}){switch(e){case"eth_accounts":case"eth_requestAccounts":return[this.address];case"eth_chainId":return"0x1";case"personal_sign":{if(this.keyType==="EXTERNAL")return(await this.openkey.findWalletProvider(this.address)).request({method:e,params:t});let s=this.hexToString(t[0]);return(await this.openkey.signMessage({message:s,keyId:this.keyId})).signature}case"eth_signTypedData_v4":{if(this.keyType==="EXTERNAL")return(await this.openkey.findWalletProvider(this.address)).request({method:e,params:t});let s=JSON.parse(t[1]);return(await this.openkey.signTypedData(s)).signature}default:throw new Error(`Unsupported method: ${e}`)}}hexToString(e){let t=new Uint8Array((e.startsWith("0x")?e.slice(2):e).match(/.{1,2}/g).map(s=>parseInt(s,16)));return new TextDecoder().decode(t)}},D=m,k=null;function N(a){return(!k||a)&&(k=new m(a)),k}0&&(module.exports={OpenKey,OpenKeyEIP1193Provider,getOpenKey});
|
|
21
47
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// OpenKey SDK - Browser client for third-party apps\n// Provides \"Sign with OpenKey\" functionality via popup or iframe\n\nexport interface EIP1193Provider {\n request(args: { method: string; params?: any[] }): Promise<any>;\n}\n\ninterface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\ninterface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport interface OpenKeyConfig {\n /** OpenKey host URL (default: https://openkey.so) */\n host?: string;\n /** App identifier for display */\n appName?: string;\n /** Use popup instead of iframe (default: true) */\n usePopup?: boolean;\n /** App-provided wallet provider for external key signing */\n externalProvider?: EIP1193Provider;\n}\n\nexport interface SignMessageRequest {\n message: string;\n keyId?: string; // If not provided, user selects\n}\n\nexport interface SignTypedDataRequest {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n keyId?: string;\n}\n\nexport interface SignResult {\n signature: string;\n address: string;\n}\n\nexport interface AuthResult {\n address: string;\n keyId: string;\n keyType: 'MANAGED' | 'EXTERNAL';\n}\n\nexport interface OpenKeyError {\n code: 'USER_CANCELLED' | 'POPUP_BLOCKED' | 'TIMEOUT' | 'NO_KEY' | 'UNAUTHORIZED' | 'UNKNOWN' | 'STATE_MISMATCH';\n message: string;\n}\n\n// ======= OAuth 2.1 Types =======\n\n/** OAuth configuration for third-party apps */\nexport interface OAuthConfig {\n /** OAuth client_id (registered with OpenKey) */\n clientId: string;\n /** Redirect URI (must match registered URI) */\n redirectUri: string;\n /** State parameter for CSRF protection (auto-generated if not provided) */\n state?: string;\n}\n\n/** Result from OAuth authorization */\nexport interface OAuthResult {\n /** Authorization code (exchange for tokens) */\n code: string;\n /** State parameter (verify matches request) */\n state: string;\n}\n\n/** Response from token exchange */\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n id_token: string;\n scope: string;\n refresh_token?: string;\n}\n\ntype MessageType =\n | { type: 'openkey:auth:request'; appName: string }\n | { type: 'openkey:auth:response'; success: true; address: string; keyId: string; keyType?: 'MANAGED' | 'EXTERNAL' }\n | { type: 'openkey:auth:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:sign:request'; message: string; keyId?: string }\n | { type: 'openkey:sign:response'; success: true; signature: string; address: string }\n | { type: 'openkey:sign:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:signTypedData:request'; data: SignTypedDataRequest }\n | { type: 'openkey:signTypedData:response'; success: true; signature: string; address: string }\n | { type: 'openkey:signTypedData:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:request' }\n | { type: 'openkey:link-wallet:response'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:ready' }\n | { type: 'openkey:close' };\n\nconst DEFAULT_HOST = 'https://openkey.so';\nconst POPUP_WIDTH = 400;\nconst POPUP_HEIGHT = 600;\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000; // 5 minutes\nconst OAUTH_STORAGE_KEY = 'openkey_oauth';\n\n// ======= PKCE Utilities =======\n\nfunction base64UrlEncode(buffer: Uint8Array): string {\n const base64 = btoa(String.fromCharCode(...buffer));\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\nasync function generateCodeVerifier(): Promise<string> {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nasync function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction generateState(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nexport class OpenKey {\n private host: string;\n private appName: string;\n private usePopup: boolean;\n private config: OpenKeyConfig;\n private popup: Window | null = null;\n private iframe: HTMLIFrameElement | null = null;\n private lastAuth: AuthResult | null = null;\n private discoveredProviders: EIP6963ProviderDetail[] = [];\n\n constructor(config: OpenKeyConfig = {}) {\n this.config = config;\n this.host = config.host || DEFAULT_HOST;\n this.appName = config.appName || window.location.hostname;\n this.usePopup = config.usePopup ?? true;\n\n // Listen for EIP-6963 wallet announcements\n if (typeof window !== 'undefined') {\n this.discoveredProviders = [];\n window.addEventListener('eip6963:announceProvider', (event: any) => {\n this.discoveredProviders.push(event.detail);\n });\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n }\n }\n\n /**\n * Connect to OpenKey and get user's wallet address\n * Opens auth flow for user to select/create a key\n */\n async connect(): Promise<AuthResult> {\n const result = await this.openFlow<AuthResult>('connect', {\n type: 'openkey:auth:request',\n appName: this.appName,\n });\n this.lastAuth = result;\n return result;\n }\n\n /**\n * Link an external wallet to the user's OpenKey account\n * Opens link-wallet widget flow\n */\n async linkWallet(): Promise<{ address: string; keyId: string }> {\n return this.openFlow<{ address: string; keyId: string }>('link-wallet', {\n type: 'openkey:link-wallet:request',\n });\n }\n\n /**\n * Sign a message with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signMessage(request: SignMessageRequest): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signWithExternalWallet(request);\n }\n return this.signWithPopup(request);\n }\n\n /**\n * Sign typed data (EIP-712) with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signTypedData(request: SignTypedDataRequest): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signTypedDataWithExternalWallet(request);\n }\n return this.signTypedDataWithPopup(request);\n }\n\n /**\n * Find a wallet provider that controls the given address.\n * Checks: 1) app-provided externalProvider, 2) EIP-6963 discovered wallets, 3) window.ethereum\n */\n async findWalletProvider(targetAddress: string): Promise<EIP1193Provider> {\n // 1. Try app-provided externalProvider first\n if (this.config.externalProvider) {\n return this.config.externalProvider;\n }\n\n // 2. Use EIP-6963 to discover wallets, requesting authorization\n for (const { provider } of this.discoveredProviders) {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n }\n\n // 3. Fall back to window.ethereum, requesting authorization\n if (typeof window !== 'undefined' && (window as any).ethereum) {\n const provider = (window as any).ethereum as EIP1193Provider;\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n return provider;\n }\n\n throw new Error('No wallet provider found for external key. Connect your wallet.');\n }\n\n private async signWithExternalWallet(request: SignMessageRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const hexMessage = this.toHex(request.message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, this.lastAuth!.address],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private async signTypedDataWithExternalWallet(request: SignTypedDataRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const signature = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [this.lastAuth!.address, JSON.stringify(request)],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private signWithPopup(request: SignMessageRequest): Promise<SignResult> {\n return this.openFlow<SignResult>('sign', {\n type: 'openkey:sign:request',\n message: request.message,\n keyId: request.keyId,\n });\n }\n\n private signTypedDataWithPopup(request: SignTypedDataRequest): Promise<SignResult> {\n return this.openFlow<SignResult>('sign-typed-data', {\n type: 'openkey:signTypedData:request',\n data: request,\n });\n }\n\n private toHex(str: string): string {\n return '0x' + Array.from(new TextEncoder().encode(str)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Check if user is already authenticated\n */\n async isConnected(): Promise<boolean> {\n // Check for existing session via API\n try {\n const res = await fetch(`${this.host}/api/auth/session`, {\n credentials: 'include',\n });\n if (!res.ok) return false;\n const data = await res.json();\n return !!data.user;\n } catch {\n return false;\n }\n }\n\n // ======= OAuth 2.1 Provider Methods =======\n\n /**\n * OAuth 2.1 methods for third-party app authentication\n * Use this when your app has registered OAuth client credentials with OpenKey\n */\n oauth = {\n /**\n * Start OAuth authorization flow\n * Opens popup/redirect to OpenKey authorization endpoint\n * @returns Promise that resolves with authorization code after user consent\n */\n connect: async (config: OAuthConfig): Promise<OAuthResult> => {\n // Generate PKCE values\n const verifier = await generateCodeVerifier();\n const challenge = await generateCodeChallenge(verifier);\n const state = config.state || generateState();\n\n // Store for later token exchange\n sessionStorage.setItem(\n OAUTH_STORAGE_KEY,\n JSON.stringify({ verifier, state })\n );\n\n // Build authorization URL\n const authUrl = new URL(`${this.host}/api/auth/oauth2/authorize`);\n authUrl.searchParams.set('client_id', config.clientId);\n authUrl.searchParams.set('redirect_uri', config.redirectUri);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', 'openid');\n authUrl.searchParams.set('state', state);\n authUrl.searchParams.set('code_challenge', challenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n\n return this.openOAuthFlow(authUrl.toString(), state, config.redirectUri);\n },\n\n /**\n * Exchange authorization code for tokens\n * Call this after receiving the callback with authorization code\n * @param code - Authorization code from callback URL\n * @param config - Same config used for connect()\n * @returns Promise that resolves with access_token, id_token, etc.\n */\n exchangeCode: async (\n code: string,\n config: OAuthConfig\n ): Promise<OAuthTokenResponse> => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) {\n throw new Error('No PKCE verifier found. Start a new OAuth flow.');\n }\n\n const { verifier } = JSON.parse(stored);\n\n const response = await fetch(`${this.host}/api/auth/oauth2/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: verifier,\n }),\n });\n\n // Clear stored verifier\n sessionStorage.removeItem(OAUTH_STORAGE_KEY);\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error_description || 'Token exchange failed');\n }\n\n return response.json();\n },\n\n /**\n * Verify state parameter from callback\n * Call this before exchangeCode to prevent CSRF attacks\n * @param receivedState - State parameter from callback URL\n * @returns true if state matches, false otherwise\n */\n verifyState: (receivedState: string): boolean => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) return false;\n const { state } = JSON.parse(stored);\n return state === receivedState;\n },\n\n /**\n * Parse authorization response from callback URL\n * @param url - Callback URL (defaults to current window.location.href)\n * @returns Parsed code and state, or error\n */\n parseCallback: (\n url?: string\n ): { code: string; state: string } | { error: string; errorDescription?: string } => {\n const urlObj = new URL(url || window.location.href);\n const error = urlObj.searchParams.get('error');\n\n if (error) {\n return {\n error,\n errorDescription: urlObj.searchParams.get('error_description') || undefined,\n };\n }\n\n const code = urlObj.searchParams.get('code');\n const state = urlObj.searchParams.get('state');\n\n if (!code || !state) {\n return { error: 'missing_params', errorDescription: 'Missing code or state parameter' };\n }\n\n return { code, state };\n },\n };\n\n private openOAuthFlow(\n url: string,\n state: string,\n redirectUri: string\n ): Promise<OAuthResult> {\n return new Promise((resolve, reject) => {\n if (this.usePopup) {\n this.openOAuthPopup(url, state, redirectUri, resolve, reject);\n } else {\n // Full page redirect - won't resolve, page navigates away\n window.location.href = url;\n }\n });\n }\n\n private openOAuthPopup(\n url: string,\n state: string,\n redirectUri: string,\n resolve: (value: OAuthResult) => void,\n reject: (error: OpenKeyError) => void\n ) {\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey-oauth',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups or use redirect mode.',\n });\n return;\n }\n\n const redirectHost = new URL(redirectUri).origin;\n\n // Poll for redirect back with code\n const pollInterval = setInterval(() => {\n try {\n if (this.popup?.closed) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n return;\n }\n\n // Check if redirected to callback URL\n const popupUrl = this.popup?.location?.href;\n if (popupUrl && popupUrl.startsWith(redirectHost)) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n\n const urlObj = new URL(popupUrl);\n const code = urlObj.searchParams.get('code');\n const returnedState = urlObj.searchParams.get('state');\n const error = urlObj.searchParams.get('error');\n\n this.popup?.close();\n\n if (error) {\n reject({\n code: 'UNAUTHORIZED',\n message: urlObj.searchParams.get('error_description') || error,\n });\n return;\n }\n\n if (returnedState !== state) {\n reject({\n code: 'STATE_MISMATCH',\n message: 'State mismatch - possible CSRF attack',\n });\n return;\n }\n\n if (code) {\n resolve({ code, state: returnedState });\n } else {\n reject({\n code: 'UNAUTHORIZED',\n message: 'Authorization failed - no code returned',\n });\n }\n }\n } catch {\n // Cross-origin - popup still on OpenKey domain, continue polling\n }\n }, 100);\n\n // Timeout\n const timeout = setTimeout(() => {\n clearInterval(pollInterval);\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'OAuth flow timed out',\n });\n }, DEFAULT_TIMEOUT);\n }\n\n private async openFlow<T>(action: string, message: object): Promise<T> {\n return new Promise((resolve, reject) => {\n const url = `${this.host}/widget/${action}?origin=${encodeURIComponent(window.location.origin)}`;\n\n if (this.usePopup) {\n this.openPopup(url, message, resolve, reject);\n } else {\n this.openIframe(url, message, resolve, reject);\n }\n });\n }\n\n private openPopup<T>(\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Calculate popup position\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups for this site.',\n });\n return;\n }\n\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearInterval(pollClosed);\n clearTimeout(timeout);\n };\n\n // Poll to detect popup close\n const pollClosed = setInterval(() => {\n if (this.popup?.closed) {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n }\n }, 500);\n\n // Timeout\n const timeout = setTimeout(() => {\n cleanup();\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n }, DEFAULT_TIMEOUT);\n\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n // Widget is ready, send our request\n this.popup?.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n cleanup();\n this.popup?.close();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n return;\n }\n\n // Handle responses\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n cleanup();\n this.popup?.close();\n\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n }\n };\n\n window.addEventListener('message', handleMessage);\n }\n\n private openIframe<T>(\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Create overlay\n const overlay = document.createElement('div');\n overlay.style.cssText = `\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n `;\n\n // Create iframe container\n const container = document.createElement('div');\n container.style.cssText = `\n width: ${POPUP_WIDTH}px;\n height: ${POPUP_HEIGHT}px;\n background: #1a1a1a;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);\n `;\n\n // Create iframe\n this.iframe = document.createElement('iframe');\n this.iframe.src = url;\n this.iframe.style.cssText = `\n width: 100%;\n height: 100%;\n border: none;\n `;\n\n container.appendChild(this.iframe);\n overlay.appendChild(container);\n document.body.appendChild(overlay);\n\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearTimeout(timeout);\n overlay.remove();\n this.iframe = null;\n };\n\n // Close on overlay click\n overlay.addEventListener('click', (e) => {\n if (e.target === overlay) {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n }\n });\n\n // Timeout\n const timeout = setTimeout(() => {\n cleanup();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n }, DEFAULT_TIMEOUT);\n\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n this.iframe?.contentWindow?.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n return;\n }\n\n // Handle responses\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n cleanup();\n\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n }\n };\n\n window.addEventListener('message', handleMessage);\n }\n\n /**\n * Disconnect and close any open flows\n */\n disconnect() {\n this.popup?.close();\n this.popup = null;\n this.iframe?.parentElement?.parentElement?.remove();\n this.iframe = null;\n }\n}\n\n/**\n * Unified EIP-1193 provider that wraps an OpenKey instance.\n * Transparently routes signing to either OpenKey (managed keys) or the user's\n * wallet (external keys).\n */\nexport class OpenKeyEIP1193Provider implements EIP1193Provider {\n private openkey: OpenKey;\n private address: string;\n private keyId: string;\n private keyType: 'MANAGED' | 'EXTERNAL';\n\n constructor(openkey: OpenKey, authResult: AuthResult) {\n this.openkey = openkey;\n this.address = authResult.address;\n this.keyId = authResult.keyId;\n this.keyType = authResult.keyType;\n }\n\n async request({ method, params }: { method: string; params?: any[] }): Promise<any> {\n switch (method) {\n case 'eth_accounts':\n case 'eth_requestAccounts':\n return [this.address];\n\n case 'eth_chainId':\n return '0x1'; // mainnet\n\n case 'personal_sign': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n // Managed key: route through OpenKey\n const message = this.hexToString(params![0] as string);\n const result = await this.openkey.signMessage({ message, keyId: this.keyId });\n return result.signature;\n }\n\n case 'eth_signTypedData_v4': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n const data = JSON.parse(params![1] as string);\n const result = await this.openkey.signTypedData(data);\n return result.signature;\n }\n\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n }\n\n private hexToString(hex: string): string {\n const bytes = new Uint8Array(\n (hex.startsWith('0x') ? hex.slice(2) : hex).match(/.{1,2}/g)!.map(b => parseInt(b, 16))\n );\n return new TextDecoder().decode(bytes);\n }\n}\n\n// Default export for convenience\nexport default OpenKey;\n\n// Create singleton instance\nlet defaultInstance: OpenKey | null = null;\n\nexport function getOpenKey(config?: OpenKeyConfig): OpenKey {\n if (!defaultInstance || config) {\n defaultInstance = new OpenKey(config);\n }\n return defaultInstance;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,2BAAAC,EAAA,YAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAN,GA8GA,IAAMO,EAAe,qBAIrB,IAAMC,EAAoB,gBAI1B,SAASC,EAAgBC,EAA4B,CAEnD,OADe,KAAK,OAAO,aAAa,GAAGA,CAAM,CAAC,EACpC,QAAQ,MAAO,GAAG,EAAE,QAAQ,MAAO,GAAG,EAAE,QAAQ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AAkB,IAAIjD,EAAQC,CAAM,GAE/BgD,CACT","names":["index_exports","__export","OpenKey","OpenKeyEIP1193Provider","index_default","getOpenKey","__toCommonJS","DEFAULT_HOST","OAUTH_STORAGE_KEY","base64UrlEncode","buffer","generateCodeVerifier","array","generateCodeChallenge","verifier","data","digest","generateState","OpenKey","config","DEFAULT_HOST","event","result","request","targetAddress","provider","a","hexMessage","str","b","res","challenge","state","authUrl","code","stored","response","error","receivedState","url","urlObj","redirectUri","resolve","reject","left","top","redirectHost","pollInterval","timeout","popupUrl","returnedState","action","message","cleanup","handleMessage","pollClosed","overlay","container","e","OpenKeyEIP1193Provider","openkey","authResult","method","params","hex","bytes","index_default","defaultInstance","getOpenKey"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// OpenKey SDK - Browser client for third-party apps\n// Provides \"Sign with OpenKey\" functionality via popup or iframe\n\nexport interface EIP1193Provider {\n request(args: { method: string; params?: any[] }): Promise<any>;\n}\n\ninterface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\ninterface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport type OpenKeyMode = 'iframe' | 'popup' | 'redirect';\n\nexport interface OpenKeyConfig {\n /** OpenKey host URL (default: https://openkey.so) */\n host?: string;\n /** App identifier for display */\n appName?: string;\n /** UI mode: 'iframe' (default), 'popup', or 'redirect' */\n mode?: OpenKeyMode;\n /** App-provided wallet provider for external key signing */\n externalProvider?: EIP1193Provider;\n}\n\nexport interface SignMessageRequest {\n message: string;\n keyId?: string; // If not provided, user selects\n}\n\nexport interface SignTypedDataRequest {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n keyId?: string;\n}\n\nexport interface SignResult {\n signature: string;\n address: string;\n}\n\nexport interface AuthResult {\n address: string;\n keyId: string;\n keyType: 'MANAGED' | 'EXTERNAL';\n}\n\nexport interface OpenKeyError {\n code: 'USER_CANCELLED' | 'POPUP_BLOCKED' | 'TIMEOUT' | 'NO_KEY' | 'UNAUTHORIZED' | 'UNKNOWN' | 'STATE_MISMATCH';\n message: string;\n}\n\n// ======= OAuth 2.1 Types =======\n\n/** OAuth configuration for third-party apps */\nexport interface OAuthConfig {\n /** OAuth client_id (registered with OpenKey) */\n clientId: string;\n /** Redirect URI (must match registered URI) */\n redirectUri: string;\n /** State parameter for CSRF protection (auto-generated if not provided) */\n state?: string;\n}\n\n/** Result from OAuth authorization */\nexport interface OAuthResult {\n /** Authorization code (exchange for tokens) */\n code: string;\n /** State parameter (verify matches request) */\n state: string;\n}\n\n/** Response from token exchange */\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n id_token: string;\n scope: string;\n refresh_token?: string;\n}\n\ntype MessageType =\n | { type: 'openkey:auth:request'; appName: string }\n | { type: 'openkey:auth:response'; success: true; address: string; keyId: string; keyType?: 'MANAGED' | 'EXTERNAL' }\n | { type: 'openkey:auth:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:sign:request'; message: string; keyId?: string }\n | { type: 'openkey:sign:response'; success: true; signature: string; address: string }\n | { type: 'openkey:sign:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:signTypedData:request'; data: SignTypedDataRequest }\n | { type: 'openkey:signTypedData:response'; success: true; signature: string; address: string }\n | { type: 'openkey:signTypedData:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:request' }\n | { type: 'openkey:link-wallet:response'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:delegate' }\n | { type: 'openkey:link-wallet:result'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:result'; success: false; error: OpenKeyError }\n | { type: 'openkey:resize'; height: number }\n | { type: 'openkey:ready' }\n | { type: 'openkey:close' };\n\nconst DEFAULT_HOST = 'https://openkey.so';\nconst POPUP_WIDTH = 400;\nconst POPUP_HEIGHT = 600;\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000; // 5 minutes\nconst IFRAME_READY_TIMEOUT = 3000; // 3 seconds\nconst OAUTH_STORAGE_KEY = 'openkey_oauth';\n\nclass IframeModal {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n private iframe: HTMLIFrameElement;\n private onClose: () => void;\n private onMessage: (data: MessageType) => void;\n private messageHandler: (event: MessageEvent) => void;\n private host: string;\n\n constructor(opts: { url: string; host: string; onClose: () => void; onMessage: (data: MessageType) => void }) {\n this.host = opts.host;\n this.onClose = opts.onClose;\n this.onMessage = opts.onMessage;\n\n const isMobile = window.matchMedia('(max-width: 639px)').matches;\n\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:999999;display:flex;align-items:${isMobile ? 'flex-end' : 'center'};justify-content:center;animation:ok-fade-in 150ms ease-out}\n .ok-card{position:relative;background:#fff;width:${isMobile ? '100%' : '400px'};border-radius:${isMobile ? '16px 16px 0 0' : '16px'};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;animation:${isMobile ? 'ok-slide-up 250ms ease-out' : 'ok-scale-in 200ms ease-out'};${isMobile ? 'max-height:85vh;' : ''}}\n .ok-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;background:transparent;color:#6b7280;font-size:18px;cursor:pointer;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:4px}\n .ok-close:hover{color:#111827}\n .ok-handle{width:40px;height:4px;background:#d1d5db;border-radius:2px;margin:8px auto 0}\n iframe{border:none;width:100%;height:400px;display:block;transition:height 200ms ease}\n .ok-backdrop.ok-exit{animation:ok-fade-out 150ms ease-in}\n .ok-backdrop.ok-exit .ok-card{animation:${isMobile ? 'ok-slide-down 200ms ease-in' : 'ok-scale-out 150ms ease-in'}}\n @keyframes ok-fade-in{from{opacity:0}to{opacity:1}}\n @keyframes ok-fade-out{from{opacity:1}to{opacity:0}}\n @keyframes ok-scale-in{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @keyframes ok-scale-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.95)}}\n @keyframes ok-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}\n @keyframes ok-slide-down{from{transform:translateY(0)}to{transform:translateY(100%)}}\n @media(prefers-color-scheme:dark){\n .ok-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}\n .ok-close{color:#9ca3af}\n .ok-close:hover{color:#f3f4f6}\n .ok-handle{background:#4b5563}\n }\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'ok-backdrop';\n backdrop.addEventListener('click', (e) => {\n if (e.target === backdrop) this.close();\n });\n\n const card = document.createElement('div');\n card.className = 'ok-card';\n\n if (isMobile) {\n const handle = document.createElement('div');\n handle.className = 'ok-handle';\n card.appendChild(handle);\n }\n\n const closeBtn = document.createElement('button');\n closeBtn.className = 'ok-close';\n closeBtn.textContent = '\\u00d7';\n closeBtn.addEventListener('click', () => this.close());\n card.appendChild(closeBtn);\n\n this.iframe = document.createElement('iframe');\n this.iframe.src = opts.url;\n this.iframe.setAttribute('allow', 'publickey-credentials-get *; publickey-credentials-create *');\n this.iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups');\n card.appendChild(this.iframe);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n\n this.messageHandler = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n const data = event.data as MessageType;\n if (data.type === 'openkey:resize') {\n const h = Math.min(data.height, Math.floor(window.innerHeight * 0.9), 700);\n this.iframe.style.height = `${h}px`;\n return;\n }\n this.onMessage(data);\n };\n window.addEventListener('message', this.messageHandler);\n document.body.appendChild(this.root);\n }\n\n postMessage(message: object) {\n this.iframe.contentWindow?.postMessage(message, this.host);\n }\n\n destroy() {\n window.removeEventListener('message', this.messageHandler);\n this.root.remove();\n }\n\n private close() {\n const backdrop = this.shadow.querySelector('.ok-backdrop');\n if (backdrop) {\n backdrop.classList.add('ok-exit');\n setTimeout(() => {\n this.destroy();\n this.onClose();\n }, 200);\n } else {\n this.destroy();\n this.onClose();\n }\n }\n}\n\nclass WalletPicker {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n\n constructor(opts: { providers: EIP6963ProviderDetail[]; onSelect: (provider: EIP1193Provider) => void; onCancel: () => void }) {\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .wp-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:1000000;display:flex;align-items:center;justify-content:center;animation:wp-fade 150ms ease-out}\n .wp-card{background:#fff;width:340px;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);padding:20px;animation:wp-scale 200ms ease-out}\n .wp-title{font:600 16px/1.3 system-ui,sans-serif;color:#111;margin:0 0 12px}\n .wp-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}\n .wp-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:10px;background:transparent;cursor:pointer;font:14px/1.3 system-ui,sans-serif;color:#111;width:100%;text-align:left;transition:border-color 150ms}\n .wp-item:hover{border-color:#6366f1}\n .wp-icon{width:28px;height:28px;border-radius:6px}\n .wp-empty{font:14px/1.4 system-ui,sans-serif;color:#6b7280;text-align:center;padding:16px 0}\n .wp-cancel{display:block;width:100%;margin-top:12px;padding:8px;border:none;background:transparent;color:#6b7280;font:14px/1.3 system-ui,sans-serif;cursor:pointer;border-radius:8px}\n .wp-cancel:hover{background:#f3f4f6;color:#111}\n @keyframes wp-fade{from{opacity:0}to{opacity:1}}\n @keyframes wp-scale{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @media(prefers-color-scheme:dark){\n .wp-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}\n .wp-title{color:#f3f4f6}\n .wp-item{border-color:#374151;color:#f3f4f6}\n .wp-item:hover{border-color:#818cf8}\n .wp-empty{color:#9ca3af}\n .wp-cancel{color:#9ca3af}\n .wp-cancel:hover{background:#262626;color:#f3f4f6}\n }\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'wp-backdrop';\n backdrop.addEventListener('click', (e) => { if (e.target === backdrop) { this.destroy(); opts.onCancel(); } });\n\n const card = document.createElement('div');\n card.className = 'wp-card';\n\n const title = document.createElement('h2');\n title.className = 'wp-title';\n title.textContent = 'Select a wallet';\n card.appendChild(title);\n\n if (opts.providers.length === 0) {\n const empty = document.createElement('div');\n empty.className = 'wp-empty';\n empty.textContent = 'No wallets detected';\n card.appendChild(empty);\n } else {\n const list = document.createElement('ul');\n list.className = 'wp-list';\n for (const { info, provider } of opts.providers) {\n const item = document.createElement('button');\n item.className = 'wp-item';\n if (info.icon) {\n const icon = document.createElement('img');\n icon.className = 'wp-icon';\n icon.src = info.icon;\n icon.alt = info.name;\n item.appendChild(icon);\n }\n const name = document.createElement('span');\n name.textContent = info.name;\n item.appendChild(name);\n item.addEventListener('click', () => { this.destroy(); opts.onSelect(provider); });\n list.appendChild(item);\n }\n card.appendChild(list);\n }\n\n const cancel = document.createElement('button');\n cancel.className = 'wp-cancel';\n cancel.textContent = 'Cancel';\n cancel.addEventListener('click', () => { this.destroy(); opts.onCancel(); });\n card.appendChild(cancel);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n document.body.appendChild(this.root);\n }\n\n destroy() {\n this.root.remove();\n }\n}\n\nfunction showToast() {\n const root = document.createElement('div');\n const shadow = root.attachShadow({ mode: 'closed' });\n shadow.innerHTML = `<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:#1f2937;color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class=\"ok-toast\">Opening in new window\\u2026</div>`;\n document.body.appendChild(root);\n setTimeout(() => root.remove(), 3000);\n}\n\n// ======= PKCE Utilities =======\n\nfunction base64UrlEncode(buffer: Uint8Array): string {\n const base64 = btoa(String.fromCharCode(...buffer));\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\nasync function generateCodeVerifier(): Promise<string> {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nasync function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction generateState(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nexport class OpenKey {\n private host: string;\n private appName: string;\n private mode: OpenKeyMode;\n private config: OpenKeyConfig;\n private popup: Window | null = null;\n private lastAuth: AuthResult | null = null;\n private discoveredProviders: EIP6963ProviderDetail[] = [];\n\n constructor(config: OpenKeyConfig = {}) {\n this.config = config;\n this.host = config.host || DEFAULT_HOST;\n this.appName = config.appName || window.location.hostname;\n this.mode = config.mode ?? 'iframe';\n\n // Listen for EIP-6963 wallet announcements\n if (typeof window !== 'undefined') {\n this.discoveredProviders = [];\n window.addEventListener('eip6963:announceProvider', (event: any) => {\n this.discoveredProviders.push(event.detail);\n });\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n }\n }\n\n /**\n * Connect to OpenKey and get user's wallet address\n * Opens auth flow for user to select/create a key\n */\n async connect(opts?: { mode?: OpenKeyMode }): Promise<AuthResult> {\n const result = await this.openFlow<AuthResult>('connect', {\n type: 'openkey:auth:request',\n appName: this.appName,\n }, opts?.mode);\n this.lastAuth = result;\n return result;\n }\n\n /**\n * Link an external wallet to the user's OpenKey account\n * Opens link-wallet widget flow\n */\n async linkWallet(opts?: { mode?: OpenKeyMode }): Promise<{ address: string; keyId: string }> {\n return this.openFlow<{ address: string; keyId: string }>('link-wallet', {\n type: 'openkey:link-wallet:request',\n }, opts?.mode);\n }\n\n /**\n * Sign a message with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signMessage(request: SignMessageRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signWithExternalWallet(request);\n }\n return this.signWithOpenKey(request, opts?.mode);\n }\n\n /**\n * Sign typed data (EIP-712) with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signTypedData(request: SignTypedDataRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signTypedDataWithExternalWallet(request);\n }\n return this.signTypedDataWithOpenKey(request, opts?.mode);\n }\n\n /**\n * Find a wallet provider that controls the given address.\n * Checks: 1) app-provided externalProvider, 2) EIP-6963 discovered wallets, 3) window.ethereum\n */\n async findWalletProvider(targetAddress: string): Promise<EIP1193Provider> {\n // 1. Try app-provided externalProvider first\n if (this.config.externalProvider) {\n return this.config.externalProvider;\n }\n\n // 2. Use EIP-6963 to discover wallets, requesting authorization\n for (const { provider } of this.discoveredProviders) {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n }\n\n // 3. Fall back to window.ethereum, requesting authorization\n if (typeof window !== 'undefined' && (window as any).ethereum) {\n const provider = (window as any).ethereum as EIP1193Provider;\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n return provider;\n }\n\n throw new Error('No wallet provider found for external key. Connect your wallet.');\n }\n\n private async signWithExternalWallet(request: SignMessageRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const hexMessage = this.toHex(request.message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, this.lastAuth!.address],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private async signTypedDataWithExternalWallet(request: SignTypedDataRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const signature = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [this.lastAuth!.address, JSON.stringify(request)],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private signWithOpenKey(request: SignMessageRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign', {\n type: 'openkey:sign:request',\n message: request.message,\n keyId: request.keyId,\n }, mode);\n }\n\n private signTypedDataWithOpenKey(request: SignTypedDataRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign-typed-data', {\n type: 'openkey:signTypedData:request',\n data: request,\n }, mode);\n }\n\n private toHex(str: string): string {\n return '0x' + Array.from(new TextEncoder().encode(str)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Check if user is already authenticated\n */\n async isConnected(): Promise<boolean> {\n // Check for existing session via API\n try {\n const res = await fetch(`${this.host}/api/auth/session`, {\n credentials: 'include',\n });\n if (!res.ok) return false;\n const data = await res.json();\n return !!data.user;\n } catch {\n return false;\n }\n }\n\n // ======= OAuth 2.1 Provider Methods =======\n\n /**\n * OAuth 2.1 methods for third-party app authentication\n * Use this when your app has registered OAuth client credentials with OpenKey\n */\n oauth = {\n /**\n * Start OAuth authorization flow\n * Opens popup/redirect to OpenKey authorization endpoint\n * @returns Promise that resolves with authorization code after user consent\n */\n connect: async (config: OAuthConfig): Promise<OAuthResult> => {\n // Generate PKCE values\n const verifier = await generateCodeVerifier();\n const challenge = await generateCodeChallenge(verifier);\n const state = config.state || generateState();\n\n // Store for later token exchange\n sessionStorage.setItem(\n OAUTH_STORAGE_KEY,\n JSON.stringify({ verifier, state })\n );\n\n // Build authorization URL\n const authUrl = new URL(`${this.host}/api/auth/oauth2/authorize`);\n authUrl.searchParams.set('client_id', config.clientId);\n authUrl.searchParams.set('redirect_uri', config.redirectUri);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', 'openid');\n authUrl.searchParams.set('state', state);\n authUrl.searchParams.set('code_challenge', challenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n\n return this.openOAuthFlow(authUrl.toString(), state, config.redirectUri);\n },\n\n /**\n * Exchange authorization code for tokens\n * Call this after receiving the callback with authorization code\n * @param code - Authorization code from callback URL\n * @param config - Same config used for connect()\n * @returns Promise that resolves with access_token, id_token, etc.\n */\n exchangeCode: async (\n code: string,\n config: OAuthConfig\n ): Promise<OAuthTokenResponse> => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) {\n throw new Error('No PKCE verifier found. Start a new OAuth flow.');\n }\n\n const { verifier } = JSON.parse(stored);\n\n const response = await fetch(`${this.host}/api/auth/oauth2/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: verifier,\n }),\n });\n\n // Clear stored verifier\n sessionStorage.removeItem(OAUTH_STORAGE_KEY);\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error_description || 'Token exchange failed');\n }\n\n return response.json();\n },\n\n /**\n * Verify state parameter from callback\n * Call this before exchangeCode to prevent CSRF attacks\n * @param receivedState - State parameter from callback URL\n * @returns true if state matches, false otherwise\n */\n verifyState: (receivedState: string): boolean => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) return false;\n const { state } = JSON.parse(stored);\n return state === receivedState;\n },\n\n /**\n * Parse authorization response from callback URL\n * @param url - Callback URL (defaults to current window.location.href)\n * @returns Parsed code and state, or error\n */\n parseCallback: (\n url?: string\n ): { code: string; state: string } | { error: string; errorDescription?: string } => {\n const urlObj = new URL(url || window.location.href);\n const error = urlObj.searchParams.get('error');\n\n if (error) {\n return {\n error,\n errorDescription: urlObj.searchParams.get('error_description') || undefined,\n };\n }\n\n const code = urlObj.searchParams.get('code');\n const state = urlObj.searchParams.get('state');\n\n if (!code || !state) {\n return { error: 'missing_params', errorDescription: 'Missing code or state parameter' };\n }\n\n return { code, state };\n },\n };\n\n private openOAuthFlow(\n url: string,\n state: string,\n redirectUri: string\n ): Promise<OAuthResult> {\n return new Promise((resolve, reject) => {\n if (this.mode !== 'redirect') {\n this.openOAuthPopup(url, state, redirectUri, resolve, reject);\n } else {\n // Full page redirect - won't resolve, page navigates away\n window.location.href = url;\n }\n });\n }\n\n private openOAuthPopup(\n url: string,\n state: string,\n redirectUri: string,\n resolve: (value: OAuthResult) => void,\n reject: (error: OpenKeyError) => void\n ) {\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey-oauth',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups or use redirect mode.',\n });\n return;\n }\n\n const redirectHost = new URL(redirectUri).origin;\n\n // Poll for redirect back with code\n const pollInterval = setInterval(() => {\n try {\n if (this.popup?.closed) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n return;\n }\n\n // Check if redirected to callback URL\n const popupUrl = this.popup?.location?.href;\n if (popupUrl && popupUrl.startsWith(redirectHost)) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n\n const urlObj = new URL(popupUrl);\n const code = urlObj.searchParams.get('code');\n const returnedState = urlObj.searchParams.get('state');\n const error = urlObj.searchParams.get('error');\n\n this.popup?.close();\n\n if (error) {\n reject({\n code: 'UNAUTHORIZED',\n message: urlObj.searchParams.get('error_description') || error,\n });\n return;\n }\n\n if (returnedState !== state) {\n reject({\n code: 'STATE_MISMATCH',\n message: 'State mismatch - possible CSRF attack',\n });\n return;\n }\n\n if (code) {\n resolve({ code, state: returnedState });\n } else {\n reject({\n code: 'UNAUTHORIZED',\n message: 'Authorization failed - no code returned',\n });\n }\n }\n } catch {\n // Cross-origin - popup still on OpenKey domain, continue polling\n }\n }, 100);\n\n // Timeout\n const timeout = setTimeout(() => {\n clearInterval(pollInterval);\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'OAuth flow timed out',\n });\n }, DEFAULT_TIMEOUT);\n }\n\n private resolveMode(override?: OpenKeyMode): OpenKeyMode {\n return override ?? this.mode;\n }\n\n private async openFlow<T>(action: string, message: object, modeOverride?: OpenKeyMode): Promise<T> {\n const mode = this.resolveMode(modeOverride);\n const origin = encodeURIComponent(window.location.origin);\n\n if (mode === 'popup') {\n const url = `${this.host}/widget/${action}?origin=${origin}`;\n return new Promise((resolve, reject) => this.openPopup(url, message, resolve, reject));\n }\n\n if (mode === 'redirect') {\n const url = `${this.host}/widget/${action}?origin=${origin}`;\n window.location.href = url;\n return new Promise(() => {}); // never resolves, page navigates\n }\n\n // iframe mode with auto-fallback\n const url = `${this.host}/widget/embed/${action}?origin=${origin}`;\n return this.openIframeModal<T>(url, action, message, origin);\n }\n\n private openIframeModal<T>(url: string, action: string, message: object, origin: string): Promise<T> {\n return new Promise((resolve, reject) => {\n let readyReceived = false;\n let settled = false;\n let modal: IframeModal | null = null;\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n\n const cleanup = () => {\n clearTimeout(readyTimeout);\n clearTimeout(overallTimeout);\n modal?.destroy();\n modal = null;\n };\n\n modal = new IframeModal({\n url,\n host: this.host,\n onClose: () => {\n settle(() => {\n clearTimeout(readyTimeout);\n clearTimeout(overallTimeout);\n modal = null;\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n },\n onMessage: (data: MessageType) => {\n if (data.type === 'openkey:ready') {\n readyReceived = true;\n modal?.postMessage(message);\n return;\n }\n\n if (data.type === 'openkey:close') {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n return;\n }\n\n if (data.type === 'openkey:link-wallet:delegate') {\n this.handleWalletLinkDelegation(modal!);\n return;\n }\n\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n settle(() => {\n cleanup();\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n });\n }\n },\n });\n\n // Auto-fallback: if no openkey:ready within 3s, fall back to popup\n const readyTimeout = setTimeout(() => {\n if (readyReceived || settled) return;\n cleanup();\n console.warn('OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP.');\n showToast();\n const popupUrl = `${this.host}/widget/${action}?origin=${origin}`;\n this.openPopup(popupUrl, message, (val: any) => settle(() => resolve(val)), (err: any) => settle(() => reject(err)));\n }, IFRAME_READY_TIMEOUT);\n\n // Overall 5-minute timeout\n const overallTimeout = setTimeout(() => {\n settle(() => {\n cleanup();\n reject({ code: 'TIMEOUT', message: 'Request timed out' } as OpenKeyError);\n });\n }, DEFAULT_TIMEOUT);\n });\n }\n\n private handleWalletLinkDelegation(modal: IframeModal) {\n const sendResult = (result: MessageType) => modal.postMessage(result);\n\n new WalletPicker({\n providers: this.discoveredProviders,\n onCancel: () => {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'USER_CANCELLED', message: 'Wallet linking cancelled' } });\n },\n onSelect: async (provider) => {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n const address = accounts[0];\n if (!address) throw new Error('No account returned');\n\n // Get challenge from API\n const challengeRes = await fetch(`${this.host}/api/keys/link/challenge`, {\n method: 'POST',\n credentials: 'include',\n });\n if (!challengeRes.ok) throw new Error('Failed to get challenge');\n const { message } = await challengeRes.json();\n\n // Sign challenge with wallet\n const hexMessage = this.toHex(message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, address],\n }) as string;\n\n // Submit to API\n const linkRes = await fetch(`${this.host}/api/keys/link`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ address, signature, message }),\n });\n if (!linkRes.ok) {\n const err = await linkRes.json();\n throw new Error(err.error || 'Failed to link wallet');\n }\n const { key } = await linkRes.json();\n\n sendResult({ type: 'openkey:link-wallet:result', success: true, address: key.address, keyId: key.id });\n } catch (e: any) {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'UNKNOWN', message: e.message || 'Wallet linking failed' } });\n }\n },\n });\n }\n\n private openPopup<T>(\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Calculate popup position\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups for this site.',\n });\n return;\n }\n\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearInterval(pollClosed);\n clearTimeout(timeout);\n };\n\n // Poll to detect popup close\n const pollClosed = setInterval(() => {\n if (this.popup?.closed) {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n }\n }, 500);\n\n // Timeout\n const timeout = setTimeout(() => {\n cleanup();\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n }, DEFAULT_TIMEOUT);\n\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n // Widget is ready, send our request\n this.popup?.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n cleanup();\n this.popup?.close();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n return;\n }\n\n // Handle responses\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n cleanup();\n this.popup?.close();\n\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n }\n };\n\n window.addEventListener('message', handleMessage);\n }\n\n /**\n * Disconnect and close any open flows\n */\n disconnect() {\n this.popup?.close();\n this.popup = null;\n }\n}\n\n/**\n * Unified EIP-1193 provider that wraps an OpenKey instance.\n * Transparently routes signing to either OpenKey (managed keys) or the user's\n * wallet (external keys).\n */\nexport class OpenKeyEIP1193Provider implements EIP1193Provider {\n private openkey: OpenKey;\n private address: string;\n private keyId: string;\n private keyType: 'MANAGED' | 'EXTERNAL';\n\n constructor(openkey: OpenKey, authResult: AuthResult) {\n this.openkey = openkey;\n this.address = authResult.address;\n this.keyId = authResult.keyId;\n this.keyType = authResult.keyType;\n }\n\n async request({ method, params }: { method: string; params?: any[] }): Promise<any> {\n switch (method) {\n case 'eth_accounts':\n case 'eth_requestAccounts':\n return [this.address];\n\n case 'eth_chainId':\n return '0x1'; // mainnet\n\n case 'personal_sign': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n // Managed key: route through OpenKey\n const message = this.hexToString(params![0] as string);\n const result = await this.openkey.signMessage({ message, keyId: this.keyId });\n return result.signature;\n }\n\n case 'eth_signTypedData_v4': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n const data = JSON.parse(params![1] as string);\n const result = await this.openkey.signTypedData(data);\n return result.signature;\n }\n\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n }\n\n private hexToString(hex: string): string {\n const bytes = new Uint8Array(\n (hex.startsWith('0x') ? hex.slice(2) : hex).match(/.{1,2}/g)!.map(b => parseInt(b, 16))\n );\n return new TextDecoder().decode(bytes);\n }\n}\n\n// Default export for convenience\nexport default OpenKey;\n\n// Create singleton instance\nlet defaultInstance: OpenKey | null = null;\n\nexport function getOpenKey(config?: OpenKeyConfig): OpenKey {\n if (!defaultInstance || config) {\n defaultInstance = new OpenKey(config);\n }\n return defaultInstance;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,2BAAAC,EAAA,YAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAN,GAoHA,IAAMO,EAAe,qBAKrB,IAAMC,EAAoB,gBAEpBC,EAAN,KAAkB,CACR,KACA,OACA,OACA,QACA,UACA,eACA,KAER,YAAYC,EAAkG,CAC5G,KAAK,KAAOA,EAAK,KACjB,KAAK,QAAUA,EAAK,QACpB,KAAK,UAAYA,EAAK,UAEtB,IAAMC,EAAW,OAAO,WAAW,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AW9D,EAAiC,CAC1D,OAAI,CAAC6D,GAAmB7D,KACtB6D,EAAkB,IAAI9D,EAAQC,CAAM,GAE/B6D,CACT","names":["index_exports","__export","OpenKey","OpenKeyEIP1193Provider","index_default","getOpenKey","__toCommonJS","DEFAULT_HOST","OAUTH_STORAGE_KEY","IframeModal","opts","isMobile","style","backdrop","e","card","handle","closeBtn","event","data","h","message","WalletPicker","title","empty","list","info","provider","item","icon","name","cancel","showToast","root","shadow","base64UrlEncode","buffer","generateCodeVerifier","array","generateCodeChallenge","verifier","digest","generateState","OpenKey","config","DEFAULT_HOST","result","request","targetAddress","a","hexMessage","mode","str","b","res","challenge","state","authUrl","code","stored","response","error","receivedState","url","urlObj","redirectUri","resolve","reject","left","top","redirectHost","pollInterval","timeout","popupUrl","returnedState","override","action","modeOverride","origin","readyReceived","settled","modal","settle","fn","cleanup","readyTimeout","overallTimeout","val","err","sendResult","address","challengeRes","signature","linkRes","key","handleMessage","pollClosed","OpenKeyEIP1193Provider","openkey","authResult","method","params","hex","bytes","index_default","defaultInstance","getOpenKey"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,21 +1,47 @@
|
|
|
1
|
-
var
|
|
2
|
-
|
|
3
|
-
inset:
|
|
4
|
-
background: rgba(0,
|
|
5
|
-
display:
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
1
|
+
var x="https://openkey.so";var m="openkey_oauth",k=class{root;shadow;iframe;onClose;onMessage;messageHandler;host;constructor(e){this.host=e.host,this.onClose=e.onClose,this.onMessage=e.onMessage;let t=window.matchMedia("(max-width: 639px)").matches;this.root=document.createElement("div"),this.shadow=this.root.attachShadow({mode:"closed"});let r=document.createElement("style");r.textContent=`
|
|
2
|
+
:host{all:initial}
|
|
3
|
+
.ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:999999;display:flex;align-items:${t?"flex-end":"center"};justify-content:center;animation:ok-fade-in 150ms ease-out}
|
|
4
|
+
.ok-card{position:relative;background:#fff;width:${t?"100%":"400px"};border-radius:${t?"16px 16px 0 0":"16px"};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;animation:${t?"ok-slide-up 250ms ease-out":"ok-scale-in 200ms ease-out"};${t?"max-height:85vh;":""}}
|
|
5
|
+
.ok-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;background:transparent;color:#6b7280;font-size:18px;cursor:pointer;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:4px}
|
|
6
|
+
.ok-close:hover{color:#111827}
|
|
7
|
+
.ok-handle{width:40px;height:4px;background:#d1d5db;border-radius:2px;margin:8px auto 0}
|
|
8
|
+
iframe{border:none;width:100%;height:400px;display:block;transition:height 200ms ease}
|
|
9
|
+
.ok-backdrop.ok-exit{animation:ok-fade-out 150ms ease-in}
|
|
10
|
+
.ok-backdrop.ok-exit .ok-card{animation:${t?"ok-slide-down 200ms ease-in":"ok-scale-out 150ms ease-in"}}
|
|
11
|
+
@keyframes ok-fade-in{from{opacity:0}to{opacity:1}}
|
|
12
|
+
@keyframes ok-fade-out{from{opacity:1}to{opacity:0}}
|
|
13
|
+
@keyframes ok-scale-in{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}
|
|
14
|
+
@keyframes ok-scale-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.95)}}
|
|
15
|
+
@keyframes ok-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}
|
|
16
|
+
@keyframes ok-slide-down{from{transform:translateY(0)}to{transform:translateY(100%)}}
|
|
17
|
+
@media(prefers-color-scheme:dark){
|
|
18
|
+
.ok-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}
|
|
19
|
+
.ok-close{color:#9ca3af}
|
|
20
|
+
.ok-close:hover{color:#f3f4f6}
|
|
21
|
+
.ok-handle{background:#4b5563}
|
|
22
|
+
}
|
|
23
|
+
`;let o=document.createElement("div");o.className="ok-backdrop",o.addEventListener("click",n=>{n.target===o&&this.close()});let s=document.createElement("div");if(s.className="ok-card",t){let n=document.createElement("div");n.className="ok-handle",s.appendChild(n)}let a=document.createElement("button");a.className="ok-close",a.textContent="\xD7",a.addEventListener("click",()=>this.close()),s.appendChild(a),this.iframe=document.createElement("iframe"),this.iframe.src=e.url,this.iframe.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *"),this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),s.appendChild(this.iframe),o.appendChild(s),this.shadow.appendChild(r),this.shadow.appendChild(o),this.messageHandler=n=>{if(n.origin!==this.host)return;let l=n.data;if(l.type==="openkey:resize"){let u=Math.min(l.height,Math.floor(window.innerHeight*.9),700);this.iframe.style.height=`${u}px`;return}this.onMessage(l)},window.addEventListener("message",this.messageHandler),document.body.appendChild(this.root)}postMessage(e){this.iframe.contentWindow?.postMessage(e,this.host)}destroy(){window.removeEventListener("message",this.messageHandler),this.root.remove()}close(){let e=this.shadow.querySelector(".ok-backdrop");e?(e.classList.add("ok-exit"),setTimeout(()=>{this.destroy(),this.onClose()},200)):(this.destroy(),this.onClose())}},v=class{root;shadow;constructor(e){this.root=document.createElement("div"),this.shadow=this.root.attachShadow({mode:"closed"});let t=document.createElement("style");t.textContent=`
|
|
24
|
+
:host{all:initial}
|
|
25
|
+
.wp-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:1000000;display:flex;align-items:center;justify-content:center;animation:wp-fade 150ms ease-out}
|
|
26
|
+
.wp-card{background:#fff;width:340px;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);padding:20px;animation:wp-scale 200ms ease-out}
|
|
27
|
+
.wp-title{font:600 16px/1.3 system-ui,sans-serif;color:#111;margin:0 0 12px}
|
|
28
|
+
.wp-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
|
|
29
|
+
.wp-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:10px;background:transparent;cursor:pointer;font:14px/1.3 system-ui,sans-serif;color:#111;width:100%;text-align:left;transition:border-color 150ms}
|
|
30
|
+
.wp-item:hover{border-color:#6366f1}
|
|
31
|
+
.wp-icon{width:28px;height:28px;border-radius:6px}
|
|
32
|
+
.wp-empty{font:14px/1.4 system-ui,sans-serif;color:#6b7280;text-align:center;padding:16px 0}
|
|
33
|
+
.wp-cancel{display:block;width:100%;margin-top:12px;padding:8px;border:none;background:transparent;color:#6b7280;font:14px/1.3 system-ui,sans-serif;cursor:pointer;border-radius:8px}
|
|
34
|
+
.wp-cancel:hover{background:#f3f4f6;color:#111}
|
|
35
|
+
@keyframes wp-fade{from{opacity:0}to{opacity:1}}
|
|
36
|
+
@keyframes wp-scale{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}
|
|
37
|
+
@media(prefers-color-scheme:dark){
|
|
38
|
+
.wp-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}
|
|
39
|
+
.wp-title{color:#f3f4f6}
|
|
40
|
+
.wp-item{border-color:#374151;color:#f3f4f6}
|
|
41
|
+
.wp-item:hover{border-color:#818cf8}
|
|
42
|
+
.wp-empty{color:#9ca3af}
|
|
43
|
+
.wp-cancel{color:#9ca3af}
|
|
44
|
+
.wp-cancel:hover{background:#262626;color:#f3f4f6}
|
|
45
|
+
}
|
|
46
|
+
`;let r=document.createElement("div");r.className="wp-backdrop",r.addEventListener("click",n=>{n.target===r&&(this.destroy(),e.onCancel())});let o=document.createElement("div");o.className="wp-card";let s=document.createElement("h2");if(s.className="wp-title",s.textContent="Select a wallet",o.appendChild(s),e.providers.length===0){let n=document.createElement("div");n.className="wp-empty",n.textContent="No wallets detected",o.appendChild(n)}else{let n=document.createElement("ul");n.className="wp-list";for(let{info:l,provider:u}of e.providers){let p=document.createElement("button");if(p.className="wp-item",l.icon){let i=document.createElement("img");i.className="wp-icon",i.src=l.icon,i.alt=l.name,p.appendChild(i)}let h=document.createElement("span");h.textContent=l.name,p.appendChild(h),p.addEventListener("click",()=>{this.destroy(),e.onSelect(u)}),n.appendChild(p)}o.appendChild(n)}let a=document.createElement("button");a.className="wp-cancel",a.textContent="Cancel",a.addEventListener("click",()=>{this.destroy(),e.onCancel()}),o.appendChild(a),r.appendChild(o),this.shadow.appendChild(t),this.shadow.appendChild(r),document.body.appendChild(this.root)}destroy(){this.root.remove()}};function P(){let c=document.createElement("div"),e=c.attachShadow({mode:"closed"});e.innerHTML='<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:#1f2937;color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class="ok-toast">Opening in new window\u2026</div>',document.body.appendChild(c),setTimeout(()=>c.remove(),3e3)}function E(c){return btoa(String.fromCharCode(...c)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function b(){let c=new Uint8Array(32);return crypto.getRandomValues(c),E(c)}async function O(c){let t=new TextEncoder().encode(c),r=await crypto.subtle.digest("SHA-256",t);return E(new Uint8Array(r))}function I(){let c=new Uint8Array(16);return crypto.getRandomValues(c),E(c)}var f=class{host;appName;mode;config;popup=null;lastAuth=null;discoveredProviders=[];constructor(e={}){this.config=e,this.host=e.host||x,this.appName=e.appName||window.location.hostname,this.mode=e.mode??"iframe",typeof window<"u"&&(this.discoveredProviders=[],window.addEventListener("eip6963:announceProvider",t=>{this.discoveredProviders.push(t.detail)}),window.dispatchEvent(new Event("eip6963:requestProvider")))}async connect(e){let t=await this.openFlow("connect",{type:"openkey:auth:request",appName:this.appName},e?.mode);return this.lastAuth=t,t}async linkWallet(e){return this.openFlow("link-wallet",{type:"openkey:link-wallet:request"},e?.mode)}async signMessage(e,t){return this.lastAuth?.keyType==="EXTERNAL"?this.signWithExternalWallet(e):this.signWithOpenKey(e,t?.mode)}async signTypedData(e,t){return this.lastAuth?.keyType==="EXTERNAL"?this.signTypedDataWithExternalWallet(e):this.signTypedDataWithOpenKey(e,t?.mode)}async findWalletProvider(e){if(this.config.externalProvider)return this.config.externalProvider;for(let{provider:t}of this.discoveredProviders)try{if((await t.request({method:"eth_requestAccounts"})).some(o=>o.toLowerCase()===e.toLowerCase()))return t}catch{}if(typeof window<"u"&&window.ethereum){let t=window.ethereum;try{if((await t.request({method:"eth_requestAccounts"})).some(o=>o.toLowerCase()===e.toLowerCase()))return t}catch{}return t}throw new Error("No wallet provider found for external key. Connect your wallet.")}async signWithExternalWallet(e){let t=await this.findWalletProvider(this.lastAuth.address),r=this.toHex(e.message);return{signature:await t.request({method:"personal_sign",params:[r,this.lastAuth.address]}),address:this.lastAuth.address}}async signTypedDataWithExternalWallet(e){return{signature:await(await this.findWalletProvider(this.lastAuth.address)).request({method:"eth_signTypedData_v4",params:[this.lastAuth.address,JSON.stringify(e)]}),address:this.lastAuth.address}}signWithOpenKey(e,t){return this.openFlow("sign",{type:"openkey:sign:request",message:e.message,keyId:e.keyId},t)}signTypedDataWithOpenKey(e,t){return this.openFlow("sign-typed-data",{type:"openkey:signTypedData:request",data:e},t)}toHex(e){return"0x"+Array.from(new TextEncoder().encode(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async isConnected(){try{let e=await fetch(`${this.host}/api/auth/session`,{credentials:"include"});return e.ok?!!(await e.json()).user:!1}catch{return!1}}oauth={connect:async e=>{let t=await b(),r=await O(t),o=e.state||I();sessionStorage.setItem(m,JSON.stringify({verifier:t,state:o}));let s=new URL(`${this.host}/api/auth/oauth2/authorize`);return s.searchParams.set("client_id",e.clientId),s.searchParams.set("redirect_uri",e.redirectUri),s.searchParams.set("response_type","code"),s.searchParams.set("scope","openid"),s.searchParams.set("state",o),s.searchParams.set("code_challenge",r),s.searchParams.set("code_challenge_method","S256"),this.openOAuthFlow(s.toString(),o,e.redirectUri)},exchangeCode:async(e,t)=>{let r=sessionStorage.getItem(m);if(!r)throw new Error("No PKCE verifier found. Start a new OAuth flow.");let{verifier:o}=JSON.parse(r),s=await fetch(`${this.host}/api/auth/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:t.redirectUri,client_id:t.clientId,code_verifier:o})});if(sessionStorage.removeItem(m),!s.ok){let a=await s.json();throw new Error(a.error_description||"Token exchange failed")}return s.json()},verifyState:e=>{let t=sessionStorage.getItem(m);if(!t)return!1;let{state:r}=JSON.parse(t);return r===e},parseCallback:e=>{let t=new URL(e||window.location.href),r=t.searchParams.get("error");if(r)return{error:r,errorDescription:t.searchParams.get("error_description")||void 0};let o=t.searchParams.get("code"),s=t.searchParams.get("state");return!o||!s?{error:"missing_params",errorDescription:"Missing code or state parameter"}:{code:o,state:s}}};openOAuthFlow(e,t,r){return new Promise((o,s)=>{this.mode!=="redirect"?this.openOAuthPopup(e,t,r,o,s):window.location.href=e})}openOAuthPopup(e,t,r,o,s){let a=window.screenX+(window.outerWidth-400)/2,n=window.screenY+(window.outerHeight-600)/2;if(this.popup=window.open(e,"openkey-oauth",`width=400,height=600,left=${a},top=${n},popup=true`),!this.popup){s({code:"POPUP_BLOCKED",message:"Popup was blocked. Please allow popups or use redirect mode."});return}let l=new URL(r).origin,u=setInterval(()=>{try{if(this.popup?.closed){clearInterval(u),clearTimeout(p),s({code:"USER_CANCELLED",message:"User closed the popup"});return}let h=this.popup?.location?.href;if(h&&h.startsWith(l)){clearInterval(u),clearTimeout(p);let i=new URL(h),y=i.searchParams.get("code"),d=i.searchParams.get("state"),g=i.searchParams.get("error");if(this.popup?.close(),g){s({code:"UNAUTHORIZED",message:i.searchParams.get("error_description")||g});return}if(d!==t){s({code:"STATE_MISMATCH",message:"State mismatch - possible CSRF attack"});return}y?o({code:y,state:d}):s({code:"UNAUTHORIZED",message:"Authorization failed - no code returned"})}}catch{}},100),p=setTimeout(()=>{clearInterval(u),this.popup?.close(),s({code:"TIMEOUT",message:"OAuth flow timed out"})},3e5)}resolveMode(e){return e??this.mode}async openFlow(e,t,r){let o=this.resolveMode(r),s=encodeURIComponent(window.location.origin);if(o==="popup"){let n=`${this.host}/widget/${e}?origin=${s}`;return new Promise((l,u)=>this.openPopup(n,t,l,u))}if(o==="redirect"){let n=`${this.host}/widget/${e}?origin=${s}`;return window.location.href=n,new Promise(()=>{})}let a=`${this.host}/widget/embed/${e}?origin=${s}`;return this.openIframeModal(a,e,t,s)}openIframeModal(e,t,r,o){return new Promise((s,a)=>{let n=!1,l=!1,u=null,p=d=>{l||(l=!0,d())},h=()=>{clearTimeout(i),clearTimeout(y),u?.destroy(),u=null};u=new k({url:e,host:this.host,onClose:()=>{p(()=>{clearTimeout(i),clearTimeout(y),u=null,a({code:"USER_CANCELLED",message:"User cancelled the request"})})},onMessage:d=>{if(d.type==="openkey:ready"){n=!0,u?.postMessage(r);return}if(d.type==="openkey:close"){p(()=>{h(),a({code:"USER_CANCELLED",message:"User cancelled the request"})});return}if(d.type==="openkey:link-wallet:delegate"){this.handleWalletLinkDelegation(u);return}(d.type==="openkey:auth:response"||d.type==="openkey:sign:response"||d.type==="openkey:signTypedData:response"||d.type==="openkey:link-wallet:response")&&p(()=>{h(),d.success?d.type==="openkey:auth:response"?s({address:d.address,keyId:d.keyId,keyType:d.keyType||"MANAGED"}):d.type==="openkey:link-wallet:response"?s({address:d.address,keyId:d.keyId}):s({signature:d.signature,address:d.address}):a(d.error)})}});let i=setTimeout(()=>{if(n||l)return;h(),console.warn("OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP."),P();let d=`${this.host}/widget/${t}?origin=${o}`;this.openPopup(d,r,g=>p(()=>s(g)),g=>p(()=>a(g)))},3e3),y=setTimeout(()=>{p(()=>{h(),a({code:"TIMEOUT",message:"Request timed out"})})},3e5)})}handleWalletLinkDelegation(e){let t=r=>e.postMessage(r);new v({providers:this.discoveredProviders,onCancel:()=>{t({type:"openkey:link-wallet:result",success:!1,error:{code:"USER_CANCELLED",message:"Wallet linking cancelled"}})},onSelect:async r=>{try{let s=(await r.request({method:"eth_requestAccounts"}))[0];if(!s)throw new Error("No account returned");let a=await fetch(`${this.host}/api/keys/link/challenge`,{method:"POST",credentials:"include"});if(!a.ok)throw new Error("Failed to get challenge");let{message:n}=await a.json(),l=this.toHex(n),u=await r.request({method:"personal_sign",params:[l,s]}),p=await fetch(`${this.host}/api/keys/link`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({address:s,signature:u,message:n})});if(!p.ok){let i=await p.json();throw new Error(i.error||"Failed to link wallet")}let{key:h}=await p.json();t({type:"openkey:link-wallet:result",success:!0,address:h.address,keyId:h.id})}catch(o){t({type:"openkey:link-wallet:result",success:!1,error:{code:"UNKNOWN",message:o.message||"Wallet linking failed"}})}}})}openPopup(e,t,r,o){let s=window.screenX+(window.outerWidth-400)/2,a=window.screenY+(window.outerHeight-600)/2;if(this.popup=window.open(e,"openkey",`width=400,height=600,left=${s},top=${a},popup=true`),!this.popup){o({code:"POPUP_BLOCKED",message:"Popup was blocked. Please allow popups for this site."});return}let n=()=>{window.removeEventListener("message",p),clearInterval(l),clearTimeout(u)},l=setInterval(()=>{this.popup?.closed&&(n(),o({code:"USER_CANCELLED",message:"User closed the popup"}))},500),u=setTimeout(()=>{n(),this.popup?.close(),o({code:"TIMEOUT",message:"Request timed out"})},3e5),p=h=>{if(h.origin!==this.host)return;let i=h.data;if(i.type==="openkey:ready"){this.popup?.postMessage(t,this.host);return}if(i.type==="openkey:close"){n(),this.popup?.close(),o({code:"USER_CANCELLED",message:"User cancelled the request"});return}(i.type==="openkey:auth:response"||i.type==="openkey:sign:response"||i.type==="openkey:signTypedData:response"||i.type==="openkey:link-wallet:response")&&(n(),this.popup?.close(),i.success?i.type==="openkey:auth:response"?r({address:i.address,keyId:i.keyId,keyType:i.keyType||"MANAGED"}):i.type==="openkey:link-wallet:response"?r({address:i.address,keyId:i.keyId}):r({signature:i.signature,address:i.address}):o(i.error))};window.addEventListener("message",p)}disconnect(){this.popup?.close(),this.popup=null}},T=class{openkey;address;keyId;keyType;constructor(e,t){this.openkey=e,this.address=t.address,this.keyId=t.keyId,this.keyType=t.keyType}async request({method:e,params:t}){switch(e){case"eth_accounts":case"eth_requestAccounts":return[this.address];case"eth_chainId":return"0x1";case"personal_sign":{if(this.keyType==="EXTERNAL")return(await this.openkey.findWalletProvider(this.address)).request({method:e,params:t});let r=this.hexToString(t[0]);return(await this.openkey.signMessage({message:r,keyId:this.keyId})).signature}case"eth_signTypedData_v4":{if(this.keyType==="EXTERNAL")return(await this.openkey.findWalletProvider(this.address)).request({method:e,params:t});let r=JSON.parse(t[1]);return(await this.openkey.signTypedData(r)).signature}default:throw new Error(`Unsupported method: ${e}`)}}hexToString(e){let t=new Uint8Array((e.startsWith("0x")?e.slice(2):e).match(/.{1,2}/g).map(r=>parseInt(r,16)));return new TextDecoder().decode(t)}},A=f,w=null;function C(c){return(!w||c)&&(w=new f(c)),w}export{f as OpenKey,T as OpenKeyEIP1193Provider,A as default,C as getOpenKey};
|
|
21
47
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// OpenKey SDK - Browser client for third-party apps\n// Provides \"Sign with OpenKey\" functionality via popup or iframe\n\nexport interface EIP1193Provider {\n request(args: { method: string; params?: any[] }): Promise<any>;\n}\n\ninterface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\ninterface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport interface OpenKeyConfig {\n /** OpenKey host URL (default: https://openkey.so) */\n host?: string;\n /** App identifier for display */\n appName?: string;\n /** Use popup instead of iframe (default: true) */\n usePopup?: boolean;\n /** App-provided wallet provider for external key signing */\n externalProvider?: EIP1193Provider;\n}\n\nexport interface SignMessageRequest {\n message: string;\n keyId?: string; // If not provided, user selects\n}\n\nexport interface SignTypedDataRequest {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n keyId?: string;\n}\n\nexport interface SignResult {\n signature: string;\n address: string;\n}\n\nexport interface AuthResult {\n address: string;\n keyId: string;\n keyType: 'MANAGED' | 'EXTERNAL';\n}\n\nexport interface OpenKeyError {\n code: 'USER_CANCELLED' | 'POPUP_BLOCKED' | 'TIMEOUT' | 'NO_KEY' | 'UNAUTHORIZED' | 'UNKNOWN' | 'STATE_MISMATCH';\n message: string;\n}\n\n// ======= OAuth 2.1 Types =======\n\n/** OAuth configuration for third-party apps */\nexport interface OAuthConfig {\n /** OAuth client_id (registered with OpenKey) */\n clientId: string;\n /** Redirect URI (must match registered URI) */\n redirectUri: string;\n /** State parameter for CSRF protection (auto-generated if not provided) */\n state?: string;\n}\n\n/** Result from OAuth authorization */\nexport interface OAuthResult {\n /** Authorization code (exchange for tokens) */\n code: string;\n /** State parameter (verify matches request) */\n state: string;\n}\n\n/** Response from token exchange */\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n id_token: string;\n scope: string;\n refresh_token?: string;\n}\n\ntype MessageType =\n | { type: 'openkey:auth:request'; appName: string }\n | { type: 'openkey:auth:response'; success: true; address: string; keyId: string; keyType?: 'MANAGED' | 'EXTERNAL' }\n | { type: 'openkey:auth:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:sign:request'; message: string; keyId?: string }\n | { type: 'openkey:sign:response'; success: true; signature: string; address: string }\n | { type: 'openkey:sign:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:signTypedData:request'; data: SignTypedDataRequest }\n | { type: 'openkey:signTypedData:response'; success: true; signature: string; address: string }\n | { type: 'openkey:signTypedData:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:request' }\n | { type: 'openkey:link-wallet:response'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:ready' }\n | { type: 'openkey:close' };\n\nconst DEFAULT_HOST = 'https://openkey.so';\nconst POPUP_WIDTH = 400;\nconst POPUP_HEIGHT = 600;\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000; // 5 minutes\nconst OAUTH_STORAGE_KEY = 'openkey_oauth';\n\n// ======= PKCE Utilities =======\n\nfunction base64UrlEncode(buffer: Uint8Array): string {\n const base64 = btoa(String.fromCharCode(...buffer));\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\nasync function generateCodeVerifier(): Promise<string> {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nasync function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction generateState(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nexport class OpenKey {\n private host: string;\n private appName: string;\n private usePopup: boolean;\n private config: OpenKeyConfig;\n private popup: Window | null = null;\n private iframe: HTMLIFrameElement | null = null;\n private lastAuth: AuthResult | null = null;\n private discoveredProviders: EIP6963ProviderDetail[] = [];\n\n constructor(config: OpenKeyConfig = {}) {\n this.config = config;\n this.host = config.host || DEFAULT_HOST;\n this.appName = config.appName || window.location.hostname;\n this.usePopup = config.usePopup ?? true;\n\n // Listen for EIP-6963 wallet announcements\n if (typeof window !== 'undefined') {\n this.discoveredProviders = [];\n window.addEventListener('eip6963:announceProvider', (event: any) => {\n this.discoveredProviders.push(event.detail);\n });\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n }\n }\n\n /**\n * Connect to OpenKey and get user's wallet address\n * Opens auth flow for user to select/create a key\n */\n async connect(): Promise<AuthResult> {\n const result = await this.openFlow<AuthResult>('connect', {\n type: 'openkey:auth:request',\n appName: this.appName,\n });\n this.lastAuth = result;\n return result;\n }\n\n /**\n * Link an external wallet to the user's OpenKey account\n * Opens link-wallet widget flow\n */\n async linkWallet(): Promise<{ address: string; keyId: string }> {\n return this.openFlow<{ address: string; keyId: string }>('link-wallet', {\n type: 'openkey:link-wallet:request',\n });\n }\n\n /**\n * Sign a message with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signMessage(request: SignMessageRequest): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signWithExternalWallet(request);\n }\n return this.signWithPopup(request);\n }\n\n /**\n * Sign typed data (EIP-712) with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signTypedData(request: SignTypedDataRequest): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signTypedDataWithExternalWallet(request);\n }\n return this.signTypedDataWithPopup(request);\n }\n\n /**\n * Find a wallet provider that controls the given address.\n * Checks: 1) app-provided externalProvider, 2) EIP-6963 discovered wallets, 3) window.ethereum\n */\n async findWalletProvider(targetAddress: string): Promise<EIP1193Provider> {\n // 1. Try app-provided externalProvider first\n if (this.config.externalProvider) {\n return this.config.externalProvider;\n }\n\n // 2. Use EIP-6963 to discover wallets, requesting authorization\n for (const { provider } of this.discoveredProviders) {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n }\n\n // 3. Fall back to window.ethereum, requesting authorization\n if (typeof window !== 'undefined' && (window as any).ethereum) {\n const provider = (window as any).ethereum as EIP1193Provider;\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n return provider;\n }\n\n throw new Error('No wallet provider found for external key. Connect your wallet.');\n }\n\n private async signWithExternalWallet(request: SignMessageRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const hexMessage = this.toHex(request.message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, this.lastAuth!.address],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private async signTypedDataWithExternalWallet(request: SignTypedDataRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const signature = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [this.lastAuth!.address, JSON.stringify(request)],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private signWithPopup(request: SignMessageRequest): Promise<SignResult> {\n return this.openFlow<SignResult>('sign', {\n type: 'openkey:sign:request',\n message: request.message,\n keyId: request.keyId,\n });\n }\n\n private signTypedDataWithPopup(request: SignTypedDataRequest): Promise<SignResult> {\n return this.openFlow<SignResult>('sign-typed-data', {\n type: 'openkey:signTypedData:request',\n data: request,\n });\n }\n\n private toHex(str: string): string {\n return '0x' + Array.from(new TextEncoder().encode(str)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Check if user is already authenticated\n */\n async isConnected(): Promise<boolean> {\n // Check for existing session via API\n try {\n const res = await fetch(`${this.host}/api/auth/session`, {\n credentials: 'include',\n });\n if (!res.ok) return false;\n const data = await res.json();\n return !!data.user;\n } catch {\n return false;\n }\n }\n\n // ======= OAuth 2.1 Provider Methods =======\n\n /**\n * OAuth 2.1 methods for third-party app authentication\n * Use this when your app has registered OAuth client credentials with OpenKey\n */\n oauth = {\n /**\n * Start OAuth authorization flow\n * Opens popup/redirect to OpenKey authorization endpoint\n * @returns Promise that resolves with authorization code after user consent\n */\n connect: async (config: OAuthConfig): Promise<OAuthResult> => {\n // Generate PKCE values\n const verifier = await generateCodeVerifier();\n const challenge = await generateCodeChallenge(verifier);\n const state = config.state || generateState();\n\n // Store for later token exchange\n sessionStorage.setItem(\n OAUTH_STORAGE_KEY,\n JSON.stringify({ verifier, state })\n );\n\n // Build authorization URL\n const authUrl = new URL(`${this.host}/api/auth/oauth2/authorize`);\n authUrl.searchParams.set('client_id', config.clientId);\n authUrl.searchParams.set('redirect_uri', config.redirectUri);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', 'openid');\n authUrl.searchParams.set('state', state);\n authUrl.searchParams.set('code_challenge', challenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n\n return this.openOAuthFlow(authUrl.toString(), state, config.redirectUri);\n },\n\n /**\n * Exchange authorization code for tokens\n * Call this after receiving the callback with authorization code\n * @param code - Authorization code from callback URL\n * @param config - Same config used for connect()\n * @returns Promise that resolves with access_token, id_token, etc.\n */\n exchangeCode: async (\n code: string,\n config: OAuthConfig\n ): Promise<OAuthTokenResponse> => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) {\n throw new Error('No PKCE verifier found. Start a new OAuth flow.');\n }\n\n const { verifier } = JSON.parse(stored);\n\n const response = await fetch(`${this.host}/api/auth/oauth2/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: verifier,\n }),\n });\n\n // Clear stored verifier\n sessionStorage.removeItem(OAUTH_STORAGE_KEY);\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error_description || 'Token exchange failed');\n }\n\n return response.json();\n },\n\n /**\n * Verify state parameter from callback\n * Call this before exchangeCode to prevent CSRF attacks\n * @param receivedState - State parameter from callback URL\n * @returns true if state matches, false otherwise\n */\n verifyState: (receivedState: string): boolean => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) return false;\n const { state } = JSON.parse(stored);\n return state === receivedState;\n },\n\n /**\n * Parse authorization response from callback URL\n * @param url - Callback URL (defaults to current window.location.href)\n * @returns Parsed code and state, or error\n */\n parseCallback: (\n url?: string\n ): { code: string; state: string } | { error: string; errorDescription?: string } => {\n const urlObj = new URL(url || window.location.href);\n const error = urlObj.searchParams.get('error');\n\n if (error) {\n return {\n error,\n errorDescription: urlObj.searchParams.get('error_description') || undefined,\n };\n }\n\n const code = urlObj.searchParams.get('code');\n const state = urlObj.searchParams.get('state');\n\n if (!code || !state) {\n return { error: 'missing_params', errorDescription: 'Missing code or state parameter' };\n }\n\n return { code, state };\n },\n };\n\n private openOAuthFlow(\n url: string,\n state: string,\n redirectUri: string\n ): Promise<OAuthResult> {\n return new Promise((resolve, reject) => {\n if (this.usePopup) {\n this.openOAuthPopup(url, state, redirectUri, resolve, reject);\n } else {\n // Full page redirect - won't resolve, page navigates away\n window.location.href = url;\n }\n });\n }\n\n private openOAuthPopup(\n url: string,\n state: string,\n redirectUri: string,\n resolve: (value: OAuthResult) => void,\n reject: (error: OpenKeyError) => void\n ) {\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey-oauth',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups or use redirect mode.',\n });\n return;\n }\n\n const redirectHost = new URL(redirectUri).origin;\n\n // Poll for redirect back with code\n const pollInterval = setInterval(() => {\n try {\n if (this.popup?.closed) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n return;\n }\n\n // Check if redirected to callback URL\n const popupUrl = this.popup?.location?.href;\n if (popupUrl && popupUrl.startsWith(redirectHost)) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n\n const urlObj = new URL(popupUrl);\n const code = urlObj.searchParams.get('code');\n const returnedState = urlObj.searchParams.get('state');\n const error = urlObj.searchParams.get('error');\n\n this.popup?.close();\n\n if (error) {\n reject({\n code: 'UNAUTHORIZED',\n message: urlObj.searchParams.get('error_description') || error,\n });\n return;\n }\n\n if (returnedState !== state) {\n reject({\n code: 'STATE_MISMATCH',\n message: 'State mismatch - possible CSRF attack',\n });\n return;\n }\n\n if (code) {\n resolve({ code, state: returnedState });\n } else {\n reject({\n code: 'UNAUTHORIZED',\n message: 'Authorization failed - no code returned',\n });\n }\n }\n } catch {\n // Cross-origin - popup still on OpenKey domain, continue polling\n }\n }, 100);\n\n // Timeout\n const timeout = setTimeout(() => {\n clearInterval(pollInterval);\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'OAuth flow timed out',\n });\n }, DEFAULT_TIMEOUT);\n }\n\n private async openFlow<T>(action: string, message: object): Promise<T> {\n return new Promise((resolve, reject) => {\n const url = `${this.host}/widget/${action}?origin=${encodeURIComponent(window.location.origin)}`;\n\n if (this.usePopup) {\n this.openPopup(url, message, resolve, reject);\n } else {\n this.openIframe(url, message, resolve, reject);\n }\n });\n }\n\n private openPopup<T>(\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Calculate popup position\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups for this site.',\n });\n return;\n }\n\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearInterval(pollClosed);\n clearTimeout(timeout);\n };\n\n // Poll to detect popup close\n const pollClosed = setInterval(() => {\n if (this.popup?.closed) {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n }\n }, 500);\n\n // Timeout\n const timeout = setTimeout(() => {\n cleanup();\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n }, DEFAULT_TIMEOUT);\n\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n // Widget is ready, send our request\n this.popup?.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n cleanup();\n this.popup?.close();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n return;\n }\n\n // Handle responses\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n cleanup();\n this.popup?.close();\n\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n }\n };\n\n window.addEventListener('message', handleMessage);\n }\n\n private openIframe<T>(\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Create overlay\n const overlay = document.createElement('div');\n overlay.style.cssText = `\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n `;\n\n // Create iframe container\n const container = document.createElement('div');\n container.style.cssText = `\n width: ${POPUP_WIDTH}px;\n height: ${POPUP_HEIGHT}px;\n background: #1a1a1a;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);\n `;\n\n // Create iframe\n this.iframe = document.createElement('iframe');\n this.iframe.src = url;\n this.iframe.style.cssText = `\n width: 100%;\n height: 100%;\n border: none;\n `;\n\n container.appendChild(this.iframe);\n overlay.appendChild(container);\n document.body.appendChild(overlay);\n\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearTimeout(timeout);\n overlay.remove();\n this.iframe = null;\n };\n\n // Close on overlay click\n overlay.addEventListener('click', (e) => {\n if (e.target === overlay) {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n }\n });\n\n // Timeout\n const timeout = setTimeout(() => {\n cleanup();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n }, DEFAULT_TIMEOUT);\n\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n this.iframe?.contentWindow?.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n return;\n }\n\n // Handle responses\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n cleanup();\n\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n }\n };\n\n window.addEventListener('message', handleMessage);\n }\n\n /**\n * Disconnect and close any open flows\n */\n disconnect() {\n this.popup?.close();\n this.popup = null;\n this.iframe?.parentElement?.parentElement?.remove();\n this.iframe = null;\n }\n}\n\n/**\n * Unified EIP-1193 provider that wraps an OpenKey instance.\n * Transparently routes signing to either OpenKey (managed keys) or the user's\n * wallet (external keys).\n */\nexport class OpenKeyEIP1193Provider implements EIP1193Provider {\n private openkey: OpenKey;\n private address: string;\n private keyId: string;\n private keyType: 'MANAGED' | 'EXTERNAL';\n\n constructor(openkey: OpenKey, authResult: AuthResult) {\n this.openkey = openkey;\n this.address = authResult.address;\n this.keyId = authResult.keyId;\n this.keyType = authResult.keyType;\n }\n\n async request({ method, params }: { method: string; params?: any[] }): Promise<any> {\n switch (method) {\n case 'eth_accounts':\n case 'eth_requestAccounts':\n return [this.address];\n\n case 'eth_chainId':\n return '0x1'; // mainnet\n\n case 'personal_sign': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n // Managed key: route through OpenKey\n const message = this.hexToString(params![0] as string);\n const result = await this.openkey.signMessage({ message, keyId: this.keyId });\n return result.signature;\n }\n\n case 'eth_signTypedData_v4': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n const data = JSON.parse(params![1] as string);\n const result = await this.openkey.signTypedData(data);\n return result.signature;\n }\n\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n }\n\n private hexToString(hex: string): string {\n const bytes = new Uint8Array(\n (hex.startsWith('0x') ? hex.slice(2) : hex).match(/.{1,2}/g)!.map(b => parseInt(b, 16))\n );\n return new TextDecoder().decode(bytes);\n }\n}\n\n// Default export for convenience\nexport default OpenKey;\n\n// Create singleton instance\nlet defaultInstance: OpenKey | null = null;\n\nexport function getOpenKey(config?: OpenKeyConfig): OpenKey {\n if (!defaultInstance || config) {\n defaultInstance = new OpenKey(config);\n }\n return defaultInstance;\n}\n"],"mappings":"AA8GA,IAAMA,EAAe,qBAIrB,IAAMC,EAAoB,gBAI1B,SAASC,EAAgBC,EAA4B,CAEnD,OADe,KAAK,OAAO,aAAa,GAAGA,CAAM,CAAC,EACpC,QAAQ,MAAO,GAAG,EAAE,QAAQ,MAAO,GAAG,EAAE,QAAQ,KAAM,EAAE,CACxE,CAEA,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M,GAE/BgD,CACT","names":["DEFAULT_HOST","OAUTH_STORAGE_KEY","base64UrlEncode","buffer","generateCodeVerifier","array","generateCodeChallenge","verifier","data","digest","generateState","OpenKey","config","DEFAULT_HOST","event","result","request","targetAddress","provider","a","hexMessage","str","b","res","challenge","state","authUrl","code","stored","response","error","receivedState","url","urlObj","redirectUri","resolve","reject","left","top","redirectHost","pollInterval","timeout","popupUrl","returnedState","action","message","cleanup","handleMessage","pollClosed","overlay","container","e","OpenKeyEIP1193Provider","openkey","authResult","method","params","hex","bytes","index_default","defaultInstance","getOpenKey"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// OpenKey SDK - Browser client for third-party apps\n// Provides \"Sign with OpenKey\" functionality via popup or iframe\n\nexport interface EIP1193Provider {\n request(args: { method: string; params?: any[] }): Promise<any>;\n}\n\ninterface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\ninterface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport type OpenKeyMode = 'iframe' | 'popup' | 'redirect';\n\nexport interface OpenKeyConfig {\n /** OpenKey host URL (default: https://openkey.so) */\n host?: string;\n /** App identifier for display */\n appName?: string;\n /** UI mode: 'iframe' (default), 'popup', or 'redirect' */\n mode?: OpenKeyMode;\n /** App-provided wallet provider for external key signing */\n externalProvider?: EIP1193Provider;\n}\n\nexport interface SignMessageRequest {\n message: string;\n keyId?: string; // If not provided, user selects\n}\n\nexport interface SignTypedDataRequest {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, unknown>;\n keyId?: string;\n}\n\nexport interface SignResult {\n signature: string;\n address: string;\n}\n\nexport interface AuthResult {\n address: string;\n keyId: string;\n keyType: 'MANAGED' | 'EXTERNAL';\n}\n\nexport interface OpenKeyError {\n code: 'USER_CANCELLED' | 'POPUP_BLOCKED' | 'TIMEOUT' | 'NO_KEY' | 'UNAUTHORIZED' | 'UNKNOWN' | 'STATE_MISMATCH';\n message: string;\n}\n\n// ======= OAuth 2.1 Types =======\n\n/** OAuth configuration for third-party apps */\nexport interface OAuthConfig {\n /** OAuth client_id (registered with OpenKey) */\n clientId: string;\n /** Redirect URI (must match registered URI) */\n redirectUri: string;\n /** State parameter for CSRF protection (auto-generated if not provided) */\n state?: string;\n}\n\n/** Result from OAuth authorization */\nexport interface OAuthResult {\n /** Authorization code (exchange for tokens) */\n code: string;\n /** State parameter (verify matches request) */\n state: string;\n}\n\n/** Response from token exchange */\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n id_token: string;\n scope: string;\n refresh_token?: string;\n}\n\ntype MessageType =\n | { type: 'openkey:auth:request'; appName: string }\n | { type: 'openkey:auth:response'; success: true; address: string; keyId: string; keyType?: 'MANAGED' | 'EXTERNAL' }\n | { type: 'openkey:auth:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:sign:request'; message: string; keyId?: string }\n | { type: 'openkey:sign:response'; success: true; signature: string; address: string }\n | { type: 'openkey:sign:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:signTypedData:request'; data: SignTypedDataRequest }\n | { type: 'openkey:signTypedData:response'; success: true; signature: string; address: string }\n | { type: 'openkey:signTypedData:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:request' }\n | { type: 'openkey:link-wallet:response'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:response'; success: false; error: OpenKeyError }\n | { type: 'openkey:link-wallet:delegate' }\n | { type: 'openkey:link-wallet:result'; success: true; address: string; keyId: string }\n | { type: 'openkey:link-wallet:result'; success: false; error: OpenKeyError }\n | { type: 'openkey:resize'; height: number }\n | { type: 'openkey:ready' }\n | { type: 'openkey:close' };\n\nconst DEFAULT_HOST = 'https://openkey.so';\nconst POPUP_WIDTH = 400;\nconst POPUP_HEIGHT = 600;\nconst DEFAULT_TIMEOUT = 5 * 60 * 1000; // 5 minutes\nconst IFRAME_READY_TIMEOUT = 3000; // 3 seconds\nconst OAUTH_STORAGE_KEY = 'openkey_oauth';\n\nclass IframeModal {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n private iframe: HTMLIFrameElement;\n private onClose: () => void;\n private onMessage: (data: MessageType) => void;\n private messageHandler: (event: MessageEvent) => void;\n private host: string;\n\n constructor(opts: { url: string; host: string; onClose: () => void; onMessage: (data: MessageType) => void }) {\n this.host = opts.host;\n this.onClose = opts.onClose;\n this.onMessage = opts.onMessage;\n\n const isMobile = window.matchMedia('(max-width: 639px)').matches;\n\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:999999;display:flex;align-items:${isMobile ? 'flex-end' : 'center'};justify-content:center;animation:ok-fade-in 150ms ease-out}\n .ok-card{position:relative;background:#fff;width:${isMobile ? '100%' : '400px'};border-radius:${isMobile ? '16px 16px 0 0' : '16px'};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;animation:${isMobile ? 'ok-slide-up 250ms ease-out' : 'ok-scale-in 200ms ease-out'};${isMobile ? 'max-height:85vh;' : ''}}\n .ok-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;background:transparent;color:#6b7280;font-size:18px;cursor:pointer;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:4px}\n .ok-close:hover{color:#111827}\n .ok-handle{width:40px;height:4px;background:#d1d5db;border-radius:2px;margin:8px auto 0}\n iframe{border:none;width:100%;height:400px;display:block;transition:height 200ms ease}\n .ok-backdrop.ok-exit{animation:ok-fade-out 150ms ease-in}\n .ok-backdrop.ok-exit .ok-card{animation:${isMobile ? 'ok-slide-down 200ms ease-in' : 'ok-scale-out 150ms ease-in'}}\n @keyframes ok-fade-in{from{opacity:0}to{opacity:1}}\n @keyframes ok-fade-out{from{opacity:1}to{opacity:0}}\n @keyframes ok-scale-in{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @keyframes ok-scale-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.95)}}\n @keyframes ok-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}\n @keyframes ok-slide-down{from{transform:translateY(0)}to{transform:translateY(100%)}}\n @media(prefers-color-scheme:dark){\n .ok-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}\n .ok-close{color:#9ca3af}\n .ok-close:hover{color:#f3f4f6}\n .ok-handle{background:#4b5563}\n }\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'ok-backdrop';\n backdrop.addEventListener('click', (e) => {\n if (e.target === backdrop) this.close();\n });\n\n const card = document.createElement('div');\n card.className = 'ok-card';\n\n if (isMobile) {\n const handle = document.createElement('div');\n handle.className = 'ok-handle';\n card.appendChild(handle);\n }\n\n const closeBtn = document.createElement('button');\n closeBtn.className = 'ok-close';\n closeBtn.textContent = '\\u00d7';\n closeBtn.addEventListener('click', () => this.close());\n card.appendChild(closeBtn);\n\n this.iframe = document.createElement('iframe');\n this.iframe.src = opts.url;\n this.iframe.setAttribute('allow', 'publickey-credentials-get *; publickey-credentials-create *');\n this.iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups');\n card.appendChild(this.iframe);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n\n this.messageHandler = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n const data = event.data as MessageType;\n if (data.type === 'openkey:resize') {\n const h = Math.min(data.height, Math.floor(window.innerHeight * 0.9), 700);\n this.iframe.style.height = `${h}px`;\n return;\n }\n this.onMessage(data);\n };\n window.addEventListener('message', this.messageHandler);\n document.body.appendChild(this.root);\n }\n\n postMessage(message: object) {\n this.iframe.contentWindow?.postMessage(message, this.host);\n }\n\n destroy() {\n window.removeEventListener('message', this.messageHandler);\n this.root.remove();\n }\n\n private close() {\n const backdrop = this.shadow.querySelector('.ok-backdrop');\n if (backdrop) {\n backdrop.classList.add('ok-exit');\n setTimeout(() => {\n this.destroy();\n this.onClose();\n }, 200);\n } else {\n this.destroy();\n this.onClose();\n }\n }\n}\n\nclass WalletPicker {\n private root: HTMLDivElement;\n private shadow: ShadowRoot;\n\n constructor(opts: { providers: EIP6963ProviderDetail[]; onSelect: (provider: EIP1193Provider) => void; onCancel: () => void }) {\n this.root = document.createElement('div');\n this.shadow = this.root.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n style.textContent = `\n :host{all:initial}\n .wp-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:1000000;display:flex;align-items:center;justify-content:center;animation:wp-fade 150ms ease-out}\n .wp-card{background:#fff;width:340px;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);padding:20px;animation:wp-scale 200ms ease-out}\n .wp-title{font:600 16px/1.3 system-ui,sans-serif;color:#111;margin:0 0 12px}\n .wp-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}\n .wp-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:10px;background:transparent;cursor:pointer;font:14px/1.3 system-ui,sans-serif;color:#111;width:100%;text-align:left;transition:border-color 150ms}\n .wp-item:hover{border-color:#6366f1}\n .wp-icon{width:28px;height:28px;border-radius:6px}\n .wp-empty{font:14px/1.4 system-ui,sans-serif;color:#6b7280;text-align:center;padding:16px 0}\n .wp-cancel{display:block;width:100%;margin-top:12px;padding:8px;border:none;background:transparent;color:#6b7280;font:14px/1.3 system-ui,sans-serif;cursor:pointer;border-radius:8px}\n .wp-cancel:hover{background:#f3f4f6;color:#111}\n @keyframes wp-fade{from{opacity:0}to{opacity:1}}\n @keyframes wp-scale{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}\n @media(prefers-color-scheme:dark){\n .wp-card{background:#1a1a1a;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5)}\n .wp-title{color:#f3f4f6}\n .wp-item{border-color:#374151;color:#f3f4f6}\n .wp-item:hover{border-color:#818cf8}\n .wp-empty{color:#9ca3af}\n .wp-cancel{color:#9ca3af}\n .wp-cancel:hover{background:#262626;color:#f3f4f6}\n }\n `;\n\n const backdrop = document.createElement('div');\n backdrop.className = 'wp-backdrop';\n backdrop.addEventListener('click', (e) => { if (e.target === backdrop) { this.destroy(); opts.onCancel(); } });\n\n const card = document.createElement('div');\n card.className = 'wp-card';\n\n const title = document.createElement('h2');\n title.className = 'wp-title';\n title.textContent = 'Select a wallet';\n card.appendChild(title);\n\n if (opts.providers.length === 0) {\n const empty = document.createElement('div');\n empty.className = 'wp-empty';\n empty.textContent = 'No wallets detected';\n card.appendChild(empty);\n } else {\n const list = document.createElement('ul');\n list.className = 'wp-list';\n for (const { info, provider } of opts.providers) {\n const item = document.createElement('button');\n item.className = 'wp-item';\n if (info.icon) {\n const icon = document.createElement('img');\n icon.className = 'wp-icon';\n icon.src = info.icon;\n icon.alt = info.name;\n item.appendChild(icon);\n }\n const name = document.createElement('span');\n name.textContent = info.name;\n item.appendChild(name);\n item.addEventListener('click', () => { this.destroy(); opts.onSelect(provider); });\n list.appendChild(item);\n }\n card.appendChild(list);\n }\n\n const cancel = document.createElement('button');\n cancel.className = 'wp-cancel';\n cancel.textContent = 'Cancel';\n cancel.addEventListener('click', () => { this.destroy(); opts.onCancel(); });\n card.appendChild(cancel);\n\n backdrop.appendChild(card);\n this.shadow.appendChild(style);\n this.shadow.appendChild(backdrop);\n document.body.appendChild(this.root);\n }\n\n destroy() {\n this.root.remove();\n }\n}\n\nfunction showToast() {\n const root = document.createElement('div');\n const shadow = root.attachShadow({ mode: 'closed' });\n shadow.innerHTML = `<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:#1f2937;color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class=\"ok-toast\">Opening in new window\\u2026</div>`;\n document.body.appendChild(root);\n setTimeout(() => root.remove(), 3000);\n}\n\n// ======= PKCE Utilities =======\n\nfunction base64UrlEncode(buffer: Uint8Array): string {\n const base64 = btoa(String.fromCharCode(...buffer));\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\nasync function generateCodeVerifier(): Promise<string> {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nasync function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction generateState(): string {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\nexport class OpenKey {\n private host: string;\n private appName: string;\n private mode: OpenKeyMode;\n private config: OpenKeyConfig;\n private popup: Window | null = null;\n private lastAuth: AuthResult | null = null;\n private discoveredProviders: EIP6963ProviderDetail[] = [];\n\n constructor(config: OpenKeyConfig = {}) {\n this.config = config;\n this.host = config.host || DEFAULT_HOST;\n this.appName = config.appName || window.location.hostname;\n this.mode = config.mode ?? 'iframe';\n\n // Listen for EIP-6963 wallet announcements\n if (typeof window !== 'undefined') {\n this.discoveredProviders = [];\n window.addEventListener('eip6963:announceProvider', (event: any) => {\n this.discoveredProviders.push(event.detail);\n });\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n }\n }\n\n /**\n * Connect to OpenKey and get user's wallet address\n * Opens auth flow for user to select/create a key\n */\n async connect(opts?: { mode?: OpenKeyMode }): Promise<AuthResult> {\n const result = await this.openFlow<AuthResult>('connect', {\n type: 'openkey:auth:request',\n appName: this.appName,\n }, opts?.mode);\n this.lastAuth = result;\n return result;\n }\n\n /**\n * Link an external wallet to the user's OpenKey account\n * Opens link-wallet widget flow\n */\n async linkWallet(opts?: { mode?: OpenKeyMode }): Promise<{ address: string; keyId: string }> {\n return this.openFlow<{ address: string; keyId: string }>('link-wallet', {\n type: 'openkey:link-wallet:request',\n }, opts?.mode);\n }\n\n /**\n * Sign a message with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signMessage(request: SignMessageRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signWithExternalWallet(request);\n }\n return this.signWithOpenKey(request, opts?.mode);\n }\n\n /**\n * Sign typed data (EIP-712) with the user's OpenKey wallet\n * For external keys, routes directly to the user's wallet provider\n */\n async signTypedData(request: SignTypedDataRequest, opts?: { mode?: OpenKeyMode }): Promise<SignResult> {\n if (this.lastAuth?.keyType === 'EXTERNAL') {\n return this.signTypedDataWithExternalWallet(request);\n }\n return this.signTypedDataWithOpenKey(request, opts?.mode);\n }\n\n /**\n * Find a wallet provider that controls the given address.\n * Checks: 1) app-provided externalProvider, 2) EIP-6963 discovered wallets, 3) window.ethereum\n */\n async findWalletProvider(targetAddress: string): Promise<EIP1193Provider> {\n // 1. Try app-provided externalProvider first\n if (this.config.externalProvider) {\n return this.config.externalProvider;\n }\n\n // 2. Use EIP-6963 to discover wallets, requesting authorization\n for (const { provider } of this.discoveredProviders) {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n }\n\n // 3. Fall back to window.ethereum, requesting authorization\n if (typeof window !== 'undefined' && (window as any).ethereum) {\n const provider = (window as any).ethereum as EIP1193Provider;\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n if (accounts.some(a => a.toLowerCase() === targetAddress.toLowerCase())) {\n return provider;\n }\n } catch {}\n return provider;\n }\n\n throw new Error('No wallet provider found for external key. Connect your wallet.');\n }\n\n private async signWithExternalWallet(request: SignMessageRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const hexMessage = this.toHex(request.message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, this.lastAuth!.address],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private async signTypedDataWithExternalWallet(request: SignTypedDataRequest): Promise<SignResult> {\n const provider = await this.findWalletProvider(this.lastAuth!.address);\n const signature = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [this.lastAuth!.address, JSON.stringify(request)],\n });\n return { signature: signature as string, address: this.lastAuth!.address };\n }\n\n private signWithOpenKey(request: SignMessageRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign', {\n type: 'openkey:sign:request',\n message: request.message,\n keyId: request.keyId,\n }, mode);\n }\n\n private signTypedDataWithOpenKey(request: SignTypedDataRequest, mode?: OpenKeyMode): Promise<SignResult> {\n return this.openFlow<SignResult>('sign-typed-data', {\n type: 'openkey:signTypedData:request',\n data: request,\n }, mode);\n }\n\n private toHex(str: string): string {\n return '0x' + Array.from(new TextEncoder().encode(str)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Check if user is already authenticated\n */\n async isConnected(): Promise<boolean> {\n // Check for existing session via API\n try {\n const res = await fetch(`${this.host}/api/auth/session`, {\n credentials: 'include',\n });\n if (!res.ok) return false;\n const data = await res.json();\n return !!data.user;\n } catch {\n return false;\n }\n }\n\n // ======= OAuth 2.1 Provider Methods =======\n\n /**\n * OAuth 2.1 methods for third-party app authentication\n * Use this when your app has registered OAuth client credentials with OpenKey\n */\n oauth = {\n /**\n * Start OAuth authorization flow\n * Opens popup/redirect to OpenKey authorization endpoint\n * @returns Promise that resolves with authorization code after user consent\n */\n connect: async (config: OAuthConfig): Promise<OAuthResult> => {\n // Generate PKCE values\n const verifier = await generateCodeVerifier();\n const challenge = await generateCodeChallenge(verifier);\n const state = config.state || generateState();\n\n // Store for later token exchange\n sessionStorage.setItem(\n OAUTH_STORAGE_KEY,\n JSON.stringify({ verifier, state })\n );\n\n // Build authorization URL\n const authUrl = new URL(`${this.host}/api/auth/oauth2/authorize`);\n authUrl.searchParams.set('client_id', config.clientId);\n authUrl.searchParams.set('redirect_uri', config.redirectUri);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', 'openid');\n authUrl.searchParams.set('state', state);\n authUrl.searchParams.set('code_challenge', challenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n\n return this.openOAuthFlow(authUrl.toString(), state, config.redirectUri);\n },\n\n /**\n * Exchange authorization code for tokens\n * Call this after receiving the callback with authorization code\n * @param code - Authorization code from callback URL\n * @param config - Same config used for connect()\n * @returns Promise that resolves with access_token, id_token, etc.\n */\n exchangeCode: async (\n code: string,\n config: OAuthConfig\n ): Promise<OAuthTokenResponse> => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) {\n throw new Error('No PKCE verifier found. Start a new OAuth flow.');\n }\n\n const { verifier } = JSON.parse(stored);\n\n const response = await fetch(`${this.host}/api/auth/oauth2/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: verifier,\n }),\n });\n\n // Clear stored verifier\n sessionStorage.removeItem(OAUTH_STORAGE_KEY);\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error_description || 'Token exchange failed');\n }\n\n return response.json();\n },\n\n /**\n * Verify state parameter from callback\n * Call this before exchangeCode to prevent CSRF attacks\n * @param receivedState - State parameter from callback URL\n * @returns true if state matches, false otherwise\n */\n verifyState: (receivedState: string): boolean => {\n const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);\n if (!stored) return false;\n const { state } = JSON.parse(stored);\n return state === receivedState;\n },\n\n /**\n * Parse authorization response from callback URL\n * @param url - Callback URL (defaults to current window.location.href)\n * @returns Parsed code and state, or error\n */\n parseCallback: (\n url?: string\n ): { code: string; state: string } | { error: string; errorDescription?: string } => {\n const urlObj = new URL(url || window.location.href);\n const error = urlObj.searchParams.get('error');\n\n if (error) {\n return {\n error,\n errorDescription: urlObj.searchParams.get('error_description') || undefined,\n };\n }\n\n const code = urlObj.searchParams.get('code');\n const state = urlObj.searchParams.get('state');\n\n if (!code || !state) {\n return { error: 'missing_params', errorDescription: 'Missing code or state parameter' };\n }\n\n return { code, state };\n },\n };\n\n private openOAuthFlow(\n url: string,\n state: string,\n redirectUri: string\n ): Promise<OAuthResult> {\n return new Promise((resolve, reject) => {\n if (this.mode !== 'redirect') {\n this.openOAuthPopup(url, state, redirectUri, resolve, reject);\n } else {\n // Full page redirect - won't resolve, page navigates away\n window.location.href = url;\n }\n });\n }\n\n private openOAuthPopup(\n url: string,\n state: string,\n redirectUri: string,\n resolve: (value: OAuthResult) => void,\n reject: (error: OpenKeyError) => void\n ) {\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey-oauth',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups or use redirect mode.',\n });\n return;\n }\n\n const redirectHost = new URL(redirectUri).origin;\n\n // Poll for redirect back with code\n const pollInterval = setInterval(() => {\n try {\n if (this.popup?.closed) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n return;\n }\n\n // Check if redirected to callback URL\n const popupUrl = this.popup?.location?.href;\n if (popupUrl && popupUrl.startsWith(redirectHost)) {\n clearInterval(pollInterval);\n clearTimeout(timeout);\n\n const urlObj = new URL(popupUrl);\n const code = urlObj.searchParams.get('code');\n const returnedState = urlObj.searchParams.get('state');\n const error = urlObj.searchParams.get('error');\n\n this.popup?.close();\n\n if (error) {\n reject({\n code: 'UNAUTHORIZED',\n message: urlObj.searchParams.get('error_description') || error,\n });\n return;\n }\n\n if (returnedState !== state) {\n reject({\n code: 'STATE_MISMATCH',\n message: 'State mismatch - possible CSRF attack',\n });\n return;\n }\n\n if (code) {\n resolve({ code, state: returnedState });\n } else {\n reject({\n code: 'UNAUTHORIZED',\n message: 'Authorization failed - no code returned',\n });\n }\n }\n } catch {\n // Cross-origin - popup still on OpenKey domain, continue polling\n }\n }, 100);\n\n // Timeout\n const timeout = setTimeout(() => {\n clearInterval(pollInterval);\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'OAuth flow timed out',\n });\n }, DEFAULT_TIMEOUT);\n }\n\n private resolveMode(override?: OpenKeyMode): OpenKeyMode {\n return override ?? this.mode;\n }\n\n private async openFlow<T>(action: string, message: object, modeOverride?: OpenKeyMode): Promise<T> {\n const mode = this.resolveMode(modeOverride);\n const origin = encodeURIComponent(window.location.origin);\n\n if (mode === 'popup') {\n const url = `${this.host}/widget/${action}?origin=${origin}`;\n return new Promise((resolve, reject) => this.openPopup(url, message, resolve, reject));\n }\n\n if (mode === 'redirect') {\n const url = `${this.host}/widget/${action}?origin=${origin}`;\n window.location.href = url;\n return new Promise(() => {}); // never resolves, page navigates\n }\n\n // iframe mode with auto-fallback\n const url = `${this.host}/widget/embed/${action}?origin=${origin}`;\n return this.openIframeModal<T>(url, action, message, origin);\n }\n\n private openIframeModal<T>(url: string, action: string, message: object, origin: string): Promise<T> {\n return new Promise((resolve, reject) => {\n let readyReceived = false;\n let settled = false;\n let modal: IframeModal | null = null;\n\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n\n const cleanup = () => {\n clearTimeout(readyTimeout);\n clearTimeout(overallTimeout);\n modal?.destroy();\n modal = null;\n };\n\n modal = new IframeModal({\n url,\n host: this.host,\n onClose: () => {\n settle(() => {\n clearTimeout(readyTimeout);\n clearTimeout(overallTimeout);\n modal = null;\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n },\n onMessage: (data: MessageType) => {\n if (data.type === 'openkey:ready') {\n readyReceived = true;\n modal?.postMessage(message);\n return;\n }\n\n if (data.type === 'openkey:close') {\n settle(() => {\n cleanup();\n reject({ code: 'USER_CANCELLED', message: 'User cancelled the request' } as OpenKeyError);\n });\n return;\n }\n\n if (data.type === 'openkey:link-wallet:delegate') {\n this.handleWalletLinkDelegation(modal!);\n return;\n }\n\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n settle(() => {\n cleanup();\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n });\n }\n },\n });\n\n // Auto-fallback: if no openkey:ready within 3s, fall back to popup\n const readyTimeout = setTimeout(() => {\n if (readyReceived || settled) return;\n cleanup();\n console.warn('OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP.');\n showToast();\n const popupUrl = `${this.host}/widget/${action}?origin=${origin}`;\n this.openPopup(popupUrl, message, (val: any) => settle(() => resolve(val)), (err: any) => settle(() => reject(err)));\n }, IFRAME_READY_TIMEOUT);\n\n // Overall 5-minute timeout\n const overallTimeout = setTimeout(() => {\n settle(() => {\n cleanup();\n reject({ code: 'TIMEOUT', message: 'Request timed out' } as OpenKeyError);\n });\n }, DEFAULT_TIMEOUT);\n });\n }\n\n private handleWalletLinkDelegation(modal: IframeModal) {\n const sendResult = (result: MessageType) => modal.postMessage(result);\n\n new WalletPicker({\n providers: this.discoveredProviders,\n onCancel: () => {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'USER_CANCELLED', message: 'Wallet linking cancelled' } });\n },\n onSelect: async (provider) => {\n try {\n const accounts = await provider.request({ method: 'eth_requestAccounts' }) as string[];\n const address = accounts[0];\n if (!address) throw new Error('No account returned');\n\n // Get challenge from API\n const challengeRes = await fetch(`${this.host}/api/keys/link/challenge`, {\n method: 'POST',\n credentials: 'include',\n });\n if (!challengeRes.ok) throw new Error('Failed to get challenge');\n const { message } = await challengeRes.json();\n\n // Sign challenge with wallet\n const hexMessage = this.toHex(message);\n const signature = await provider.request({\n method: 'personal_sign',\n params: [hexMessage, address],\n }) as string;\n\n // Submit to API\n const linkRes = await fetch(`${this.host}/api/keys/link`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ address, signature, message }),\n });\n if (!linkRes.ok) {\n const err = await linkRes.json();\n throw new Error(err.error || 'Failed to link wallet');\n }\n const { key } = await linkRes.json();\n\n sendResult({ type: 'openkey:link-wallet:result', success: true, address: key.address, keyId: key.id });\n } catch (e: any) {\n sendResult({ type: 'openkey:link-wallet:result', success: false, error: { code: 'UNKNOWN', message: e.message || 'Wallet linking failed' } });\n }\n },\n });\n }\n\n private openPopup<T>(\n url: string,\n message: object,\n resolve: (value: T) => void,\n reject: (error: OpenKeyError) => void\n ) {\n // Calculate popup position\n const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;\n const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;\n\n this.popup = window.open(\n url,\n 'openkey',\n `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`\n );\n\n if (!this.popup) {\n reject({\n code: 'POPUP_BLOCKED',\n message: 'Popup was blocked. Please allow popups for this site.',\n });\n return;\n }\n\n const cleanup = () => {\n window.removeEventListener('message', handleMessage);\n clearInterval(pollClosed);\n clearTimeout(timeout);\n };\n\n // Poll to detect popup close\n const pollClosed = setInterval(() => {\n if (this.popup?.closed) {\n cleanup();\n reject({\n code: 'USER_CANCELLED',\n message: 'User closed the popup',\n });\n }\n }, 500);\n\n // Timeout\n const timeout = setTimeout(() => {\n cleanup();\n this.popup?.close();\n reject({\n code: 'TIMEOUT',\n message: 'Request timed out',\n });\n }, DEFAULT_TIMEOUT);\n\n // Listen for messages\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== this.host) return;\n\n const data = event.data as MessageType;\n\n if (data.type === 'openkey:ready') {\n // Widget is ready, send our request\n this.popup?.postMessage(message, this.host);\n return;\n }\n\n if (data.type === 'openkey:close') {\n cleanup();\n this.popup?.close();\n reject({\n code: 'USER_CANCELLED',\n message: 'User cancelled the request',\n });\n return;\n }\n\n // Handle responses\n if (\n data.type === 'openkey:auth:response' ||\n data.type === 'openkey:sign:response' ||\n data.type === 'openkey:signTypedData:response' ||\n data.type === 'openkey:link-wallet:response'\n ) {\n cleanup();\n this.popup?.close();\n\n if (data.success) {\n if (data.type === 'openkey:auth:response') {\n resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || 'MANAGED' } as T);\n } else if (data.type === 'openkey:link-wallet:response') {\n resolve({ address: data.address, keyId: data.keyId } as T);\n } else {\n resolve({ signature: data.signature, address: data.address } as T);\n }\n } else {\n reject(data.error);\n }\n }\n };\n\n window.addEventListener('message', handleMessage);\n }\n\n /**\n * Disconnect and close any open flows\n */\n disconnect() {\n this.popup?.close();\n this.popup = null;\n }\n}\n\n/**\n * Unified EIP-1193 provider that wraps an OpenKey instance.\n * Transparently routes signing to either OpenKey (managed keys) or the user's\n * wallet (external keys).\n */\nexport class OpenKeyEIP1193Provider implements EIP1193Provider {\n private openkey: OpenKey;\n private address: string;\n private keyId: string;\n private keyType: 'MANAGED' | 'EXTERNAL';\n\n constructor(openkey: OpenKey, authResult: AuthResult) {\n this.openkey = openkey;\n this.address = authResult.address;\n this.keyId = authResult.keyId;\n this.keyType = authResult.keyType;\n }\n\n async request({ method, params }: { method: string; params?: any[] }): Promise<any> {\n switch (method) {\n case 'eth_accounts':\n case 'eth_requestAccounts':\n return [this.address];\n\n case 'eth_chainId':\n return '0x1'; // mainnet\n\n case 'personal_sign': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n // Managed key: route through OpenKey\n const message = this.hexToString(params![0] as string);\n const result = await this.openkey.signMessage({ message, keyId: this.keyId });\n return result.signature;\n }\n\n case 'eth_signTypedData_v4': {\n if (this.keyType === 'EXTERNAL') {\n const provider = await this.openkey.findWalletProvider(this.address);\n return provider.request({ method, params });\n }\n const data = JSON.parse(params![1] as string);\n const result = await this.openkey.signTypedData(data);\n return result.signature;\n }\n\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n }\n\n private hexToString(hex: string): string {\n const bytes = new Uint8Array(\n (hex.startsWith('0x') ? hex.slice(2) : hex).match(/.{1,2}/g)!.map(b => parseInt(b, 16))\n );\n return new TextDecoder().decode(bytes);\n }\n}\n\n// Default export for convenience\nexport default OpenKey;\n\n// Create singleton instance\nlet defaultInstance: OpenKey | null = null;\n\nexport function getOpenKey(config?: OpenKeyConfig): OpenKey {\n if (!defaultInstance || config) {\n defaultInstance = new OpenKey(config);\n }\n return defaultInstance;\n}\n"],"mappings":"AAoHA,IAAMA,EAAe,qBAKrB,IAAMC,EAAoB,gBAEpBC,EAAN,KAAkB,CACR,KACA,OACA,OACA,QACA,UACA,eACA,KAER,YAAYC,EAAkG,CAC5G,KAAK,KAAOA,EAAK,KACjB,KAAK,QAAUA,EAAK,QACpB,KAAK,UAAYA,EAAK,UAEtB,IAAMC,EAAW,OAAO,WAAW,oBAAoB,EAAE,QAEzD,KAAK,KAAO,SAAS,cAAc,KAAK,EACxC,KAAK,OAAS,KAAK,KAAK,aAAa,CAAE,KAAM,QAAS,CAAC,EAEvD,IAAMC,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,YAAc;AAAA;AAAA,yIAEiHD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,CAAE,OAAAC,EAAQ,OAAAC,CAAO,EAAqD,CAClF,OAAQD,EAAQ,CACd,IAAK,eACL,IAAK,sBACH,MAAO,CAAC,KAAK,OAAO,EAEtB,IAAK,cACH,MAAO,MAET,IAAK,gBAAiB,CACpB,GAAI,KAAK,UAAY,WAEnB,OADiB,MAAM,KAAK,QAAQ,mBAAmB,KAAK,OAAO,GACnD,QAAQ,CAAE,OAAAA,EAAQ,OAAAC,CAAO,CAAC,EAG5C,IAAMhF,EAAU,KAAK,YAAYgF,EAAQ,CAAC,CAAW,EAErD,OADe,MAAM,KAAK,QAAQ,YAAY,CAAE,QAAAhF,EAAS,MAAO,KAAK,KAAM,CAAC,GAC9D,SAChB,CAEA,IAAK,uBAAwB,CAC3B,GAAI,KAAK,UAAY,WAEnB,OADiB,MAAM,KAAK,QAAQ,mBAAmB,KAAK,OAAO,GACnD,QAAQ,CAAE,OAAA+E,EAAQ,OAAAC,CAAO,CAAC,EAE5C,IAAMlF,EAAO,KAAK,MAAMkF,EAAQ,CAAC,CAAW,EAE5C,OADe,MAAM,KAAK,QAAQ,cAAclF,CAAI,GACtC,SAChB,CAEA,QACE,MAAM,IAAI,MAAM,uBAAuBiF,CAAM,EAAE,CACnD,CACF,CAEQ,YAAYE,EAAqB,CACvC,IAAMC,EAAQ,IAAI,YACfD,EAAI,WAAW,IAAI,EAAIA,EAAI,MAAM,CAAC,EAAIA,GAAK,MAAM,SAAS,EAAG,IAAIjD,GAAK,SAASA,EAAG,EAAE,CAAC,CACxF,EACA,OAAO,IAAI,YAAY,EAAE,OAAOkD,CAAK,CACvC,CACF,EAGOC,EAAQ7D,EAGX8D,EAAkC,KAE/B,SAASC,EAAW9D,EAAiC,CAC1D,OAAI,CAAC6D,GAAmB7D,KACtB6D,EAAkB,IAAI9D,EAAQC,CAAM,GAE/B6D,CACT","names":["DEFAULT_HOST","OAUTH_STORAGE_KEY","IframeModal","opts","isMobile","style","backdrop","e","card","handle","closeBtn","event","data","h","message","WalletPicker","title","empty","list","info","provider","item","icon","name","cancel","showToast","root","shadow","base64UrlEncode","buffer","generateCodeVerifier","array","generateCodeChallenge","verifier","digest","generateState","OpenKey","config","DEFAULT_HOST","result","request","targetAddress","a","hexMessage","mode","str","b","res","challenge","state","authUrl","code","stored","response","error","receivedState","url","urlObj","redirectUri","resolve","reject","left","top","redirectHost","pollInterval","timeout","popupUrl","returnedState","override","action","modeOverride","origin","readyReceived","settled","modal","settle","fn","cleanup","readyTimeout","overallTimeout","val","err","sendResult","address","challengeRes","signature","linkRes","key","handleMessage","pollClosed","OpenKeyEIP1193Provider","openkey","authResult","method","params","hex","bytes","index_default","defaultInstance","getOpenKey"]}
|