@minca/core 0.1.7 → 0.1.9

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 (154) hide show
  1. package/dist/elements/auth-styles.d.ts +1 -1
  2. package/dist/elements/auth-styles.d.ts.map +1 -1
  3. package/dist/elements/auth-styles.js +16 -8
  4. package/dist/elements/auth-styles.js.map +1 -1
  5. package/dist/elements/minca-auth.d.ts +7 -0
  6. package/dist/elements/minca-auth.d.ts.map +1 -1
  7. package/dist/elements/minca-auth.js +107 -49
  8. package/dist/elements/minca-auth.js.map +1 -1
  9. package/dist/files/file-id.d.ts +51 -0
  10. package/dist/files/file-id.d.ts.map +1 -0
  11. package/dist/files/file-id.js +97 -0
  12. package/dist/files/file-id.js.map +1 -0
  13. package/dist/files/seal.d.ts +20 -0
  14. package/dist/files/seal.d.ts.map +1 -0
  15. package/dist/files/seal.js +77 -0
  16. package/dist/files/seal.js.map +1 -0
  17. package/dist/files/space-files.d.ts +51 -0
  18. package/dist/files/space-files.d.ts.map +1 -0
  19. package/dist/files/space-files.js +476 -0
  20. package/dist/files/space-files.js.map +1 -0
  21. package/dist/index.d.ts +5 -4
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/node/api.d.ts +6 -1
  26. package/dist/node/api.d.ts.map +1 -1
  27. package/dist/node/api.js +17 -3
  28. package/dist/node/api.js.map +1 -1
  29. package/dist/node/carrier.d.ts +17 -2
  30. package/dist/node/carrier.d.ts.map +1 -1
  31. package/dist/node/carrier.js +26 -4
  32. package/dist/node/carrier.js.map +1 -1
  33. package/dist/node/copy.d.ts +0 -4
  34. package/dist/node/copy.d.ts.map +1 -1
  35. package/dist/node/copy.js +26 -0
  36. package/dist/node/copy.js.map +1 -1
  37. package/dist/node/host.d.ts +66 -1
  38. package/dist/node/host.d.ts.map +1 -1
  39. package/dist/node/host.js +571 -5
  40. package/dist/node/host.js.map +1 -1
  41. package/dist/node/index.d.ts +2 -2
  42. package/dist/node/index.d.ts.map +1 -1
  43. package/dist/node/index.js +1 -1
  44. package/dist/node/index.js.map +1 -1
  45. package/dist/node/node.d.ts.map +1 -1
  46. package/dist/node/node.js +235 -75
  47. package/dist/node/node.js.map +1 -1
  48. package/dist/node/space-runtime.d.ts +9 -0
  49. package/dist/node/space-runtime.d.ts.map +1 -1
  50. package/dist/node/space-runtime.js +125 -16
  51. package/dist/node/space-runtime.js.map +1 -1
  52. package/dist/node/stores.d.ts +44 -8
  53. package/dist/node/stores.d.ts.map +1 -1
  54. package/dist/node/stores.js +44 -7
  55. package/dist/node/stores.js.map +1 -1
  56. package/dist/node/types.d.ts +73 -6
  57. package/dist/node/types.d.ts.map +1 -1
  58. package/dist/node/usage.d.ts +54 -0
  59. package/dist/node/usage.d.ts.map +1 -0
  60. package/dist/node/usage.js +201 -0
  61. package/dist/node/usage.js.map +1 -0
  62. package/dist/node/writer-keys.d.ts +4 -1
  63. package/dist/node/writer-keys.d.ts.map +1 -1
  64. package/dist/node/writer-keys.js +25 -6
  65. package/dist/node/writer-keys.js.map +1 -1
  66. package/dist/node/writers.d.ts.map +1 -1
  67. package/dist/node/writers.js +10 -3
  68. package/dist/node/writers.js.map +1 -1
  69. package/dist/react/minca-auth.d.ts +3 -1
  70. package/dist/react/minca-auth.d.ts.map +1 -1
  71. package/dist/react/minca-auth.js +5 -3
  72. package/dist/react/minca-auth.js.map +1 -1
  73. package/dist/schema/version.d.ts +5 -0
  74. package/dist/schema/version.d.ts.map +1 -1
  75. package/dist/schema/version.js +1 -0
  76. package/dist/schema/version.js.map +1 -1
  77. package/dist/schemas/fragments.d.ts +23 -2
  78. package/dist/schemas/fragments.d.ts.map +1 -1
  79. package/dist/schemas/fragments.js +5 -2
  80. package/dist/schemas/fragments.js.map +1 -1
  81. package/dist/schemas/library/annotations.d.ts +24 -0
  82. package/dist/schemas/library/annotations.d.ts.map +1 -1
  83. package/dist/schemas/library/community.d.ts +24 -0
  84. package/dist/schemas/library/community.d.ts.map +1 -1
  85. package/dist/schemas/library/life.d.ts +72 -0
  86. package/dist/schemas/library/life.d.ts.map +1 -1
  87. package/dist/schemas/library/media.d.ts +144 -0
  88. package/dist/schemas/library/media.d.ts.map +1 -1
  89. package/dist/schemas/library/money.d.ts +24 -0
  90. package/dist/schemas/library/money.d.ts.map +1 -1
  91. package/dist/schemas/library/publishing.d.ts +96 -0
  92. package/dist/schemas/library/publishing.d.ts.map +1 -1
  93. package/dist/schemas/library/social.d.ts +72 -0
  94. package/dist/schemas/library/social.d.ts.map +1 -1
  95. package/dist/session/account-hint.d.ts +13 -0
  96. package/dist/session/account-hint.d.ts.map +1 -0
  97. package/dist/session/account-hint.js +51 -0
  98. package/dist/session/account-hint.js.map +1 -0
  99. package/dist/session/auth.d.ts +51 -3
  100. package/dist/session/auth.d.ts.map +1 -1
  101. package/dist/session/auth.js +262 -36
  102. package/dist/session/auth.js.map +1 -1
  103. package/dist/session/connect.d.ts.map +1 -1
  104. package/dist/session/connect.js +6 -2
  105. package/dist/session/connect.js.map +1 -1
  106. package/dist/session/hosting.d.ts +73 -28
  107. package/dist/session/hosting.d.ts.map +1 -1
  108. package/dist/session/hosting.js +85 -5
  109. package/dist/session/hosting.js.map +1 -1
  110. package/dist/session/index.d.ts +1 -0
  111. package/dist/session/index.d.ts.map +1 -1
  112. package/dist/session/index.js +1 -0
  113. package/dist/session/index.js.map +1 -1
  114. package/dist/session/pairing.d.ts +2 -0
  115. package/dist/session/pairing.d.ts.map +1 -1
  116. package/dist/session/pairing.js +8 -0
  117. package/dist/session/pairing.js.map +1 -1
  118. package/dist/session/places.d.ts +7 -0
  119. package/dist/session/places.d.ts.map +1 -1
  120. package/dist/session/places.js +20 -2
  121. package/dist/session/places.js.map +1 -1
  122. package/dist/space/account-registry.d.ts +13 -0
  123. package/dist/space/account-registry.d.ts.map +1 -1
  124. package/dist/space/account-registry.js +13 -0
  125. package/dist/space/account-registry.js.map +1 -1
  126. package/dist/storage/blob/directory.d.ts +14 -0
  127. package/dist/storage/blob/directory.d.ts.map +1 -0
  128. package/dist/storage/blob/directory.js +80 -0
  129. package/dist/storage/blob/directory.js.map +1 -0
  130. package/dist/storage/folder-adapter.d.ts +22 -0
  131. package/dist/storage/folder-adapter.d.ts.map +1 -1
  132. package/dist/storage/folder-adapter.js +5 -5
  133. package/dist/storage/folder-adapter.js.map +1 -1
  134. package/dist/storage/mirror.d.ts +9 -2
  135. package/dist/storage/mirror.d.ts.map +1 -1
  136. package/dist/storage/mirror.js +60 -35
  137. package/dist/storage/mirror.js.map +1 -1
  138. package/dist/storage/segment.d.ts +7 -2
  139. package/dist/storage/segment.d.ts.map +1 -1
  140. package/dist/storage/segment.js +25 -3
  141. package/dist/storage/segment.js.map +1 -1
  142. package/dist/sync/sync-engine.d.ts +2 -0
  143. package/dist/sync/sync-engine.d.ts.map +1 -1
  144. package/dist/sync/sync-engine.js +5 -0
  145. package/dist/sync/sync-engine.js.map +1 -1
  146. package/dist/sync/sync-messages.d.ts +24 -0
  147. package/dist/sync/sync-messages.d.ts.map +1 -1
  148. package/dist/sync/sync-messages.js.map +1 -1
  149. package/docs/node.md +63 -24
  150. package/docs/sign-in.md +123 -24
  151. package/docs/spaces.md +18 -10
  152. package/docs/standard-library.md +16 -20
  153. package/docs/storage.md +120 -15
  154. package/package.json +1 -1
@@ -20,7 +20,7 @@ import { base64UrlEncode } from '../utils/encoding.js';
20
20
  import { startPageNode } from '../node/worker.js';
21
21
  import { copyAccountData } from '../node/copy.js';
22
22
  import { isProtocolError, protocolError } from '../utils/errors.js';
23
- import { deleteBrowserData, forgetPod, inspectPod, listAccounts, pickPod, recallPod, rememberPod, describeStores, storesFor, } from './places.js';
23
+ import { deleteBrowserData, forgetPod, inspectPod, listAccounts, pickPod, podToReopen, recallPod, rememberPod, describeStores, storesFor, } from './places.js';
24
24
  import { createStaySignedIn, defaultStorage, guardedStorage, rememberedSessionKey, } from './stay-signed-in.js';
25
25
  import { grantTerms, GRANT_VERSION, MAX_GRANT_DAYS, checkKeyProof, requestTerms, } from './connect.js';
26
26
  import { fromProposal, proposalSpaces, sameAutomation } from '../space/own-automations.js';
@@ -114,6 +114,8 @@ async function addAutomations(node, origin, automations) {
114
114
  const EXPIRY_SWEEP_MS = 15 * 60 * 1000;
115
115
  /** How long signing out waits for its revokes to reach the peers here, at most, unless configured: offline, they wait until next time */
116
116
  const SIGN_OUT_GRACE_MS = 5000;
117
+ /** How long `confirm` lets the recovery code be read, or the account offered to a phone */
118
+ const CONFIRMED_MS = 5 * 60 * 1000;
117
119
  /** Creates the sign-in flow for this page. */
118
120
  export function createMincaAuth(config = {}) {
119
121
  const rpId = config.rpId ?? globalThis.location?.hostname ?? 'localhost';
@@ -144,8 +146,11 @@ export function createMincaAuth(config = {}) {
144
146
  folderAvailable: isFolderStorageAvailable(),
145
147
  pairing: readPairingTicket(),
146
148
  pairingStage: null,
149
+ pairingArrival: null,
147
150
  podChoice: null,
148
151
  moved: null,
152
+ signingOut: false,
153
+ podToReopen: null,
149
154
  });
150
155
  const listeners = new Set();
151
156
  const update = (patch) => {
@@ -155,6 +160,22 @@ export function createMincaAuth(config = {}) {
155
160
  };
156
161
  /** The seed behind the open session. Never leaves this closure except as the recovery code. */
157
162
  let seed = null;
163
+ /** When the person last proved it is them (`confirm`); nothing that hands out the seed works without it */
164
+ let confirmedAt = 0;
165
+ /** Which account that proof was for, so it never carries over to another */
166
+ let confirmedFor = null;
167
+ /** When the open account was last opened with a password, passkey or the recovery code here, and which */
168
+ let signedInAt = 0;
169
+ let signedInFor = null;
170
+ const provedSignIn = (did) => {
171
+ signedInAt = Date.now();
172
+ signedInFor = did;
173
+ };
174
+ /**
175
+ * Whether a session just landed and is choosing its first way in: only `arrive`
176
+ * opens this, so no call can step back into setup to skip `confirm`.
177
+ */
178
+ let setupOpen = false;
158
179
  let localKey = null;
159
180
  let stopFollowingName = null;
160
181
  let expiryTimer = null;
@@ -165,7 +186,14 @@ export function createMincaAuth(config = {}) {
165
186
  directory: null,
166
187
  });
167
188
  const storesOf = (place, account, key) => place.directory
168
- ? storesFor(account, { directory: place.directory, localKey: key })
189
+ ? storesFor(account, {
190
+ directory: place.directory,
191
+ localKey: key,
192
+ // Given stores of its own, this browser keeps a pod's beside them too.
193
+ ...(config.browser
194
+ ? { local: config.browser.stores({ ...account, id: `pod-${account.id}` }) }
195
+ : {}),
196
+ })
169
197
  : browserStores(account);
170
198
  // ─── Accounts in a place ───────────────────────────────────────────
171
199
  async function openEntry(place, id) {
@@ -216,6 +244,11 @@ export function createMincaAuth(config = {}) {
216
244
  clearInterval(expiryTimer);
217
245
  expiryTimer = null;
218
246
  seed = null;
247
+ confirmedAt = 0;
248
+ confirmedFor = null;
249
+ signedInAt = 0;
250
+ signedInFor = null;
251
+ setupOpen = false;
219
252
  localKey = null;
220
253
  await node?.close();
221
254
  }
@@ -267,7 +300,11 @@ export function createMincaAuth(config = {}) {
267
300
  }
268
301
  }
269
302
  writeConnections(auth.connections().filter((known) => !goes(known)));
270
- return { delivered: Promise.all(revoked).then((taken) => taken.every(Boolean)) };
303
+ // A home that closes once delivered must also have taken the removed automations' wakes off its carriers.
304
+ const refilled = node && waitMs > 0 ? node.carriers.settled(waitMs) : Promise.resolve(true);
305
+ return {
306
+ delivered: Promise.all([Promise.all(revoked), refilled]).then(([taken]) => taken.every(Boolean)),
307
+ };
271
308
  }
272
309
  /**
273
310
  * Revokes the key a connection was given, where it could write; never this node's own.
@@ -453,13 +490,12 @@ export function createMincaAuth(config = {}) {
453
490
  * Lands a new session: in, or on through the setup screens.
454
491
  *
455
492
  * With no reason to set up, or a passkey or password already here, that is
456
- * the app. Otherwise the recovery code is shown first — a new account's for
457
- * the first time, a restored one's as a reminder to keep it apart from the
458
- * password about to be set, which a password manager may file in its place —
459
- * then a way in is chosen. A paired device skips the code: it was never
460
- * shown one, and the device it came from keeps it.
493
+ * the app. Otherwise a new account's recovery code is shown first, then a way
494
+ * in is chosen. A restored account skips the code, since the person just
495
+ * typed it, and so does a paired device, which was never shown one.
461
496
  */
462
497
  async function arrive(session, setup) {
498
+ update({ podToReopen: null });
463
499
  const place = state.place;
464
500
  const entry = place ? await openEntry(place, session.account.id) : null;
465
501
  const landed = {
@@ -471,15 +507,18 @@ export function createMincaAuth(config = {}) {
471
507
  if (setup === null || hasEverydayWay(entry)) {
472
508
  update({ ...landed, stage: 'ready', setup: null, freshCode: null });
473
509
  }
474
- else if (setup === 'paired') {
475
- update({ ...landed, stage: 'unlock', setup });
510
+ else if (setup === 'paired' || setup === 'restored') {
511
+ setupOpen = true;
512
+ update({ ...landed, stage: 'unlock', setup, freshCode: null });
476
513
  }
477
514
  else {
515
+ setupOpen = true;
478
516
  update({ ...landed, stage: 'recovery', setup, freshCode: seed ? seedToRecoveryCode(seed) : null });
479
517
  }
480
518
  }
481
519
  /** After a way in is set up: offer a pod to a new account that could use one, or go in. */
482
520
  function afterUnlock() {
521
+ setupOpen = false;
483
522
  const offerPod = config.offerPod !== false &&
484
523
  state.setup === 'new' &&
485
524
  state.folderAvailable &&
@@ -487,8 +526,12 @@ export function createMincaAuth(config = {}) {
487
526
  update(offerPod ? { stage: 'pod' } : { stage: 'ready', setup: null });
488
527
  }
489
528
  /** Runs a way in. One that took the recovery code may lead on to setting up an everyday one. */
529
+ // Every way in says whether it proved someone is there, so a new one can't count by omission.
490
530
  const enter = (open) => run(async () => {
491
- const { session, byCode } = await open();
531
+ const { session, byCode, proved } = await open();
532
+ // Opening it took the password, a passkey or the recovery code: proof enough to give an app access, for a few minutes.
533
+ if (proved)
534
+ provedSignIn(session.did);
492
535
  await arrive(session, byCode ? 'restored' : null);
493
536
  }).then(() => undefined);
494
537
  /**
@@ -563,10 +606,31 @@ export function createMincaAuth(config = {}) {
563
606
  update({ session: Object.freeze({ ...session, account: renamed }), accounts: await listAccounts(place) });
564
607
  return renamed;
565
608
  }
566
- /** Changes to the open account's shortcuts, then re-reads them. During setup, moves the flow on. */
609
+ /** Whether the person proved it is them (`confirm`) in the last few minutes */
610
+ const isConfirmed = () => seed !== null &&
611
+ confirmedFor !== null &&
612
+ state.session?.did === confirmedFor &&
613
+ Date.now() - confirmedAt < CONFIRMED_MS;
614
+ /**
615
+ * Whether an app may be given access now: the person proved it is them, or
616
+ * opened the account with a password, passkey or the recovery code, in the
617
+ * last few minutes. A sign-in kept from before is neither.
618
+ */
619
+ const mayGrant = () => isConfirmed() ||
620
+ (seed !== null &&
621
+ signedInFor !== null &&
622
+ state.session?.did === signedInFor &&
623
+ Date.now() - signedInAt < CONFIRMED_MS);
624
+ /**
625
+ * Changes to the open account's shortcuts, then re-reads them. During setup,
626
+ * moves the flow on. Outside setup they need `confirm` first: a new password
627
+ * would otherwise both open the gate and lock the owner out.
628
+ */
567
629
  const changeShortcut = (apply) => run(async () => {
568
630
  if (!seed)
569
631
  throw new Error('Not signed in.');
632
+ if (!setupOpen && !isConfirmed())
633
+ throw new Error('Confirm it is you first.');
570
634
  await apply(seed);
571
635
  await refreshEntry();
572
636
  if (state.stage === 'unlock' && hasEverydayWay(state.entry))
@@ -588,6 +652,31 @@ export function createMincaAuth(config = {}) {
588
652
  set(`${prefix}.connections:${account}`, JSON.stringify(connections));
589
653
  update({});
590
654
  }
655
+ /** An account a pairing brought, held while a signed-in device asks whether to take it */
656
+ let heldHandover = null;
657
+ /** Counts pairings begun and dismissed: one that ends after a dismiss is dropped */
658
+ let pairingRun = 0;
659
+ /** Stops the pairing under way, so a dismissed one leaves the room rather than waiting it out */
660
+ let stopPairing = null;
661
+ /** Signs in with what a pairing brought, then joins its spaces */
662
+ async function takeHandover(handover) {
663
+ const onStage = (stage) => update({ pairingStage: stage });
664
+ // Starting the node takes a moment; the code on screen is done with.
665
+ onStage({ kind: 'sending' });
666
+ const opened = await run(async () => {
667
+ await arrive(await openWithCode(seedToRecoveryCode(handover.seed), null), 'paired');
668
+ });
669
+ const session = state.session;
670
+ if (!opened || !session)
671
+ return;
672
+ let joined = 0;
673
+ for (const [index, invite] of handover.spaces.entries()) {
674
+ onStage({ kind: 'joining', joined: index, total: handover.spaces.length });
675
+ if (await session.node.spaces.join(invite).then(() => true, () => false))
676
+ joined++;
677
+ }
678
+ onStage({ kind: 'received', spaces: joined });
679
+ }
591
680
  // ─── The flow ──────────────────────────────────────────────────────
592
681
  const auth = {
593
682
  getState: () => state,
@@ -612,11 +701,16 @@ export function createMincaAuth(config = {}) {
612
701
  const pod = await recallPod(false).catch(() => null);
613
702
  const place = pod ?? (await browserPlace());
614
703
  const accounts = await refresh(place);
704
+ // Remembered, but the browser wants a click first: say so, rather than start as if new.
705
+ if (!pod)
706
+ update({ podToReopen: await podToReopen().catch(() => null) });
615
707
  if (accounts.length > 0) {
616
708
  const kept = await stay.recall(place.kind).catch(() => null);
617
709
  const summary = kept && accounts.find((account) => account.id === kept.accountId);
618
710
  if (kept && summary) {
619
- update({ session: await begin(place, summary, kept.seed), stage: 'ready' });
711
+ const session = await begin(place, summary, kept.seed);
712
+ // A pairing link still asks first: it would put another account here (spec 01 §15.3).
713
+ update({ session, stage: state.pairing ? 'pair' : 'ready' });
620
714
  return;
621
715
  }
622
716
  }
@@ -638,6 +732,30 @@ export function createMincaAuth(config = {}) {
638
732
  })();
639
733
  return started;
640
734
  },
735
+ async reopenPod() {
736
+ await run(async () => {
737
+ // Signed in meanwhile (another tab's sign-in taken up, say): moving pods asks first, through choosePod.
738
+ if (state.session) {
739
+ update({ podToReopen: null });
740
+ return;
741
+ }
742
+ const pod = await recallPod(true);
743
+ if (!pod)
744
+ throw new Error('The browser did not open the folder. Try again, or choose it with “Open a folder”.');
745
+ update({ podToReopen: null });
746
+ const accounts = await refresh(pod);
747
+ // Kept signed in there: straight in, as a page load with the permission would have been.
748
+ const kept = await stay.recall(pod.kind).catch(() => null);
749
+ const summary = kept && accounts.find((account) => account.id === kept.accountId);
750
+ if (kept && summary) {
751
+ const session = await begin(pod, summary, kept.seed);
752
+ // A pairing link still asks first, as at start (spec 01 §15.3).
753
+ update({ session, stage: state.pairing ? 'pair' : 'ready' });
754
+ return;
755
+ }
756
+ update({ stage: state.pairing ? 'pair' : afterStorage(accounts) });
757
+ });
758
+ },
641
759
  async choosePod() {
642
760
  const picked = await run(async () => {
643
761
  const pod = await pickPod();
@@ -678,7 +796,11 @@ export function createMincaAuth(config = {}) {
678
796
  update({ entry: await openEntry(state.place, accountId) });
679
797
  },
680
798
  signInWithCode(code) {
681
- return enter(async () => ({ session: await openWithCode(code, selectedAccount()), byCode: true }));
799
+ return enter(async () => ({
800
+ session: await openWithCode(code, selectedAccount()),
801
+ byCode: true,
802
+ proved: true,
803
+ }));
682
804
  },
683
805
  signInWithPassword(password) {
684
806
  return enter(async () => {
@@ -698,12 +820,16 @@ export function createMincaAuth(config = {}) {
698
820
  failed = error instanceof Error ? error : new Error(String(error));
699
821
  }
700
822
  if (unlocked)
701
- return { session: await begin(place, entry.summary, unlocked), byCode: false };
823
+ return { session: await begin(place, entry.summary, unlocked), byCode: false, proved: true };
702
824
  }
703
825
  if (failed && !code)
704
826
  throw failed;
705
827
  if (code)
706
- return { session: await openWithCode(code, entry?.summary ?? selectedAccount()), byCode: true };
828
+ return {
829
+ session: await openWithCode(code, entry?.summary ?? selectedAccount()),
830
+ byCode: true,
831
+ proved: true,
832
+ };
707
833
  throw protocolError('VAULT_UNLOCK_FAILED', 'No password is set for this account here.', 'Use your recovery code, and you can set one up afterwards.');
708
834
  });
709
835
  },
@@ -724,6 +850,8 @@ export function createMincaAuth(config = {}) {
724
850
  return {
725
851
  session: await begin(place, entry.summary, await unwrapSeedWithDeviceKey(target, key, entry.vault.did)),
726
852
  byCode: false,
853
+ // A wrap with no passkey behind it skipped the check that someone is there.
854
+ proved: Boolean(target.credentialId),
727
855
  };
728
856
  });
729
857
  },
@@ -764,17 +892,20 @@ export function createMincaAuth(config = {}) {
764
892
  // shows it. Only at creation and on rename — never on a plain start,
765
893
  // where a device that has not synced yet would publish a stale name.
766
894
  await session.node.account.setName(summary.name).catch(() => { });
895
+ // Made just now, by whoever is here: an app asking next needs no more proof.
896
+ provedSignIn(session.did);
767
897
  await arrive(session, 'new');
768
898
  });
769
899
  },
770
900
  codeSaved() {
771
- if (!state.session)
901
+ if (!state.session || state.stage !== 'recovery')
772
902
  return;
773
903
  update({ freshCode: null, stage: 'unlock' });
774
904
  },
775
905
  finishSetup() {
776
- if (!state.session)
906
+ if (!state.session || state.stage !== 'pod')
777
907
  return;
908
+ setupOpen = false;
778
909
  update({ stage: 'ready', setup: null, error: null });
779
910
  },
780
911
  async acceptPairing() {
@@ -784,34 +915,77 @@ export function createMincaAuth(config = {}) {
784
915
  if (!state.place)
785
916
  update({ place: await browserPlace() });
786
917
  const onStage = (stage) => update({ pairingStage: stage });
787
- let spaces = [];
918
+ const mine = ++pairingRun;
919
+ const stop = new AbortController();
920
+ stopPairing = stop;
921
+ const got = { handover: null };
788
922
  // The account arrives over the exchange, after the person has compared
789
923
  // the codes; the link only says where to meet.
790
- const opened = await run(async () => {
791
- const handover = await receiveFromDesktop(ticket, onStage);
792
- spaces = handover.spaces;
793
- // Starting the node takes a moment; the code on screen is done with.
794
- onStage({ kind: 'sending' });
795
- await arrive(await openWithCode(seedToRecoveryCode(handover.seed), null), 'paired');
924
+ await run(async () => {
925
+ try {
926
+ got.handover = await receiveFromDesktop(ticket, onStage, {
927
+ transport: config.pairingTransport,
928
+ signal: stop.signal,
929
+ });
930
+ }
931
+ catch (error) {
932
+ // Stopped by "Not now": nothing went wrong to tell the person about.
933
+ if (!stop.signal.aborted)
934
+ throw error;
935
+ }
796
936
  });
937
+ const arrived = got.handover;
938
+ // "Not now" while the code showed: the computer may still have sent it, but it is not taken.
939
+ if (mine !== pairingRun) {
940
+ arrived?.seed.fill(0);
941
+ return;
942
+ }
797
943
  clearPairingTicket();
798
944
  update({ pairing: null });
799
- const session = state.session;
800
- if (!opened || !session)
945
+ if (!arrived)
801
946
  return;
802
- let joined = 0;
803
- for (const [index, invite] of spaces.entries()) {
804
- onStage({ kind: 'joining', joined: index, total: spaces.length });
805
- if (await session.node.spaces.join(invite).then(() => true, () => false))
806
- joined++;
947
+ // Signed in to another account, the device asks first: add the one that
948
+ // arrived, or switch to it if it is already here (spec 01 §15.3).
949
+ const signedIn = state.session;
950
+ if (signedIn) {
951
+ const { did } = await createIdentityManager().fromSeed(arrived.seed);
952
+ // "Not now" while the account was being looked at: let it go.
953
+ if (mine !== pairingRun) {
954
+ arrived.seed.fill(0);
955
+ return;
956
+ }
957
+ if (did !== signedIn.did) {
958
+ heldHandover = arrived;
959
+ update({
960
+ pairingArrival: { did, account: state.accounts.find((account) => account.did === did) ?? null },
961
+ });
962
+ return;
963
+ }
807
964
  }
808
- onStage({ kind: 'received', spaces: joined });
965
+ await takeHandover(arrived);
966
+ },
967
+ async answerPairing(take) {
968
+ const arrived = heldHandover;
969
+ heldHandover = null;
970
+ update({ pairingArrival: null });
971
+ if (!arrived)
972
+ return;
973
+ if (take)
974
+ return takeHandover(arrived);
975
+ arrived.seed.fill(0);
976
+ update({ pairingStage: null, stage: state.session ? 'ready' : afterStorage(state.accounts) });
809
977
  },
810
978
  dismissPairing() {
979
+ pairingRun++;
980
+ stopPairing?.abort();
981
+ stopPairing = null;
811
982
  clearPairingTicket();
983
+ heldHandover?.seed.fill(0);
984
+ heldHandover = null;
812
985
  update({
813
986
  pairing: null,
814
987
  pairingStage: null,
988
+ pairingArrival: null,
815
989
  stage: state.session ? 'ready' : afterStorage(state.accounts),
816
990
  });
817
991
  },
@@ -942,19 +1116,63 @@ export function createMincaAuth(config = {}) {
942
1116
  dismissMoved() {
943
1117
  update({ moved: null });
944
1118
  },
1119
+ confirm(proof) {
1120
+ return run(async () => {
1121
+ const { entry, place } = state;
1122
+ const unlocked = seed;
1123
+ if (!unlocked || !entry || !place)
1124
+ throw new Error('Sign in first.');
1125
+ const same = (other) => other.length === unlocked.length && other.every((byte, at) => byte === unlocked[at]);
1126
+ const wrong = (message) => protocolError('VAULT_UNLOCK_FAILED', message);
1127
+ if ('code' in proof) {
1128
+ if (!isValidRecoveryCode(proof.code) || !same(recoveryCodeToSeed(proof.code)))
1129
+ throw wrong('That is not this account’s recovery code.');
1130
+ }
1131
+ else if ('password' in proof) {
1132
+ const wraps = entry.vault.wraps.filter((candidate) => candidate.kind === 'passphrase');
1133
+ let opened = false;
1134
+ for (const wrap of wraps) {
1135
+ const tried = await unwrapSeedWithPassphrase(wrap, proof.password, entry.vault.did).catch(() => null);
1136
+ if (tried && same(tried))
1137
+ opened = true;
1138
+ }
1139
+ if (!opened)
1140
+ throw wrong('That is not the password.');
1141
+ }
1142
+ else {
1143
+ const target = entry.shortcuts[entry.shortcuts.length - 1];
1144
+ // The passkey's own check that someone is there: a fingerprint, a face or a PIN.
1145
+ // A wrap with no passkey behind it would skip that check, so it is no proof.
1146
+ if (!target?.credentialId)
1147
+ throw wrong('No passkey on this device opens this account.');
1148
+ await authenticatePasskey(target.credentialId, { rpId });
1149
+ const key = await getDeviceKey(target.deviceKeyId);
1150
+ if (!key || !same(await unwrapSeedWithDeviceKey(target, key, entry.vault.did)))
1151
+ throw wrong('That passkey does not open this account here.');
1152
+ }
1153
+ confirmedAt = Date.now();
1154
+ confirmedFor = state.session?.did ?? null;
1155
+ });
1156
+ },
1157
+ isConfirmed,
1158
+ mayGrant,
945
1159
  recoveryCode() {
946
- return seed ? seedToRecoveryCode(seed) : null;
1160
+ return seed && isConfirmed() ? seedToRecoveryCode(seed) : null;
947
1161
  },
948
1162
  offerToPhone(onStage) {
949
1163
  const session = state.session;
950
1164
  if (!session || !seed)
951
1165
  return Promise.reject(new Error('Sign in first.'));
1166
+ // It sends the whole account: the same proof as reading the recovery code.
1167
+ if (!isConfirmed())
1168
+ return Promise.reject(new Error('Confirm it is you first.'));
952
1169
  const location = globalThis.location;
953
1170
  return offerPairing({
954
1171
  seed,
955
1172
  invites: async () => Promise.all((await session.node.spaces.list()).map((space) => session.node.spaces.invite(space.id))),
956
1173
  relays: config.network?.relays ?? [],
957
1174
  link: config.pairingLink ?? (location ? `${location.origin}${location.pathname}` : ''),
1175
+ transport: config.pairingTransport,
958
1176
  }, onStage);
959
1177
  },
960
1178
  async grant(choice) {
@@ -976,6 +1194,10 @@ export function createMincaAuth(config = {}) {
976
1194
  if (recordsOnly && request.contacts)
977
1195
  throw new Error('A key given records only is not given your contacts.');
978
1196
  const whole = request.scope === 'account';
1197
+ // Like any sign-in elsewhere: the person proves it is them before an app gets anything,
1198
+ // not only a home that stayed signed in on a computer anyone may walk up to.
1199
+ if (!mayGrant())
1200
+ throw new Error('Confirm it is you first.');
979
1201
  const created = [];
980
1202
  for (const params of request.create ?? [])
981
1203
  created.push(await node.spaces.create(params));
@@ -1095,6 +1317,8 @@ export function createMincaAuth(config = {}) {
1095
1317
  const problem = await audienceProblem(request, origin);
1096
1318
  if (problem)
1097
1319
  throw new Error(problem);
1320
+ if (!mayGrant())
1321
+ throw new Error('Confirm it is you first.');
1098
1322
  // One carrier per origin: a new key there replaces the old one. The same key again keeps its
1099
1323
  // carry space (`carriers.add`). An app at the same origin is not it, and stays (§2.10).
1100
1324
  const carrierHere = (known) => known.origin === origin && known.access === 'carry';
@@ -1159,7 +1383,7 @@ export function createMincaAuth(config = {}) {
1159
1383
  },
1160
1384
  async signOut(options = {}) {
1161
1385
  // Not ready from now on: nothing may be granted from this account while it goes.
1162
- update({ stage: 'starting' });
1386
+ update({ stage: 'starting', signingOut: true });
1163
1387
  await stay.forget();
1164
1388
  const leaving = state.session?.node;
1165
1389
  // Every app and the programs connected through it; carriers stay, holding nothing that writes.
@@ -1174,6 +1398,8 @@ export function createMincaAuth(config = {}) {
1174
1398
  await Promise.all([
1175
1399
  disconnected?.delivered,
1176
1400
  leaving?.revokeSelf({ waitMs: signOutGraceMs }).catch(() => { }),
1401
+ // Whatever changed for the carriers just now is written for them before the node stops.
1402
+ leaving?.carriers.settled(signOutGraceMs).catch(() => false),
1177
1403
  ]);
1178
1404
  update({
1179
1405
  stage: 'starting',
@@ -1186,7 +1412,7 @@ export function createMincaAuth(config = {}) {
1186
1412
  });
1187
1413
  await stopNode(leaving).catch(() => { });
1188
1414
  const place = state.place;
1189
- update({ stage: place ? afterStorage(await refresh(place)) : 'welcome' });
1415
+ update({ stage: place ? afterStorage(await refresh(place)) : 'welcome', signingOut: false });
1190
1416
  },
1191
1417
  };
1192
1418
  return auth;