@etherplay/connect 0.0.50 → 0.1.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/dist/popup.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { writable } from 'svelte/store';
2
2
  import { createStorePromise } from './utils.js';
3
+ import { importPublicKeyB64, deriveAesKey, b64ToBuf } from '@etherplay/connect-core';
3
4
  export function createPopupLauncher() {
4
5
  let id = 1;
5
6
  let currentPopup = { popup: undefined };
@@ -39,10 +40,22 @@ export function createPopupLauncher() {
39
40
  }
40
41
  let _resolveRecovery;
41
42
  let _rejectRecovery;
43
+ // Same-Origin Callback Bridge: the encrypted result may arrive on a
44
+ // BroadcastChannel (from the bridge page running on our own origin).
45
+ let channel;
46
+ let handled = false; // de-dupe: the same result may arrive on both transports
47
+ function closeChannel() {
48
+ try {
49
+ channel?.close();
50
+ }
51
+ catch (e) { }
52
+ channel = undefined;
53
+ }
42
54
  function resolveRecovery(state) {
43
55
  currentPopup = { popup: undefined };
44
56
  console.log(`stop listening to message as we resolved it`);
45
57
  window.removeEventListener('message', onMessage);
58
+ closeChannel();
46
59
  if (_resolveRecovery) {
47
60
  set({
48
61
  closed: true,
@@ -56,6 +69,7 @@ export function createPopupLauncher() {
56
69
  currentPopup = { popup: undefined };
57
70
  console.log(`stop listening to message as we rejected it`, error);
58
71
  window.removeEventListener('message', onMessage);
72
+ closeChannel();
59
73
  if (_rejectRecovery) {
60
74
  set({
61
75
  closed: true,
@@ -69,10 +83,56 @@ export function createPopupLauncher() {
69
83
  _rejectRecovery(error);
70
84
  }
71
85
  }
86
+ // Handles the encrypted `domain-redirect-result` package coming from the
87
+ // bridge page (`_etherplay_accounts.html`). It can arrive via the window
88
+ // `message` listener (window.opener.postMessage) OR via BroadcastChannel.
89
+ async function handleEncryptedResult(d, transport, source) {
90
+ if (!d || d.type !== 'domain-redirect-result')
91
+ return;
92
+ // loose compare: `id` is a number here but arrives as a string
93
+ if (id != d.id)
94
+ return;
95
+ if (handled) {
96
+ console.log(`[domain-redirect] duplicate result via ${transport} ignored (already handled)`);
97
+ return;
98
+ }
99
+ if (!options?.decryptKeyPair)
100
+ return;
101
+ handled = true;
102
+ console.log(`[domain-redirect] result delivered via ${transport}`);
103
+ try {
104
+ const popupPub = await importPublicKeyB64(d.ephemeralPublicKey);
105
+ const aesKey = await deriveAesKey(options.decryptKeyPair.privateKey, popupPub, ['decrypt']);
106
+ const plain = await window.crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64ToBuf(d.iv) }, aesKey, b64ToBuf(d.encryptedResult));
107
+ const result = JSON.parse(new TextDecoder().decode(plain));
108
+ // ACK so the bridge page can close itself cleanly (sent on both transports)
109
+ try {
110
+ channel?.postMessage({ type: 'ack', id: d.id });
111
+ }
112
+ catch (e) { }
113
+ try {
114
+ source?.postMessage({ type: 'ack', id: d.id }, window.origin);
115
+ }
116
+ catch (e) { }
117
+ resolveRecovery(result);
118
+ }
119
+ catch (err) {
120
+ rejectRecovery({ message: 'domain-redirect decryption failed', cause: err });
121
+ }
122
+ }
72
123
  const onMessage = (messageEvent) => {
124
+ const data = messageEvent.data;
125
+ if (data && data.type === 'domain-redirect-result') {
126
+ // The bridge page posts from the parent's OWN origin, so accept both
127
+ // the expected popup origin AND our own origin. The encrypted payload
128
+ // + id match are the real authentication.
129
+ if (messageEvent.origin === expectedOrigin || messageEvent.origin === window.origin) {
130
+ handleEncryptedResult(data, 'window message', messageEvent.source);
131
+ }
132
+ return;
133
+ }
73
134
  if (messageEvent.origin === expectedOrigin) {
74
135
  console.log(messageEvent);
75
- const data = messageEvent.data;
76
136
  if (id == data.id) {
77
137
  if (data.error) {
78
138
  console.error(`ERROR`, data.error);
@@ -156,6 +216,12 @@ export function createPopupLauncher() {
156
216
  currentPopup = { popup, onMessage, rejectRecovery: _rejectRecovery };
157
217
  console.log(`listening to message... ${id}`);
158
218
  window.addEventListener('message', currentPopup.onMessage);
219
+ // Same-Origin Callback Bridge: listen on BroadcastChannel for the
220
+ // encrypted result when the opener relationship was severed.
221
+ if (options?.decryptKeyPair && typeof BroadcastChannel !== 'undefined') {
222
+ channel = new BroadcastChannel('etherplay-connect');
223
+ channel.onmessage = (event) => handleEncryptedResult(event.data, 'BroadcastChannel');
224
+ }
159
225
  watchForPopupClosed(popup);
160
226
  // continuouslyPingPopup(popup);
161
227
  });
package/dist/popup.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"popup.js","sourceRoot":"","sources":["../src/popup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAgB,MAAM,cAAc,CAAC;AACrD,OAAO,EAAC,kBAAkB,EAAC,MAAM,YAAY,CAAC;AAiB9C,MAAM,UAAU,mBAAmB;IAClC,IAAI,EAAE,GAAG,CAAC,CAAC;IACX,IAAI,YAAY,GAMQ,EAAC,KAAK,EAAE,SAAS,EAAC,CAAC;IAE3C,SAAS,WAAW,CACnB,GAAW,EACX,OAAgC;QAEhC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,cAAc,GAAG,GAAG,SAAS,CAAC,QAAQ,KAAK,SAAS,CAAC,IAAI,EAAE,CAAC;QAClE,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC;QAEpC,IAAI,MAAM,GAAU;YACnB,MAAM,EAAE,KAAK;YACb,QAAQ,EAAE,KAAK;YACf,QAAQ,EAAE,KAAK;SACf,CAAC;QACF,MAAM,MAAM,GAAG,QAAQ,CAAQ,MAAM,CAAC,CAAC;QACvC,SAAS,GAAG,CAAC,KAAY;YACxB,MAAM,GAAG,KAAK,CAAC;YACf,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACnB,CAAC;QAED,IAAI,YAAY,CAAC,KAAK,EAAE,CAAC;YACxB,OAAO,CAAC,GAAG,CAAC,0CAA0C,CAAC,CAAC;YACxD,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,YAAY,CAAC,SAAS,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AAE,YAAY,CAAC,SAAS,CAAC,CAAC;YAE3D,kEAAkE;YAClE,6DAA6D;YAC7D,IAAI,OAAO,EAAE,cAAc,IAAI,OAAO,gBAAgB,KAAK,WAAW,EAAE,CAAC;gBACxE,OAAO,GAAG,IAAI,gBAAgB,CAAC,mBAAmB,CAAC,CAAC;gBACpD,OAAO,CAAC,SAAS,GAAG,CAAC,KAAK,EAAE,EAAE,CAAC,qBAAqB,CAAC,KAAK,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAC;YACtF,CAAC;YAED,mBAAmB,CAAC,KAAK,CAAC,CAAC;YAC3B,gCAAgC;QACjC,CAAC,CACD,CAAC;QAEF,OAAO,YAAY,CAAC;IACrB,CAAC;IAED,OAAO,EAAC,WAAW,EAAC,CAAC;AACtB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@etherplay/connect",
3
- "version": "0.0.50",
3
+ "version": "0.1.0",
4
4
  "description": "Main connection library for Etherplay Accounts - provides seamless wallet and social authentication with session account management",
5
5
  "keywords": [
6
6
  "web3",
@@ -44,7 +44,7 @@
44
44
  "src"
45
45
  ],
46
46
  "dependencies": {
47
- "@etherplay/connect-core": "0.0.0",
47
+ "@etherplay/connect-core": "0.1.0",
48
48
  "@etherplay/wallet-connector": "0.0.5",
49
49
  "@etherplay/wallet-connector-ethereum": "0.0.11"
50
50
  },
package/src/crypto.ts ADDED
@@ -0,0 +1,11 @@
1
+ // Zero-dependency Web Crypto helpers for the Same-Origin Callback Bridge
2
+ // (domain-redirect fallback). Implementation lives in @etherplay/connect-core
3
+ // so it can be shared with the login app; re-exported here per plan conventions.
4
+ export {
5
+ bufToB64,
6
+ b64ToBuf,
7
+ generateEcdhKeyPair,
8
+ exportPublicKeyB64,
9
+ importPublicKeyB64,
10
+ deriveAesKey,
11
+ } from '@etherplay/connect-core';
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
  | {
@@ -257,6 +263,33 @@ export type EnsureConnectedOptions = ConnectOptions & {
257
263
  skipChainCheck?: boolean; // Skip chain validation for WalletConnected step
258
264
  };
259
265
 
266
+ // Error thrown by `ensureConnected` when a connection attempt ends without reaching the target step.
267
+ // `cause` (and the convenience `code` copied from it) is the underlying error reported by the wallet,
268
+ // so callers can distinguish a user rejection (EIP-1193 code 4001) from a genuine failure.
269
+ export class ConnectionFailure extends Error {
270
+ name = 'ConnectionFailure';
271
+ readonly code?: unknown;
272
+ constructor(message: string, cause?: unknown) {
273
+ super(message);
274
+ this.cause = cause;
275
+ this.code = (cause as {code?: unknown} | undefined)?.code;
276
+ }
277
+ }
278
+
279
+ // Steps where a connection attempt is actively in progress: reaching one of them means an attempt started,
280
+ // and staying in one means we should keep waiting.
281
+ const stepsInProgress: readonly string[] = [
282
+ 'FetchingWallets',
283
+ 'WaitingForWalletConnection',
284
+ 'ChooseWalletAccount',
285
+ 'PopupLaunched',
286
+ 'WaitingForSignature',
287
+ ];
288
+ // Steps where the flow is at rest, waiting for a brand new user decision.
289
+ // Note these are also the steps `ensureConnected` is commonly called from (the picker is showing),
290
+ // so being in one of them is NOT a failure by itself: only a transition back into one after an attempt started is.
291
+ const stepsAtRest: readonly string[] = ['Idle', 'MechanismToChoose', 'WalletToChoose'];
292
+
260
293
  export type ConnectionStore<
261
294
  WalletProviderType,
262
295
  Target extends TargetStep = 'SignedIn',
@@ -392,6 +425,7 @@ export function createConnection<WalletProviderType>(settings: {
392
425
  useCurrentAccount?: 'always' | 'whenSingle' | false;
393
426
  prioritizeWalletProvider?: boolean;
394
427
  requestsPerSecond?: number;
428
+ domainRedirectBridge?: boolean;
395
429
  }): ConnectionStore<WalletProviderType, 'SignedIn', true>;
396
430
 
397
431
  // SignedIn target with walletOnly: true (default Ethereum connector) - walletHost optional
@@ -408,6 +442,7 @@ export function createConnection(settings: {
408
442
  useCurrentAccount?: 'always' | 'whenSingle' | false;
409
443
  prioritizeWalletProvider?: boolean;
410
444
  requestsPerSecond?: number;
445
+ domainRedirectBridge?: boolean;
411
446
  }): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', true>;
412
447
 
413
448
  // SignedIn target (explicit) with custom wallet connector - walletHost required
@@ -424,6 +459,7 @@ export function createConnection<WalletProviderType>(settings: {
424
459
  useCurrentAccount?: 'always' | 'whenSingle' | false;
425
460
  prioritizeWalletProvider?: boolean;
426
461
  requestsPerSecond?: number;
462
+ domainRedirectBridge?: boolean;
427
463
  }): ConnectionStore<WalletProviderType, 'SignedIn', false>;
428
464
 
429
465
  // SignedIn target (default) with default Ethereum connector - walletHost required
@@ -440,6 +476,7 @@ export function createConnection(settings: {
440
476
  useCurrentAccount?: 'always' | 'whenSingle' | false;
441
477
  prioritizeWalletProvider?: boolean;
442
478
  requestsPerSecond?: number;
479
+ domainRedirectBridge?: boolean;
443
480
  }): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', false>;
444
481
 
445
482
  // Implementation signature
@@ -456,6 +493,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
456
493
  chainInfo: ChainInfo<WalletProviderType>;
457
494
  prioritizeWalletProvider?: boolean;
458
495
  requestsPerSecond?: number;
496
+ // opt-in: enable the Same-Origin Callback Bridge (domain-redirect fallback)
497
+ // for the oauth-redirection flow. Requires hosting `_etherplay_accounts.html`
498
+ // on the parent origin.
499
+ domainRedirectBridge?: boolean;
459
500
  }): ConnectionStore<WalletProviderType, TargetStep, boolean> {
460
501
  function originToSignWith() {
461
502
  return settings.signingOrigin || origin;
@@ -568,7 +609,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
568
609
  if (existingAccount && existingAccount.signer) {
569
610
  autoConnectHandled = true;
570
611
  const mechanismUsed = existingAccount.mechanismUsed as
571
- | AlchemyMechanism
612
+ | AuthMechanism
572
613
  | WalletMechanism<string, `0x${string}`>;
573
614
  if (mechanismUsed.type == 'wallet') {
574
615
  const walletMechanism = mechanismUsed as WalletMechanism<string, `0x${string}`>;
@@ -1194,9 +1235,31 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1194
1235
  if (!settings.walletHost) {
1195
1236
  throw new Error('walletHost is required for popup-based authentication (email, oauth, mnemonic)');
1196
1237
  }
1238
+ // Same-Origin Callback Bridge (domain-redirect fallback): only relevant
1239
+ // for the oauth-redirection flow, where the opener can be severed by COOP.
1240
+ let decryptKeyPair: CryptoKeyPair | undefined;
1241
+ let domainRedirectPublicKeyB64: string | undefined;
1242
+ const isOauthRedirection = mechanism.type === 'oauth' && !mechanism.usePopup;
1243
+ if (
1244
+ settings.domainRedirectBridge &&
1245
+ isOauthRedirection &&
1246
+ typeof window !== 'undefined' &&
1247
+ window.crypto?.subtle
1248
+ ) {
1249
+ try {
1250
+ decryptKeyPair = await generateEcdhKeyPair();
1251
+ domainRedirectPublicKeyB64 = await exportPublicKeyB64(decryptKeyPair.publicKey);
1252
+ } catch (err) {
1253
+ console.error('failed to set up domain-redirect bridge', err);
1254
+ decryptKeyPair = undefined;
1255
+ domainRedirectPublicKeyB64 = undefined;
1256
+ }
1257
+ }
1197
1258
  popup = connectViaPopup({
1198
1259
  mechanism,
1199
1260
  walletHost: settings.walletHost,
1261
+ decryptKeyPair,
1262
+ domainRedirectPublicKeyB64,
1200
1263
  });
1201
1264
  set({
1202
1265
  step: 'PopupLaunched',
@@ -1301,6 +1364,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1301
1364
  (resolve, reject) => {
1302
1365
  let forceConnect = false;
1303
1366
 
1367
+ // The error (if any) already sitting in the store before we start.
1368
+ // Only an error that appears after this point tells us that *our* attempt failed.
1369
+ const errorOnEntry = $connection.error;
1370
+
1304
1371
  // Helper to check if resolution conditions are met
1305
1372
  const canResolve = (connection: Connection<WalletProviderType>): boolean => {
1306
1373
  // Must be at the target step
@@ -1332,21 +1399,63 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1332
1399
  if (!idlePassed || forceConnect) {
1333
1400
  connect(mechanism, opts);
1334
1401
  }
1335
- const unsubscribe = _store.subscribe((connection) => {
1402
+
1403
+ // An attempt is considered started once we observe a step where the connection is in progress.
1404
+ // Falling back to a resting step from there means the attempt ended without reaching the target.
1405
+ let attemptStarted = false;
1406
+ let settled = false;
1407
+ let unsubscribe: (() => void) | undefined;
1408
+ const settle = (perform: () => void) => {
1409
+ if (settled) {
1410
+ return;
1411
+ }
1412
+ settled = true;
1413
+ // unsubscribe can still be undefined here if the store settles during the initial (synchronous) subscription
1414
+ unsubscribe?.();
1415
+ perform();
1416
+ };
1417
+
1418
+ unsubscribe = _store.subscribe((connection) => {
1419
+ if (settled) {
1420
+ return;
1421
+ }
1336
1422
  // Reject on disconnect/back to Idle
1337
1423
  if (connection.step === 'Idle' && idlePassed) {
1338
- unsubscribe();
1339
- reject(new Error('Connection cancelled'));
1424
+ settle(() => reject(new ConnectionFailure('Connection cancelled')));
1425
+ return;
1340
1426
  }
1341
1427
  if (!idlePassed && connection.step !== 'Idle') {
1342
1428
  idlePassed = true;
1343
1429
  }
1344
1430
  // Check full resolution conditions including chain validity
1345
1431
  if (canResolve(connection)) {
1346
- unsubscribe();
1347
- resolve(connection as any);
1432
+ settle(() => resolve(connection as any));
1433
+ return;
1434
+ }
1435
+
1436
+ if (stepsInProgress.includes(connection.step)) {
1437
+ // still going, nothing to decide yet
1438
+ attemptStarted = true;
1439
+ return;
1440
+ }
1441
+
1442
+ // A fresh error means the attempt failed (rejected wallet prompt, no accounts, unusable wallet, ...).
1443
+ // The failure handlers set it at the very moment they fall back to a non-target step.
1444
+ const error = connection.error;
1445
+ if (error && error !== errorOnEntry) {
1446
+ settle(() => reject(new ConnectionFailure(error.message, error.cause)));
1447
+ return;
1448
+ }
1449
+
1450
+ // The attempt went back to a resting step without an error: it was aborted (back/cancel).
1451
+ // This must never trigger on a resting step we merely started from, hence `attemptStarted`.
1452
+ if (attemptStarted && stepsAtRest.includes(connection.step)) {
1453
+ settle(() => reject(new ConnectionFailure('Connection cancelled')));
1348
1454
  }
1349
1455
  });
1456
+ if (settled) {
1457
+ unsubscribe();
1458
+ }
1350
1459
  },
1351
1460
  );
1352
1461
 
@@ -1387,6 +1496,17 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1387
1496
  function connectViaPopup(popupSettings: PopupSettings) {
1388
1497
  let popupURL = new URL(`${popupSettings.walletHost}/login/`);
1389
1498
  let fullWindow = false;
1499
+
1500
+ // Same-Origin Callback Bridge (domain-redirect fallback): the parent's public
1501
+ // key is carried through the redirect chain as a query param so it survives
1502
+ // the full-page OAuth round-trip.
1503
+ if (popupSettings.domainRedirectPublicKeyB64) {
1504
+ popupURL.searchParams.append('domain-redirect-public-key', popupSettings.domainRedirectPublicKeyB64);
1505
+ }
1506
+
1507
+ const authProvider = (import.meta as any).env?.VITE_AUTH_PROVIDER || 'openfort';
1508
+ popupURL.searchParams.append('provider', authProvider);
1509
+
1390
1510
  if (popupSettings.mechanism.type === 'mnemonic') {
1391
1511
  popupURL.searchParams.append('type', 'mnemonic');
1392
1512
  } else if (popupSettings.mechanism.type === 'email') {
@@ -1400,7 +1520,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1400
1520
  } else if (popupSettings.mechanism.type === 'oauth') {
1401
1521
  popupURL.searchParams.append('type', 'oauth');
1402
1522
 
1403
- if (popupSettings.mechanism.provider.id === 'auth0') {
1523
+ if ('connection' in popupSettings.mechanism.provider) {
1404
1524
  popupURL.searchParams.append('oauth-provider', popupSettings.mechanism.provider.id);
1405
1525
  popupURL.searchParams.append('oauth-connection', popupSettings.mechanism.provider.connection);
1406
1526
  } else {
@@ -1440,6 +1560,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1440
1560
  if (currentURL.searchParams.has('log')) {
1441
1561
  entriesToAdd.push(['log', currentURL.searchParams.get('log') || '']);
1442
1562
  }
1563
+ // Testing aid for the domain-redirect bridge: forces the BroadcastChannel
1564
+ // delivery path on the bridge page (skips window.opener.postMessage).
1565
+ if (currentURL.searchParams.has('forceBroadcastChannel')) {
1566
+ entriesToAdd.push(['forceBroadcastChannel', currentURL.searchParams.get('forceBroadcastChannel') || '']);
1567
+ }
1443
1568
 
1444
1569
  if (settings.signingOrigin) {
1445
1570
  entriesToAdd.push(['signingOrigin', settings.signingOrigin]);
@@ -1448,7 +1573,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1448
1573
  for (const entryToAdd of entriesToAdd) {
1449
1574
  popupURL.searchParams.append(entryToAdd[0], entryToAdd[1]);
1450
1575
  }
1451
- return popupLauncher.launchPopup(popupURL.toString(), {fullWindow});
1576
+ return popupLauncher.launchPopup(popupURL.toString(), {
1577
+ fullWindow,
1578
+ decryptKeyPair: popupSettings.decryptKeyPair,
1579
+ });
1452
1580
  }
1453
1581
 
1454
1582
  function cancel() {
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":""}