@oxyhq/core 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,6 +34,7 @@ exports.runSessionColdBoot = runSessionColdBoot;
34
34
  const contracts_1 = require("@oxyhq/contracts");
35
35
  const coldBoot_1 = require("../utils/coldBoot");
36
36
  const platform_1 = require("../utils/platform");
37
+ const errorUtils_1 = require("../utils/errorUtils");
37
38
  const keyManager_1 = require("../crypto/keyManager");
38
39
  const loggerUtils_1 = require("../utils/loggerUtils");
39
40
  const refresh_1 = require("../session/refresh");
@@ -165,6 +166,18 @@ function isSameApex(pageHost, apiHost) {
165
166
  function sessionFromPersisted(state, accessToken) {
166
167
  return { sessionId: state.sessionId, userId: state.userId, accessToken };
167
168
  }
169
+ function classifyMintFailure(error) {
170
+ if ((0, errorUtils_1.extractErrorStatus)(error) === 401) {
171
+ // Structural read (not `instanceof Error`): the thrown value can be a plain
172
+ // ApiError-shaped object or come from another realm, where instanceof fails
173
+ // and a `no_active_session` would be misread as a stale secret and dropped.
174
+ const message = error?.message;
175
+ return typeof message === 'string' && message.includes('no_active_session')
176
+ ? 'no_active_session'
177
+ : 'invalid_secret';
178
+ }
179
+ return 'transient';
180
+ }
168
181
  /**
169
182
  * Run the device-first cold boot. Resolves to the `runColdBoot` outcome and, as
170
183
  * a side effect, invokes `onSession` (winning session, token already planted)
@@ -180,7 +193,73 @@ async function runSessionColdBoot(opts) {
180
193
  // they cannot leak across boots or break under bundler re-evaluation.
181
194
  let signedOutReason = 'no_session';
182
195
  let navigating = false;
196
+ // Set when the zero-cookie mint reports `no_active_session` (phase 2c): the
197
+ // device is authoritatively signed out, so the migratory fallback lanes below
198
+ // (stored-tokens / shared-key / bootstrap-hop) must NOT run — we already know
199
+ // there is no session and must not bounce a known-signed-out device.
200
+ let deviceKnownSignedOut = false;
183
201
  const steps = [];
202
+ // 0. device-secret-mint (phase 2c) — the zero-cookie fast path. When the
203
+ // origin persisted a deviceId + deviceSecret, mint a short access token with
204
+ // a single bearer-less POST (no cookie, no navigation). FIRST in the chain
205
+ // so it wins over the migratory cookie lanes below. Gated OFF while a
206
+ // #oxy_boot return fragment is present so `bootstrap-return` still consumes
207
+ // + strips it first (a device holding a secret never triggers that hop, so
208
+ // this only defers a rare stale/forged fragment). The rest of the chain
209
+ // stays as the additive migratory fallback for devices not yet on the secret.
210
+ steps.push({
211
+ id: 'device-secret-mint',
212
+ enabled: () => !(isWeb && (0, deviceBootReturn_1.hashHasBootFragment)(dom.getHash())),
213
+ run: async () => {
214
+ const persisted = await store.load();
215
+ if (!persisted?.deviceId || !persisted?.deviceSecret) {
216
+ return { kind: 'skip' };
217
+ }
218
+ try {
219
+ const mint = await oxy.mintFromDeviceSecret(persisted.deviceId, persisted.deviceSecret);
220
+ // Rotation-in-use anti-loss: persist the NEXT secret (+ refreshed warm
221
+ // fields, + the server's authoritative active account) BEFORE planting
222
+ // the minted access token, so a multi-tab race that rotates again can
223
+ // never strand this tab with a superseded secret.
224
+ const active = mint.state.accounts.find((a) => a.accountId === mint.state.activeAccountId);
225
+ const next = {
226
+ ...persisted,
227
+ deviceId: mint.state.deviceId,
228
+ deviceSecret: mint.nextDeviceSecret,
229
+ accessToken: mint.accessToken,
230
+ expiresAt: mint.expiresAt,
231
+ ...(active ? { sessionId: active.sessionId, userId: active.accountId } : {}),
232
+ };
233
+ await store.save(next);
234
+ oxy.setTokens(mint.accessToken);
235
+ return {
236
+ kind: 'session',
237
+ session: { sessionId: next.sessionId, userId: next.userId, accessToken: mint.accessToken },
238
+ };
239
+ }
240
+ catch (error) {
241
+ const failure = classifyMintFailure(error);
242
+ if (failure === 'invalid_secret') {
243
+ // Stale/diverged secret — drop it so the mint lane stops firing, then
244
+ // fall through to the migratory refresh/cookie lanes. Setting it
245
+ // undefined drops the key on the store's JSON serialization, and the
246
+ // mint guard treats undefined as absent.
247
+ await store.save({ ...persisted, deviceSecret: undefined });
248
+ return { kind: 'skip' };
249
+ }
250
+ if (failure === 'no_active_session') {
251
+ // Device known, no live session — authoritative signed-out. KEEP the
252
+ // secret and stop the chain (do not bounce a known-signed-out device).
253
+ deviceKnownSignedOut = true;
254
+ signedOutReason = 'no_session';
255
+ return { kind: 'skip' };
256
+ }
257
+ // Transient (network / 5xx): keep the secret, let the fallback lanes try.
258
+ loggerUtils_1.logger.debug('device-secret mint failed (transient) — keeping secret, falling back', { component: 'coldBootV2', method: 'device-secret-mint' }, error);
259
+ return { kind: 'skip' };
260
+ }
261
+ },
262
+ });
184
263
  // 1. bootstrap-return (web) — consume a #oxy_boot fragment.
185
264
  steps.push({
186
265
  id: 'bootstrap-return',
@@ -214,6 +293,7 @@ async function runSessionColdBoot(opts) {
214
293
  // 2. stored-tokens — warm-plant or rotate the persisted refresh family.
215
294
  steps.push({
216
295
  id: 'stored-tokens',
296
+ enabled: () => !deviceKnownSignedOut,
217
297
  run: async () => {
218
298
  const persisted = await store.load();
219
299
  if (!persisted) {
@@ -240,7 +320,7 @@ async function runSessionColdBoot(opts) {
240
320
  // 3. shared-key-signin (native) — re-mint from the shared identity.
241
321
  steps.push({
242
322
  id: 'shared-key-signin',
243
- enabled: () => isNative,
323
+ enabled: () => isNative && !deviceKnownSignedOut,
244
324
  run: async () => {
245
325
  const session = await oxy.signInWithSharedIdentity();
246
326
  if (!session?.accessToken) {
@@ -273,7 +353,7 @@ async function runSessionColdBoot(opts) {
273
353
  // 4. bootstrap-hop (web, terminal) — same-apex inline fetch OR cross-apex nav.
274
354
  steps.push({
275
355
  id: 'bootstrap-hop',
276
- enabled: () => isWeb,
356
+ enabled: () => isWeb && !deviceKnownSignedOut,
277
357
  run: async () => {
278
358
  const pageHost = dom.getLocationHostname();
279
359
  let apiHost = null;
@@ -306,6 +386,21 @@ async function runSessionColdBoot(opts) {
306
386
  accessToken: bundle.accessToken,
307
387
  expiresAt: bundle.expiresAt,
308
388
  };
389
+ // Phase 2c: the web-session bundle may carry a rotating `deviceSecret`
390
+ // but NOT a deviceId. Persist the secret and carry any prior deviceId
391
+ // (from a deviceId-bearing login lane) forward so the mint lane stays
392
+ // usable — this overwrite must not orphan it.
393
+ const prior = await store.load();
394
+ if (prior?.deviceId) {
395
+ next.deviceId = prior.deviceId;
396
+ }
397
+ // Prefer the bundle's secret (the server just rotated onto it); keep the
398
+ // prior one when the bundle omits it — this lane also runs as the
399
+ // TRANSIENT-mint fallback, and must not orphan a still-valid secret.
400
+ const carriedSecret = bundle.deviceSecret ?? prior?.deviceSecret;
401
+ if (carriedSecret) {
402
+ next.deviceSecret = carriedSecret;
403
+ }
309
404
  await store.save(next);
310
405
  oxy.setTokens(bundle.accessToken);
311
406
  return { kind: 'session', session: sessionFromPersisted(next, bundle.accessToken) };
@@ -135,6 +135,21 @@ async function consumeDeviceBootReturn(deps) {
135
135
  accessToken: bundle.accessToken,
136
136
  expiresAt: bundle.expiresAt,
137
137
  };
138
+ // Phase 2c: the cookie-bootstrap bundle may carry a rotating `deviceSecret`
139
+ // but NOT a deviceId. Persist the secret, and carry any prior deviceId
140
+ // forward (from a deviceId-bearing login lane) so the pair stays usable by
141
+ // the zero-cookie mint — an overwrite here must not orphan the mint lane.
142
+ const prior = await deps.store.load();
143
+ if (prior?.deviceId) {
144
+ next.deviceId = prior.deviceId;
145
+ }
146
+ // Prefer the bundle's secret (the server just rotated onto it); keep the
147
+ // prior one when the bundle omits it so a cookie-lane boot can never orphan
148
+ // a still-valid secret captured by an earlier login lane.
149
+ const carriedSecret = bundle.deviceSecret ?? prior?.deviceSecret;
150
+ if (carriedSecret) {
151
+ next.deviceSecret = carriedSecret;
152
+ }
138
153
  await deps.store.save(next);
139
154
  deps.plantAccessToken(bundle.accessToken);
140
155
  return {
@@ -105,6 +105,34 @@ function OxyServicesDeviceBootMixin(Base) {
105
105
  throw this.handleError(error);
106
106
  }
107
107
  }
108
+ /**
109
+ * Zero-cookie mint (phase 2c). Present the first-party `deviceId` +
110
+ * `deviceSecret` to `POST /session/device/token` — NO bearer, NO cookies:
111
+ * possession of the secret IS the device-ownership proof. Returns a fresh
112
+ * short access token for the device's active account plus `nextDeviceSecret`
113
+ * (rotation-in-use) and the projected device-session `state`.
114
+ *
115
+ * `skipAuth` (like {@link refreshWithToken}): this call carries no bearer, so
116
+ * a 401 must surface DIRECTLY — never trigger `HttpService`'s 401→refresh→
117
+ * retry dance (which would pointlessly rotate the refresh family). The cold
118
+ * boot reads the 401 body (`invalid_device_secret` vs `no_active_session`) to
119
+ * decide whether to drop the secret and fall back or resolve signed-out.
120
+ *
121
+ * @throws if the response does not match {@link deviceTokenMintResponseSchema}.
122
+ */
123
+ async mintFromDeviceSecret(deviceId, deviceSecret) {
124
+ try {
125
+ const res = await this.makeRequest('POST', '/session/device/token', { deviceId, deviceSecret }, { cache: false, skipAuth: true });
126
+ const parsed = (0, contracts_1.safeParseContract)(contracts_1.deviceTokenMintResponseSchema, res);
127
+ if (!parsed) {
128
+ throw new Error('session/device/token returned an unexpected response shape');
129
+ }
130
+ return parsed;
131
+ }
132
+ catch (error) {
133
+ throw this.handleError(error);
134
+ }
135
+ }
108
136
  /**
109
137
  * Build the top-level `GET /auth/device/bootstrap` URL for the cross-apex
110
138
  * hop. The server validates `return_to` against the trusted-origin lane and
@@ -70,6 +70,12 @@ function deserialize(raw) {
70
70
  if (typeof candidate.deviceToken === 'string' && candidate.deviceToken.length > 0) {
71
71
  state.deviceToken = candidate.deviceToken;
72
72
  }
73
+ if (typeof candidate.deviceId === 'string' && candidate.deviceId.length > 0) {
74
+ state.deviceId = candidate.deviceId;
75
+ }
76
+ if (typeof candidate.deviceSecret === 'string' && candidate.deviceSecret.length > 0) {
77
+ state.deviceSecret = candidate.deviceSecret;
78
+ }
73
79
  if (typeof candidate.accessToken === 'string' && candidate.accessToken.length > 0) {
74
80
  state.accessToken = candidate.accessToken;
75
81
  }
@@ -92,6 +92,15 @@ async function refreshPersistedSession(deps) {
92
92
  if (persisted.deviceToken) {
93
93
  next.deviceToken = persisted.deviceToken;
94
94
  }
95
+ // The refresh response carries no device credentials — carry the persisted
96
+ // deviceId/deviceSecret (phase 2c) forward so a rotation never drops the
97
+ // zero-cookie mint lane (mirrors the deviceToken preservation above).
98
+ if (persisted.deviceId) {
99
+ next.deviceId = persisted.deviceId;
100
+ }
101
+ if (persisted.deviceSecret) {
102
+ next.deviceSecret = persisted.deviceSecret;
103
+ }
95
104
  await store.save(next);
96
105
  return rotated.accessToken;
97
106
  }