@etherplay/connect 0.0.50 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -15,11 +15,14 @@ import {
15
15
  originPublicKeyPublicationMessage,
16
16
  originKeyMessage,
17
17
  fromSignatureToKey,
18
- AlchemyMechanism,
18
+ AuthMechanism,
19
+ generateEcdhKeyPair,
20
+ exportPublicKeyB64,
19
21
  } from '@etherplay/connect-core';
20
22
 
21
23
  export {fromEntropyKeyToMnemonic, originPublicKeyPublicationMessage, originKeyMessage};
22
- export type {OriginAccount};
24
+
25
+ export type {OriginAccount, AuthMechanism};
23
26
 
24
27
  export type {UnderlyingEthereumProvider};
25
28
 
@@ -62,7 +65,10 @@ export type ChainInfo<WalletProviderType> = ChainInfoWithRPCUrl | ChainInfoWithP
62
65
 
63
66
  export type PopupSettings = {
64
67
  walletHost: string;
65
- mechanism: AlchemyMechanism;
68
+ mechanism: AuthMechanism;
69
+ // Same-Origin Callback Bridge (domain-redirect fallback)
70
+ decryptKeyPair?: CryptoKeyPair;
71
+ domainRedirectPublicKeyB64?: string;
66
72
  // extraParams?: Record<string, string>;
67
73
  };
68
74
 
@@ -71,9 +77,9 @@ export type WalletMechanism<WalletName extends string | undefined, Address exten
71
77
  } & (WalletName extends undefined ? {name?: undefined} : {name: WalletName}) &
72
78
  (Address extends undefined ? {address?: undefined} : {address: Address});
73
79
 
74
- export type Mechanism = AlchemyMechanism | WalletMechanism<string | undefined, `0x${string}` | undefined>;
80
+ export type Mechanism = AuthMechanism | WalletMechanism<string | undefined, `0x${string}` | undefined>;
75
81
 
76
- export type FullfilledMechanism = AlchemyMechanism | WalletMechanism<string, `0x${string}`>;
82
+ export type FullfilledMechanism = AuthMechanism | WalletMechanism<string, `0x${string}`>;
77
83
 
78
84
  export type TargetStep = 'WalletConnected' | 'SignedIn';
79
85
 
@@ -104,7 +110,7 @@ type WalletConnected<WalletProviderType> = {
104
110
  type SignedIn<WalletProviderType> =
105
111
  | {
106
112
  step: 'SignedIn';
107
- mechanism: AlchemyMechanism;
113
+ mechanism: AuthMechanism;
108
114
  account: OriginAccount;
109
115
  wallet: undefined;
110
116
  }
@@ -139,7 +145,7 @@ export type Connection<WalletProviderType> = {
139
145
  step: 'PopupLaunched';
140
146
  wallet: undefined;
141
147
  popupClosed: boolean;
142
- mechanism: AlchemyMechanism;
148
+ mechanism: AuthMechanism;
143
149
  }
144
150
  // If the user has chosen to use web3-wallet there might be multi-choice for it
145
151
  | {
@@ -255,8 +261,39 @@ export type ConnectOptions = {
255
261
 
256
262
  export type EnsureConnectedOptions = ConnectOptions & {
257
263
  skipChainCheck?: boolean; // Skip chain validation for WalletConnected step
264
+ // Initiate a connection attempt even when the flow is at rest on a picker step.
265
+ // Only use it when you know no picker is on screen: it connects with the given (or default) mechanism
266
+ // instead of waiting for the user's choice.
267
+ forceConnect?: boolean;
258
268
  };
259
269
 
270
+ // Error thrown by `ensureConnected` when a connection attempt ends without reaching the target step.
271
+ // `cause` (and the convenience `code` copied from it) is the underlying error reported by the wallet,
272
+ // so callers can distinguish a user rejection (EIP-1193 code 4001) from a genuine failure.
273
+ export class ConnectionFailure extends Error {
274
+ name = 'ConnectionFailure';
275
+ readonly code?: unknown;
276
+ constructor(message: string, cause?: unknown) {
277
+ super(message);
278
+ this.cause = cause;
279
+ this.code = (cause as {code?: unknown} | undefined)?.code;
280
+ }
281
+ }
282
+
283
+ // Steps where a connection attempt is actively in progress: reaching one of them means an attempt started,
284
+ // and staying in one means we should keep waiting.
285
+ const stepsInProgress: readonly string[] = [
286
+ 'FetchingWallets',
287
+ 'WaitingForWalletConnection',
288
+ 'ChooseWalletAccount',
289
+ 'PopupLaunched',
290
+ 'WaitingForSignature',
291
+ ];
292
+ // Steps where the flow is at rest, waiting for a brand new user decision.
293
+ // Note these are also the steps `ensureConnected` is commonly called from (the picker is showing),
294
+ // so being in one of them is NOT a failure by itself: only a transition back into one after an attempt started is.
295
+ const stepsAtRest: readonly string[] = ['Idle', 'MechanismToChoose', 'WalletToChoose'];
296
+
260
297
  export type ConnectionStore<
261
298
  WalletProviderType,
262
299
  Target extends TargetStep = 'SignedIn',
@@ -392,6 +429,7 @@ export function createConnection<WalletProviderType>(settings: {
392
429
  useCurrentAccount?: 'always' | 'whenSingle' | false;
393
430
  prioritizeWalletProvider?: boolean;
394
431
  requestsPerSecond?: number;
432
+ domainRedirectBridge?: boolean;
395
433
  }): ConnectionStore<WalletProviderType, 'SignedIn', true>;
396
434
 
397
435
  // SignedIn target with walletOnly: true (default Ethereum connector) - walletHost optional
@@ -408,6 +446,7 @@ export function createConnection(settings: {
408
446
  useCurrentAccount?: 'always' | 'whenSingle' | false;
409
447
  prioritizeWalletProvider?: boolean;
410
448
  requestsPerSecond?: number;
449
+ domainRedirectBridge?: boolean;
411
450
  }): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', true>;
412
451
 
413
452
  // SignedIn target (explicit) with custom wallet connector - walletHost required
@@ -424,6 +463,7 @@ export function createConnection<WalletProviderType>(settings: {
424
463
  useCurrentAccount?: 'always' | 'whenSingle' | false;
425
464
  prioritizeWalletProvider?: boolean;
426
465
  requestsPerSecond?: number;
466
+ domainRedirectBridge?: boolean;
427
467
  }): ConnectionStore<WalletProviderType, 'SignedIn', false>;
428
468
 
429
469
  // SignedIn target (default) with default Ethereum connector - walletHost required
@@ -440,6 +480,7 @@ export function createConnection(settings: {
440
480
  useCurrentAccount?: 'always' | 'whenSingle' | false;
441
481
  prioritizeWalletProvider?: boolean;
442
482
  requestsPerSecond?: number;
483
+ domainRedirectBridge?: boolean;
443
484
  }): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', false>;
444
485
 
445
486
  // Implementation signature
@@ -456,6 +497,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
456
497
  chainInfo: ChainInfo<WalletProviderType>;
457
498
  prioritizeWalletProvider?: boolean;
458
499
  requestsPerSecond?: number;
500
+ // opt-in: enable the Same-Origin Callback Bridge (domain-redirect fallback)
501
+ // for the oauth-redirection flow. Requires hosting `_etherplay_accounts.html`
502
+ // on the parent origin.
503
+ domainRedirectBridge?: boolean;
459
504
  }): ConnectionStore<WalletProviderType, TargetStep, boolean> {
460
505
  function originToSignWith() {
461
506
  return settings.signingOrigin || origin;
@@ -494,6 +539,9 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
494
539
  // Determine target step (defaults to 'SignedIn')
495
540
  const targetStep: TargetStep = settings.targetStep || 'SignedIn';
496
541
 
542
+ // Determine walletOnly (defaults to false, but true implies WalletConnected target behavior for mechanism)
543
+ const walletOnly = settings.walletOnly || targetStep === 'WalletConnected';
544
+
497
545
  let autoConnect = true;
498
546
  if (typeof settings.autoConnect !== 'undefined') {
499
547
  autoConnect = settings.autoConnect;
@@ -511,6 +559,29 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
511
559
  _store.set($connection);
512
560
  return $connection;
513
561
  }
562
+ // Where the flow comes to rest when a connection attempt fails.
563
+ //
564
+ // The rule: rest on the step that offers the user a real next decision, and never on a step this app has
565
+ // no reason to render. In wallet-only mode the mechanism picker is never shown (`connect` always defaults
566
+ // the mechanism to `{type: 'wallet'}`), so resting on `MechanismToChoose` there is a dead end: the app
567
+ // renders nothing and the user can neither retry nor cancel.
568
+ // - not wallet-only: `MechanismToChoose`, the user can pick another mechanism.
569
+ // - wallet-only with several wallets detected: `WalletToChoose`, the user can pick another wallet.
570
+ // - wallet-only with a single (or no) wallet: `Idle`, there is no choice left to offer.
571
+ // The error is always kept, since the UI uses it to explain the failure next to the picker.
572
+ //
573
+ // Auto-connect failures follow the same rule and rest on `Idle`: the user asked for nothing, so there is
574
+ // no decision to offer them. A cancelled popup is likewise a cancellation, not a failure, and rests on `Idle`.
575
+ function setConnectionFailure(error: {message: string; cause?: any}) {
576
+ const wallets = $connection.wallets;
577
+ if (!walletOnly) {
578
+ set({step: 'MechanismToChoose', wallets, wallet: undefined, error});
579
+ } else if (wallets.length > 1) {
580
+ set({step: 'WalletToChoose', mechanism: {type: 'wallet'}, wallets, wallet: undefined, error});
581
+ } else {
582
+ set({step: 'Idle', loading: false, wallets, wallet: undefined, error});
583
+ }
584
+ }
514
585
  function setError(error: {message: string; cause?: any}) {
515
586
  if ($connection) {
516
587
  set({
@@ -568,7 +639,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
568
639
  if (existingAccount && existingAccount.signer) {
569
640
  autoConnectHandled = true;
570
641
  const mechanismUsed = existingAccount.mechanismUsed as
571
- | AlchemyMechanism
642
+ | AuthMechanism
572
643
  | WalletMechanism<string, `0x${string}`>;
573
644
  if (mechanismUsed.type == 'wallet') {
574
645
  const walletMechanism = mechanismUsed as WalletMechanism<string, `0x${string}`>;
@@ -1082,12 +1153,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1082
1153
  watchForAccountChange(_wallet.provider);
1083
1154
  }
1084
1155
  } else {
1085
- set({
1086
- step: 'MechanismToChoose',
1087
- wallets: $connection.wallets,
1088
- wallet: undefined,
1089
- error: {message: 'could not get any accounts'},
1090
- });
1156
+ setConnectionFailure({message: 'could not get any accounts'});
1091
1157
  }
1092
1158
  } else {
1093
1159
  let account = accounts[0];
@@ -1159,21 +1225,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1159
1225
  }
1160
1226
  }
1161
1227
  } catch (err) {
1162
- set({
1163
- step: 'MechanismToChoose',
1164
- wallets: $connection.wallets,
1165
- wallet: undefined,
1166
- error: {message: `failed to connect to wallet`, cause: err},
1167
- });
1228
+ setConnectionFailure({message: `failed to connect to wallet`, cause: err});
1168
1229
  }
1169
1230
  } else {
1170
1231
  console.error(`failed to get wallet ${walletName}`, $connection.wallets);
1171
- set({
1172
- step: 'MechanismToChoose',
1173
- wallets: $connection.wallets,
1174
- wallet: undefined,
1175
- error: {message: `failed to get wallet ${walletName}`},
1176
- });
1232
+ setConnectionFailure({message: `failed to get wallet ${walletName}`});
1177
1233
  }
1178
1234
  } else {
1179
1235
  // TODO can also be done automatically before hand
@@ -1194,9 +1250,31 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1194
1250
  if (!settings.walletHost) {
1195
1251
  throw new Error('walletHost is required for popup-based authentication (email, oauth, mnemonic)');
1196
1252
  }
1253
+ // Same-Origin Callback Bridge (domain-redirect fallback): only relevant
1254
+ // for the oauth-redirection flow, where the opener can be severed by COOP.
1255
+ let decryptKeyPair: CryptoKeyPair | undefined;
1256
+ let domainRedirectPublicKeyB64: string | undefined;
1257
+ const isOauthRedirection = mechanism.type === 'oauth' && !mechanism.usePopup;
1258
+ if (
1259
+ settings.domainRedirectBridge &&
1260
+ isOauthRedirection &&
1261
+ typeof window !== 'undefined' &&
1262
+ window.crypto?.subtle
1263
+ ) {
1264
+ try {
1265
+ decryptKeyPair = await generateEcdhKeyPair();
1266
+ domainRedirectPublicKeyB64 = await exportPublicKeyB64(decryptKeyPair.publicKey);
1267
+ } catch (err) {
1268
+ console.error('failed to set up domain-redirect bridge', err);
1269
+ decryptKeyPair = undefined;
1270
+ domainRedirectPublicKeyB64 = undefined;
1271
+ }
1272
+ }
1197
1273
  popup = connectViaPopup({
1198
1274
  mechanism,
1199
1275
  walletHost: settings.walletHost,
1276
+ decryptKeyPair,
1277
+ domainRedirectPublicKeyB64,
1200
1278
  });
1201
1279
  set({
1202
1280
  step: 'PopupLaunched',
@@ -1245,6 +1323,19 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1245
1323
  }
1246
1324
  }
1247
1325
 
1326
+ /**
1327
+ * Resolve once the flow reaches `step`, initiating a connection attempt when needed.
1328
+ *
1329
+ * It never sits doing nothing: it either initiates an attempt, resolves, or rejects with
1330
+ * a `ConnectionFailure` (whose `cause`/`code` carry the underlying wallet error, so a user
1331
+ * rejection shows up as EIP-1193 code 4001).
1332
+ *
1333
+ * It initiates from `Idle`, and from a picker step (`MechanismToChoose`, `WalletToChoose`) that still
1334
+ * carries the error of a previous failed attempt, which is what makes a retry after a rejected wallet
1335
+ * prompt work. It deliberately does NOT initiate from a picker step without an error: that means the
1336
+ * user is mid-choice with the picker on screen, and connecting there would hijack their choice. In that
1337
+ * case it waits for the user to pick (or cancel). Pass `{forceConnect: true}` to connect anyway.
1338
+ */
1248
1339
  // ensureConnected overloads - the default step depends on targetStep
1249
1340
  function ensureConnected(
1250
1341
  options?: EnsureConnectedOptions,
@@ -1301,6 +1392,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1301
1392
  (resolve, reject) => {
1302
1393
  let forceConnect = false;
1303
1394
 
1395
+ // The error (if any) already sitting in the store before we start.
1396
+ // Only an error that appears after this point tells us that *our* attempt failed.
1397
+ const errorOnEntry = $connection.error;
1398
+
1304
1399
  // Helper to check if resolution conditions are met
1305
1400
  const canResolve = (connection: Connection<WalletProviderType>): boolean => {
1306
1401
  // Must be at the target step
@@ -1329,24 +1424,76 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1329
1424
  return;
1330
1425
  }
1331
1426
  let idlePassed = $connection.step != 'Idle';
1332
- if (!idlePassed || forceConnect) {
1427
+
1428
+ // Initiating from a picker step is only safe when we can tell it apart from "the user is choosing
1429
+ // right now": a picker still carrying the error of a previous attempt means that attempt failed and
1430
+ // nothing has driven the flow since, so re-initiating is exactly what the caller asked for. It cannot
1431
+ // hijack a choice either: when a choice is genuinely needed, `connect` with a default mechanism just
1432
+ // re-enters the same picker (and clears the stale error), and we keep waiting for the user.
1433
+ const retryingAfterFailure = idlePassed && stepsAtRest.includes($connection.step) && !!errorOnEntry;
1434
+ if (!idlePassed || forceConnect || opts?.forceConnect || retryingAfterFailure) {
1333
1435
  connect(mechanism, opts);
1334
1436
  }
1335
- const unsubscribe = _store.subscribe((connection) => {
1336
- // Reject on disconnect/back to Idle
1337
- if (connection.step === 'Idle' && idlePassed) {
1338
- unsubscribe();
1339
- reject(new Error('Connection cancelled'));
1437
+
1438
+ // An attempt is considered started once we observe a step where the connection is in progress.
1439
+ // Falling back to a resting step from there means the attempt ended without reaching the target.
1440
+ let attemptStarted = false;
1441
+ let settled = false;
1442
+ let unsubscribe: (() => void) | undefined;
1443
+ const settle = (perform: () => void) => {
1444
+ if (settled) {
1445
+ return;
1446
+ }
1447
+ settled = true;
1448
+ // unsubscribe can still be undefined here if the store settles during the initial (synchronous) subscription
1449
+ unsubscribe?.();
1450
+ perform();
1451
+ };
1452
+
1453
+ unsubscribe = _store.subscribe((connection) => {
1454
+ if (settled) {
1455
+ return;
1340
1456
  }
1341
1457
  if (!idlePassed && connection.step !== 'Idle') {
1342
1458
  idlePassed = true;
1343
1459
  }
1344
1460
  // Check full resolution conditions including chain validity
1345
1461
  if (canResolve(connection)) {
1346
- unsubscribe();
1347
- resolve(connection as any);
1462
+ settle(() => resolve(connection as any));
1463
+ return;
1464
+ }
1465
+
1466
+ if (stepsInProgress.includes(connection.step)) {
1467
+ // still going, nothing to decide yet
1468
+ attemptStarted = true;
1469
+ return;
1470
+ }
1471
+
1472
+ // A fresh error means the attempt failed (rejected wallet prompt, no accounts, unusable wallet, ...).
1473
+ // The failure handlers set it at the very moment they fall back to a resting step, which can be `Idle`,
1474
+ // so this is checked before the cancellation case below to report the actual cause rather than
1475
+ // a generic cancellation.
1476
+ const error = connection.error;
1477
+ if (error && error !== errorOnEntry) {
1478
+ settle(() => reject(new ConnectionFailure(error.message, error.cause)));
1479
+ return;
1480
+ }
1481
+
1482
+ // Reject on disconnect/back to Idle
1483
+ if (connection.step === 'Idle' && idlePassed) {
1484
+ settle(() => reject(new ConnectionFailure('Connection cancelled')));
1485
+ return;
1486
+ }
1487
+
1488
+ // The attempt went back to a resting step without an error: it was aborted (back/cancel).
1489
+ // This must never trigger on a resting step we merely started from, hence `attemptStarted`.
1490
+ if (attemptStarted && stepsAtRest.includes(connection.step)) {
1491
+ settle(() => reject(new ConnectionFailure('Connection cancelled')));
1348
1492
  }
1349
1493
  });
1494
+ if (settled) {
1495
+ unsubscribe();
1496
+ }
1350
1497
  },
1351
1498
  );
1352
1499
 
@@ -1387,6 +1534,17 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1387
1534
  function connectViaPopup(popupSettings: PopupSettings) {
1388
1535
  let popupURL = new URL(`${popupSettings.walletHost}/login/`);
1389
1536
  let fullWindow = false;
1537
+
1538
+ // Same-Origin Callback Bridge (domain-redirect fallback): the parent's public
1539
+ // key is carried through the redirect chain as a query param so it survives
1540
+ // the full-page OAuth round-trip.
1541
+ if (popupSettings.domainRedirectPublicKeyB64) {
1542
+ popupURL.searchParams.append('domain-redirect-public-key', popupSettings.domainRedirectPublicKeyB64);
1543
+ }
1544
+
1545
+ const authProvider = (import.meta as any).env?.VITE_AUTH_PROVIDER || 'openfort';
1546
+ popupURL.searchParams.append('provider', authProvider);
1547
+
1390
1548
  if (popupSettings.mechanism.type === 'mnemonic') {
1391
1549
  popupURL.searchParams.append('type', 'mnemonic');
1392
1550
  } else if (popupSettings.mechanism.type === 'email') {
@@ -1400,7 +1558,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1400
1558
  } else if (popupSettings.mechanism.type === 'oauth') {
1401
1559
  popupURL.searchParams.append('type', 'oauth');
1402
1560
 
1403
- if (popupSettings.mechanism.provider.id === 'auth0') {
1561
+ if ('connection' in popupSettings.mechanism.provider) {
1404
1562
  popupURL.searchParams.append('oauth-provider', popupSettings.mechanism.provider.id);
1405
1563
  popupURL.searchParams.append('oauth-connection', popupSettings.mechanism.provider.connection);
1406
1564
  } else {
@@ -1440,6 +1598,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1440
1598
  if (currentURL.searchParams.has('log')) {
1441
1599
  entriesToAdd.push(['log', currentURL.searchParams.get('log') || '']);
1442
1600
  }
1601
+ // Testing aid for the domain-redirect bridge: forces the BroadcastChannel
1602
+ // delivery path on the bridge page (skips window.opener.postMessage).
1603
+ if (currentURL.searchParams.has('forceBroadcastChannel')) {
1604
+ entriesToAdd.push(['forceBroadcastChannel', currentURL.searchParams.get('forceBroadcastChannel') || '']);
1605
+ }
1443
1606
 
1444
1607
  if (settings.signingOrigin) {
1445
1608
  entriesToAdd.push(['signingOrigin', settings.signingOrigin]);
@@ -1448,7 +1611,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1448
1611
  for (const entryToAdd of entriesToAdd) {
1449
1612
  popupURL.searchParams.append(entryToAdd[0], entryToAdd[1]);
1450
1613
  }
1451
- return popupLauncher.launchPopup(popupURL.toString(), {fullWindow});
1614
+ return popupLauncher.launchPopup(popupURL.toString(), {
1615
+ fullWindow,
1616
+ decryptKeyPair: popupSettings.decryptKeyPair,
1617
+ });
1452
1618
  }
1453
1619
 
1454
1620
  function cancel() {
@@ -1653,9 +1819,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1653
1819
  }
1654
1820
  }
1655
1821
 
1656
- // Determine walletOnly (defaults to false, but true implies WalletConnected target behavior for mechanism)
1657
- const walletOnly = settings.walletOnly || targetStep === 'WalletConnected';
1658
-
1659
1822
  // Method on the store to check if target step is reached
1660
1823
  function storeIsTargetStepReached(connection: Connection<WalletProviderType>): boolean {
1661
1824
  if (targetStep === 'WalletConnected') {
package/src/popup.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {writable, type Readable} from 'svelte/store';
2
2
  import {createStorePromise} from './utils.js';
3
+ import {importPublicKeyB64, deriveAesKey, b64ToBuf} from '@etherplay/connect-core';
3
4
 
4
5
  export type Error = {
5
6
  message: string;
@@ -28,7 +29,7 @@ export function createPopupLauncher<T>() {
28
29
 
29
30
  function launchPopup(
30
31
  url: string,
31
- options?: {fullWindow?: boolean},
32
+ options?: {fullWindow?: boolean; decryptKeyPair?: CryptoKeyPair},
32
33
  ): Promise<T> & Readable<Popup> & {cancel: () => void} {
33
34
  const urlObject = new URL(url);
34
35
  const expectedOrigin = `${urlObject.protocol}//${urlObject.host}`;
@@ -67,10 +68,23 @@ export function createPopupLauncher<T>() {
67
68
  let _resolveRecovery: (state: T) => void;
68
69
  let _rejectRecovery: (error: Error) => void;
69
70
 
71
+ // Same-Origin Callback Bridge: the encrypted result may arrive on a
72
+ // BroadcastChannel (from the bridge page running on our own origin).
73
+ let channel: BroadcastChannel | undefined;
74
+ let handled = false; // de-dupe: the same result may arrive on both transports
75
+
76
+ function closeChannel() {
77
+ try {
78
+ channel?.close();
79
+ } catch (e) {}
80
+ channel = undefined;
81
+ }
82
+
70
83
  function resolveRecovery(state: T) {
71
84
  currentPopup = {popup: undefined};
72
85
  console.log(`stop listening to message as we resolved it`);
73
86
  window.removeEventListener('message', onMessage);
87
+ closeChannel();
74
88
 
75
89
  if (_resolveRecovery) {
76
90
  set({
@@ -86,6 +100,7 @@ export function createPopupLauncher<T>() {
86
100
  currentPopup = {popup: undefined};
87
101
  console.log(`stop listening to message as we rejected it`, error);
88
102
  window.removeEventListener('message', onMessage);
103
+ closeChannel();
89
104
  if (_rejectRecovery) {
90
105
  set({
91
106
  closed: true,
@@ -100,10 +115,59 @@ export function createPopupLauncher<T>() {
100
115
  }
101
116
  }
102
117
 
118
+ // Handles the encrypted `domain-redirect-result` package coming from the
119
+ // bridge page (`_etherplay_accounts.html`). It can arrive via the window
120
+ // `message` listener (window.opener.postMessage) OR via BroadcastChannel.
121
+ async function handleEncryptedResult(
122
+ d: any,
123
+ transport: 'window message' | 'BroadcastChannel',
124
+ source?: MessageEventSource | null,
125
+ ) {
126
+ if (!d || d.type !== 'domain-redirect-result') return;
127
+ // loose compare: `id` is a number here but arrives as a string
128
+ if (id != d.id) return;
129
+ if (handled) {
130
+ console.log(`[domain-redirect] duplicate result via ${transport} ignored (already handled)`);
131
+ return;
132
+ }
133
+ if (!options?.decryptKeyPair) return;
134
+ handled = true;
135
+ console.log(`[domain-redirect] result delivered via ${transport}`);
136
+ try {
137
+ const popupPub = await importPublicKeyB64(d.ephemeralPublicKey);
138
+ const aesKey = await deriveAesKey(options.decryptKeyPair.privateKey, popupPub, ['decrypt']);
139
+ const plain = await window.crypto.subtle.decrypt(
140
+ {name: 'AES-GCM', iv: b64ToBuf(d.iv)},
141
+ aesKey,
142
+ b64ToBuf(d.encryptedResult),
143
+ );
144
+ const result = JSON.parse(new TextDecoder().decode(plain));
145
+ // ACK so the bridge page can close itself cleanly (sent on both transports)
146
+ try {
147
+ channel?.postMessage({type: 'ack', id: d.id});
148
+ } catch (e) {}
149
+ try {
150
+ (source as any)?.postMessage({type: 'ack', id: d.id}, window.origin);
151
+ } catch (e) {}
152
+ resolveRecovery(result);
153
+ } catch (err) {
154
+ rejectRecovery({message: 'domain-redirect decryption failed', cause: err});
155
+ }
156
+ }
157
+
103
158
  const onMessage = (messageEvent: MessageEvent) => {
159
+ const data = messageEvent.data;
160
+ if (data && data.type === 'domain-redirect-result') {
161
+ // The bridge page posts from the parent's OWN origin, so accept both
162
+ // the expected popup origin AND our own origin. The encrypted payload
163
+ // + id match are the real authentication.
164
+ if (messageEvent.origin === expectedOrigin || messageEvent.origin === window.origin) {
165
+ handleEncryptedResult(data, 'window message', messageEvent.source);
166
+ }
167
+ return;
168
+ }
104
169
  if (messageEvent.origin === expectedOrigin) {
105
170
  console.log(messageEvent);
106
- const data = messageEvent.data;
107
171
  if (id == data.id) {
108
172
  if (data.error) {
109
173
  console.error(`ERROR`, data.error);
@@ -192,6 +256,14 @@ export function createPopupLauncher<T>() {
192
256
  currentPopup = {popup, onMessage, rejectRecovery: _rejectRecovery};
193
257
  console.log(`listening to message... ${id}`);
194
258
  window.addEventListener('message', currentPopup.onMessage);
259
+
260
+ // Same-Origin Callback Bridge: listen on BroadcastChannel for the
261
+ // encrypted result when the opener relationship was severed.
262
+ if (options?.decryptKeyPair && typeof BroadcastChannel !== 'undefined') {
263
+ channel = new BroadcastChannel('etherplay-connect');
264
+ channel.onmessage = (event) => handleEncryptedResult(event.data, 'BroadcastChannel');
265
+ }
266
+
195
267
  watchForPopupClosed(popup);
196
268
  // continuouslyPingPopup(popup);
197
269
  },
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=index.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}