@oxy.so/core 7.11.0 → 7.12.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.
@@ -56,6 +56,21 @@ export type AccessTokenProvider = () => string | null;
56
56
  */
57
57
  export type AnonymousAuthProvider = () => Promise<string | null>;
58
58
 
59
+ declare const credentialGenerationBrand: unique symbol;
60
+ /**
61
+ * An opaque, immutable token for ONE installation of a bearer in a client.
62
+ *
63
+ * `TokenStore` swaps it on every write path (setter, refresh, account or actor
64
+ * switch, cross-tab or restored token, clear), so two installations of the same
65
+ * bytes (A, B, A) are different generations. It names a local sequence only: it
66
+ * is not evidence of an account, a scope or authorization.
67
+ */
68
+ export type CredentialGeneration = { readonly [credentialGenerationBrand]: true };
69
+
70
+ function newCredentialGeneration(): CredentialGeneration {
71
+ return Object.freeze({}) as CredentialGeneration;
72
+ }
73
+
59
74
  /** Comparison only fences local async work; it never validates token authority. */
60
75
  function sameTokenSession(left: string | null, right: string | null): boolean {
61
76
  if (left === right) return true;
@@ -190,6 +205,13 @@ interface FormDataLike {
190
205
  }
191
206
 
192
207
  export interface RequestOptions {
208
+ /**
209
+ * Bind a write to ONE installation of the source's bearer. The transport
210
+ * rejects (`AUTH_SESSION_CHANGED`) when the generation was replaced before
211
+ * dispatch, after queueing, or before the result is returned. Implies no cache,
212
+ * deduplication or retry, and a 401 neither refreshes nor clears the session.
213
+ */
214
+ expectedCredentialGeneration?: CredentialGeneration;
193
215
  cache?: boolean;
194
216
  cacheTTL?: number;
195
217
  deduplicate?: boolean;
@@ -434,16 +456,29 @@ const CACHE_SIZE_WARNING_THROTTLE_MS = 60000;
434
456
  */
435
457
  class TokenStore {
436
458
  private accessToken: string | null = null;
459
+ private generation: CredentialGeneration = newCredentialGeneration();
437
460
 
438
461
  setTokens(accessToken: string): void {
462
+ this.generation = newCredentialGeneration();
439
463
  this.accessToken = accessToken;
440
464
  }
441
465
 
466
+ /** The identity of the bearer's current installation, never of its bytes. */
467
+ getGeneration(): CredentialGeneration {
468
+ return this.generation;
469
+ }
470
+
471
+ /** Retire the current generation without touching the bearer (provider swaps). */
472
+ invalidateGeneration(): void {
473
+ this.generation = newCredentialGeneration();
474
+ }
475
+
442
476
  getAccessToken(): string | null {
443
477
  return this.accessToken;
444
478
  }
445
479
 
446
480
  clearTokens(): void {
481
+ this.generation = newCredentialGeneration();
447
482
  this.accessToken = null;
448
483
  }
449
484
 
@@ -576,6 +611,7 @@ export class HttpService {
576
611
  * bearer — and through the token listeners, the account — back.
577
612
  */
578
613
  private sessionEpoch = 0;
614
+ private readonly credentialSource: HttpService | null;
579
615
  /** Preserve a known device across legacy rotations which omit the claim. */
580
616
  private sessionDeviceId: string | null = null;
581
617
  /** Preserve known actor and context hints across rotations without those claims. */
@@ -618,8 +654,9 @@ export class HttpService {
618
654
  averageResponseTime: 0,
619
655
  };
620
656
 
621
- constructor(config: OxyConfig) {
657
+ constructor(config: OxyConfig, credentialSource: HttpService | null = null) {
622
658
  this.config = config;
659
+ this.credentialSource = credentialSource;
623
660
  this.baseURL = config.baseURL;
624
661
  this.tokenStore = new TokenStore();
625
662
 
@@ -760,6 +797,21 @@ export class HttpService {
760
797
  */
761
798
  async request<T = unknown>(config: RequestConfig): Promise<ResponsePayload<T>> {
762
799
  if (config.signal?.aborted) throw createCancelledError('Request cancelled before it was sent');
800
+ if (config.expectedCredentialGeneration) {
801
+ // The prototype is deliberately limited to writes; it does not
802
+ // yet define leases for cached/deduplicated reads or raw response paths.
803
+ if (
804
+ !['POST', 'PUT', 'PATCH', 'DELETE'].includes(config.method) ||
805
+ config.skipAuth ||
806
+ Object.keys(config.headers ?? {}).some((key) => key.toLowerCase() === 'authorization')
807
+ ) {
808
+ throw new Error('A credential generation requires an implicitly authenticated write');
809
+ }
810
+ (this.credentialSource ?? this).assertCredentialGeneration(
811
+ config.expectedCredentialGeneration,
812
+ );
813
+ config = { ...config, cache: false, deduplicate: false, retry: false };
814
+ }
763
815
  // The provider can change independently of the last request. Synchronize
764
816
  // before deriving the cache and deduplication identity, including hits.
765
817
  const explicitAuthorization = Object.keys(config.headers ?? {}).some(
@@ -878,6 +930,15 @@ export class HttpService {
878
930
  const authHeader = usesSessionAuth
879
931
  ? await awaitRequestSignal(this.getAuthHeader(), signal)
880
932
  : null;
933
+ const assertExpectedCredential = () => {
934
+ if (config.expectedCredentialGeneration) {
935
+ (this.credentialSource ?? this).assertCredentialGeneration(
936
+ config.expectedCredentialGeneration,
937
+ authHeader,
938
+ );
939
+ }
940
+ };
941
+ assertExpectedCredential();
881
942
  const isOriginalSession = () => {
882
943
  if (this.sessionEpoch !== contextEpoch) return false;
883
944
  const currentToken = this.syncAccessTokenFromProvider();
@@ -929,6 +990,7 @@ export class HttpService {
929
990
  if (usesSessionAuth && !isOriginalSession()) {
930
991
  throw new OxyAuthenticationError('The request session changed', 'AUTH_SESSION_CHANGED');
931
992
  }
993
+ assertExpectedCredential();
932
994
 
933
995
  /**
934
996
  * Whether OUR timer fired, so a timeout can be told apart from a
@@ -1042,6 +1104,9 @@ export class HttpService {
1042
1104
  throw new Error('Requester proofs require a transport that rejects redirects');
1043
1105
  }
1044
1106
 
1107
+ // Header and source generation are checked together in this synchronous
1108
+ // dispatch segment, after the preflight and any queue wait.
1109
+ assertExpectedCredential();
1045
1110
  const response = useXhrForUpload
1046
1111
  ? await this.uploadViaXHR(
1047
1112
  fullUrl,
@@ -1065,6 +1130,13 @@ export class HttpService {
1065
1130
  // it, including on every throw between here and there.
1066
1131
  if (timeoutId) clearTimeout(timeoutId);
1067
1132
 
1133
+ try {
1134
+ assertExpectedCredential();
1135
+ } catch (error) {
1136
+ void discardResponseBody(response);
1137
+ throw error;
1138
+ }
1139
+
1068
1140
  if (usesSessionAuth && !isOriginalSession()) {
1069
1141
  void discardResponseBody(response);
1070
1142
  throw new OxyAuthenticationError('The request session changed', 'AUTH_SESSION_CHANGED');
@@ -1077,6 +1149,7 @@ export class HttpService {
1077
1149
  // session routes; the refresh handler owns session rotation.
1078
1150
  if (
1079
1151
  response.status === 401 &&
1152
+ !config.expectedCredentialGeneration &&
1080
1153
  !config._isAuthRetry &&
1081
1154
  usesSessionAuth &&
1082
1155
  isOriginalSession()
@@ -1218,12 +1291,14 @@ export class HttpService {
1218
1291
  if (usesSessionAuth && !isOriginalSession()) {
1219
1292
  throw new OxyAuthenticationError('The request session changed', 'AUTH_SESSION_CHANGED');
1220
1293
  }
1294
+ assertExpectedCredential();
1221
1295
  const duration = Date.now() - startTime;
1222
1296
  this.updateMetrics(true, duration);
1223
1297
  this.config.onRequestEnd?.(url, method, duration, true);
1224
1298
 
1225
1299
  return responseData as T;
1226
1300
  } catch (error: unknown) {
1301
+ assertExpectedCredential();
1227
1302
  const duration = Date.now() - startTime;
1228
1303
  this.updateMetrics(false, duration);
1229
1304
  // A body reader can reject or finish parsing an error after the viewer
@@ -1348,6 +1423,7 @@ export class HttpService {
1348
1423
  if (usesSessionAuth && !isOriginalSession()) {
1349
1424
  throw new OxyAuthenticationError('The request session changed', 'AUTH_SESSION_CHANGED');
1350
1425
  }
1426
+ assertExpectedCredential();
1351
1427
 
1352
1428
  // Cache the result if caching is enabled
1353
1429
  if (cache && cacheKey && lease.valid && result) {
@@ -2192,6 +2268,36 @@ export class HttpService {
2192
2268
  return this.sessionEpoch;
2193
2269
  }
2194
2270
 
2271
+ /** Capture only the local generation; the caller must separately bind authority. */
2272
+ captureCredentialGeneration(): CredentialGeneration | null {
2273
+ // A pull-only provider can change A→B→A between reads without notifying us.
2274
+ if (this.accessTokenProvider) return null;
2275
+ return this.tokenStore.getAccessToken() ? this.tokenStore.getGeneration() : null;
2276
+ }
2277
+
2278
+ isCredentialGenerationCurrent(generation: CredentialGeneration): boolean {
2279
+ return (
2280
+ !this.accessTokenProvider &&
2281
+ this.tokenStore.getAccessToken() !== null &&
2282
+ generation === this.tokenStore.getGeneration()
2283
+ );
2284
+ }
2285
+
2286
+ private assertCredentialGeneration(
2287
+ generation: CredentialGeneration,
2288
+ selectedHeader?: string | null,
2289
+ ): void {
2290
+ const token = this.tokenStore.getAccessToken();
2291
+ if (
2292
+ this.accessTokenProvider ||
2293
+ !token ||
2294
+ generation !== this.tokenStore.getGeneration() ||
2295
+ (selectedHeader !== undefined && selectedHeader !== `Bearer ${token}`)
2296
+ ) {
2297
+ throw new OxyAuthenticationError('The request credential changed', 'AUTH_SESSION_CHANGED');
2298
+ }
2299
+ }
2300
+
2195
2301
  /** Whether {@link endSession} ran and no token has been planted since. */
2196
2302
  hasSessionEnded(): boolean {
2197
2303
  return this.sessionEnded;
@@ -2202,6 +2308,7 @@ export class HttpService {
2202
2308
  }
2203
2309
 
2204
2310
  setAccessTokenProvider(provider: AccessTokenProvider | null): void {
2311
+ this.tokenStore.invalidateGeneration();
2205
2312
  this.accessTokenProvider = provider;
2206
2313
  }
2207
2314
 
@@ -159,7 +159,10 @@ export class OxyServices {
159
159
  * Query). Pass `enableCache: true` to opt in.
160
160
  */
161
161
  createLinkedClient(config: OxyConfig): LinkedHttpClient {
162
- const client = new HttpService({ ...config, enableCache: config.enableCache ?? false });
162
+ const client = new HttpService(
163
+ { ...config, enableCache: config.enableCache ?? false },
164
+ this.http,
165
+ );
163
166
 
164
167
  const syncToken = (accessToken: string | null): void => {
165
168
  const current = client.getAccessToken();
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Holder-context evidence: the server's point-in-time observation of which
3
+ * shared-device context a bearer is installed in, bound to ONE installation of
4
+ * that bearer in this client (ADR 0053).
5
+ *
6
+ * Evidence is never authorization. It lets a caller that already captured a
7
+ * viewer intent prove, before a write is dispatched, that the bearer the write
8
+ * will carry belongs to that viewer's account and actor, and then pin the write
9
+ * to the exact installation with `expectedCredentialGeneration`. Anything that
10
+ * cannot be proven is `unavailable`, and the caller keeps its existing checks.
11
+ */
12
+ import type { HolderContextEvidenceV1Response } from '@oxy.so/contracts';
13
+ import type { CredentialGeneration } from '../HttpService';
14
+
15
+ /** The identifiers the server observed; none of them is a credential. */
16
+ export type HolderEvidenceIdentity = Readonly<
17
+ Pick<
18
+ HolderContextEvidenceV1Response,
19
+ 'deviceId' | 'deviceSessionId' | 'contextId' | 'actorId' | 'accountId' | 'sessionId'
20
+ >
21
+ >;
22
+
23
+ export interface HolderEvidence {
24
+ /** The installation of the bearer this evidence was observed for. */
25
+ readonly generation: CredentialGeneration;
26
+ readonly identity: HolderEvidenceIdentity;
27
+ /** The device-session revision the server observed. */
28
+ readonly deviceRevision: number;
29
+ /** Epoch milliseconds: the earlier of the bearer and session expiry. */
30
+ readonly expiresAtMs: number;
31
+ }
32
+
33
+ /**
34
+ * Why no evidence exists. Every reason means "keep the existing checks": none of
35
+ * them says the session is revoked, and none may clear or refresh credentials.
36
+ *
37
+ * - `no_credential`: no bearer is installed, or it comes from a pull-only provider.
38
+ * - `no_holder`: this client holds no device credential to prove the holder with.
39
+ * - `changed`: the bearer was replaced while the evidence was being acquired.
40
+ * - `unsupported`: a delegated, OAuth or legacy bearer, or the endpoint is not offered.
41
+ * - `binding_unavailable`: the server could not match holder, context and bearer.
42
+ * - `unavailable`: the endpoint is off, rate limited, unreachable or answered wrongly.
43
+ */
44
+ export type HolderEvidenceUnavailableReason =
45
+ | 'no_credential'
46
+ | 'no_holder'
47
+ | 'changed'
48
+ | 'unsupported'
49
+ | 'binding_unavailable'
50
+ | 'unavailable';
51
+
52
+ export type HolderEvidenceResult =
53
+ | { readonly status: 'ok'; readonly evidence: HolderEvidence }
54
+ | { readonly status: 'unavailable'; readonly reason: HolderEvidenceUnavailableReason };
55
+
56
+ /** The one comparison that decides whether two observations name the same viewer context. */
57
+ export function sameHolderIdentity(a: HolderEvidenceIdentity, b: HolderEvidenceIdentity): boolean {
58
+ return (
59
+ a.deviceId === b.deviceId &&
60
+ a.deviceSessionId === b.deviceSessionId &&
61
+ a.contextId === b.contextId &&
62
+ a.actorId === b.actorId &&
63
+ a.accountId === b.accountId &&
64
+ a.sessionId === b.sessionId
65
+ );
66
+ }
@@ -12,6 +12,20 @@ import type { ClientSession } from '../models/session';
12
12
  import type { User } from '../models/interfaces';
13
13
  import { normalizeUserIdentity } from '../utils/userIdentity';
14
14
  import { OxyApiError } from '../OxyServices.errors';
15
+ import { checkContract, holderContextEvidenceV1ResponseCheck } from '@oxy.so/contracts/client';
16
+ import type { CredentialGeneration } from '../HttpService';
17
+ import type {
18
+ HolderEvidence,
19
+ HolderEvidenceResult,
20
+ HolderEvidenceUnavailableReason,
21
+ } from './holderEvidence';
22
+
23
+ /** How long a refusal (disabled, rate limited, unreachable) is remembered per installation. */
24
+ const EVIDENCE_REFUSAL_MS = 5_000;
25
+ const unavailable = (reason: HolderEvidenceUnavailableReason): HolderEvidenceResult => ({
26
+ status: 'unavailable',
27
+ reason,
28
+ });
15
29
 
16
30
  /**
17
31
  * Reads the device credential this client holds, if any — `{ deviceId,
@@ -42,12 +56,21 @@ interface AccessTokenClaims {
42
56
  exp?: number;
43
57
  userId?: string;
44
58
  id?: string;
59
+ sessionId?: string;
60
+ deviceId?: string;
61
+ device_context_id?: string;
62
+ act?: { sub?: string };
45
63
  }
46
64
 
47
65
  export class SessionApi {
48
66
  private deviceCredentialProvider: DeviceCredentialProvider | null = null;
49
67
  private decodedFor: string | null = null;
50
68
  private decoded: AccessTokenClaims | null = null;
69
+ /** One server round trip per installed bearer; the key is the opaque generation. */
70
+ private readonly evidence = new WeakMap<
71
+ CredentialGeneration,
72
+ { result: Promise<HolderEvidenceResult>; settledAt?: number }
73
+ >();
51
74
 
52
75
  constructor(protected readonly ctx: OxyContext) {}
53
76
 
@@ -163,6 +186,128 @@ export class SessionApi {
163
186
  }
164
187
  }
165
188
 
189
+ // ── Holder-context evidence (ADR 0053) ───────────────────────────────────
190
+
191
+ /**
192
+ * Ask the server which shared-device context the INSTALLED bearer belongs to,
193
+ * and bind the answer to that exact installation.
194
+ *
195
+ * The result is honored only if the credential generation captured before
196
+ * the request is still current when the answer is committed, so a refresh,
197
+ * setter, account or actor switch, cross-tab change, restore or A to B to A
198
+ * during the request yields `changed`. The answer must also agree with the
199
+ * claims of the bearer that was captured; a disagreement is
200
+ * `binding_unavailable`. Nothing here refreshes, clears or mints a credential,
201
+ * and no outcome is a revocation verdict: callers keep their existing checks.
202
+ * Concurrent callers share one request per installation.
203
+ */
204
+ observeHolderEvidence(): Promise<HolderEvidenceResult> {
205
+ const generation = this.ctx.http.captureCredentialGeneration();
206
+ const token = this.ctx.http.getAccessToken();
207
+ if (!generation || !token) return Promise.resolve(unavailable('no_credential'));
208
+ const known = this.evidence.get(generation);
209
+ if (known) {
210
+ const refused = known.settledAt !== undefined;
211
+ if (!refused || Date.now() - (known.settledAt as number) < EVIDENCE_REFUSAL_MS) {
212
+ return known.result.then((result) =>
213
+ result.status === 'ok' && result.evidence.expiresAtMs <= Date.now()
214
+ ? this.refreshEvidence(generation, token)
215
+ : result,
216
+ );
217
+ }
218
+ }
219
+ return this.refreshEvidence(generation, token);
220
+ }
221
+
222
+ /** Whether evidence still names the installed bearer and has not expired. */
223
+ isHolderEvidenceCurrent(evidence: HolderEvidence): boolean {
224
+ return (
225
+ Date.now() < evidence.expiresAtMs &&
226
+ this.ctx.http.isCredentialGenerationCurrent(evidence.generation)
227
+ );
228
+ }
229
+
230
+ private refreshEvidence(
231
+ generation: CredentialGeneration,
232
+ token: string,
233
+ ): Promise<HolderEvidenceResult> {
234
+ const entry: { result: Promise<HolderEvidenceResult>; settledAt?: number } = {
235
+ result: this.acquireEvidence(generation, token).then((result) => {
236
+ if (result.status !== 'ok') entry.settledAt = Date.now();
237
+ return result;
238
+ }),
239
+ };
240
+ this.evidence.set(generation, entry);
241
+ return entry.result;
242
+ }
243
+
244
+ private async acquireEvidence(
245
+ generation: CredentialGeneration,
246
+ token: string,
247
+ ): Promise<HolderEvidenceResult> {
248
+ let claims: AccessTokenClaims;
249
+ try {
250
+ claims = jwtDecode<AccessTokenClaims>(token);
251
+ } catch {
252
+ return unavailable('unsupported');
253
+ }
254
+ const proof = await this.readDeviceProof();
255
+ if (!proof) return unavailable('no_holder');
256
+ let response: unknown;
257
+ try {
258
+ response = await this.ctx.request<unknown>(
259
+ 'POST',
260
+ '/session/device/context-evidence-v1',
261
+ proof,
262
+ {
263
+ cache: false,
264
+ retry: false,
265
+ expectedCredentialGeneration: generation,
266
+ },
267
+ );
268
+ } catch (error) {
269
+ if ((error as { code?: unknown } | null)?.code === 'AUTH_SESSION_CHANGED') {
270
+ return unavailable('changed');
271
+ }
272
+ const status = error instanceof OxyApiError ? error.status : 0;
273
+ if (status === 403) return unavailable('unsupported');
274
+ if (status === 409) return unavailable('binding_unavailable');
275
+ return unavailable('unavailable');
276
+ }
277
+ const parsed = checkContract(holderContextEvidenceV1ResponseCheck, response);
278
+ if (!parsed) return unavailable('unavailable');
279
+ // Commit synchronously: nothing may replace the bearer between this check
280
+ // and the evidence becoming visible to its caller.
281
+ if (!this.ctx.http.isCredentialGenerationCurrent(generation)) return unavailable('changed');
282
+ const expiresAtMs = Date.parse(parsed.expiresAt);
283
+ if (
284
+ parsed.deviceId !== proof.deviceId ||
285
+ parsed.accountId !== claims.userId ||
286
+ parsed.sessionId !== claims.sessionId ||
287
+ (claims.act?.sub !== undefined && parsed.actorId !== claims.act.sub) ||
288
+ (claims.device_context_id !== undefined && parsed.contextId !== claims.device_context_id)
289
+ ) {
290
+ return unavailable('binding_unavailable');
291
+ }
292
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
293
+ return unavailable('unavailable');
294
+ }
295
+ const evidence: HolderEvidence = Object.freeze({
296
+ generation,
297
+ identity: Object.freeze({
298
+ deviceId: parsed.deviceId,
299
+ deviceSessionId: parsed.deviceSessionId,
300
+ contextId: parsed.contextId,
301
+ actorId: parsed.actorId,
302
+ accountId: parsed.accountId,
303
+ sessionId: parsed.sessionId,
304
+ }),
305
+ deviceRevision: parsed.revision,
306
+ expiresAtMs,
307
+ });
308
+ return { status: 'ok', evidence };
309
+ }
310
+
166
311
  // ── The server session ───────────────────────────────────────────────────
167
312
 
168
313
  /** Ask the server whether the current access token is valid. */
package/src/aws/index.ts CHANGED
@@ -10,8 +10,22 @@ import type { WorkloadCredentialProvider } from '../server/workloadIdentity';
10
10
  export function createAwsWorkloadCredentialProvider(
11
11
  options: { profile?: string } = {},
12
12
  ): WorkloadCredentialProvider {
13
- const provider = defaultProvider(options);
13
+ // An explicitly selected profile is an authority boundary. defaultProvider
14
+ // falls through a missing profile to ambient ECS/IMDS credentials, which may
15
+ // name another application. fromIni resolves only the selected profile and
16
+ // its declared source chain, or rejects; there is no ambient fallback.
17
+ if (options.profile !== undefined && !options.profile.trim())
18
+ throw new Error('An explicit AWS workload profile must not be empty');
19
+ const ambient = options.profile === undefined ? defaultProvider(options) : undefined;
20
+ const resolveProfile = async () =>
21
+ (await import('@aws-sdk/credential-provider-ini')).fromIni(options);
22
+ let selectedProfile: ReturnType<typeof resolveProfile> | undefined;
14
23
  return async () => {
24
+ let provider = ambient;
25
+ if (!provider) {
26
+ selectedProfile ??= resolveProfile();
27
+ provider = await selectedProfile;
28
+ }
15
29
  const credentials = await provider();
16
30
  if (
17
31
  !credentials.sessionToken ||
package/src/index.ts CHANGED
@@ -48,7 +48,15 @@ export type {
48
48
  AuthenticatedResponseRequest,
49
49
  AuthRefreshReason,
50
50
  AuthRefreshHandler,
51
+ CredentialGeneration,
51
52
  } from './HttpService';
53
+ export { sameHolderIdentity } from './api/holderEvidence';
54
+ export type {
55
+ HolderEvidence,
56
+ HolderEvidenceIdentity,
57
+ HolderEvidenceResult,
58
+ HolderEvidenceUnavailableReason,
59
+ } from './api/holderEvidence';
52
60
 
53
61
  // The namespaces — their classes (for typing) and their input/output types.
54
62
  export type { SessionApi, DeviceCredentialProvider, SessionValidation } from './api/session';