@oxyhq/core 20.0.0 → 21.0.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 (94) hide show
  1. package/NOTICE +10 -9
  2. package/dist/cjs/.tsbuildinfo +1 -1
  3. package/dist/cjs/boot/sessionColdBoot.js +107 -8
  4. package/dist/cjs/i18n/locales/en-US.json +19 -2
  5. package/dist/cjs/i18n/locales/es-ES.json +19 -2
  6. package/dist/cjs/i18n/locales/locales/en-US.json +19 -2
  7. package/dist/cjs/i18n/locales/locales/es-ES.json +19 -2
  8. package/dist/cjs/index.js +50 -16
  9. package/dist/cjs/mixins/OxyServices.auth.js +27 -3
  10. package/dist/cjs/mixins/OxyServices.chains.js +73 -0
  11. package/dist/cjs/mixins/OxyServices.store.js +266 -0
  12. package/dist/cjs/mixins/OxyServices.utility.js +159 -104
  13. package/dist/cjs/mixins/index.js +7 -0
  14. package/dist/cjs/server/rateLimit.js +15 -6
  15. package/dist/cjs/session/SessionClient.js +361 -1
  16. package/dist/cjs/session/accountDialogController.js +121 -147
  17. package/dist/cjs/session/accountSwitchTargets.js +75 -0
  18. package/dist/cjs/session/deviceDirectory.js +143 -0
  19. package/dist/cjs/session/deviceSwitcherRows.js +76 -0
  20. package/dist/cjs/session/projectSessionState.js +8 -1
  21. package/dist/cjs/session/sharedDeviceCredential.js +247 -0
  22. package/dist/esm/.tsbuildinfo +1 -1
  23. package/dist/esm/boot/sessionColdBoot.js +107 -8
  24. package/dist/esm/i18n/locales/en-US.json +19 -2
  25. package/dist/esm/i18n/locales/es-ES.json +19 -2
  26. package/dist/esm/i18n/locales/locales/en-US.json +19 -2
  27. package/dist/esm/i18n/locales/locales/es-ES.json +19 -2
  28. package/dist/esm/index.js +32 -10
  29. package/dist/esm/mixins/OxyServices.auth.js +27 -3
  30. package/dist/esm/mixins/OxyServices.chains.js +70 -0
  31. package/dist/esm/mixins/OxyServices.store.js +263 -0
  32. package/dist/esm/mixins/OxyServices.utility.js +159 -104
  33. package/dist/esm/mixins/index.js +7 -0
  34. package/dist/esm/server/rateLimit.js +15 -6
  35. package/dist/esm/session/SessionClient.js +362 -2
  36. package/dist/esm/session/accountDialogController.js +121 -147
  37. package/dist/esm/session/accountSwitchTargets.js +71 -0
  38. package/dist/esm/session/deviceDirectory.js +135 -0
  39. package/dist/esm/session/deviceSwitcherRows.js +72 -0
  40. package/dist/esm/session/projectSessionState.js +8 -2
  41. package/dist/esm/session/sharedDeviceCredential.js +239 -0
  42. package/dist/types/.tsbuildinfo +1 -1
  43. package/dist/types/boot/sessionColdBoot.d.ts +24 -4
  44. package/dist/types/index.d.ts +15 -3
  45. package/dist/types/mixins/OxyServices.auth.d.ts +75 -3
  46. package/dist/types/mixins/OxyServices.chains.d.ts +156 -0
  47. package/dist/types/mixins/OxyServices.store.d.ts +334 -0
  48. package/dist/types/mixins/OxyServices.utility.d.ts +31 -8
  49. package/dist/types/mixins/index.d.ts +3 -1
  50. package/dist/types/models/session.d.ts +11 -0
  51. package/dist/types/session/SessionClient.d.ts +202 -1
  52. package/dist/types/session/accountDialogController.d.ts +76 -64
  53. package/dist/types/session/accountSwitchTargets.d.ts +64 -0
  54. package/dist/types/session/deviceDirectory.d.ts +182 -0
  55. package/dist/types/session/deviceSwitcherRows.d.ts +92 -0
  56. package/dist/types/session/projectSessionState.d.ts +29 -0
  57. package/dist/types/session/sharedDeviceCredential.d.ts +202 -0
  58. package/package.json +3 -3
  59. package/src/boot/__tests__/sessionColdBoot.sharedDevice.test.ts +325 -0
  60. package/src/boot/sessionColdBoot.ts +133 -9
  61. package/src/i18n/locales/en-US.json +19 -2
  62. package/src/i18n/locales/es-ES.json +19 -2
  63. package/src/index.ts +105 -18
  64. package/src/mixins/OxyServices.auth.ts +67 -5
  65. package/src/mixins/OxyServices.chains.ts +134 -0
  66. package/src/mixins/OxyServices.store.ts +585 -0
  67. package/src/mixins/OxyServices.utility.ts +161 -108
  68. package/src/mixins/__tests__/chains.test.ts +113 -0
  69. package/src/mixins/__tests__/preSessionSkipAuth.test.ts +54 -1
  70. package/src/mixins/__tests__/store.test.ts +304 -0
  71. package/src/mixins/__tests__/userTokenAuth.test.ts +746 -0
  72. package/src/mixins/index.ts +9 -0
  73. package/src/models/session.ts +11 -0
  74. package/src/server/__tests__/rateLimit.test.ts +47 -0
  75. package/src/server/rateLimit.ts +18 -8
  76. package/src/session/SessionClient.ts +386 -1
  77. package/src/session/__tests__/SessionClient.directory.test.ts +688 -0
  78. package/src/session/__tests__/accountDialogController.test.ts +411 -278
  79. package/src/session/__tests__/accountSwitchTargets.test.ts +132 -0
  80. package/src/session/__tests__/deviceDirectory.test.ts +422 -0
  81. package/src/session/__tests__/deviceSwitcherRows.test.ts +223 -0
  82. package/src/session/__tests__/projectSessionState.test.ts +17 -0
  83. package/src/session/__tests__/sharedDeviceCredential.test.ts +300 -0
  84. package/src/session/accountDialogController.ts +141 -179
  85. package/src/session/accountSwitchTargets.ts +87 -0
  86. package/src/session/deviceDirectory.ts +269 -0
  87. package/src/session/deviceSwitcherRows.ts +145 -0
  88. package/src/session/projectSessionState.ts +9 -3
  89. package/src/session/sharedDeviceCredential.ts +349 -0
  90. package/dist/cjs/session/accountProjection.js +0 -213
  91. package/dist/esm/session/accountProjection.js +0 -207
  92. package/dist/types/session/accountProjection.d.ts +0 -198
  93. package/src/session/__tests__/accountProjection.test.ts +0 -447
  94. package/src/session/accountProjection.ts +0 -354
@@ -15,10 +15,17 @@
15
15
  * origin persisted a `deviceId` + `deviceSecret`, mint a short access token
16
16
  * with a single bearer-less POST to `/session/device/token` (no cookie, no
17
17
  * navigation) and rotate the secret in-use.
18
- * 3. `shared-key-signin` (native, ACCOUNT mode) — re-mint from the
19
- * shared-keychain identity OR `identity-key-signin` (IDENTITY mode)
20
- * re-mint from THIS device's primary identity key.
21
- * 4. Signed out.
18
+ * 3. `shared-device-adopt` (native, ACCOUNT mode) — this app has no credential
19
+ * of its own but a sibling official app already put one in the shared native
20
+ * slot: adopt it and mint. This is how a newly installed official app joins
21
+ * the device's existing session WITHOUT another QR and without ever touching
22
+ * the Commons private key.
23
+ * 4. `shared-key-signin` (native, ACCOUNT mode) — the legacy lane: re-mint by
24
+ * signing with the shared-keychain IDENTITY key. Retained as a recovery /
25
+ * compatibility path for devices whose apps have not yet published a shared
26
+ * device credential — OR `identity-key-signin` (IDENTITY mode) — re-mint
27
+ * from THIS device's primary identity key.
28
+ * 5. Signed out.
22
29
  *
23
30
  * Two session modes (see {@link RunSessionColdBootOptions.sessionMode}):
24
31
  * - `account` (default) — the device's ACTIVE account owns the session. Every
@@ -37,6 +44,7 @@ import { logger } from '../logger/index.js';
37
44
  import { computeIdentityTag } from '../utils/cacheKey.js';
38
45
  import { TOKEN_REFRESH_LEAD_MS, refreshDeviceSecretArm } from '../session/refresh.js';
39
46
  import { establishIdentitySession, resolveIdentityPin, } from '../session/identitySession.js';
47
+ import { decideSharedDeviceJoin, } from '../session/sharedDeviceCredential.js';
40
48
  /**
41
49
  * Run the device-first cold boot. Resolves to the `runColdBoot` outcome and, as
42
50
  * a side effect, invokes `onSession` (winning session, token already planted) or
@@ -236,10 +244,101 @@ export async function runSessionColdBoot(opts) {
236
244
  },
237
245
  });
238
246
  }
239
- else {
240
- // 3. shared-key-signin (native) — re-mint from the shared identity. Native
241
- // AND online: it is a network step (challenge + verify round-trips), so it
242
- // is gated by the same offline hint as the mint lane. `{ retry: false }`
247
+ else if (opts.sharedDeviceCredential) {
248
+ // 3. shared-device-adopt (native, ACCOUNT mode) — join the device's existing
249
+ // session through the shared native credential slot.
250
+ //
251
+ // This is the lane that separates identity from session transport. What it
252
+ // reads is an ordinary, individually revocable `deviceId` + `deviceSecret`
253
+ // put there by a sibling official app — never the Commons private key. It
254
+ // is what lets a freshly installed official app land signed in with no QR,
255
+ // and it is why an ordinary app never needs identity-key access at all.
256
+ //
257
+ // `decideSharedDeviceJoin` gates it: an app that already holds its own
258
+ // credential is never moved, and an UNREADABLE slot is never mistaken for
259
+ // an empty one. The lane therefore cannot sign anyone out, in either
260
+ // upgrade order.
261
+ const sharedSlot = opts.sharedDeviceCredential;
262
+ steps.push({
263
+ id: 'shared-device-adopt',
264
+ // The adoption itself is local, but it is only worth committing alongside
265
+ // a mint that proves the credential — so the whole lane is online-gated
266
+ // like every other network step.
267
+ enabled: () => isNative && !isOffline(),
268
+ run: async () => {
269
+ const before = await store.load();
270
+ const decision = decideSharedDeviceJoin(before, await sharedSlot.read());
271
+ if (decision.action === 'skip') {
272
+ logger.debug(`shared device credential not adopted (${decision.reason})`, { component: 'sessionColdBoot', method: 'shared-device-adopt' });
273
+ return { kind: 'skip' };
274
+ }
275
+ // Restore the store to exactly what it held before this lane touched it.
276
+ // A credential we adopted and could not prove must not be left behind for
277
+ // the next boot's mint lane to keep retrying.
278
+ const revert = async () => {
279
+ if (before) {
280
+ await store.save(before);
281
+ }
282
+ else {
283
+ await store.clear();
284
+ }
285
+ };
286
+ const adopted = {
287
+ // The mint fills both in from the device's live state; carrying the
288
+ // previous session's ids into a different device session would be a
289
+ // lie for however long the mint takes.
290
+ sessionId: '',
291
+ userId: '',
292
+ deviceId: decision.credential.deviceId,
293
+ deviceSecret: decision.credential.deviceSecret,
294
+ };
295
+ if (!(await store.save(adopted))) {
296
+ logger.error('adopted the shared device credential but it could not be durably persisted — reverting', undefined, { component: 'sessionColdBoot', method: 'shared-device-adopt' });
297
+ await revert();
298
+ return { kind: 'skip' };
299
+ }
300
+ const result = await refreshDeviceSecretArm({ oxy, store, pin: null });
301
+ if (result.status === 'ok') {
302
+ return {
303
+ kind: 'session',
304
+ session: {
305
+ sessionId: result.sessionId,
306
+ userId: result.userId,
307
+ accessToken: result.token,
308
+ },
309
+ };
310
+ }
311
+ if (result.status === 'invalid-secret') {
312
+ // The one place we hold POSITIVE proof that the exact bytes in the
313
+ // shared slot are dead — the server rejected them by name. Clearing it
314
+ // signs nobody out (a credential the server does not recognise cannot
315
+ // be minting for anyone) and it is what stops a dead credential from
316
+ // blocking every future install: a stale slot owned by a different
317
+ // `deviceId` is otherwise never overwritten, by design.
318
+ await sharedSlot.clear();
319
+ }
320
+ else if (result.status === 'no-session') {
321
+ signedOutReason = 'no_session';
322
+ }
323
+ await revert();
324
+ return { kind: 'skip' };
325
+ },
326
+ });
327
+ }
328
+ if (identityBinding === null) {
329
+ // 4. shared-key-signin (native) — the RECOVERY / COMPATIBILITY lane: sign a
330
+ // challenge with the shared-keychain IDENTITY key to re-mint a session.
331
+ //
332
+ // It runs LAST on purpose. Using the self-custody key to obtain an ordinary
333
+ // session is the over-sharing #937 sets out to end, so it is now reachable
334
+ // only on a device where no sibling app has published a shared device
335
+ // credential yet — an install that predates this lane, or one where the
336
+ // shared slot is unreadable. Its own `store.save` below feeds the shared
337
+ // slot through the mirroring store, so the FIRST boot that takes this lane
338
+ // is also the last one that needs to: every later app joins by credential.
339
+ //
340
+ // Native AND online: it is a network step (challenge + verify round-trips),
341
+ // so it is gated by the same offline hint as the mint lane. `{ retry: false }`
243
342
  // keeps the two round-trips as single attempts — the refresh scheduler /
244
343
  // 401 lane own later retries — so this step cannot multiply boot latency.
245
344
  steps.push({
@@ -396,13 +396,22 @@
396
396
  "remoteSignOutFailed": "There was a problem signing out from the device. Please try again.",
397
397
  "noOtherDeviceSessions": "No other device sessions found to sign out from.",
398
398
  "signOutOthersSuccess": "Signed out from all other devices successfully!",
399
- "signOutOthersFailed": "There was a problem signing out from other devices. Please try again."
399
+ "signOutOthersFailed": "There was a problem signing out from other devices. Please try again.",
400
+ "contextRemoved": "Removed {{account}}",
401
+ "contextRemoveFailed": "There was a problem removing that account. Please try again.",
402
+ "principalRemoved": "Signed {{name}} out of this device",
403
+ "principalRemoveFailed": "There was a problem signing that person out. Please try again.",
404
+ "activateFailed": "There was a problem switching accounts. Please try again."
400
405
  },
401
406
  "confirms": {
402
407
  "remove": "Are you sure you want to remove {{displayName}} from this device? You'll need to sign in again to access this account.",
403
408
  "logoutAll": "Are you sure you want to sign out of all accounts? This will remove all saved accounts from this device.",
404
409
  "remoteLogout": "Are you sure you want to sign out from \"{{deviceName}}\"? This will end the session on that device.",
405
- "logoutOthers": "Are you sure you want to sign out from all {{count}} other device(s)? This will end sessions on all other devices except this one."
410
+ "logoutOthers": "Are you sure you want to sign out from all {{count}} other device(s)? This will end sessions on all other devices except this one.",
411
+ "removeContextTitle": "Remove this account?",
412
+ "removeContext": "Stop {{person}} acting as {{account}} on this device? Anyone else who reaches {{account}} here keeps their access.",
413
+ "removePrincipalTitle": "Sign out of this device?",
414
+ "removePrincipal": "Sign {{name}} out of this device? Every account they reach here is removed. Nobody else is affected."
406
415
  },
407
416
  "device": {
408
417
  "loadingTitle": "Loading device sessions...",
@@ -439,6 +448,14 @@
439
448
  "openedInCommons": "Opened in Commons",
440
449
  "confirming": "Confirming identity",
441
450
  "confirmed": "Identity confirmed"
451
+ },
452
+ "context": {
453
+ "unavailable": "Unavailable right now",
454
+ "operatedBy": "Operated by {{name}}",
455
+ "remove": "Remove {{account}} from {{person}}"
456
+ },
457
+ "principal": {
458
+ "signOut": "Sign {{name}} out of this device"
442
459
  }
443
460
  },
444
461
  "reputation": {
@@ -636,13 +636,22 @@
636
636
  "remoteSignOutFailed": "Hubo un problema al cerrar sesión en el dispositivo. Inténtalo de nuevo.",
637
637
  "noOtherDeviceSessions": "No se encontraron otras sesiones de dispositivo para cerrar.",
638
638
  "signOutOthersSuccess": "¡Sesiones cerradas correctamente en los demás dispositivos!",
639
- "signOutOthersFailed": "Hubo un problema al cerrar sesión en otros dispositivos. Inténtalo de nuevo."
639
+ "signOutOthersFailed": "Hubo un problema al cerrar sesión en otros dispositivos. Inténtalo de nuevo.",
640
+ "contextRemoved": "Se quitó {{account}}",
641
+ "contextRemoveFailed": "Hubo un problema al quitar esa cuenta. Inténtalo de nuevo.",
642
+ "principalRemoved": "Se cerró la sesión de {{name}} en este dispositivo",
643
+ "principalRemoveFailed": "Hubo un problema al cerrar esa sesión. Inténtalo de nuevo.",
644
+ "activateFailed": "Hubo un problema al cambiar de cuenta. Inténtalo de nuevo."
640
645
  },
641
646
  "confirms": {
642
647
  "remove": "¿Seguro que quieres eliminar a {{displayName}} de este dispositivo? Tendrás que iniciar sesión de nuevo para acceder a esta cuenta.",
643
648
  "logoutAll": "¿Seguro que quieres cerrar sesión en todas las cuentas? Esto eliminará todas las cuentas guardadas de este dispositivo.",
644
649
  "remoteLogout": "¿Seguro que quieres cerrar sesión en \"{{deviceName}}\"? Esto finalizará la sesión en ese dispositivo.",
645
- "logoutOthers": "¿Seguro que quieres cerrar sesión en los otros {{count}} dispositivo(s)? Esto finalizará las sesiones en todos los demás dispositivos excepto en este."
650
+ "logoutOthers": "¿Seguro que quieres cerrar sesión en los otros {{count}} dispositivo(s)? Esto finalizará las sesiones en todos los demás dispositivos excepto en este.",
651
+ "removeContextTitle": "¿Quitar esta cuenta?",
652
+ "removeContext": "¿Dejar de usar {{account}} como {{person}} en este dispositivo? Quien más acceda a {{account}} aquí lo conserva.",
653
+ "removePrincipalTitle": "¿Cerrar sesión en este dispositivo?",
654
+ "removePrincipal": "¿Cerrar la sesión de {{name}} en este dispositivo? Se quitan todas las cuentas a las que llega desde aquí. No afecta a nadie más."
646
655
  },
647
656
  "device": {
648
657
  "loadingTitle": "Cargando sesiones de dispositivo...",
@@ -679,6 +688,14 @@
679
688
  "openedInCommons": "Abierto en Commons",
680
689
  "confirming": "Confirmando identidad",
681
690
  "confirmed": "Identidad confirmada"
691
+ },
692
+ "context": {
693
+ "unavailable": "No disponible ahora mismo",
694
+ "operatedBy": "Gestionada por {{name}}",
695
+ "remove": "Quitar {{account}} de {{person}}"
696
+ },
697
+ "principal": {
698
+ "signOut": "Cerrar la sesión de {{name}} en este dispositivo"
682
699
  }
683
700
  },
684
701
  "feedback": {
@@ -396,13 +396,22 @@
396
396
  "remoteSignOutFailed": "There was a problem signing out from the device. Please try again.",
397
397
  "noOtherDeviceSessions": "No other device sessions found to sign out from.",
398
398
  "signOutOthersSuccess": "Signed out from all other devices successfully!",
399
- "signOutOthersFailed": "There was a problem signing out from other devices. Please try again."
399
+ "signOutOthersFailed": "There was a problem signing out from other devices. Please try again.",
400
+ "contextRemoved": "Removed {{account}}",
401
+ "contextRemoveFailed": "There was a problem removing that account. Please try again.",
402
+ "principalRemoved": "Signed {{name}} out of this device",
403
+ "principalRemoveFailed": "There was a problem signing that person out. Please try again.",
404
+ "activateFailed": "There was a problem switching accounts. Please try again."
400
405
  },
401
406
  "confirms": {
402
407
  "remove": "Are you sure you want to remove {{displayName}} from this device? You'll need to sign in again to access this account.",
403
408
  "logoutAll": "Are you sure you want to sign out of all accounts? This will remove all saved accounts from this device.",
404
409
  "remoteLogout": "Are you sure you want to sign out from \"{{deviceName}}\"? This will end the session on that device.",
405
- "logoutOthers": "Are you sure you want to sign out from all {{count}} other device(s)? This will end sessions on all other devices except this one."
410
+ "logoutOthers": "Are you sure you want to sign out from all {{count}} other device(s)? This will end sessions on all other devices except this one.",
411
+ "removeContextTitle": "Remove this account?",
412
+ "removeContext": "Stop {{person}} acting as {{account}} on this device? Anyone else who reaches {{account}} here keeps their access.",
413
+ "removePrincipalTitle": "Sign out of this device?",
414
+ "removePrincipal": "Sign {{name}} out of this device? Every account they reach here is removed. Nobody else is affected."
406
415
  },
407
416
  "device": {
408
417
  "loadingTitle": "Loading device sessions...",
@@ -439,6 +448,14 @@
439
448
  "openedInCommons": "Opened in Commons",
440
449
  "confirming": "Confirming identity",
441
450
  "confirmed": "Identity confirmed"
451
+ },
452
+ "context": {
453
+ "unavailable": "Unavailable right now",
454
+ "operatedBy": "Operated by {{name}}",
455
+ "remove": "Remove {{account}} from {{person}}"
456
+ },
457
+ "principal": {
458
+ "signOut": "Sign {{name}} out of this device"
442
459
  }
443
460
  },
444
461
  "reputation": {
@@ -636,13 +636,22 @@
636
636
  "remoteSignOutFailed": "Hubo un problema al cerrar sesión en el dispositivo. Inténtalo de nuevo.",
637
637
  "noOtherDeviceSessions": "No se encontraron otras sesiones de dispositivo para cerrar.",
638
638
  "signOutOthersSuccess": "¡Sesiones cerradas correctamente en los demás dispositivos!",
639
- "signOutOthersFailed": "Hubo un problema al cerrar sesión en otros dispositivos. Inténtalo de nuevo."
639
+ "signOutOthersFailed": "Hubo un problema al cerrar sesión en otros dispositivos. Inténtalo de nuevo.",
640
+ "contextRemoved": "Se quitó {{account}}",
641
+ "contextRemoveFailed": "Hubo un problema al quitar esa cuenta. Inténtalo de nuevo.",
642
+ "principalRemoved": "Se cerró la sesión de {{name}} en este dispositivo",
643
+ "principalRemoveFailed": "Hubo un problema al cerrar esa sesión. Inténtalo de nuevo.",
644
+ "activateFailed": "Hubo un problema al cambiar de cuenta. Inténtalo de nuevo."
640
645
  },
641
646
  "confirms": {
642
647
  "remove": "¿Seguro que quieres eliminar a {{displayName}} de este dispositivo? Tendrás que iniciar sesión de nuevo para acceder a esta cuenta.",
643
648
  "logoutAll": "¿Seguro que quieres cerrar sesión en todas las cuentas? Esto eliminará todas las cuentas guardadas de este dispositivo.",
644
649
  "remoteLogout": "¿Seguro que quieres cerrar sesión en \"{{deviceName}}\"? Esto finalizará la sesión en ese dispositivo.",
645
- "logoutOthers": "¿Seguro que quieres cerrar sesión en los otros {{count}} dispositivo(s)? Esto finalizará las sesiones en todos los demás dispositivos excepto en este."
650
+ "logoutOthers": "¿Seguro que quieres cerrar sesión en los otros {{count}} dispositivo(s)? Esto finalizará las sesiones en todos los demás dispositivos excepto en este.",
651
+ "removeContextTitle": "¿Quitar esta cuenta?",
652
+ "removeContext": "¿Dejar de usar {{account}} como {{person}} en este dispositivo? Quien más acceda a {{account}} aquí lo conserva.",
653
+ "removePrincipalTitle": "¿Cerrar sesión en este dispositivo?",
654
+ "removePrincipal": "¿Cerrar la sesión de {{name}} en este dispositivo? Se quitan todas las cuentas a las que llega desde aquí. No afecta a nadie más."
646
655
  },
647
656
  "device": {
648
657
  "loadingTitle": "Cargando sesiones de dispositivo...",
@@ -679,6 +688,14 @@
679
688
  "openedInCommons": "Abierto en Commons",
680
689
  "confirming": "Confirmando identidad",
681
690
  "confirmed": "Identidad confirmada"
691
+ },
692
+ "context": {
693
+ "unavailable": "No disponible ahora mismo",
694
+ "operatedBy": "Gestionada por {{name}}",
695
+ "remove": "Quitar {{account}} de {{person}}"
696
+ },
697
+ "principal": {
698
+ "signOut": "Cerrar la sesión de {{name}} en este dispositivo"
682
699
  }
683
700
  },
684
701
  "feedback": {
package/dist/esm/index.js CHANGED
@@ -173,16 +173,32 @@ export { SessionClient } from './session/SessionClient.js';
173
173
  export { createSessionClientHost } from './session/sessionClientHost.js';
174
174
  export { createSessionClient } from './session/createSessionClient.js';
175
175
  export { deviceStateToClientSessions, activeSessionIdOf, activeUserOf, accountIdsOf, } from './session/projectSessionState.js';
176
- // Unified account-list projection (THE single source of truth for the account
177
- // chooser: device sign-ins account graph, deduped by accountId). Pure +
178
- // I/O-free the caller hydrates profiles via `getUsersByIds`. Shared by
179
- // `@oxyhq/services` and auth.oxy.so so the list can't diverge.
180
- // `isSwitchTargetAccount` is the structural half ("is this kind switchable at
181
- // all?"); `canSwitchIntoAccount` adds the caller's `account:act_as` permission.
182
- // Both are exported so surfaces that render `AccountNode`s rather than the
183
- // projection the Console workspace switcher, managed-accounts rows ask the
184
- // SAME questions instead of testing a kind literal.
185
- export { isSwitchTargetAccount, canSwitchIntoAccount, projectSwitchableAccounts, switchableAccountIds, } from './session/accountProjection.js';
176
+ // Pure projections over the device DIRECTORY (`GET /session/device/directory`,
177
+ // ADR 0002) the read model that keeps the actor (the human who authenticated)
178
+ // and the subject (the account being acted as) apart. The flat
179
+ // `DeviceSessionState` collapses them into one row, so it can neither tell
180
+ // "signed in as an org" from "a person operating that org" nor hold two people
181
+ // reaching the same org on one device.
182
+ // `canActivateContext` is the switchability question `available` alone, never
183
+ // composed with `onDevice`, which is a different fact in both directions.
184
+ // `projectDevicePrincipals` is the switcher's shape: people, each with what
185
+ // they may become. Grouped rather than flat because the same organization
186
+ // reached through two people is TWO rows under two humans, which a list keyed
187
+ // by account cannot say.
188
+ export { canActivateContext, directoryDisplayName, directoryHandle, projectDevicePrincipals, resolveActiveContext, resolveDeviceContext, } from './session/deviceDirectory.js';
189
+ // The switcher's RENDER model over that projection — names, handles and avatar
190
+ // URLs resolved once. Shared by `@oxyhq/services`' account dialog and the
191
+ // auth.oxy.so chooser so the two cannot drift, the same reason the flat
192
+ // projection lived here before it.
193
+ export { buildSwitcherRows, showsPrincipalHeaders } from './session/deviceSwitcherRows.js';
194
+ // The switch-target predicates over the account GRAPH — a list of accounts to
195
+ // manage, not the device's list of identities to become (that is the directory
196
+ // above). `isSwitchTargetAccount` is the structural half ("is this kind
197
+ // switchable at all?"); `canSwitchIntoAccount` adds the caller's
198
+ // `account:act_as` permission. Exported so the surfaces that render
199
+ // `AccountNode`s — the Console workspace switcher, managed-accounts rows — ask
200
+ // the SAME questions instead of testing a kind literal.
201
+ export { isSwitchTargetAccount, canSwitchIntoAccount, } from './session/accountSwitchTargets.js';
186
202
  // Headless controller for the unified account dialog. Framework-agnostic
187
203
  // state machine + subscribe/getSnapshot store (bind via `useSyncExternalStore`)
188
204
  // — sign-in is passkey (WebAuthn) or the Commons QR / shared-keychain handoff;
@@ -198,6 +214,12 @@ export { AccountDialogController, createAccountDialogController, } from './sessi
198
214
  // via `POST /session/device/token`.
199
215
  // ---------------------------------------------------------------------------
200
216
  export { createWebAuthStateStore, createNativeAuthStateStore, createMemoryAuthStateStore, AUTH_STATE_STORAGE_KEY, } from './session/authStateStore.js';
217
+ // The shared NATIVE DeviceSession credential — how several official apps on one
218
+ // device end up on ONE `DeviceSession` and therefore one active context. It is an
219
+ // ordinary rotatable/revocable `deviceId` + `deviceSecret`, deliberately NOT the
220
+ // Commons private identity key: an app that only needs a session must never be
221
+ // handed the key that signs identity approvals.
222
+ export { createSharedMirroringAuthStateStore, decideSharedDeviceJoin, decideSharedDevicePublish, normalizeSharedDeviceSessionRead, publishProvenDeviceCredential, readLocalDeviceCredential, } from './session/sharedDeviceCredential.js';
201
223
  // Identity-bound sessions (the identity vault). The pin is the durable
202
224
  // `{publicKey, accountId}` binding between this device's PRIMARY identity key
203
225
  // and the account it authenticates as; it is what keeps such a client from
@@ -1140,6 +1140,23 @@ export function OxyServicesAuthMixin(Base) {
1140
1140
  * response this method used before were an Oxy invention no OAuth library
1141
1141
  * could interoperate with; the endpoint no longer accepts them. The method's
1142
1142
  * OWN signature is unchanged, so callers are unaffected.
1143
+ *
1144
+ * `deviceId` + `deviceSecret` are OPTIONAL and their absence is a valid
1145
+ * outcome, not an error. A third-party grant is meant to be isolated from the
1146
+ * browser's shared DeviceSession, so the token endpoint must be free to return
1147
+ * no device credential at all — the guard that used to require the pair made
1148
+ * that omission unshippable, since it turned every third-party sign-in through
1149
+ * the SDK into a silent `exchange-failed`.
1150
+ *
1151
+ * The cost is real and deliberate: a DEVICE-LESS session cannot use the
1152
+ * zero-cookie mint lane (`POST /session/device/token`), because that lane's
1153
+ * whole proof is possession of a `deviceSecret`. Its lifetime is therefore the
1154
+ * access token itself — nothing persists a restore credential, the cold boot's
1155
+ * `device-secret-mint` step reports `no-secret` and skips, and the refresh
1156
+ * scheduler has nothing to re-mint from. When the token expires the session
1157
+ * ends LOUDLY: the 401 lane clears the tokens and the provider resolves signed
1158
+ * out, so the app can run the OAuth flow again. It never degrades into a
1159
+ * session that looks alive and cannot refresh.
1143
1160
  */
1144
1161
  async exchangeOAuthCode(params) {
1145
1162
  try {
@@ -1161,7 +1178,9 @@ export function OxyServicesAuthMixin(Base) {
1161
1178
  const deviceId = typeof record.deviceId === 'string' ? record.deviceId : undefined;
1162
1179
  const deviceSecret = typeof record.deviceSecret === 'string' ? record.deviceSecret : undefined;
1163
1180
  const userRaw = record.user;
1164
- if (!sessionId || !deviceId || !deviceSecret || !userRaw || typeof userRaw !== 'object') {
1181
+ // The device pair is NOT part of this guard see the note above. What is
1182
+ // still mandatory is what identifies the session at all.
1183
+ if (!sessionId || !userRaw || typeof userRaw !== 'object') {
1165
1184
  throw new Error('auth/oauth/token returned an incomplete session payload');
1166
1185
  }
1167
1186
  const userObj = userRaw;
@@ -1174,12 +1193,17 @@ export function OxyServicesAuthMixin(Base) {
1174
1193
  if (accessToken) {
1175
1194
  this.setTokens(accessToken);
1176
1195
  }
1196
+ if (!deviceId || !deviceSecret) {
1197
+ logger.debug('auth/oauth/token returned no device credential — this session lives only as long as its access token', { component: 'oxy.auth', method: 'exchangeOAuthCode' });
1198
+ }
1177
1199
  return {
1178
1200
  sessionId,
1179
- deviceId,
1180
1201
  expiresAt,
1181
1202
  accessToken,
1182
- deviceSecret,
1203
+ // Omitted rather than set to `undefined` when the server sent no device
1204
+ // credential, so a device-less grant serializes as the absence it is.
1205
+ ...(deviceId ? { deviceId } : {}),
1206
+ ...(deviceSecret ? { deviceSecret } : {}),
1183
1207
  user: {
1184
1208
  id: userId,
1185
1209
  username: typeof userObj.username === 'string' ? userObj.username : undefined,
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Chains — the shared record log every Oxy app reads and writes.
3
+ *
4
+ * A person has ONE chain. An app appends its own records to it and projects its
5
+ * feeds from what it reads back, instead of keeping a private copy of the same
6
+ * person's activity. This mixin is the client half of `/chains` in oxy-api, and
7
+ * it exists so that adopting the chain costs an app no HTTP of its own — the
8
+ * whole point of the shared substrate is that the second app writes less code
9
+ * than the first, not the same amount in a different file.
10
+ *
11
+ * ## Both calls are SERVICE-authenticated
12
+ *
13
+ * They go through `makeServiceRequest`, so they only work on a backend that has
14
+ * called `configureServiceAuth()`. That is not an accident of implementation: an
15
+ * append writes to someone else's chain and a read spans many subjects, so
16
+ * neither belongs in a browser holding a user session. A frontend that needs
17
+ * this asks its own backend.
18
+ *
19
+ * The authority is checked server-side and cannot be talked out of from here:
20
+ * `chains:write` plus the application's own `chainNamespaces` for an append,
21
+ * `chains:read` plus the public-collection policy for a read. A call that
22
+ * violates either gets a 403 or an empty page — this client adds no
23
+ * pre-validation that could drift from the server's answer.
24
+ */
25
+ export function OxyServicesChainsMixin(Base) {
26
+ return class extends Base {
27
+ constructor(...args) {
28
+ super(...args);
29
+ }
30
+ /**
31
+ * Append a record to `oxyUserId`'s chain under `collection`/`rkey`.
32
+ *
33
+ * Oxy issues and signs it; the calling app never holds a chain signing key.
34
+ * `rkey` is the app's own id for the thing — reusing it later supersedes the
35
+ * earlier record for that key, which is how an edit works.
36
+ *
37
+ * Requires the `chains:write` scope AND `collection` falling under one of
38
+ * this application's granted `chainNamespaces`. Both are enforced by the
39
+ * server; a violation throws with a 403.
40
+ */
41
+ async appendChainRecord(params) {
42
+ return this.makeServiceRequest('POST', '/chains/records', params);
43
+ }
44
+ /**
45
+ * Records published by any of `oxyUserIds` under any of `collections`,
46
+ * oldest first — the read a cross-app feed is projected from.
47
+ *
48
+ * Only collections Oxy declares PUBLIC come back, whatever is asked for; a
49
+ * private one yields nothing rather than an error.
50
+ *
51
+ * **Re-poll from slightly BEFORE your last cursor and dedupe by
52
+ * `recordId`.** The chain's pagination axis is a transaction-start
53
+ * timestamp, so a record can commit behind a cursor that already passed it.
54
+ * Re-delivering one costs bytes; skipping one costs a record that never
55
+ * appears. Projections are expected to be idempotent for exactly this
56
+ * reason.
57
+ */
58
+ async readChainRecords(params) {
59
+ const query = new URLSearchParams({
60
+ authors: params.oxyUserIds.join(','),
61
+ collections: params.collections.join(','),
62
+ });
63
+ if (params.since)
64
+ query.set('since', params.since);
65
+ if (params.limit !== undefined)
66
+ query.set('limit', String(params.limit));
67
+ return this.makeServiceRequest('GET', `/chains/records?${query.toString()}`);
68
+ }
69
+ };
70
+ }