@ab-org/sdk-core 0.1.0 → 0.1.2-beta.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.
Files changed (48) hide show
  1. package/README.md +29 -0
  2. package/dist/chunk-5HURLKIK.js +1005 -0
  3. package/dist/chunk-MVZIAM4H.js +363 -0
  4. package/dist/cubeSignerAuth-DrPc9FeB.d.ts +426 -0
  5. package/dist/index.d.ts +237 -16
  6. package/dist/index.js +1119 -16
  7. package/dist/social-auth.d.ts +11 -0
  8. package/dist/social-auth.js +1 -0
  9. package/dist/social-provider-Bq58TBRt.d.ts +88 -0
  10. package/dist/social-provider.d.ts +2 -0
  11. package/dist/social-provider.js +2 -0
  12. package/dist/social.d.ts +3 -0
  13. package/dist/social.js +2 -0
  14. package/package.json +24 -6
  15. package/dist/core/capabilities.d.ts +0 -32
  16. package/dist/core/capabilities.js +0 -88
  17. package/dist/core/chains.d.ts +0 -23
  18. package/dist/core/chains.js +0 -83
  19. package/dist/core/errors.d.ts +0 -9
  20. package/dist/core/errors.js +0 -51
  21. package/dist/core/sessionStore.d.ts +0 -26
  22. package/dist/core/sessionStore.js +0 -129
  23. package/dist/core/types.d.ts +0 -75
  24. package/dist/core/types.js +0 -1
  25. package/dist/core/walletConnector.d.ts +0 -29
  26. package/dist/core/walletConnector.js +0 -153
  27. package/dist/core/walletExecution.d.ts +0 -22
  28. package/dist/core/walletExecution.js +0 -89
  29. package/dist/hooks/useAccount.d.ts +0 -11
  30. package/dist/hooks/useAccount.js +0 -32
  31. package/dist/hooks/useWalletConnect.d.ts +0 -16
  32. package/dist/hooks/useWalletConnect.js +0 -24
  33. package/dist/providers/base.d.ts +0 -15
  34. package/dist/providers/base.js +0 -30
  35. package/dist/providers/plugin/injectedEvmProvider.d.ts +0 -112
  36. package/dist/providers/plugin/injectedEvmProvider.js +0 -352
  37. package/dist/providers/plugin/injectedWalletRegistry.d.ts +0 -9
  38. package/dist/providers/plugin/injectedWalletRegistry.js +0 -34
  39. package/dist/providers/plugin/metamaskProvider.d.ts +0 -1
  40. package/dist/providers/plugin/metamaskProvider.js +0 -1
  41. package/dist/providers/social/baseSocialProvider.d.ts +0 -21
  42. package/dist/providers/social/baseSocialProvider.js +0 -11
  43. package/dist/providers/social/cubeSignerAuth.d.ts +0 -89
  44. package/dist/providers/social/cubeSignerAuth.js +0 -128
  45. package/dist/providers/social/cubistEvmWalletProvider.d.ts +0 -9
  46. package/dist/providers/social/cubistEvmWalletProvider.js +0 -175
  47. package/dist/providers/social/cubistProvider.d.ts +0 -52
  48. package/dist/providers/social/cubistProvider.js +0 -160
@@ -1,352 +0,0 @@
1
- import { getChainInfo } from "@ab-org/wallet-utils";
2
- import { AbstractProvider } from "../base.js";
3
- import { createChainContext, getSupportedChainFromEvmChainId } from "../../core/chains.js";
4
- import { normalizeEvmTransactionSigningError } from "../../core/errors.js";
5
- const injectedWalletCapabilities = [
6
- "eth_accounts",
7
- "eth_requestAccounts",
8
- "eth_chainId",
9
- "eth_signTransaction",
10
- "eth_sendTransaction",
11
- "personal_sign",
12
- "eth_signTypedData_v4",
13
- "wallet_disconnect",
14
- "wallet_rehydrate",
15
- ];
16
- function unwrapProvider(candidate) {
17
- if (!candidate)
18
- return undefined;
19
- if ("request" in candidate)
20
- return candidate;
21
- return candidate.ethereum;
22
- }
23
- function collectCandidates() {
24
- if (typeof window === "undefined")
25
- return [];
26
- const providers = [];
27
- const seen = new Set();
28
- const push = (candidate) => {
29
- const provider = unwrapProvider(candidate);
30
- if (!provider || seen.has(provider))
31
- return;
32
- seen.add(provider);
33
- providers.push(provider);
34
- };
35
- push(window.ethereum);
36
- window.ethereum?.providers?.forEach(push);
37
- push(window.okxwallet);
38
- push(window.coinbaseWalletExtension);
39
- push(window.trustwallet);
40
- push(window.phantom?.ethereum);
41
- push(window.rabby);
42
- push(window.bitkeep);
43
- push(window.rainbow?.ethereum);
44
- push(window.zerionWallet);
45
- push(unwrapProvider(window.bitget));
46
- return providers;
47
- }
48
- export function discoverEIP6963Providers() {
49
- if (typeof window === "undefined")
50
- return [];
51
- const details = [];
52
- const seen = new Set();
53
- const onAnnounce = (event) => {
54
- const detail = event.detail;
55
- if (!detail?.info?.uuid || !detail.provider)
56
- return;
57
- if (seen.has(detail.info.uuid))
58
- return;
59
- seen.add(detail.info.uuid);
60
- details.push(detail);
61
- };
62
- window.addEventListener("eip6963:announceProvider", onAnnounce);
63
- window.dispatchEvent(new Event("eip6963:requestProviderInfo"));
64
- window.removeEventListener("eip6963:announceProvider", onAnnounce);
65
- return details;
66
- }
67
- function getWindow() {
68
- return typeof window === "undefined" ? undefined : window;
69
- }
70
- function getKnownNonMetaMaskProviders() {
71
- const currentWindow = getWindow();
72
- if (!currentWindow)
73
- return [];
74
- const providers = [
75
- unwrapProvider(currentWindow.okxwallet),
76
- unwrapProvider(currentWindow.coinbaseWalletExtension),
77
- unwrapProvider(currentWindow.trustwallet),
78
- unwrapProvider(currentWindow.phantom?.ethereum),
79
- unwrapProvider(currentWindow.rabby),
80
- unwrapProvider(currentWindow.bitkeep),
81
- unwrapProvider(currentWindow.rainbow?.ethereum),
82
- currentWindow.zerionWallet,
83
- unwrapProvider(currentWindow.bitget),
84
- ];
85
- return providers.filter((provider) => Boolean(provider));
86
- }
87
- export function findInjectedProvider(predicate) {
88
- return collectCandidates().find(predicate);
89
- }
90
- export function findEIP6963Provider(predicate) {
91
- return discoverEIP6963Providers().find(predicate)?.provider;
92
- }
93
- function isMetaMaskOnly(provider) {
94
- const knownNonMetaMaskProviders = getKnownNonMetaMaskProviders();
95
- return (provider.isMetaMask === true &&
96
- !knownNonMetaMaskProviders.includes(provider) &&
97
- provider.isCoinbaseWallet !== true &&
98
- provider.isPhantom !== true &&
99
- provider.isRabby !== true &&
100
- provider.isOkxWallet !== true &&
101
- provider.isTrust !== true &&
102
- provider.isTrustWallet !== true &&
103
- provider.isBitKeep !== true &&
104
- provider.isRainbow !== true &&
105
- provider.isZerion !== true &&
106
- provider.isBraveWallet !== true &&
107
- provider.isBitget !== true);
108
- }
109
- function rdnsIncludes(info, value) {
110
- return info.rdns.toLowerCase().includes(value.toLowerCase());
111
- }
112
- function nameIncludes(info, value) {
113
- return info.name.toLowerCase().includes(value.toLowerCase());
114
- }
115
- /** Default funding chain (see `@ab-org/wallet-utils` `getChainInfo()`, currently Tenderly BSC 3131). */
116
- const FALLBACK_FUNDING_CHAIN = getChainInfo();
117
- function evmChainInfoToWalletAddEthereumChainParams(info) {
118
- const chainIdHex = `0x${BigInt(info.chainId).toString(16)}`;
119
- return {
120
- chainId: chainIdHex,
121
- chainName: info.chainName,
122
- nativeCurrency: {
123
- name: info.nativeCurrencyName,
124
- symbol: info.nativeCurrencySymbol,
125
- decimals: info.nativeCurrencyDecimals,
126
- },
127
- rpcUrls: [...info.rpcUrls],
128
- blockExplorerUrls: [info.blockExplorerUrl],
129
- };
130
- }
131
- const FALLBACK_FUNDING_CHAIN_ID_HEX = `0x${BigInt(FALLBACK_FUNDING_CHAIN.chainId).toString(16)}`;
132
- const FALLBACK_FUNDING_CHAIN_PARAMS = evmChainInfoToWalletAddEthereumChainParams(FALLBACK_FUNDING_CHAIN);
133
- /**
134
- * Force wallet to the default funding chain (e.g. 3131). If the chain is missing (4902), add it then switch.
135
- * Call after external wallet connect so subsequent business runs on the configured funding network.
136
- */
137
- export async function switchToFallbackFundingChain(provider) {
138
- const switchChain = () => provider.request({
139
- method: "wallet_switchEthereumChain",
140
- params: [{ chainId: FALLBACK_FUNDING_CHAIN_ID_HEX }],
141
- });
142
- try {
143
- await switchChain();
144
- }
145
- catch (err) {
146
- const code = err?.code;
147
- if (code === 4902) {
148
- await provider.request({
149
- method: "wallet_addEthereumChain",
150
- params: [FALLBACK_FUNDING_CHAIN_PARAMS],
151
- });
152
- await switchChain();
153
- return;
154
- }
155
- throw err;
156
- }
157
- }
158
- function createInjectedWalletProvider(title, provider) {
159
- return {
160
- async request(payload) {
161
- try {
162
- return await provider.request(payload);
163
- }
164
- catch (error) {
165
- if (payload.method === "eth_signTransaction") {
166
- throw normalizeEvmTransactionSigningError(title, error);
167
- }
168
- throw error;
169
- }
170
- },
171
- async disconnect() {
172
- await provider.disconnect();
173
- },
174
- };
175
- }
176
- export class InjectedEvmProvider extends AbstractProvider {
177
- constructor(config, injected) {
178
- super();
179
- this.config = config;
180
- this.injected = injected;
181
- this.category = "plugin";
182
- this.id = config.id;
183
- this.title = config.title;
184
- }
185
- isAvailable() {
186
- return Boolean(this.injected ?? this.config.resolveProvider());
187
- }
188
- get client() {
189
- const provider = this.injected ?? this.config.resolveProvider();
190
- if (provider)
191
- return provider;
192
- throw new Error(`${this.title} provider not available`);
193
- }
194
- async connect(_args) {
195
- const provider = this.client;
196
- const walletProvider = createInjectedWalletProvider(this.title, provider);
197
- const [address] = (await walletProvider.request({ method: "eth_requestAccounts" })) ?? [];
198
- if (!address) {
199
- throw new Error(`${this.title} did not return an account`);
200
- }
201
- await switchToFallbackFundingChain(provider);
202
- const chainId = await walletProvider.request({ method: "eth_chainId" });
203
- const chain = getSupportedChainFromEvmChainId(chainId);
204
- const session = {
205
- address,
206
- chain,
207
- provider: walletProvider,
208
- walletType: "injected",
209
- authSource: "wallet",
210
- sessionId: `${this.id}:${address.toLowerCase()}`,
211
- capabilities: injectedWalletCapabilities,
212
- chainContext: createChainContext(chain),
213
- };
214
- return this.setSession(session);
215
- }
216
- async reconnect(_persistedSession) {
217
- const provider = this.injected ?? this.config.resolveProvider();
218
- if (!provider)
219
- return null;
220
- const walletProvider = createInjectedWalletProvider(this.title, provider);
221
- const accounts = await provider.request({
222
- method: "eth_accounts",
223
- params: [],
224
- });
225
- const [address] = accounts ?? [];
226
- if (!address)
227
- return null;
228
- let chain;
229
- try {
230
- const chainId = await walletProvider.request({ method: "eth_chainId" });
231
- chain = getSupportedChainFromEvmChainId(chainId);
232
- }
233
- catch {
234
- return null;
235
- }
236
- const session = {
237
- address,
238
- chain,
239
- provider: walletProvider,
240
- walletType: "injected",
241
- authSource: "wallet",
242
- sessionId: `${this.id}:${address.toLowerCase()}`,
243
- capabilities: injectedWalletCapabilities,
244
- chainContext: createChainContext(chain),
245
- };
246
- return this.setSession(session);
247
- }
248
- }
249
- export class MetaMaskProvider extends InjectedEvmProvider {
250
- constructor(injected) {
251
- super({
252
- id: "metamask",
253
- title: "MetaMask",
254
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "io.metamask") || nameIncludes(info, "metamask")) ?? findInjectedProvider(isMetaMaskOnly),
255
- }, injected);
256
- }
257
- }
258
- export class OKXProvider extends InjectedEvmProvider {
259
- constructor(injected) {
260
- super({
261
- id: "okx",
262
- title: "OKX Wallet",
263
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "okx") || nameIncludes(info, "okx")) ??
264
- unwrapProvider(getWindow()?.okxwallet) ??
265
- findInjectedProvider((provider) => provider.isOkxWallet === true),
266
- }, injected);
267
- }
268
- }
269
- export class CoinbaseWalletProvider extends InjectedEvmProvider {
270
- constructor(injected) {
271
- super({
272
- id: "coinbase",
273
- title: "Coinbase Wallet",
274
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "com.coinbase.wallet") || nameIncludes(info, "coinbase")) ??
275
- unwrapProvider(getWindow()?.coinbaseWalletExtension) ??
276
- findInjectedProvider((provider) => provider.isCoinbaseWallet === true),
277
- }, injected);
278
- }
279
- }
280
- export class TrustWalletProvider extends InjectedEvmProvider {
281
- constructor(injected) {
282
- super({
283
- id: "trust",
284
- title: "Trust Wallet",
285
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "trust") || nameIncludes(info, "trust")) ??
286
- unwrapProvider(getWindow()?.trustwallet) ??
287
- findInjectedProvider((provider) => provider.isTrust === true || provider.isTrustWallet === true),
288
- }, injected);
289
- }
290
- }
291
- export class PhantomProvider extends InjectedEvmProvider {
292
- constructor(injected) {
293
- super({
294
- id: "phantom",
295
- title: "Phantom",
296
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "phantom") || nameIncludes(info, "phantom")) ??
297
- unwrapProvider(getWindow()?.phantom?.ethereum) ??
298
- findInjectedProvider((provider) => provider.isPhantom === true),
299
- }, injected);
300
- }
301
- }
302
- export class RabbyProvider extends InjectedEvmProvider {
303
- constructor(injected) {
304
- super({
305
- id: "rabby",
306
- title: "Rabby",
307
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "rabby") || nameIncludes(info, "rabby")) ??
308
- unwrapProvider(getWindow()?.rabby) ??
309
- findInjectedProvider((provider) => provider.isRabby === true),
310
- }, injected);
311
- }
312
- }
313
- export class RainbowProvider extends InjectedEvmProvider {
314
- constructor(injected) {
315
- super({
316
- id: "rainbow",
317
- title: "Rainbow",
318
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "rainbow") || nameIncludes(info, "rainbow")) ??
319
- unwrapProvider(getWindow()?.rainbow?.ethereum) ??
320
- findInjectedProvider((provider) => provider.isRainbow === true),
321
- }, injected);
322
- }
323
- }
324
- export class ZerionProvider extends InjectedEvmProvider {
325
- constructor(injected) {
326
- super({
327
- id: "zerion",
328
- title: "Zerion",
329
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "zerion") || nameIncludes(info, "zerion")) ?? getWindow()?.zerionWallet ?? findInjectedProvider((provider) => provider.isZerion === true),
330
- }, injected);
331
- }
332
- }
333
- export class BraveWalletProvider extends InjectedEvmProvider {
334
- constructor(injected) {
335
- super({
336
- id: "brave",
337
- title: "Brave Wallet",
338
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "brave") || nameIncludes(info, "brave")) ?? findInjectedProvider((provider) => provider.isBraveWallet === true),
339
- }, injected);
340
- }
341
- }
342
- export class BitgetProvider extends InjectedEvmProvider {
343
- constructor(injected) {
344
- super({
345
- id: "bitget",
346
- title: "Bitget",
347
- resolveProvider: () => findEIP6963Provider(({ info }) => rdnsIncludes(info, "bitget") || nameIncludes(info, "bitget")) ??
348
- unwrapProvider(getWindow()?.bitget) ??
349
- findInjectedProvider((provider) => provider.isBitget === true),
350
- }, injected);
351
- }
352
- }
@@ -1,9 +0,0 @@
1
- import { type InjectedEvmProvider } from "./injectedEvmProvider.js";
2
- export interface InjectedWalletRegistryItem {
3
- id: string;
4
- title: string;
5
- installUrl?: string;
6
- provider: InjectedEvmProvider;
7
- installed: boolean;
8
- }
9
- export declare function createDefaultInjectedWalletRegistry(): InjectedWalletRegistryItem[];
@@ -1,34 +0,0 @@
1
- import { BitgetProvider, BraveWalletProvider, CoinbaseWalletProvider, MetaMaskProvider, OKXProvider, PhantomProvider, RabbyProvider, RainbowProvider, TrustWalletProvider, ZerionProvider, } from "./injectedEvmProvider.js";
2
- const installUrls = {
3
- metamask: "https://metamask.io/download/",
4
- okx: "https://www.okx.com/web3",
5
- coinbase: "https://www.coinbase.com/wallet/downloads",
6
- trust: "https://trustwallet.com/browser-extension",
7
- phantom: "https://phantom.com/download",
8
- rabby: "https://rabby.io/",
9
- rainbow: "https://rainbow.me/extension",
10
- zerion: "https://zerion.io/extension",
11
- brave: "https://brave.com/wallet/",
12
- bitget: "https://web3.bitget.com/en/wallet-download",
13
- };
14
- export function createDefaultInjectedWalletRegistry() {
15
- const providers = [
16
- new MetaMaskProvider(),
17
- new OKXProvider(),
18
- new CoinbaseWalletProvider(),
19
- new TrustWalletProvider(),
20
- new PhantomProvider(),
21
- new RabbyProvider(),
22
- new RainbowProvider(),
23
- new ZerionProvider(),
24
- new BraveWalletProvider(),
25
- new BitgetProvider(),
26
- ];
27
- return providers.map((provider) => ({
28
- id: provider.id,
29
- title: provider.title,
30
- installUrl: installUrls[provider.id],
31
- provider,
32
- installed: provider.isAvailable(),
33
- }));
34
- }
@@ -1 +0,0 @@
1
- export { MetaMaskProvider, type InjectedEthereumProvider, } from "./injectedEvmProvider.js";
@@ -1 +0,0 @@
1
- export { MetaMaskProvider, } from "./injectedEvmProvider.js";
@@ -1,21 +0,0 @@
1
- import { AbstractProvider } from "../base.js";
2
- import type { WalletConnectArgs, WalletSession } from "../../core/types.js";
3
- export interface SocialLoginOptions {
4
- hint?: string;
5
- redirectUri?: string;
6
- }
7
- export interface SocialConnectArgs extends WalletConnectArgs {
8
- options?: SocialLoginOptions;
9
- }
10
- export declare abstract class AbstractSocialProvider extends AbstractProvider {
11
- readonly category: "social";
12
- /**
13
- * Authenticate and cache a social-wallet session.
14
- *
15
- * Some providers only need `options`, while others may require an
16
- * additional credential payload (for example an OIDC token or OAuth result).
17
- */
18
- abstract signIn(options?: SocialLoginOptions, payload?: unknown): Promise<void>;
19
- abstract signOut(): Promise<void>;
20
- connect(args?: WalletConnectArgs): Promise<WalletSession>;
21
- }
@@ -1,11 +0,0 @@
1
- import { AbstractProvider } from "../base.js";
2
- export class AbstractSocialProvider extends AbstractProvider {
3
- constructor() {
4
- super(...arguments);
5
- this.category = "social";
6
- }
7
- async connect(args) {
8
- await this.signIn(args?.options, args?.payload);
9
- return this.requireSession();
10
- }
11
- }
@@ -1,89 +0,0 @@
1
- import { CubeSignerClient, type EnvInterface, type Environment, type SessionData } from "@cubist-labs/cubesigner-sdk";
2
- import type { SessionCapabilityPolicy } from "../../core/capabilities.js";
3
- /**
4
- * Hook for OIDC login when user does not yet exist in CubeSigner.
5
- * Before creating a session, we call CubeSigner SDK's proof (proveOidcIdentity) to check
6
- * if the user exists. If proof fails (e.g. user not registered), this is invoked so the
7
- * caller can register the user on their backend; then login proceeds.
8
- */
9
- export interface OidcLoginHooks {
10
- /**
11
- * Register the user on your backend when CubeSigner proof indicates the user does not exist.
12
- * Called with the same OIDC token; after this resolves, OIDC session creation continues.
13
- */
14
- registerUser(oidcToken: string): Promise<void>;
15
- }
16
- export interface CubeSignerConfig {
17
- /** CubeSigner environment name or custom env object. */
18
- env: Environment | EnvInterface;
19
- /** Organization ID. */
20
- orgId: string;
21
- /** Session scopes (default: `["sign:*", "manage:*"]`). */
22
- scopes?: string[];
23
- /** Optional capability policy applied to smart-wallet sessions created from this auth flow. */
24
- defaultSessionPolicy?: Partial<SessionCapabilityPolicy>;
25
- /**
26
- * Optional OIDC login hook. When provided, OIDC login will call CubeSigner SDK's
27
- * proveOidcIdentity first; if the user does not exist (proof fails), registerUser is
28
- * called, then login proceeds. If omitted, login uses the OIDC token directly.
29
- */
30
- oidcLoginHooks?: OidcLoginHooks;
31
- }
32
- export interface CubeSignerSession {
33
- /** Authenticated CubeSigner client — use it for signing, key management, etc. */
34
- client: CubeSignerClient;
35
- /** Raw session data (can be persisted / refreshed). */
36
- sessionData: SessionData;
37
- }
38
- export interface TwitterCodeExchangeParams {
39
- /** Authorization code from Twitter OAuth 2.0 PKCE flow. */
40
- code: string;
41
- /** PKCE code_verifier that was generated for the auth request. */
42
- codeVerifier: string;
43
- /** redirect_uri that was used in the authorization request. */
44
- redirectUri: string;
45
- }
46
- export declare class CubeSignerAuth {
47
- private readonly env;
48
- private readonly orgId;
49
- private readonly scopes;
50
- readonly defaultSessionPolicy?: Partial<SessionCapabilityPolicy>;
51
- private readonly oidcLoginHooks?;
52
- private _client;
53
- private _sessionData;
54
- constructor(config: CubeSignerConfig);
55
- /** Currently authenticated client (null if not logged in). */
56
- get client(): CubeSignerClient | null;
57
- get currentSession(): CubeSignerSession | null;
58
- /**
59
- * Login with a Google ID token (JWT).
60
- * The token is used directly as the OIDC credential.
61
- */
62
- loginWithGoogle(idToken: string): Promise<CubeSignerSession>;
63
- /**
64
- * Login with a Twitter OAuth 2.0 authorization code.
65
- *
66
- * 1. Exchange the code for an OIDC `id_token` via CubeSigner's
67
- * `/v0/org/{org_id}/oauth2/twitter` endpoint.
68
- * 2. Create a CubeSigner session with that token.
69
- */
70
- loginWithTwitter(params: TwitterCodeExchangeParams): Promise<CubeSignerSession>;
71
- signOut(): Promise<void>;
72
- /**
73
- * Restore a CubeSigner session from previously persisted SessionData.
74
- * Useful for reconnecting after page reload without re-authentication.
75
- */
76
- restoreSession(sessionData: SessionData): Promise<CubeSignerSession>;
77
- private authenticateWithOidcToken;
78
- /**
79
- * Exchange a Twitter authorization code for an OIDC id_token
80
- * via CubeSigner's dedicated endpoint.
81
- *
82
- * `POST {SignerApiRoot}/v0/org/{org_id}/oauth2/twitter`
83
- */
84
- private exchangeTwitterCode;
85
- /**
86
- * Create a CubeSigner OIDC session from a generic OIDC id_token.
87
- */
88
- private createOidcSession;
89
- }
@@ -1,128 +0,0 @@
1
- import { CubeSignerClient, envs, MemorySessionManager, } from "@cubist-labs/cubesigner-sdk";
2
- /* ─── Helper ────────────────────────────────── */
3
- function resolveEnv(env) {
4
- return typeof env === "string" ? envs[env] : env;
5
- }
6
- /* ─── CubeSignerAuth service ────────────────── */
7
- export class CubeSignerAuth {
8
- constructor(config) {
9
- this._client = null;
10
- this._sessionData = null;
11
- this.env = resolveEnv(config.env);
12
- this.orgId = config.orgId;
13
- this.scopes = config.scopes ?? ["sign:*", "manage:*"];
14
- this.defaultSessionPolicy = config.defaultSessionPolicy;
15
- this.oidcLoginHooks = config.oidcLoginHooks;
16
- }
17
- /** Currently authenticated client (null if not logged in). */
18
- get client() {
19
- return this._client;
20
- }
21
- get currentSession() {
22
- if (!this._client || !this._sessionData)
23
- return null;
24
- return {
25
- client: this._client,
26
- sessionData: this._sessionData,
27
- };
28
- }
29
- /* ── Google ───────────────────────────────── */
30
- /**
31
- * Login with a Google ID token (JWT).
32
- * The token is used directly as the OIDC credential.
33
- */
34
- async loginWithGoogle(idToken) {
35
- return this.authenticateWithOidcToken(idToken);
36
- }
37
- /* ── Twitter / X ──────────────────────────── */
38
- /**
39
- * Login with a Twitter OAuth 2.0 authorization code.
40
- *
41
- * 1. Exchange the code for an OIDC `id_token` via CubeSigner's
42
- * `/v0/org/{org_id}/oauth2/twitter` endpoint.
43
- * 2. Create a CubeSigner session with that token.
44
- */
45
- async loginWithTwitter(params) {
46
- const idToken = await this.exchangeTwitterCode(params);
47
- return this.authenticateWithOidcToken(idToken);
48
- }
49
- /* ── Sign-out ─────────────────────────────── */
50
- async signOut() {
51
- if (this._client) {
52
- try {
53
- await this._client.revokeSession();
54
- }
55
- catch {
56
- /* best-effort */
57
- }
58
- this._client = null;
59
- this._sessionData = null;
60
- }
61
- }
62
- /* ── Session restore ────────────────────── */
63
- /**
64
- * Restore a CubeSigner session from previously persisted SessionData.
65
- * Useful for reconnecting after page reload without re-authentication.
66
- */
67
- async restoreSession(sessionData) {
68
- if (this._client) {
69
- await this.signOut();
70
- }
71
- const client = await CubeSignerClient.create(new MemorySessionManager(sessionData));
72
- this._client = client;
73
- this._sessionData = sessionData;
74
- return { client, sessionData };
75
- }
76
- /* ── Private ──────────────────────────────── */
77
- async authenticateWithOidcToken(oidcToken) {
78
- if (this._client) {
79
- await this.signOut();
80
- }
81
- const hooks = this.oidcLoginHooks;
82
- if (hooks) {
83
- const proof = await CubeSignerClient.proveOidcIdentity(this.env, this.orgId, oidcToken);
84
- if (!proof.user_info?.initialized) {
85
- await hooks.registerUser(oidcToken);
86
- }
87
- }
88
- return this.createOidcSession(oidcToken);
89
- }
90
- /**
91
- * Exchange a Twitter authorization code for an OIDC id_token
92
- * via CubeSigner's dedicated endpoint.
93
- *
94
- * `POST {SignerApiRoot}/v0/org/{org_id}/oauth2/twitter`
95
- */
96
- async exchangeTwitterCode(params) {
97
- const url = `${this.env.SignerApiRoot}/v0/org/${this.orgId}/oauth2/twitter`;
98
- const res = await fetch(url, {
99
- method: "POST",
100
- headers: { "Content-Type": "application/json" },
101
- body: JSON.stringify({
102
- code: params.code,
103
- code_verifier: params.codeVerifier,
104
- redirect_uri: params.redirectUri,
105
- }),
106
- });
107
- if (!res.ok) {
108
- const text = await res.text().catch(() => "");
109
- throw new Error(`Twitter code exchange failed (${res.status}): ${text}`);
110
- }
111
- const data = await res.json();
112
- if (!data.id_token) {
113
- throw new Error("CubeSigner twitter exchange did not return id_token");
114
- }
115
- return data.id_token;
116
- }
117
- /**
118
- * Create a CubeSigner OIDC session from a generic OIDC id_token.
119
- */
120
- async createOidcSession(oidcToken) {
121
- const resp = await CubeSignerClient.createOidcSession(this.env, this.orgId, oidcToken, this.scopes);
122
- const sessionData = resp.data();
123
- const client = await CubeSignerClient.create(new MemorySessionManager(sessionData));
124
- this._client = client;
125
- this._sessionData = sessionData;
126
- return { client, sessionData };
127
- }
128
- }
@@ -1,9 +0,0 @@
1
- import type { SupportedChain, WalletProvider } from "../../core/types.js";
2
- import type { CubeSignerSession } from "./cubeSignerAuth.js";
3
- interface CreateCubistEvmWalletProviderArgs {
4
- session: CubeSignerSession;
5
- address: string;
6
- chain: SupportedChain;
7
- }
8
- export declare const createCubistEvmWalletProvider: ({ session, address, chain, }: CreateCubistEvmWalletProviderArgs) => WalletProvider;
9
- export {};