@oxy.so/core 1.5.0 → 1.6.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 (131) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/HttpService.js +72 -9
  3. package/dist/cjs/crypto/identityMove.js +53 -34
  4. package/dist/cjs/crypto/identityProof.js +28 -0
  5. package/dist/cjs/crypto/webIdentityCarrier.js +145 -82
  6. package/dist/cjs/i18n/locales/ar-SA.json +1 -0
  7. package/dist/cjs/i18n/locales/ca-ES.json +1 -0
  8. package/dist/cjs/i18n/locales/de-DE.json +1 -0
  9. package/dist/cjs/i18n/locales/en-US.json +1 -0
  10. package/dist/cjs/i18n/locales/es-ES.json +1 -0
  11. package/dist/cjs/i18n/locales/fr-FR.json +1 -0
  12. package/dist/cjs/i18n/locales/it-IT.json +1 -0
  13. package/dist/cjs/i18n/locales/ja-JP.json +1 -0
  14. package/dist/cjs/i18n/locales/ko-KR.json +1 -0
  15. package/dist/cjs/i18n/locales/locales/ar-SA.json +1 -0
  16. package/dist/cjs/i18n/locales/locales/ca-ES.json +1 -0
  17. package/dist/cjs/i18n/locales/locales/de-DE.json +1 -0
  18. package/dist/cjs/i18n/locales/locales/en-US.json +1 -0
  19. package/dist/cjs/i18n/locales/locales/es-ES.json +1 -0
  20. package/dist/cjs/i18n/locales/locales/fr-FR.json +1 -0
  21. package/dist/cjs/i18n/locales/locales/it-IT.json +1 -0
  22. package/dist/cjs/i18n/locales/locales/ja-JP.json +1 -0
  23. package/dist/cjs/i18n/locales/locales/ko-KR.json +1 -0
  24. package/dist/cjs/i18n/locales/locales/pt-PT.json +1 -0
  25. package/dist/cjs/i18n/locales/locales/zh-CN.json +1 -0
  26. package/dist/cjs/i18n/locales/pt-PT.json +1 -0
  27. package/dist/cjs/i18n/locales/zh-CN.json +1 -0
  28. package/dist/cjs/index.js +22 -14
  29. package/dist/cjs/inference/OxyInferenceClient.js +62 -5
  30. package/dist/cjs/mixins/OxyServices.auth.js +129 -0
  31. package/dist/cjs/mixins/OxyServices.identity.js +11 -44
  32. package/dist/cjs/mixins/index.js +0 -2
  33. package/dist/cjs/server/index.js +10 -1
  34. package/dist/cjs/server/securityHeaders.js +9 -2
  35. package/dist/cjs/server/workloadIdentity.js +170 -0
  36. package/dist/cjs/session/refresh.js +12 -0
  37. package/dist/esm/.tsbuildinfo +1 -1
  38. package/dist/esm/HttpService.js +72 -9
  39. package/dist/esm/crypto/identityMove.js +51 -33
  40. package/dist/esm/crypto/identityProof.js +24 -0
  41. package/dist/esm/crypto/webIdentityCarrier.js +137 -77
  42. package/dist/esm/i18n/locales/ar-SA.json +1 -0
  43. package/dist/esm/i18n/locales/ca-ES.json +1 -0
  44. package/dist/esm/i18n/locales/de-DE.json +1 -0
  45. package/dist/esm/i18n/locales/en-US.json +1 -0
  46. package/dist/esm/i18n/locales/es-ES.json +1 -0
  47. package/dist/esm/i18n/locales/fr-FR.json +1 -0
  48. package/dist/esm/i18n/locales/it-IT.json +1 -0
  49. package/dist/esm/i18n/locales/ja-JP.json +1 -0
  50. package/dist/esm/i18n/locales/ko-KR.json +1 -0
  51. package/dist/esm/i18n/locales/locales/ar-SA.json +1 -0
  52. package/dist/esm/i18n/locales/locales/ca-ES.json +1 -0
  53. package/dist/esm/i18n/locales/locales/de-DE.json +1 -0
  54. package/dist/esm/i18n/locales/locales/en-US.json +1 -0
  55. package/dist/esm/i18n/locales/locales/es-ES.json +1 -0
  56. package/dist/esm/i18n/locales/locales/fr-FR.json +1 -0
  57. package/dist/esm/i18n/locales/locales/it-IT.json +1 -0
  58. package/dist/esm/i18n/locales/locales/ja-JP.json +1 -0
  59. package/dist/esm/i18n/locales/locales/ko-KR.json +1 -0
  60. package/dist/esm/i18n/locales/locales/pt-PT.json +1 -0
  61. package/dist/esm/i18n/locales/locales/zh-CN.json +1 -0
  62. package/dist/esm/i18n/locales/pt-PT.json +1 -0
  63. package/dist/esm/i18n/locales/zh-CN.json +1 -0
  64. package/dist/esm/index.js +5 -4
  65. package/dist/esm/inference/OxyInferenceClient.js +63 -6
  66. package/dist/esm/mixins/OxyServices.auth.js +96 -0
  67. package/dist/esm/mixins/OxyServices.identity.js +11 -44
  68. package/dist/esm/mixins/index.js +0 -2
  69. package/dist/esm/server/index.js +7 -0
  70. package/dist/esm/server/securityHeaders.js +9 -2
  71. package/dist/esm/server/workloadIdentity.js +166 -0
  72. package/dist/esm/session/refresh.js +12 -0
  73. package/dist/types/.tsbuildinfo +1 -1
  74. package/dist/types/HttpService.d.ts +24 -0
  75. package/dist/types/OxyServices.d.ts +3 -0
  76. package/dist/types/crypto/identityMove.d.ts +48 -32
  77. package/dist/types/crypto/identityProof.d.ts +16 -0
  78. package/dist/types/crypto/webIdentityCarrier.d.ts +74 -47
  79. package/dist/types/index.d.ts +7 -6
  80. package/dist/types/inference/OxyInferenceClient.d.ts +21 -1
  81. package/dist/types/mixins/OxyServices.auth.d.ts +32 -0
  82. package/dist/types/mixins/OxyServices.identity.d.ts +16 -30
  83. package/dist/types/mixins/OxyServices.utility.d.ts +2 -0
  84. package/dist/types/mixins/index.d.ts +1 -2
  85. package/dist/types/server/index.d.ts +8 -0
  86. package/dist/types/server/securityHeaders.d.ts +8 -0
  87. package/dist/types/server/workloadIdentity.d.ts +32 -0
  88. package/package.json +1 -1
  89. package/src/HttpService.ts +74 -9
  90. package/src/OxyServices.ts +9 -0
  91. package/src/__tests__/httpServiceRateLimitedRefresh.test.ts +160 -0
  92. package/src/__tests__/publicInterfaceParity.test.ts +75 -0
  93. package/src/__tests__/serviceTokenWorkloadFallback.test.ts +85 -0
  94. package/src/crypto/__tests__/identityMove.test.ts +93 -51
  95. package/src/crypto/__tests__/identityProof.test.ts +81 -0
  96. package/src/crypto/__tests__/webIdentityCarrier.test.ts +21 -63
  97. package/src/crypto/__tests__/webIdentityRecoveryMaterial.test.ts +117 -0
  98. package/src/crypto/identityMove.ts +77 -43
  99. package/src/crypto/identityProof.ts +36 -0
  100. package/src/crypto/webIdentityCarrier.ts +185 -117
  101. package/src/i18n/locales/ar-SA.json +1 -0
  102. package/src/i18n/locales/ca-ES.json +1 -0
  103. package/src/i18n/locales/de-DE.json +1 -0
  104. package/src/i18n/locales/en-US.json +1 -0
  105. package/src/i18n/locales/es-ES.json +1 -0
  106. package/src/i18n/locales/fr-FR.json +1 -0
  107. package/src/i18n/locales/it-IT.json +1 -0
  108. package/src/i18n/locales/ja-JP.json +1 -0
  109. package/src/i18n/locales/ko-KR.json +1 -0
  110. package/src/i18n/locales/pt-PT.json +1 -0
  111. package/src/i18n/locales/zh-CN.json +1 -0
  112. package/src/index.ts +26 -15
  113. package/src/inference/OxyInferenceClient.ts +84 -7
  114. package/src/inference/__tests__/OxyInferenceClient.test.ts +48 -0
  115. package/src/mixins/OxyServices.auth.ts +100 -1
  116. package/src/mixins/OxyServices.identity.ts +17 -67
  117. package/src/mixins/OxyServices.utility.ts +2 -0
  118. package/src/mixins/__tests__/OxyServices.identity.test.ts +1 -76
  119. package/src/mixins/index.ts +0 -3
  120. package/src/server/__tests__/securityHeaders.test.ts +15 -0
  121. package/src/server/__tests__/workloadIdentity.test.ts +128 -0
  122. package/src/server/index.ts +9 -0
  123. package/src/server/securityHeaders.ts +19 -6
  124. package/src/server/workloadIdentity.ts +207 -0
  125. package/src/session/__tests__/refresh.test.ts +53 -3
  126. package/src/session/refresh.ts +12 -0
  127. package/dist/cjs/mixins/OxyServices.deviceTransfer.js +0 -314
  128. package/dist/esm/mixins/OxyServices.deviceTransfer.js +0 -311
  129. package/dist/types/mixins/OxyServices.deviceTransfer.d.ts +0 -149
  130. package/src/mixins/OxyServices.deviceTransfer.ts +0 -393
  131. package/src/mixins/__tests__/OxyServices.deviceTransfer.test.ts +0 -271
@@ -3,9 +3,7 @@
3
3
  *
4
4
  * Stubs `makeRequest` so the tests run with no network. We assert request shape
5
5
  * (method, URL, body, cache options), response unwrapping, the DID derivation,
6
- * the EXACT signed payload `linkIdentityKey` produces (it must match the
7
- * server's `JSON.stringify({ action, userId, timestamp })` reconstruction
8
- * byte-for-byte), and the cache sweep on every mutation.
6
+ * and the cache sweep on every mutation.
9
7
  */
10
8
 
11
9
  import type { AuthMethodsResponse, DidDocument, SignedRecordEnvelope, VerifiedDomain } from '@oxy.so/contracts';
@@ -129,79 +127,6 @@ describe('OxyServices.identity', () => {
129
127
  });
130
128
  });
131
129
 
132
- describe('linkIdentityKey', () => {
133
- it('signs the exact server-expected payload and POSTs /auth/link', async () => {
134
- jest.spyOn(Date, 'now').mockReturnValue(1700000000000);
135
- jest.spyOn(KeyManager, 'getPublicKey').mockResolvedValue('pub-hex');
136
- const signSpy = jest.spyOn(SignatureService, 'sign').mockResolvedValue('sig-hex');
137
- makeRequestSpy.mockResolvedValue({ success: true, message: 'Identity linked successfully' });
138
-
139
- const result = await oxy.linkIdentityKey();
140
-
141
- // The signed message MUST match the server's reconstruction byte-for-byte:
142
- // JSON.stringify({ action, userId, timestamp }) in that key order.
143
- const expectedMessage = JSON.stringify({
144
- action: 'link_identity',
145
- userId: 'user-123',
146
- timestamp: 1700000000000,
147
- });
148
- expect(signSpy).toHaveBeenCalledWith(expectedMessage);
149
- expect(expectedMessage).toBe(
150
- '{"action":"link_identity","userId":"user-123","timestamp":1700000000000}',
151
- );
152
-
153
- expect(makeRequestSpy).toHaveBeenCalledWith(
154
- 'POST',
155
- '/auth/link',
156
- { type: 'identity', publicKey: 'pub-hex', signature: 'sig-hex', timestamp: 1700000000000 },
157
- expect.objectContaining({ cache: false }),
158
- );
159
- expect(result).toEqual({ success: true, message: 'Identity linked successfully' });
160
- });
161
-
162
- it('sweeps /users/me, auth methods, domains and the DID cache after linking', async () => {
163
- jest.spyOn(KeyManager, 'getPublicKey').mockResolvedValue('pub-hex');
164
- jest.spyOn(SignatureService, 'sign').mockResolvedValue('sig-hex');
165
- makeRequestSpy.mockResolvedValue({ success: true, message: 'ok' });
166
-
167
- await oxy.linkIdentityKey();
168
-
169
- expect(clearPrefixSpy).toHaveBeenCalledWith('GET:/users/me');
170
- expect(clearEntrySpy).toHaveBeenCalledWith('GET:/auth/methods');
171
- expect(clearEntrySpy).toHaveBeenCalledWith('GET:/identity/domains');
172
- expect(clearEntrySpy).toHaveBeenCalledWith('GET:/u/user-123/did.json');
173
- });
174
-
175
- it('throws (no network) when the device has no identity', async () => {
176
- jest.spyOn(KeyManager, 'getPublicKey').mockResolvedValue(null);
177
- await expect(oxy.linkIdentityKey()).rejects.toThrow(/No identity found/);
178
- expect(makeRequestSpy).not.toHaveBeenCalled();
179
- });
180
-
181
- it('throws when no user is authenticated', async () => {
182
- jest.spyOn(oxy, 'getCurrentUserId').mockReturnValue(null);
183
- jest.spyOn(KeyManager, 'getPublicKey').mockResolvedValue('pub-hex');
184
- await expect(oxy.linkIdentityKey()).rejects.toThrow(/No authenticated user/);
185
- expect(makeRequestSpy).not.toHaveBeenCalled();
186
- });
187
- });
188
-
189
- describe('unlinkAuthMethod', () => {
190
- it('DELETEs /auth/link/:type and sweeps cache', async () => {
191
- makeRequestSpy.mockResolvedValue({ success: true, message: 'identity auth unlinked successfully' });
192
-
193
- await oxy.unlinkAuthMethod('identity');
194
-
195
- expect(makeRequestSpy).toHaveBeenCalledWith(
196
- 'DELETE',
197
- '/auth/link/identity',
198
- undefined,
199
- expect.objectContaining({ cache: false }),
200
- );
201
- expect(clearEntrySpy).toHaveBeenCalledWith('GET:/u/user-123/did.json');
202
- });
203
- });
204
-
205
130
  describe('removePasskey', () => {
206
131
  it('DELETEs /auth/link/webauthn/:credentialID and sweeps cache', async () => {
207
132
  makeRequestSpy.mockResolvedValue({ success: true, message: 'Passkey unlinked successfully' });
@@ -35,7 +35,6 @@ import { OxyServicesNodesMixin } from './OxyServices.nodes';
35
35
  import { OxyServicesFollowGraphMixin } from './OxyServices.followGraph';
36
36
  import { OxyServicesInferenceMixin } from './OxyServices.inference';
37
37
  import { OxyServicesDeviceBootMixin } from './OxyServices.deviceBoot';
38
- import { OxyServicesDeviceTransferMixin } from './OxyServices.deviceTransfer';
39
38
 
40
39
  /**
41
40
  * Instance shape of every mixin in the pipeline, intersected. The runtime
@@ -75,7 +74,6 @@ type AllMixinInstances =
75
74
  & InstanceType<ReturnType<typeof OxyServicesFollowGraphMixin<typeof OxyServicesBase>>>
76
75
  & InstanceType<ReturnType<typeof OxyServicesInferenceMixin<typeof OxyServicesBase>>>
77
76
  & InstanceType<ReturnType<typeof OxyServicesDeviceBootMixin<typeof OxyServicesBase>>>
78
- & InstanceType<ReturnType<typeof OxyServicesDeviceTransferMixin<typeof OxyServicesBase>>>
79
77
  & InstanceType<ReturnType<typeof OxyServicesUtilityMixin<typeof OxyServicesBase>>>;
80
78
 
81
79
  /**
@@ -169,7 +167,6 @@ const MIXIN_PIPELINE: MixinFunction[] = [
169
167
 
170
168
  // Device-to-device identity transfer ("add a device"): E2E-encrypted key
171
169
  // clone over a short-lived relay (b3 Feature 2).
172
- OxyServicesDeviceTransferMixin,
173
170
 
174
171
  // Utility (last, can use all above)
175
172
  OxyServicesUtilityMixin,
@@ -198,6 +198,21 @@ function expoExportHtml(body = EXPO_HYDRATE_SCRIPT): string {
198
198
  ].join('');
199
199
  }
200
200
 
201
+ describe('@oxy.so/core/server buildOxyPagesHeaders on a sensitive origin (ADR 0024 D1)', () => {
202
+ it('removes the Cloudflare Insights beacon from script-src and connect-src, and nothing else', () => {
203
+ const csp = (block: string) => block.split('\n').find((line) => line.includes('Content-Security-Policy')) ?? '';
204
+ const normal = csp(buildOxyPagesHeaders({ csp: { connectSrc: ['https://example.test'] } }));
205
+ const sensitive = csp(buildOxyPagesHeaders({ csp: { connectSrc: ['https://example.test'] }, sensitive: true }));
206
+
207
+ expect(normal).toContain('static.cloudflareinsights.com');
208
+ expect(sensitive).not.toContain('cloudflareinsights.com');
209
+ expect(sensitive).toContain("script-src 'self'");
210
+ expect(sensitive).toContain('https://example.test');
211
+ expect(sensitive).toContain('https://api.oxy.so');
212
+ expect(sensitive).toContain("frame-ancestors 'none'");
213
+ });
214
+ });
215
+
201
216
  describe('@oxy.so/core/server extractInlineScripts', () => {
202
217
  it('returns inline bodies and skips external scripts', () => {
203
218
  expect(extractInlineScripts(expoExportHtml())).toEqual([EXPO_HYDRATE_SCRIPT]);
@@ -0,0 +1,128 @@
1
+ import { describe, expect, it, jest } from '@jest/globals';
2
+
3
+ import { canAttestWorkloadIdentity, requestWorkloadServiceToken } from '../workloadIdentity';
4
+
5
+ /**
6
+ * The client half of ADR 0026, and the two properties that decide whether it
7
+ * works at all against the verifier in `packages/api`:
8
+ *
9
+ * 1. **The nonce is inside the signature.** The verifier refuses an attestation
10
+ * whose `SignedHeaders` omits the nonce header, so a signer that merely sets
11
+ * the header produces attestations that are always rejected — a failure that
12
+ * would only show up in production, against the real verifier.
13
+ * 2. **The signed request is never sent to AWS.** Only Oxy replays it. A client
14
+ * that called STS itself would work in a test and leak an identity call per
15
+ * token in production.
16
+ *
17
+ * The signature's cryptographic correctness is AWS's to judge; what is asserted
18
+ * here is its SHAPE, which is what the two halves have to agree on.
19
+ */
20
+
21
+ const CREDENTIALS = {
22
+ AccessKeyId: 'ASIAEXAMPLE',
23
+ SecretAccessKey: 'secret-example',
24
+ Token: 'session-token-example',
25
+ };
26
+
27
+ function harness(overrides: { tokenStatus?: number } = {}) {
28
+ const calls: { url: string; init?: RequestInit }[] = [];
29
+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
30
+ const url = String(input);
31
+ calls.push({ url, init });
32
+ if (url.endsWith('/auth/service-token/workload/challenge')) {
33
+ return new Response(JSON.stringify({ data: { nonce: 'nonce-from-oxy', expiresIn: 60 } }), { status: 200 });
34
+ }
35
+ if (url.includes('169.254.170.2')) {
36
+ return new Response(JSON.stringify(CREDENTIALS), { status: 200 });
37
+ }
38
+ if (url.endsWith('/auth/service-token/workload')) {
39
+ const status = overrides.tokenStatus ?? 200;
40
+ if (status !== 200) return new Response('{}', { status });
41
+ return new Response(
42
+ JSON.stringify({ data: { token: 'service-token', expiresIn: 3600, appName: 'Mention' } }),
43
+ { status: 200 },
44
+ );
45
+ }
46
+ throw new Error(`unexpected request to ${url}`);
47
+ }) as unknown as typeof fetch;
48
+ return { calls, fetchImpl };
49
+ }
50
+
51
+ describe('workload identity client', () => {
52
+ const previous = process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI;
53
+
54
+ beforeEach(() => {
55
+ process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = '/v2/credentials/abc';
56
+ });
57
+
58
+ afterAll(() => {
59
+ // Cleared by assignment rather than `delete`: Biome refuses `delete` on a
60
+ // property access, and an empty value reads as "cannot attest" everywhere
61
+ // that matters here.
62
+ process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = previous ?? '';
63
+ });
64
+
65
+ it('knows whether this process can attest at all', () => {
66
+ expect(canAttestWorkloadIdentity({ AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: '/v2/x' } as NodeJS.ProcessEnv)).toBe(true);
67
+ expect(canAttestWorkloadIdentity({} as NodeJS.ProcessEnv)).toBe(false);
68
+ });
69
+
70
+ it('answers the challenge with a signature that covers the nonce', async () => {
71
+ const { calls, fetchImpl } = harness();
72
+
73
+ const granted = await requestWorkloadServiceToken({ baseUrl: 'https://api.oxy.so/', fetch: fetchImpl });
74
+
75
+ expect(granted).toEqual({ token: 'service-token', expiresIn: 3600, appName: 'Mention' });
76
+
77
+ const exchange = calls.find((call) => call.url.endsWith('/auth/service-token/workload'));
78
+ const body = JSON.parse(String(exchange?.init?.body)) as {
79
+ provider: string;
80
+ nonce: string;
81
+ attestation: { headers: Record<string, string> };
82
+ };
83
+
84
+ expect(body.provider).toBe('aws-iam');
85
+ expect(body.nonce).toBe('nonce-from-oxy');
86
+ expect(body.attestation.headers['x-oxy-attestation-nonce']).toBe('nonce-from-oxy');
87
+ expect(body.attestation.headers.host).toBe('sts.amazonaws.com');
88
+ expect(body.attestation.headers['x-amz-security-token']).toBe(CREDENTIALS.Token);
89
+ // The property the verifier actually checks.
90
+ expect(body.attestation.headers.authorization).toMatch(
91
+ /^AWS4-HMAC-SHA256 Credential=ASIAEXAMPLE\/\d{8}\/us-east-1\/sts\/aws4_request, SignedHeaders=[^,]*x-oxy-attestation-nonce[^,]*, Signature=[0-9a-f]{64}$/,
92
+ );
93
+ });
94
+
95
+ it('never sends the signed request to AWS itself', async () => {
96
+ const { calls, fetchImpl } = harness();
97
+
98
+ await requestWorkloadServiceToken({ baseUrl: 'https://api.oxy.so', fetch: fetchImpl });
99
+
100
+ expect(calls.some((call) => call.url.includes('sts.amazonaws.com'))).toBe(false);
101
+ });
102
+
103
+ it('carries no credential material into the request body', async () => {
104
+ const { calls, fetchImpl } = harness();
105
+
106
+ await requestWorkloadServiceToken({ baseUrl: 'https://api.oxy.so', fetch: fetchImpl });
107
+
108
+ const exchange = calls.find((call) => call.url.endsWith('/auth/service-token/workload'));
109
+ expect(String(exchange?.init?.body)).not.toContain(CREDENTIALS.SecretAccessKey);
110
+ });
111
+
112
+ it('throws rather than returning an empty token when Oxy refuses', async () => {
113
+ const { fetchImpl } = harness({ tokenStatus: 403 });
114
+
115
+ await expect(
116
+ requestWorkloadServiceToken({ baseUrl: 'https://api.oxy.so', fetch: fetchImpl }),
117
+ ).rejects.toThrow(/refused the workload attestation \(403\)/);
118
+ });
119
+
120
+ it('throws when the process has no identity to prove', async () => {
121
+ process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = '';
122
+ const { fetchImpl } = harness();
123
+
124
+ await expect(
125
+ requestWorkloadServiceToken({ baseUrl: 'https://api.oxy.so', fetch: fetchImpl }),
126
+ ).rejects.toThrow(/cannot attest its identity/);
127
+ });
128
+ });
@@ -168,3 +168,12 @@ export { createEcosystemTraffic } from './traffic';
168
168
  export type { EcosystemTrafficOptions } from './traffic';
169
169
 
170
170
  export { observeNodeHttp, withoutNodeHttpObservation } from './trafficNodeHttp';
171
+
172
+ /**
173
+ * Workload identity (ADR 0026): a first-party service asks Oxy for a service
174
+ * token by proving what it IS, with no api key and no secret. Server-only, and
175
+ * exported from this subpath rather than the root barrel because it reaches the
176
+ * container credentials endpoint.
177
+ */
178
+ export { canAttestWorkloadIdentity, requestWorkloadServiceToken } from './workloadIdentity';
179
+ export type { WorkloadServiceToken, WorkloadServiceTokenOptions } from './workloadIdentity';
@@ -360,6 +360,14 @@ const MAX_INLINE_SCRIPT_HASHES = 8;
360
360
  export interface OxyPagesHeadersOptions {
361
361
  /** Per-app additions merged into {@link OXY_CSP_BASELINE}. */
362
362
  csp?: OxyCspExtensions;
363
+ /**
364
+ * An origin where people authenticate, consent or recover (`auth.oxy.so`,
365
+ * ADR 0024 D1). The Cloudflare Insights beacon — injected by the edge, not by
366
+ * the app — is REMOVED from `script-src` and `connect-src`, so third-party
367
+ * measurement cannot run there even when the zone has Web Analytics enabled.
368
+ * A structural block in the policy the page is served with, not a build flag.
369
+ */
370
+ sensitive?: boolean;
363
371
  /**
364
372
  * Emit `Strict-Transport-Security` (default `true`). Cloudflare Pages serves
365
373
  * HTTPS only, so static deploys should keep this on.
@@ -399,13 +407,18 @@ export function buildOxyPagesHeaders(options: OxyPagesHeadersOptions = {}): stri
399
407
  );
400
408
  }
401
409
 
402
- const csp = formatOxyCspPolicy(
403
- buildOxyCspDirectives(
404
- hashes.length === 0
405
- ? options.csp
406
- : { ...options.csp, scriptSrc: [...(options.csp?.scriptSrc ?? []), ...hashes] },
407
- ),
410
+ const directives = buildOxyCspDirectives(
411
+ hashes.length === 0
412
+ ? options.csp
413
+ : { ...options.csp, scriptSrc: [...(options.csp?.scriptSrc ?? []), ...hashes] },
408
414
  );
415
+ if (options.sensitive) {
416
+ const beacon = new Set([CLOUDFLARE_INSIGHTS_SCRIPT_ORIGIN, CLOUDFLARE_INSIGHTS_REPORT_ORIGIN]);
417
+ for (const name of ['script-src', 'connect-src']) {
418
+ directives[name] = (directives[name] ?? []).filter((source) => !beacon.has(source));
419
+ }
420
+ }
421
+ const csp = formatOxyCspPolicy(directives);
409
422
  const lines = [
410
423
  '/*',
411
424
  ` Content-Security-Policy: ${csp}`,
@@ -0,0 +1,207 @@
1
+ import { createHash, createHmac } from 'node:crypto';
2
+
3
+ /**
4
+ * Asking Oxy for a service token by proving what this process IS (ADR 0026).
5
+ *
6
+ * The other half of the credential-free path: `packages/api` verifies the proof,
7
+ * this builds one. A first-party service that calls
8
+ * {@link requestWorkloadServiceToken} needs no api key, no secret and no entry in
9
+ * a parameter store — only to be running as itself.
10
+ *
11
+ * ## Why this signs SigV4 by hand
12
+ *
13
+ * The attestation is a signed `GetCallerIdentity` request that is never sent to
14
+ * AWS by us; Oxy replays it. Producing one needs credentials and a signature,
15
+ * and the obvious way to get both is the AWS SDK — which this package must not
16
+ * depend on. `@oxy.so/core` ships to React Native and Expo, where several
17
+ * megabytes of AWS client for a call that only ever happens on a server is not a
18
+ * trade worth making, and the package rules keep optional heavyweights out of
19
+ * the root barrel for exactly this reason.
20
+ *
21
+ * So: credentials come from the container credentials endpoint ECS already
22
+ * exposes to every task, and the signature is ~40 lines of HMAC out of
23
+ * `node:crypto`. No dependency, and nothing here is AWS-specific above
24
+ * {@link awsContainerAttestation} — a second provider is another function with
25
+ * the same shape.
26
+ *
27
+ * ## What this never does
28
+ *
29
+ * It never sends the signed request to AWS. It never logs a credential, a
30
+ * signature or a token. It caches the TOKEN (short-lived, from Oxy) and never
31
+ * the AWS credentials, which the endpoint hands out fresh anyway.
32
+ */
33
+
34
+ /** The header Oxy's verifier requires inside the signature. Must match `ATTESTATION_NONCE_HEADER`. */
35
+ const NONCE_HEADER = 'x-oxy-attestation-nonce';
36
+ const STS_HOST = 'sts.amazonaws.com';
37
+ const STS_REGION = 'us-east-1';
38
+ const STS_BODY = 'Action=GetCallerIdentity&Version=2011-06-15';
39
+
40
+ export interface WorkloadServiceTokenOptions {
41
+ /** Oxy's base URL, e.g. `https://api.oxy.so`. */
42
+ baseUrl: string;
43
+ /** Injected in tests; defaults to the global. */
44
+ fetch?: typeof fetch;
45
+ }
46
+
47
+ export interface WorkloadServiceToken {
48
+ token: string;
49
+ /** Seconds from now, as Oxy reported it. */
50
+ expiresIn: number;
51
+ appName: string;
52
+ }
53
+
54
+ /** Credentials as the ECS container credentials endpoint returns them. */
55
+ interface ContainerCredentials {
56
+ AccessKeyId: string;
57
+ SecretAccessKey: string;
58
+ Token?: string;
59
+ }
60
+
61
+ /**
62
+ * Whether this process can attest at all.
63
+ *
64
+ * The relative URI is set by ECS on every task and by nothing else, so its
65
+ * presence is the honest test for "we can prove what we are here". A local
66
+ * checkout has no attestation to offer and must fall back to a credential.
67
+ */
68
+ export function canAttestWorkloadIdentity(env: NodeJS.ProcessEnv = process.env): boolean {
69
+ return Boolean(env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || env.AWS_CONTAINER_CREDENTIALS_FULL_URI);
70
+ }
71
+
72
+ async function containerCredentials(fetchImpl: typeof fetch): Promise<ContainerCredentials> {
73
+ const relative = process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI;
74
+ const url = relative
75
+ ? `http://169.254.170.2${relative}`
76
+ : (process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI as string);
77
+ if (!url) {
78
+ throw new Error('No container credentials endpoint: this process cannot attest its identity.');
79
+ }
80
+ const response = await fetchImpl(url, {
81
+ headers: process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN
82
+ ? { authorization: process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN }
83
+ : {},
84
+ });
85
+ if (!response.ok) {
86
+ throw new Error(`The container credentials endpoint answered ${response.status}.`);
87
+ }
88
+ const credentials = (await response.json()) as ContainerCredentials;
89
+ if (!credentials.AccessKeyId || !credentials.SecretAccessKey) {
90
+ throw new Error('The container credentials endpoint answered without credentials.');
91
+ }
92
+ return credentials;
93
+ }
94
+
95
+ function hmac(key: Buffer | string, data: string): Buffer {
96
+ return createHmac('sha256', key).update(data, 'utf8').digest();
97
+ }
98
+
99
+ function sha256Hex(value: string): string {
100
+ return createHash('sha256').update(value, 'utf8').digest('hex');
101
+ }
102
+
103
+ /**
104
+ * Signs `GetCallerIdentity` with SigV4, binding the nonce into the signature.
105
+ *
106
+ * `SignedHeaders` includes the nonce header deliberately: Oxy refuses an
107
+ * attestation whose signature does not cover it, because a nonce the signature
108
+ * does not cover can be swapped by whoever captured the attestation.
109
+ */
110
+ function signGetCallerIdentity(credentials: ContainerCredentials, nonce: string, now: Date): Record<string, string> {
111
+ const amzDate = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
112
+ const dateStamp = amzDate.slice(0, 8);
113
+
114
+ const headers: Record<string, string> = {
115
+ host: STS_HOST,
116
+ 'x-amz-date': amzDate,
117
+ [NONCE_HEADER]: nonce,
118
+ };
119
+ if (credentials.Token) headers['x-amz-security-token'] = credentials.Token;
120
+
121
+ const signedHeaderNames = Object.keys(headers).sort();
122
+ const canonicalHeaders = signedHeaderNames.map((name) => `${name}:${headers[name]}\n`).join('');
123
+ const signedHeaders = signedHeaderNames.join(';');
124
+
125
+ const canonicalRequest = [
126
+ 'POST',
127
+ '/',
128
+ '',
129
+ canonicalHeaders,
130
+ signedHeaders,
131
+ sha256Hex(STS_BODY),
132
+ ].join('\n');
133
+
134
+ const scope = `${dateStamp}/${STS_REGION}/sts/aws4_request`;
135
+ const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonicalRequest)].join('\n');
136
+
137
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${credentials.SecretAccessKey}`, dateStamp), STS_REGION), 'sts'), 'aws4_request');
138
+ const signature = createHmac('sha256', signingKey).update(stringToSign, 'utf8').digest('hex');
139
+
140
+ return {
141
+ ...headers,
142
+ authorization:
143
+ `AWS4-HMAC-SHA256 Credential=${credentials.AccessKeyId}/${scope}, ` +
144
+ `SignedHeaders=${signedHeaders}, Signature=${signature}`,
145
+ };
146
+ }
147
+
148
+ /** The AWS attestation: signed headers, and nothing else. */
149
+ async function awsContainerAttestation(fetchImpl: typeof fetch, nonce: string): Promise<{ headers: Record<string, string> }> {
150
+ const credentials = await containerCredentials(fetchImpl);
151
+ return { headers: signGetCallerIdentity(credentials, nonce, new Date()) };
152
+ }
153
+
154
+ /**
155
+ * Exchanges this process's identity for an Oxy service token.
156
+ *
157
+ * Two round trips by design (see ADR 0026): a nonce, then an attestation that
158
+ * signs it. The caller caches the token — it lives an hour — rather than doing
159
+ * this per request.
160
+ *
161
+ * Failures are thrown, never swallowed into an empty token: a caller that
162
+ * cannot prove what it is must not go on to make an unauthenticated request and
163
+ * discover the problem as a 401 somewhere else.
164
+ */
165
+ export async function requestWorkloadServiceToken(
166
+ options: WorkloadServiceTokenOptions,
167
+ ): Promise<WorkloadServiceToken> {
168
+ const fetchImpl = options.fetch ?? fetch;
169
+ const base = options.baseUrl.replace(/\/+$/, '');
170
+
171
+ const challengeResponse = await fetchImpl(`${base}/auth/service-token/workload/challenge`, {
172
+ method: 'POST',
173
+ headers: { 'content-type': 'application/json' },
174
+ });
175
+ if (!challengeResponse.ok) {
176
+ throw new Error(`Oxy refused to issue a workload challenge (${challengeResponse.status}).`);
177
+ }
178
+ const challenge = unwrap<{ nonce?: string }>(await challengeResponse.json());
179
+ if (!challenge?.nonce) {
180
+ throw new Error('Oxy issued a workload challenge with no nonce.');
181
+ }
182
+
183
+ const attestation = await awsContainerAttestation(fetchImpl, challenge.nonce);
184
+
185
+ const tokenResponse = await fetchImpl(`${base}/auth/service-token/workload`, {
186
+ method: 'POST',
187
+ headers: { 'content-type': 'application/json' },
188
+ body: JSON.stringify({ provider: 'aws-iam', nonce: challenge.nonce, attestation }),
189
+ });
190
+ if (!tokenResponse.ok) {
191
+ // The body carries a bounded `reason`; the token never travels on a failure,
192
+ // so there is nothing here that must not be seen.
193
+ throw new Error(`Oxy refused the workload attestation (${tokenResponse.status}).`);
194
+ }
195
+ const granted = unwrap<Partial<WorkloadServiceToken>>(await tokenResponse.json());
196
+ if (!granted?.token || typeof granted.expiresIn !== 'number') {
197
+ throw new Error('Oxy answered the attestation without a usable token.');
198
+ }
199
+ return { token: granted.token, expiresIn: granted.expiresIn, appName: granted.appName ?? '' };
200
+ }
201
+
202
+ /** Oxy wraps successful bodies in `{ data }`; older routes answer flat. */
203
+ function unwrap<T>(body: unknown): T | null {
204
+ if (typeof body !== 'object' || body === null) return null;
205
+ const envelope = body as { data?: unknown };
206
+ return (typeof envelope.data === 'object' && envelope.data !== null ? envelope.data : body) as T;
207
+ }
@@ -57,17 +57,23 @@ interface RefreshMockOverrides {
57
57
  signInWithSharedIdentity?: OxyServices['signInWithSharedIdentity'];
58
58
  }
59
59
 
60
- function makeOxy(overrides: RefreshMockOverrides = {}): { oxy: OxyServices; setTokens: jest.Mock } {
60
+ function makeOxy(
61
+ overrides: RefreshMockOverrides = {},
62
+ ): { oxy: OxyServices; setTokens: jest.Mock; noteRefreshRateLimited: jest.Mock } {
61
63
  const setTokens = jest.fn();
64
+ const noteRefreshRateLimited = jest.fn();
62
65
  const oxy = {
63
66
  setTokens,
64
67
  mintFromDeviceSecret: overrides.mintFromDeviceSecret ?? (async () => MINT),
65
68
  signInWithSharedIdentity: overrides.signInWithSharedIdentity ?? (async () => null),
66
69
  // The rotating mint runs under the client's process-wide single-flight; the
67
70
  // arm reaches for it via `oxy.httpService.runSingleFlightDeviceSecretMint`.
68
- httpService: { runSingleFlightDeviceSecretMint: makeMintSingleFlight() },
71
+ httpService: {
72
+ runSingleFlightDeviceSecretMint: makeMintSingleFlight(),
73
+ noteRefreshRateLimited,
74
+ },
69
75
  } as unknown as OxyServices;
70
- return { oxy, setTokens };
76
+ return { oxy, setTokens, noteRefreshRateLimited };
71
77
  }
72
78
 
73
79
  describe('refreshPersistedSession — arm 1 (device-secret mint)', () => {
@@ -179,6 +185,50 @@ describe('refreshPersistedSession — arm 1 (device-secret mint)', () => {
179
185
  expect(await store.load()).toEqual(STORED);
180
186
  expect(signInWithSharedIdentity).not.toHaveBeenCalled();
181
187
  });
188
+
189
+ it('KEEPS the store on a 429 and does NOT fall through to shared-key — a rationed mint never judged the secret', async () => {
190
+ const store = createMemoryAuthStateStore();
191
+ await store.save(STORED);
192
+ const signInWithSharedIdentity = jest.fn(async () => null);
193
+ const { oxy } = makeOxy({
194
+ mintFromDeviceSecret: async () => {
195
+ throw Object.assign(new Error('Too many requests'), { status: 429 });
196
+ },
197
+ signInWithSharedIdentity,
198
+ });
199
+
200
+ expect(await refreshPersistedSession({ oxy, store, allowSharedKeyFallback: true })).toBeNull();
201
+ expect(await store.load()).toEqual(STORED);
202
+ expect(signInWithSharedIdentity).not.toHaveBeenCalled();
203
+ });
204
+
205
+ it('tells HttpService to lengthen the refresh cooldown when the mint is rate limited', async () => {
206
+ const store = createMemoryAuthStateStore();
207
+ await store.save(STORED);
208
+ const { oxy, noteRefreshRateLimited } = makeOxy({
209
+ mintFromDeviceSecret: async () => {
210
+ throw Object.assign(new Error('Too many requests'), { status: 429 });
211
+ },
212
+ });
213
+
214
+ await refreshPersistedSession({ oxy, store, allowSharedKeyFallback: false });
215
+
216
+ expect(noteRefreshRateLimited).toHaveBeenCalledTimes(1);
217
+ });
218
+
219
+ it('does NOT lengthen the cooldown for failures the server did not ration', async () => {
220
+ const store = createMemoryAuthStateStore();
221
+ await store.save(STORED);
222
+ const { oxy, noteRefreshRateLimited } = makeOxy({
223
+ mintFromDeviceSecret: async () => {
224
+ throw Object.assign(new Error('server'), { status: 500 });
225
+ },
226
+ });
227
+
228
+ await refreshPersistedSession({ oxy, store, allowSharedKeyFallback: false });
229
+
230
+ expect(noteRefreshRateLimited).not.toHaveBeenCalled();
231
+ });
182
232
  });
183
233
 
184
234
  describe('refreshPersistedSession — arm 2 (native shared-key fallback)', () => {
@@ -159,6 +159,18 @@ export async function refreshDeviceSecretArm(deps: {
159
159
  })
160
160
  : await oxy.mintFromDeviceSecret(persisted.deviceId, persisted.deviceSecret);
161
161
  } catch (error) {
162
+ // 429 keeps the credential like any other transient failure — the secret
163
+ // was never judged — but it must NOT retry on the transient cadence. The
164
+ // request-driven lanes (request-time preflight, 401 retry) reattempt every
165
+ // second once the access token is expired, which is 60 mints/min against a
166
+ // 30/min server budget: the client's own retries then hold the limiter
167
+ // tripped and the session cannot recover while the app keeps making
168
+ // requests. Telling HttpService lengthens the next cooldown to one attempt
169
+ // per limiter window, which lets the budget drain and the session heal.
170
+ if (extractErrorStatus(error) === 429) {
171
+ oxy.httpService.noteRefreshRateLimited();
172
+ return { status: 'transient' };
173
+ }
162
174
  if (extractErrorStatus(error) === 401) {
163
175
  // Structural read (not `instanceof Error`): the thrown value can be a
164
176
  // plain ApiError-shaped object or come from another realm.