@oxyhq/core 12.10.6 → 12.11.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 (126) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/boot/sessionColdBoot.js +142 -37
  3. package/dist/cjs/i18n/locales/ar-SA.json +13 -1
  4. package/dist/cjs/i18n/locales/ca-ES.json +13 -1
  5. package/dist/cjs/i18n/locales/de-DE.json +13 -1
  6. package/dist/cjs/i18n/locales/en-US.json +13 -4
  7. package/dist/cjs/i18n/locales/es-ES.json +13 -4
  8. package/dist/cjs/i18n/locales/fr-FR.json +13 -1
  9. package/dist/cjs/i18n/locales/it-IT.json +13 -1
  10. package/dist/cjs/i18n/locales/ja-JP.json +13 -1
  11. package/dist/cjs/i18n/locales/ko-KR.json +13 -1
  12. package/dist/cjs/i18n/locales/locales/ar-SA.json +13 -1
  13. package/dist/cjs/i18n/locales/locales/ca-ES.json +13 -1
  14. package/dist/cjs/i18n/locales/locales/de-DE.json +13 -1
  15. package/dist/cjs/i18n/locales/locales/en-US.json +13 -4
  16. package/dist/cjs/i18n/locales/locales/es-ES.json +13 -4
  17. package/dist/cjs/i18n/locales/locales/fr-FR.json +13 -1
  18. package/dist/cjs/i18n/locales/locales/it-IT.json +13 -1
  19. package/dist/cjs/i18n/locales/locales/ja-JP.json +13 -1
  20. package/dist/cjs/i18n/locales/locales/ko-KR.json +13 -1
  21. package/dist/cjs/i18n/locales/locales/pt-PT.json +13 -1
  22. package/dist/cjs/i18n/locales/locales/zh-CN.json +13 -1
  23. package/dist/cjs/i18n/locales/pt-PT.json +13 -1
  24. package/dist/cjs/i18n/locales/zh-CN.json +13 -1
  25. package/dist/cjs/index.js +31 -5
  26. package/dist/cjs/mixins/OxyServices.auth.js +257 -17
  27. package/dist/cjs/mixins/OxyServices.deviceBoot.js +54 -3
  28. package/dist/cjs/mixins/OxyServices.notifications.js +63 -0
  29. package/dist/cjs/mixins/index.js +5 -0
  30. package/dist/cjs/session/SessionClient.js +40 -4
  31. package/dist/cjs/session/accountDialogController.js +288 -41
  32. package/dist/cjs/session/identityPin.js +256 -0
  33. package/dist/cjs/session/identitySession.js +135 -0
  34. package/dist/cjs/session/projectSessionState.js +54 -15
  35. package/dist/cjs/session/refresh.js +73 -8
  36. package/dist/cjs/utils/commonsDelivery.js +59 -0
  37. package/dist/cjs/utils/oauthPkce.js +33 -3
  38. package/dist/esm/.tsbuildinfo +1 -1
  39. package/dist/esm/boot/sessionColdBoot.js +142 -37
  40. package/dist/esm/i18n/locales/ar-SA.json +13 -1
  41. package/dist/esm/i18n/locales/ca-ES.json +13 -1
  42. package/dist/esm/i18n/locales/de-DE.json +13 -1
  43. package/dist/esm/i18n/locales/en-US.json +13 -4
  44. package/dist/esm/i18n/locales/es-ES.json +13 -4
  45. package/dist/esm/i18n/locales/fr-FR.json +13 -1
  46. package/dist/esm/i18n/locales/it-IT.json +13 -1
  47. package/dist/esm/i18n/locales/ja-JP.json +13 -1
  48. package/dist/esm/i18n/locales/ko-KR.json +13 -1
  49. package/dist/esm/i18n/locales/locales/ar-SA.json +13 -1
  50. package/dist/esm/i18n/locales/locales/ca-ES.json +13 -1
  51. package/dist/esm/i18n/locales/locales/de-DE.json +13 -1
  52. package/dist/esm/i18n/locales/locales/en-US.json +13 -4
  53. package/dist/esm/i18n/locales/locales/es-ES.json +13 -4
  54. package/dist/esm/i18n/locales/locales/fr-FR.json +13 -1
  55. package/dist/esm/i18n/locales/locales/it-IT.json +13 -1
  56. package/dist/esm/i18n/locales/locales/ja-JP.json +13 -1
  57. package/dist/esm/i18n/locales/locales/ko-KR.json +13 -1
  58. package/dist/esm/i18n/locales/locales/pt-PT.json +13 -1
  59. package/dist/esm/i18n/locales/locales/zh-CN.json +13 -1
  60. package/dist/esm/i18n/locales/pt-PT.json +13 -1
  61. package/dist/esm/i18n/locales/zh-CN.json +13 -1
  62. package/dist/esm/index.js +14 -1
  63. package/dist/esm/mixins/OxyServices.auth.js +257 -17
  64. package/dist/esm/mixins/OxyServices.deviceBoot.js +52 -3
  65. package/dist/esm/mixins/OxyServices.notifications.js +60 -0
  66. package/dist/esm/mixins/index.js +5 -0
  67. package/dist/esm/session/SessionClient.js +40 -4
  68. package/dist/esm/session/accountDialogController.js +288 -41
  69. package/dist/esm/session/identityPin.js +249 -0
  70. package/dist/esm/session/identitySession.js +131 -0
  71. package/dist/esm/session/projectSessionState.js +54 -15
  72. package/dist/esm/session/refresh.js +73 -8
  73. package/dist/esm/utils/commonsDelivery.js +54 -0
  74. package/dist/esm/utils/oauthPkce.js +31 -2
  75. package/dist/types/.tsbuildinfo +1 -1
  76. package/dist/types/boot/sessionColdBoot.d.ts +38 -1
  77. package/dist/types/index.d.ts +12 -4
  78. package/dist/types/mixins/OxyServices.auth.d.ts +262 -11
  79. package/dist/types/mixins/OxyServices.deviceBoot.d.ts +31 -1
  80. package/dist/types/mixins/OxyServices.notifications.d.ts +143 -0
  81. package/dist/types/mixins/index.d.ts +2 -1
  82. package/dist/types/session/SessionClient.d.ts +28 -0
  83. package/dist/types/session/accountDialogController.d.ts +187 -9
  84. package/dist/types/session/identityPin.d.ts +87 -0
  85. package/dist/types/session/identitySession.d.ts +105 -0
  86. package/dist/types/session/projectSessionState.d.ts +21 -19
  87. package/dist/types/session/refresh.d.ts +32 -1
  88. package/dist/types/utils/commonsDelivery.d.ts +105 -0
  89. package/dist/types/utils/oauthPkce.d.ts +21 -1
  90. package/package.json +2 -2
  91. package/src/boot/__tests__/sessionColdBoot.identity.test.ts +393 -0
  92. package/src/boot/sessionColdBoot.ts +183 -37
  93. package/src/i18n/locales/ar-SA.json +13 -1
  94. package/src/i18n/locales/ca-ES.json +13 -1
  95. package/src/i18n/locales/de-DE.json +13 -1
  96. package/src/i18n/locales/en-US.json +13 -4
  97. package/src/i18n/locales/es-ES.json +13 -4
  98. package/src/i18n/locales/fr-FR.json +13 -1
  99. package/src/i18n/locales/it-IT.json +13 -1
  100. package/src/i18n/locales/ja-JP.json +13 -1
  101. package/src/i18n/locales/ko-KR.json +13 -1
  102. package/src/i18n/locales/pt-PT.json +13 -1
  103. package/src/i18n/locales/zh-CN.json +13 -1
  104. package/src/index.ts +49 -0
  105. package/src/mixins/OxyServices.auth.ts +464 -24
  106. package/src/mixins/OxyServices.deviceBoot.ts +54 -2
  107. package/src/mixins/OxyServices.notifications.ts +142 -0
  108. package/src/mixins/__tests__/commonsSignIn.test.ts +754 -2
  109. package/src/mixins/__tests__/deviceTokenMintPinned.test.ts +113 -0
  110. package/src/mixins/__tests__/preSessionSkipAuth.test.ts +18 -0
  111. package/src/mixins/index.ts +6 -0
  112. package/src/session/SessionClient.ts +57 -4
  113. package/src/session/__tests__/SessionClient.identityPin.test.ts +175 -0
  114. package/src/session/__tests__/accountDialogController.test.ts +812 -1
  115. package/src/session/__tests__/identityPin.test.ts +131 -0
  116. package/src/session/__tests__/identitySession.test.ts +194 -0
  117. package/src/session/__tests__/projectSessionState.test.ts +88 -0
  118. package/src/session/__tests__/refresh.identityPin.test.ts +306 -0
  119. package/src/session/accountDialogController.ts +435 -44
  120. package/src/session/identityPin.ts +310 -0
  121. package/src/session/identitySession.ts +206 -0
  122. package/src/session/projectSessionState.ts +61 -13
  123. package/src/session/refresh.ts +103 -9
  124. package/src/utils/__tests__/oauthPkce.test.ts +51 -0
  125. package/src/utils/commonsDelivery.ts +132 -0
  126. package/src/utils/oauthPkce.ts +56 -3
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Identity pin — the durable binding between THIS device's PRIMARY identity key
3
+ * and the account that key authenticates as.
4
+ *
5
+ * An identity-bound client (Commons, the identity vault) must always act as the
6
+ * owner of the local signing key — permanently. The `DeviceSession` it shares
7
+ * with every other Oxy app on the same device tracks a MUTABLE `activeAccountId`
8
+ * that any sibling app can switch; following it silently changes both the user
9
+ * such a client renders and the bearer it sends. The pin is the client-side
10
+ * record that breaks that coupling: `{ publicKey, accountId }`, written when an
11
+ * identity-mode session is established (the only moment both facts are known
12
+ * first-hand), read on every boot, and reconciled against the live
13
+ * `KeyManager.getPublicKey()` before it is trusted (see
14
+ * `resolveIdentityPin` in `identitySession.ts`).
15
+ *
16
+ * It holds NO secret — a public key and an account id, both already known to the
17
+ * server — so it lives in the same per-origin storage as {@link PersistedAuthState}
18
+ * (`authStateStore.ts`) rather than the keychain, and mirrors that module's
19
+ * store shape: `load / save / clear`, an in-memory mirror, a read-back-verified
20
+ * durable write, and graceful degradation when storage is unavailable.
21
+ *
22
+ * ESM-safe (no `require()`); no react/react-native/expo imports.
23
+ */
24
+ import { logger } from '../logger/index.js';
25
+ /**
26
+ * Versioned storage key. Deliberately distinct from the `oxy.auth.*` keys so a
27
+ * session sign-out (which clears the auth blob) and an identity change (which
28
+ * clears the pin) can never take each other down.
29
+ */
30
+ export const IDENTITY_PIN_STORAGE_KEY = 'oxy.identity.pin.v1';
31
+ /**
32
+ * Structural check for a storable identity public key: `KeyManager` only ever
33
+ * persists secp256k1 hex — compressed (66 chars) or uncompressed (130). A stored
34
+ * value of any other shape is corrupt, so it is treated as "no pin" (fail
35
+ * closed) rather than compared. Full curve validation belongs to `KeyManager`;
36
+ * the pin's real authority is the reconcile against the live local key.
37
+ */
38
+ function isStorablePublicKey(value) {
39
+ if (typeof value !== 'string') {
40
+ return false;
41
+ }
42
+ if (value.length !== 66 && value.length !== 130) {
43
+ return false;
44
+ }
45
+ return /^[0-9a-fA-F]+$/.test(value);
46
+ }
47
+ /**
48
+ * Parse + shape-validate a stored blob. Returns `null` for anything that is not
49
+ * a well-formed {@link IdentityPin} (absent, malformed JSON, wrong types, junk
50
+ * public key) so a corrupt entry degrades to "not pinned" rather than throwing —
51
+ * and, critically, never yields a pin that could bind a client to the wrong
52
+ * account.
53
+ */
54
+ function deserialize(raw) {
55
+ if (!raw) {
56
+ return null;
57
+ }
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(raw);
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ if (!parsed || typeof parsed !== 'object') {
66
+ return null;
67
+ }
68
+ const candidate = parsed;
69
+ if (!isStorablePublicKey(candidate.publicKey)) {
70
+ return null;
71
+ }
72
+ if (typeof candidate.accountId !== 'string' || candidate.accountId.length === 0) {
73
+ return null;
74
+ }
75
+ return {
76
+ publicKey: candidate.publicKey.toLowerCase(),
77
+ accountId: candidate.accountId,
78
+ };
79
+ }
80
+ /**
81
+ * Serialize a pin, or `null` when the caller handed over a value that would not
82
+ * survive {@link deserialize} — writing it would produce an entry that silently
83
+ * reads back as "not pinned".
84
+ */
85
+ function serialize(pin) {
86
+ if (!isStorablePublicKey(pin.publicKey) || pin.accountId.length === 0) {
87
+ return null;
88
+ }
89
+ return JSON.stringify({ publicKey: pin.publicKey.toLowerCase(), accountId: pin.accountId });
90
+ }
91
+ /**
92
+ * Whether `pin` still describes the identity currently on this device.
93
+ *
94
+ * `publicKey` comparison is case-insensitive (hex). A `null` local key is a
95
+ * definitive "no identity here" and therefore never a match — the caller clears
96
+ * the pin rather than binding to an account whose key is gone.
97
+ */
98
+ export function identityPinMatches(pin, localPublicKey) {
99
+ if (!pin || !localPublicKey) {
100
+ return false;
101
+ }
102
+ return pin.publicKey.toLowerCase() === localPublicKey.toLowerCase();
103
+ }
104
+ /**
105
+ * A process-lifetime, in-memory {@link IdentityPinStore}. Used directly for
106
+ * tests/SSR and as the degraded fallback of the web store.
107
+ */
108
+ export function createMemoryIdentityPinStore() {
109
+ let current = null;
110
+ return {
111
+ load: async () => current,
112
+ save: async (pin) => {
113
+ if (!serialize(pin)) {
114
+ return false;
115
+ }
116
+ // Memory IS this store's durability backing — the write always lands.
117
+ current = { publicKey: pin.publicKey.toLowerCase(), accountId: pin.accountId };
118
+ return true;
119
+ },
120
+ clear: async () => {
121
+ current = null;
122
+ },
123
+ };
124
+ }
125
+ /**
126
+ * Read the ambient `localStorage`, tolerating the case where merely ACCESSING
127
+ * `window.localStorage` throws (sandboxed iframe `SecurityError`). Returns
128
+ * `null` when storage is unavailable.
129
+ */
130
+ function safeGetLocalStorage() {
131
+ try {
132
+ if (typeof globalThis === 'undefined') {
133
+ return null;
134
+ }
135
+ const store = globalThis.localStorage;
136
+ return store ?? null;
137
+ }
138
+ catch {
139
+ return null;
140
+ }
141
+ }
142
+ /**
143
+ * A `localStorage`-backed {@link IdentityPinStore}. Degrades to an in-memory
144
+ * store when `localStorage` is unreachable, and keeps an in-memory mirror so a
145
+ * failed persist still pins THIS page's lifetime.
146
+ */
147
+ export function createWebIdentityPinStore() {
148
+ const storage = safeGetLocalStorage();
149
+ if (!storage) {
150
+ return createMemoryIdentityPinStore();
151
+ }
152
+ // `undefined` = never written this session → fall back to storage; any set
153
+ // value (including `null` after clear) is authoritative.
154
+ let sessionMirror;
155
+ return {
156
+ load: async () => {
157
+ if (sessionMirror !== undefined) {
158
+ return sessionMirror;
159
+ }
160
+ try {
161
+ return deserialize(storage.getItem(IDENTITY_PIN_STORAGE_KEY));
162
+ }
163
+ catch {
164
+ return null;
165
+ }
166
+ },
167
+ save: async (pin) => {
168
+ const json = serialize(pin);
169
+ if (!json) {
170
+ logger.error('[identityPin] refusing to persist a malformed identity pin', undefined, { component: 'identityPin' });
171
+ return false;
172
+ }
173
+ sessionMirror = { publicKey: pin.publicKey.toLowerCase(), accountId: pin.accountId };
174
+ try {
175
+ storage.setItem(IDENTITY_PIN_STORAGE_KEY, json);
176
+ if (storage.getItem(IDENTITY_PIN_STORAGE_KEY) === json) {
177
+ return true;
178
+ }
179
+ logger.error('[identityPin] read-back mismatch after save — the identity pin did not persist; this process stays pinned via the in-memory mirror but the next boot must re-establish the identity session', undefined, { component: 'identityPin' });
180
+ return false;
181
+ }
182
+ catch (error) {
183
+ logger.error('[identityPin] persist threw — the identity pin did not persist; this process stays pinned via the in-memory mirror but the next boot must re-establish the identity session', error, { component: 'identityPin' });
184
+ return false;
185
+ }
186
+ },
187
+ clear: async () => {
188
+ sessionMirror = null;
189
+ try {
190
+ storage.removeItem(IDENTITY_PIN_STORAGE_KEY);
191
+ }
192
+ catch (error) {
193
+ logger.debug('[identityPin] clear failed', { component: 'identityPin' }, error);
194
+ }
195
+ },
196
+ };
197
+ }
198
+ /**
199
+ * A native {@link IdentityPinStore} over an injected async key/value store —
200
+ * the same seam `createNativeAuthStateStore` uses, so `@oxyhq/core` never
201
+ * imports `expo-secure-store`.
202
+ */
203
+ export function createNativeIdentityPinStore(storage) {
204
+ let sessionMirror;
205
+ return {
206
+ load: async () => {
207
+ if (sessionMirror !== undefined) {
208
+ return sessionMirror;
209
+ }
210
+ try {
211
+ return deserialize(await storage.getItem(IDENTITY_PIN_STORAGE_KEY));
212
+ }
213
+ catch {
214
+ return null;
215
+ }
216
+ },
217
+ save: async (pin) => {
218
+ const json = serialize(pin);
219
+ if (!json) {
220
+ logger.error('[identityPin] refusing to persist a malformed identity pin', undefined, { component: 'identityPin' });
221
+ return false;
222
+ }
223
+ sessionMirror = { publicKey: pin.publicKey.toLowerCase(), accountId: pin.accountId };
224
+ try {
225
+ await storage.setItem(IDENTITY_PIN_STORAGE_KEY, json);
226
+ // A native write can resolve WITHOUT throwing yet not land, so a
227
+ // read-back is the only reliable proof.
228
+ if ((await storage.getItem(IDENTITY_PIN_STORAGE_KEY)) === json) {
229
+ return true;
230
+ }
231
+ logger.error('[identityPin] read-back mismatch after save — the identity pin did not persist; this app run stays pinned via the in-memory mirror but the next cold start must re-establish the identity session', undefined, { component: 'identityPin' });
232
+ return false;
233
+ }
234
+ catch (error) {
235
+ logger.error('[identityPin] persist threw — the identity pin did not persist; this app run stays pinned via the in-memory mirror but the next cold start must re-establish the identity session', error, { component: 'identityPin' });
236
+ return false;
237
+ }
238
+ },
239
+ clear: async () => {
240
+ sessionMirror = null;
241
+ try {
242
+ await storage.removeItem(IDENTITY_PIN_STORAGE_KEY);
243
+ }
244
+ catch (error) {
245
+ logger.debug('[identityPin] clear failed', { component: 'identityPin' }, error);
246
+ }
247
+ },
248
+ };
249
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Identity-bound session — pin reconciliation + establishment.
3
+ *
4
+ * This is the SDK half of "an identity vault's authenticated user is whoever
5
+ * owns the local primary key". Two operations, both consumed by the cold boot
6
+ * (`boot/sessionColdBoot.ts`) and the re-mint lane (`session/refresh.ts`):
7
+ *
8
+ * - {@link resolveIdentityPin} — read the persisted `{publicKey, accountId}`
9
+ * pin and reconcile it against the identity currently on this device. A
10
+ * definitive mismatch (the key was replaced, or is gone) CLEARS the pin; an
11
+ * INDETERMINATE read (keychain locked / storage threw) leaves it untouched.
12
+ * - {@link establishIdentitySession} — mint a session from the PRIMARY local
13
+ * key (`getPublicKey` → `requestChallenge` → `signChallenge` →
14
+ * `verifyChallenge`), persist the resulting device credential, and write the
15
+ * pin. This is the identity-mode replacement for the shared-keychain lane,
16
+ * which reads the CROSS-APP shared slot and may therefore hold a different
17
+ * identity than this device's primary.
18
+ *
19
+ * Both take their key/signature functions from an injectable {@link IdentityBinding}
20
+ * (defaulting to `KeyManager` / `SignatureService`) so the lanes above stay
21
+ * testable without a keychain.
22
+ *
23
+ * ESM-safe (no `require()`); no react/react-native/expo imports.
24
+ */
25
+ import { KeyManager } from '../crypto/keyManager.js';
26
+ import { SignatureService } from '../crypto/signatureService.js';
27
+ import { identityPinMatches } from './identityPin.js';
28
+ import { logger } from '../logger/index.js';
29
+ function readPublicKeyOf(binding) {
30
+ return binding.readPublicKey ?? (() => KeyManager.getPublicKey());
31
+ }
32
+ function signChallengeOf(binding) {
33
+ return binding.signChallenge ?? ((challenge) => SignatureService.signChallenge(challenge));
34
+ }
35
+ /**
36
+ * Read the persisted pin and reconcile it against the identity on this device.
37
+ *
38
+ * Returns the pin ONLY when the local primary public key still matches it — that
39
+ * is the single condition under which a client may bind its token and its
40
+ * rendered user to that account.
41
+ *
42
+ * Outcomes:
43
+ * - no pin stored → `null` (nothing to clear).
44
+ * - local key MATCHES → the pin (trusted).
45
+ * - local key read succeeded and differs / is absent → the identity was
46
+ * replaced or lost: CLEAR the pin and return `null`. Keeping it would pin the
47
+ * client to an account it can no longer prove control of.
48
+ * - the local key read THREW (keychain locked, storage unavailable) → return
49
+ * `null` WITHOUT clearing. A read that produced no verdict is never evidence
50
+ * of an identity change (the same rule `KeyManager` applies to its own
51
+ * transient errors); the caller falls through to the identity sign-in lane,
52
+ * which fails closed on a locked keychain rather than adopting a foreign
53
+ * account.
54
+ */
55
+ export async function resolveIdentityPin(binding) {
56
+ const pin = await binding.pinStore.load();
57
+ if (!pin) {
58
+ return null;
59
+ }
60
+ let localPublicKey;
61
+ try {
62
+ localPublicKey = await readPublicKeyOf(binding)();
63
+ }
64
+ catch (error) {
65
+ logger.debug('Identity key read did not produce a verdict — keeping the pin untouched', { component: 'identitySession', method: 'resolveIdentityPin' }, error);
66
+ return null;
67
+ }
68
+ if (identityPinMatches(pin, localPublicKey)) {
69
+ return pin;
70
+ }
71
+ logger.warn('Identity pin no longer matches the device identity key — clearing it (the identity was replaced or removed)', { component: 'identitySession', method: 'resolveIdentityPin' });
72
+ await binding.pinStore.clear();
73
+ return null;
74
+ }
75
+ /**
76
+ * Establish a session for the device's PRIMARY identity key and pin it.
77
+ *
78
+ * `requestChallenge` → `signChallenge` → `verifyChallenge`; `verifyChallenge`
79
+ * plants the access token itself. The server resolves the account from the
80
+ * VERIFIED SIGNER, so the returned session is identity-authoritative — it
81
+ * ignores the device's `activeAccountId` entirely.
82
+ *
83
+ * Side effects on success: the durable device credential is persisted (so the
84
+ * next boot can take the fast pinned-mint lane) and the pin is written.
85
+ *
86
+ * Returns `null` — never throws — for the two "nothing to do" cases: no local
87
+ * identity (including every web caller, where `KeyManager` has no key), and a
88
+ * verify that produced no access token. Network/crypto failures propagate so the
89
+ * caller can classify them.
90
+ */
91
+ export async function establishIdentitySession(args) {
92
+ const { oxy, store, binding, requestOptions } = args;
93
+ const publicKey = await readPublicKeyOf(binding)();
94
+ if (!publicKey) {
95
+ return null;
96
+ }
97
+ const { challenge } = await oxy.requestChallenge(publicKey, requestOptions);
98
+ const signed = await signChallengeOf(binding)(challenge);
99
+ if (signed.publicKey.toLowerCase() !== publicKey.toLowerCase()) {
100
+ // The signer disagrees with the key we resolved a challenge for — the
101
+ // identity changed mid-flight, or a custom signer was misconfigured. Refuse:
102
+ // verifying under a different key would bind this client to another account.
103
+ throw new Error('Identity sign-in aborted: the signing key does not match the device identity key');
104
+ }
105
+ // `signed.challenge` carries the SIGNATURE (mirrors `signChallengeWithSharedKey`).
106
+ const session = await oxy.verifyChallenge(signed.publicKey, challenge, signed.challenge, signed.timestamp, binding.deviceName, binding.deviceFingerprint, requestOptions);
107
+ if (!session?.accessToken) {
108
+ return null;
109
+ }
110
+ // Persist the rotating device credential so later boots re-mint through the
111
+ // fast `POST /session/device/token` lane instead of re-signing a challenge.
112
+ if (session.deviceId && session.deviceSecret) {
113
+ await store.save({
114
+ sessionId: session.sessionId,
115
+ userId: session.user.id,
116
+ deviceId: session.deviceId,
117
+ deviceSecret: session.deviceSecret,
118
+ accessToken: session.accessToken,
119
+ expiresAt: session.expiresAt,
120
+ });
121
+ }
122
+ const pin = { publicKey: publicKey.toLowerCase(), accountId: session.user.id };
123
+ // A failed pin persist is NOT fatal: this process is already pinned in memory,
124
+ // and a later boot without a pin skips the (unpinned) mint lane and re-runs
125
+ // this exact lane, which rewrites it. Never fail an established session on it.
126
+ const pinned = await binding.pinStore.save(pin);
127
+ if (!pinned) {
128
+ logger.warn('Identity session established but the pin did not durably persist — the next cold start will re-establish it', { component: 'identitySession', method: 'establishIdentitySession' });
129
+ }
130
+ return { session, pin };
131
+ }
@@ -8,7 +8,25 @@
8
8
  * `oxyServices.getUsersByIds(accountIdsOf(state))` and builds `usersById`
9
9
  * from the result before calling `deviceStateToClientSessions` /
10
10
  * `activeUserOf`.
11
+ *
12
+ * Each projection takes an OPTIONAL `pinnedAccountId`. Omit it (or pass `null`)
13
+ * and the projection resolves the device's `activeAccountId` exactly as before.
14
+ * Pass it — an IDENTITY-BOUND client, whose user is fixed by the local identity
15
+ * key — and the projection resolves THAT account instead, so an account switch
16
+ * made by another app on the same device changes `state` but never the user this
17
+ * client renders.
11
18
  */
19
+ /**
20
+ * The account a projection should resolve: the pin when one is supplied and
21
+ * non-empty, else the device's active account. An empty-string pin is treated as
22
+ * "not pinned" rather than as an account that can never match.
23
+ */
24
+ function boundAccountIdOf(state, pinnedAccountId) {
25
+ if (typeof pinnedAccountId === 'string' && pinnedAccountId.length > 0) {
26
+ return pinnedAccountId;
27
+ }
28
+ return state.activeAccountId;
29
+ }
12
30
  /**
13
31
  * Maps every `SessionAccount` in `state.accounts` to a `ClientSession`.
14
32
  *
@@ -20,9 +38,14 @@
20
38
  * though `ClientSession` only stores `userId` — a session is still
21
39
  * projected for an account whose id is absent from `usersById` (no
22
40
  * placeholder user is fabricated).
41
+ *
42
+ * `isCurrent` marks the PINNED account when one is supplied, so it can never
43
+ * disagree with {@link activeSessionIdOf} / {@link activeUserOf} for the same
44
+ * pin.
23
45
  */
24
- export function deviceStateToClientSessions(state, usersById) {
46
+ export function deviceStateToClientSessions(state, usersById, pinnedAccountId) {
25
47
  const provisionalTimestamp = new Date(state.updatedAt).toISOString();
48
+ const boundAccountId = boundAccountIdOf(state, pinnedAccountId);
26
49
  return state.accounts.map((account) => ({
27
50
  sessionId: account.sessionId,
28
51
  deviceId: state.deviceId,
@@ -30,32 +53,48 @@ export function deviceStateToClientSessions(state, usersById) {
30
53
  expiresAt: provisionalTimestamp,
31
54
  lastActive: provisionalTimestamp,
32
55
  userId: account.accountId,
33
- isCurrent: account.accountId === state.activeAccountId,
56
+ isCurrent: account.accountId === boundAccountId,
34
57
  authuser: account.authuser,
35
58
  }));
36
59
  }
37
60
  /**
38
- * The active account's `sessionId`, or `null` when there is no state or no
39
- * active account is set.
61
+ * The bound account's `sessionId`, or `null` when there is no state, no bound
62
+ * account, or that account has no session on this device.
63
+ *
64
+ * A pinned account that is ABSENT from `state.accounts` yields `null` — the
65
+ * honest signal that this device no longer carries a session for the pinned
66
+ * identity, which the caller answers by re-establishing the identity session
67
+ * (never by adopting the device's active account).
40
68
  */
41
- export function activeSessionIdOf(state) {
42
- if (state === null || state.activeAccountId === null) {
69
+ export function activeSessionIdOf(state, pinnedAccountId) {
70
+ if (state === null) {
71
+ return null;
72
+ }
73
+ const boundAccountId = boundAccountIdOf(state, pinnedAccountId);
74
+ if (boundAccountId === null) {
43
75
  return null;
44
76
  }
45
- const activeAccountId = state.activeAccountId;
46
- const activeAccount = state.accounts.find((account) => account.accountId === activeAccountId);
47
- return activeAccount?.sessionId ?? null;
77
+ const boundAccount = state.accounts.find((account) => account.accountId === boundAccountId);
78
+ return boundAccount?.sessionId ?? null;
48
79
  }
49
80
  /**
50
- * The active account's `User`, resolved from `usersById`. `null` when there
51
- * is no state, no active account is set, or the active account id is absent
52
- * from `usersById`.
81
+ * The bound account's `User`, resolved from `usersById`. `null` when there is no
82
+ * state, no bound account, or the bound account id is absent from `usersById`.
83
+ *
84
+ * A pinned user is resolved from `usersById` alone — deliberately NOT gated on
85
+ * device membership — so a transient device-state gap cannot flicker the
86
+ * identity vault's rendered user. Whether the pinned session still exists on the
87
+ * device is answered by {@link activeSessionIdOf}.
53
88
  */
54
- export function activeUserOf(state, usersById) {
55
- if (state === null || state.activeAccountId === null) {
89
+ export function activeUserOf(state, usersById, pinnedAccountId) {
90
+ if (state === null) {
91
+ return null;
92
+ }
93
+ const boundAccountId = boundAccountIdOf(state, pinnedAccountId);
94
+ if (boundAccountId === null) {
56
95
  return null;
57
96
  }
58
- return usersById.get(state.activeAccountId) ?? null;
97
+ return usersById.get(boundAccountId) ?? null;
59
98
  }
60
99
  /**
61
100
  * All account ids in `state`, suitable for an `oxyServices.getUsersByIds(...)`
@@ -1,3 +1,4 @@
1
+ import { establishIdentitySession, resolveIdentityPin } from './identitySession.js';
1
2
  import { isNative } from '../utils/platform.js';
2
3
  import { extractErrorStatus } from '../utils/errorUtils.js';
3
4
  import { logger } from '../logger/index.js';
@@ -50,9 +51,16 @@ const MAX_FAILURE_BACKOFF_MS = 5 * 60000;
50
51
  * planting. This function performs NO store mutation on failure — the caller
51
52
  * applies the drop/clear policy (which differs web vs native) from the returned
52
53
  * status.
54
+ *
55
+ * `pin` makes the mint IDENTITY-BOUND: the request carries the pinned
56
+ * `accountId` (so the server mints that account's token without touching
57
+ * `activeAccountId`), and the persisted `sessionId`/`userId` are resolved from
58
+ * the PINNED account entry — never from `state.activeAccountId`, whose drift is
59
+ * exactly what the pin exists to stop.
53
60
  */
54
61
  export async function refreshDeviceSecretArm(deps) {
55
62
  const { oxy, store } = deps;
63
+ const pin = deps.pin ?? null;
56
64
  return oxy.httpService.runSingleFlightDeviceSecretMint(async () => {
57
65
  const persisted = await store.load();
58
66
  if (!persisted?.deviceId || !persisted?.deviceSecret) {
@@ -60,7 +68,13 @@ export async function refreshDeviceSecretArm(deps) {
60
68
  }
61
69
  let mint;
62
70
  try {
63
- mint = await oxy.mintFromDeviceSecret(persisted.deviceId, persisted.deviceSecret);
71
+ // Unpinned callers pass NO third argument at all, so the account-mode call
72
+ // shape (and therefore the request body) is untouched by this feature.
73
+ mint = pin
74
+ ? await oxy.mintFromDeviceSecret(persisted.deviceId, persisted.deviceSecret, {
75
+ accountId: pin.accountId,
76
+ })
77
+ : await oxy.mintFromDeviceSecret(persisted.deviceId, persisted.deviceSecret);
64
78
  }
65
79
  catch (error) {
66
80
  if (extractErrorStatus(error) === 401) {
@@ -80,18 +94,26 @@ export async function refreshDeviceSecretArm(deps) {
80
94
  return { status: 'invalid-secret' };
81
95
  if (body.includes('no_active_session'))
82
96
  return { status: 'no-session' };
97
+ // A pinned mint whose account left the device set. The secret is intact —
98
+ // never classify this as a bad secret, or the caller would drop a healthy
99
+ // credential over a stale identity binding.
100
+ if (body.includes('account_not_on_device'))
101
+ return { status: 'account-not-on-device' };
83
102
  return { status: 'transient' };
84
103
  }
85
104
  return { status: 'transient' };
86
105
  }
87
- const active = mint.state.accounts.find((a) => a.accountId === mint.state.activeAccountId);
106
+ // The account this session is BOUND to: the pinned one when identity-bound
107
+ // (the server already minted for it), else the device's active account.
108
+ const boundAccountId = pin ? pin.accountId : mint.state.activeAccountId;
109
+ const bound = mint.state.accounts.find((a) => a.accountId === boundAccountId);
88
110
  const next = {
89
111
  ...persisted,
90
112
  deviceId: mint.state.deviceId,
91
113
  deviceSecret: mint.nextDeviceSecret,
92
114
  accessToken: mint.accessToken,
93
115
  expiresAt: mint.expiresAt,
94
- ...(active ? { sessionId: active.sessionId, userId: active.accountId } : {}),
116
+ ...(bound ? { sessionId: bound.sessionId, userId: bound.accountId } : {}),
95
117
  };
96
118
  // Rotation-in-use anti-loss: persist the NEXT secret and read-back-VERIFY it
97
119
  // landed BEFORE planting the token. A failed durable persist must NOT plant.
@@ -119,11 +141,25 @@ export async function refreshDeviceSecretArm(deps) {
119
141
  * recovered `{deviceId, deviceSecret, …}` is PERSISTED so the fast device-secret
120
142
  * lane is repopulated (mirrors the cold boot's `shared-key-signin` step) — an
121
143
  * in-session shared-key recovery must not leave the fast-lane credential empty.
144
+ *
145
+ * IDENTITY-BOUND clients (`deps.identity`) run a different arm 2: the
146
+ * shared-keychain lane is DISABLED (its cross-app slot may hold a different
147
+ * identity) and replaced by {@link establishIdentitySession}, which re-signs a
148
+ * challenge with the PRIMARY local key and rewrites the pin. Arm 1 is pinned.
122
149
  */
123
150
  export async function refreshPersistedSession(deps) {
124
151
  const { oxy, store } = deps;
125
- const allowSharedKeyFallback = deps.allowSharedKeyFallback ?? isNative();
126
- const arm1 = await refreshDeviceSecretArm({ oxy, store });
152
+ const identity = deps.identity ?? null;
153
+ // The shared keychain is never an identity-bound client's recovery path.
154
+ const allowSharedKeyFallback = identity ? false : (deps.allowSharedKeyFallback ?? isNative());
155
+ // Resolved per call: a re-established identity session can move the pin, and a
156
+ // replaced/removed local key clears it (in which case arm 1 must NOT mint —
157
+ // an unpinned mint would adopt whatever account the device switched to).
158
+ const pin = identity ? await resolveIdentityPin(identity) : null;
159
+ if (identity && !pin) {
160
+ return recoverIdentitySession(oxy, store, identity);
161
+ }
162
+ const arm1 = await refreshDeviceSecretArm({ oxy, store, pin });
127
163
  switch (arm1.status) {
128
164
  case 'ok':
129
165
  return arm1.token;
@@ -139,11 +175,12 @@ export async function refreshPersistedSession(deps) {
139
175
  return null;
140
176
  case 'invalid-secret':
141
177
  case 'no-session': {
142
- // 401: secret diverged or no live session. On a shared-key device drop only
143
- // the secret (keep the identity so arm 2 can recover); otherwise (web) the
178
+ // 401: secret diverged or no live session. When a key-based arm 2 can still
179
+ // recover (native shared key, or an identity-bound client's own primary
180
+ // key) drop ONLY the secret and keep the deviceId; otherwise (web) the
144
181
  // session is over — clear the store.
145
182
  const persisted = await store.load();
146
- if (allowSharedKeyFallback) {
183
+ if (allowSharedKeyFallback || identity) {
147
184
  if (persisted) {
148
185
  await store.save({ ...persisted, deviceSecret: undefined });
149
186
  }
@@ -153,9 +190,17 @@ export async function refreshPersistedSession(deps) {
153
190
  }
154
191
  break;
155
192
  }
193
+ case 'account-not-on-device':
194
+ // The pinned account left this device's session set. The secret is healthy —
195
+ // leave the store untouched and let the identity arm re-establish.
196
+ logger.debug('Pinned device-secret mint rejected: the pinned account is no longer on this device — re-establishing from the identity key', { component: 'refresh', method: 'refreshPersistedSession' });
197
+ break;
156
198
  case 'no-secret':
157
199
  break;
158
200
  }
201
+ if (identity) {
202
+ return recoverIdentitySession(oxy, store, identity);
203
+ }
159
204
  if (allowSharedKeyFallback) {
160
205
  try {
161
206
  const session = await oxy.signInWithSharedIdentity();
@@ -180,6 +225,26 @@ export async function refreshPersistedSession(deps) {
180
225
  }
181
226
  return null;
182
227
  }
228
+ /**
229
+ * Arm 2 for an IDENTITY-BOUND client: re-establish the session from the PRIMARY
230
+ * local key and rewrite the pin (`establishIdentitySession` plants the token and
231
+ * persists the device credential itself).
232
+ *
233
+ * Returns `null` — never throws — when there is no local identity, the verify
234
+ * yielded no token, or the exchange failed: the caller treats that as "could not
235
+ * refresh", exactly like the shared-key arm. A locked keychain therefore ends
236
+ * signed out rather than falling back to the device's active account.
237
+ */
238
+ async function recoverIdentitySession(oxy, store, binding) {
239
+ try {
240
+ const established = await establishIdentitySession({ oxy, store, binding });
241
+ return established?.session.accessToken ?? null;
242
+ }
243
+ catch (error) {
244
+ logger.debug('Identity-key re-sign-in failed', { component: 'refresh', method: 'recoverIdentitySession' }, error);
245
+ return null;
246
+ }
247
+ }
183
248
  /**
184
249
  * Build the reactive `AuthRefreshHandler` (arm 1 + arm 2). Install it via
185
250
  * {@link installAuthRefreshHandler} or directly on