@oxyhq/core 21.0.0 → 21.0.1

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 (57) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/HttpService.js +47 -8
  3. package/dist/cjs/i18n/locales/en-US.json +7 -2
  4. package/dist/cjs/i18n/locales/es-ES.json +7 -2
  5. package/dist/cjs/i18n/locales/locales/en-US.json +7 -2
  6. package/dist/cjs/i18n/locales/locales/es-ES.json +7 -2
  7. package/dist/cjs/index.js +8 -1
  8. package/dist/cjs/inference/OxyInferenceClient.js +330 -0
  9. package/dist/cjs/mixins/OxyServices.accounts.js +5 -72
  10. package/dist/cjs/mixins/OxyServices.inference.js +59 -0
  11. package/dist/cjs/mixins/OxyServices.utility.js +18 -6
  12. package/dist/cjs/mixins/index.js +6 -0
  13. package/dist/cjs/server/auth.js +76 -0
  14. package/dist/cjs/server/index.js +5 -1
  15. package/dist/esm/.tsbuildinfo +1 -1
  16. package/dist/esm/HttpService.js +47 -8
  17. package/dist/esm/i18n/locales/en-US.json +7 -2
  18. package/dist/esm/i18n/locales/es-ES.json +7 -2
  19. package/dist/esm/i18n/locales/locales/en-US.json +7 -2
  20. package/dist/esm/i18n/locales/locales/es-ES.json +7 -2
  21. package/dist/esm/index.js +4 -0
  22. package/dist/esm/inference/OxyInferenceClient.js +325 -0
  23. package/dist/esm/mixins/OxyServices.accounts.js +5 -72
  24. package/dist/esm/mixins/OxyServices.inference.js +56 -0
  25. package/dist/esm/mixins/OxyServices.utility.js +18 -6
  26. package/dist/esm/mixins/index.js +6 -0
  27. package/dist/esm/server/auth.js +72 -0
  28. package/dist/esm/server/index.js +1 -1
  29. package/dist/types/.tsbuildinfo +1 -1
  30. package/dist/types/HttpService.d.ts +39 -1
  31. package/dist/types/index.d.ts +3 -1
  32. package/dist/types/inference/OxyInferenceClient.d.ts +324 -0
  33. package/dist/types/mixins/OxyServices.accounts.d.ts +73 -95
  34. package/dist/types/mixins/OxyServices.inference.d.ts +95 -0
  35. package/dist/types/mixins/OxyServices.utility.d.ts +44 -13
  36. package/dist/types/mixins/index.d.ts +2 -1
  37. package/dist/types/server/auth.d.ts +80 -0
  38. package/dist/types/server/index.d.ts +2 -2
  39. package/package.json +2 -2
  40. package/src/HttpService.ts +50 -10
  41. package/src/__tests__/httpServiceUnwrapEnvelope.test.ts +115 -0
  42. package/src/i18n/locales/en-US.json +7 -2
  43. package/src/i18n/locales/es-ES.json +7 -2
  44. package/src/index.ts +19 -7
  45. package/src/inference/OxyInferenceClient.ts +590 -0
  46. package/src/inference/__tests__/OxyInferenceClient.test.ts +383 -0
  47. package/src/mixins/OxyServices.accounts.ts +75 -176
  48. package/src/mixins/OxyServices.inference.ts +57 -0
  49. package/src/mixins/OxyServices.utility.ts +58 -14
  50. package/src/mixins/__tests__/accounts.test.ts +57 -102
  51. package/src/mixins/__tests__/inferenceFactory.test.ts +58 -0
  52. package/src/mixins/__tests__/serviceAuth.test.ts +2 -0
  53. package/src/mixins/index.ts +8 -0
  54. package/src/server/__tests__/serviceTokenAttribution.test.ts +396 -0
  55. package/src/server/auth.ts +118 -0
  56. package/src/server/index.ts +6 -0
  57. package/src/session/__tests__/accountDialogShape.test.ts +118 -0
@@ -19,6 +19,12 @@ export interface OxyServiceAppContext {
19
19
  appName: string;
20
20
  scopes: string[];
21
21
  credentialId: string;
22
+ /**
23
+ * The Oxy account that owns `appId` and is financially responsible for it.
24
+ * Read off the VERIFIED service-token claim set — never a user id, and never
25
+ * the delegated `X-Oxy-User-Id` (ADR 0007).
26
+ */
27
+ ownerAccountId: string;
22
28
  environment: OxyServiceEnvironment;
23
29
  }
24
30
 
@@ -84,6 +90,118 @@ export function isOxyAuthenticated(req: Request): req is OxyAuthenticatedRequest
84
90
  return getOxyUserId(req) !== null;
85
91
  }
86
92
 
93
+ /**
94
+ * The principal a request is CHARGED to, and the identifiers a receipt needs.
95
+ *
96
+ * Every field is read from the verified service-token claim set. It is an
97
+ * OBJECT, not a string, and that is the point: `getOxyUserId` returns a
98
+ * `string | null`, so a delegated end-user id cannot be passed anywhere an
99
+ * `OxyBillingPrincipal` is expected. The confusion ADR 0007 forbids —
100
+ * attributing spend to the person a service is acting for rather than to the
101
+ * service's own account — stops being a code-review question and becomes a
102
+ * compile error.
103
+ *
104
+ * `scopes` are the effective scopes minted into the token (credential ∩
105
+ * application). Nothing re-intersects them here.
106
+ */
107
+ export interface OxyBillingPrincipal {
108
+ /** `applications.owner_account_id` — the financially responsible account. */
109
+ readonly accountId: string;
110
+ readonly applicationId: string;
111
+ readonly credentialId: string;
112
+ readonly environment: OxyServiceEnvironment;
113
+ readonly scopes: readonly string[];
114
+ }
115
+
116
+ /**
117
+ * The full canonical attribution of ADR 0007 for a request: the billing
118
+ * principal PLUS the optional delegated end user.
119
+ *
120
+ * `delegatedUserId` is named for what it is. It answers "on whose behalf" and
121
+ * is absent for a machine credential acting for itself — its absence is normal,
122
+ * and nothing may synthesize one. If removing it would change what any account
123
+ * is charged, the code reading it is wrong.
124
+ */
125
+ export interface OxyRequestAttribution extends OxyBillingPrincipal {
126
+ readonly delegatedUserId: string | null;
127
+ }
128
+
129
+ /**
130
+ * The billing principal of a request, or `null` when the request carries no
131
+ * verified service principal (an ordinary user session is not a billable
132
+ * machine principal — its account is resolved from the account graph, not from
133
+ * a token claim).
134
+ *
135
+ * Reads `req.serviceApp` and NOTHING else: not `req.userId`, not `req.user`,
136
+ * not `req.serviceActingAs`. That exclusivity is the invariant this function
137
+ * exists to hold, and `serviceTokenAttribution.test.ts` mutation-tests it.
138
+ *
139
+ * **It answers for the SERVICE-TOKEN lane only.** The API's machine-credential
140
+ * lane (`oxy_sk_*`, issue #972 §2.3) resolves the same five facts into its own
141
+ * `req.machineCredential`, deliberately never `req.serviceApp` — populating the
142
+ * latter would hand a self-serve third-party credential the lane that only
143
+ * platform-trusted applications may enter. So a machine-credential request has
144
+ * no billing principal HERE and resolves `null`, which fails closed: the caller
145
+ * must handle it, and `getRequiredOxyBillingPrincipal` throws rather than
146
+ * charging anyone. One accessor answering for both lanes belongs to the public
147
+ * inference edge that has to admit both, and it needs the machine principal's
148
+ * shape to move into this package first.
149
+ */
150
+ export function getOxyBillingPrincipal(req: Request): OxyBillingPrincipal | null {
151
+ const serviceApp = (req as OxyAuthRequest).serviceApp;
152
+ if (!serviceApp) {
153
+ return null;
154
+ }
155
+ const accountId = normalizeId(serviceApp.ownerAccountId);
156
+ const applicationId = normalizeId(serviceApp.appId);
157
+ const credentialId = normalizeId(serviceApp.credentialId);
158
+ if (!accountId || !applicationId || !credentialId) {
159
+ return null;
160
+ }
161
+ return {
162
+ accountId,
163
+ applicationId,
164
+ credentialId,
165
+ environment: serviceApp.environment,
166
+ scopes: serviceApp.scopes,
167
+ };
168
+ }
169
+
170
+ /**
171
+ * {@link getOxyBillingPrincipal}, throwing when the request has none. Use on
172
+ * routes that have already required a service token.
173
+ */
174
+ export function getRequiredOxyBillingPrincipal(req: Request): OxyBillingPrincipal {
175
+ const principal = getOxyBillingPrincipal(req);
176
+ if (!principal) {
177
+ throw new Error('Request has no verified Oxy service principal');
178
+ }
179
+ return principal;
180
+ }
181
+
182
+ /**
183
+ * The delegated end user of a service request, or `null`.
184
+ *
185
+ * Deliberately reads `req.serviceActingAs` — the grant-verified delegation —
186
+ * and not `req.userId`, which on a non-service request is the caller's own
187
+ * session identity and is not a delegation at all.
188
+ */
189
+ export function getOxyDelegatedUserId(req: Request): string | null {
190
+ return normalizeId((req as OxyAuthRequest).serviceActingAs?.userId);
191
+ }
192
+
193
+ /**
194
+ * The whole attribution tuple for a service request: who pays, which
195
+ * application and credential, and optionally on whose behalf.
196
+ */
197
+ export function getOxyRequestAttribution(req: Request): OxyRequestAttribution | null {
198
+ const principal = getOxyBillingPrincipal(req);
199
+ if (!principal) {
200
+ return null;
201
+ }
202
+ return { ...principal, delegatedUserId: getOxyDelegatedUserId(req) };
203
+ }
204
+
87
205
  export function getRequiredOxyUserId(req: Request): string {
88
206
  const userId = getOxyUserId(req);
89
207
  if (!userId) {
@@ -18,7 +18,11 @@
18
18
  export {
19
19
  createOptionalOxyAuth,
20
20
  createOxyAuthMiddleware,
21
+ getOxyBillingPrincipal,
22
+ getOxyDelegatedUserId,
23
+ getOxyRequestAttribution,
21
24
  getOxyUserId,
25
+ getRequiredOxyBillingPrincipal,
22
26
  getRequiredOxyUserId,
23
27
  isOxyAuthenticated,
24
28
  requireOxyAuth,
@@ -28,6 +32,8 @@ export type {
28
32
  OxyAuthenticatedRequest,
29
33
  OxyAuthMiddlewareOptions,
30
34
  OxyAuthRequest,
35
+ OxyBillingPrincipal,
36
+ OxyRequestAttribution,
31
37
  OxyRequestUser,
32
38
  OxyServiceActingAsContext,
33
39
  OxyServiceAppContext,
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The two halves of the retired flat account list that a text scan cannot prove
3
+ * gone.
4
+ *
5
+ * `scripts/validate-no-flat-account-list.mjs` bans the identifiers that left the
6
+ * packages outright — `SwitchableAccount`, `projectSwitchableAccounts`,
7
+ * `useSwitchableAccounts`, `useAccountStore` and the rest — because each of
8
+ * those names is unique enough that a match is always a reintroduction. Two
9
+ * pieces of the same removal are NOT: an `accounts` field on the snapshot and a
10
+ * `switchTo` method on the controller are ordinary words. `'accounts'` is a live
11
+ * VIEW name three lines away in the same file, so a scoped grep there would fire
12
+ * on the thing that is supposed to be there.
13
+ *
14
+ * ## Why this is a RUNTIME check and not a type-level one
15
+ *
16
+ * A `type Has<S, K> = K extends keyof S ? true : false` assertion reads better
17
+ * and is checked by nothing here. `packages/core/tsconfig*.json` all carry
18
+ * `"exclude": ["**\/__tests__"]`, so `tsc` never sees a test file, and
19
+ * `jest.config.js` sets `diagnostics: false`, so ts-jest transpiles without
20
+ * typechecking. That version was written first and MUTATION-TESTED: putting
21
+ * `accounts: string[]` back on the interface and `switchTo()` back on the class
22
+ * left both assertions green. It is recorded here because the type-level form is
23
+ * the obvious thing to reach for, and it cannot fail in this package.
24
+ *
25
+ * The residual gap of the runtime form is an OPTIONAL field nobody writes —
26
+ * `accounts?: SwitchableAccount[]` would satisfy `tsc` without appearing on a
27
+ * snapshot. A REQUIRED one cannot hide: `computeSnapshot()` is strict, so the
28
+ * field has to be populated, and then it is here. An optional list nothing
29
+ * writes is not the mechanism coming back.
30
+ */
31
+
32
+ import type { DeviceSessionState } from '@oxyhq/contracts';
33
+ import type { OxyServices } from '../../OxyServices';
34
+ import { SessionClient, type SessionClientHost } from '../SessionClient';
35
+ import { createAccountDialogController } from '../accountDialogController';
36
+
37
+ const host: SessionClientHost = {
38
+ makeRequest: jest.fn(async () => undefined),
39
+ getBaseURL: () => 'http://test.invalid',
40
+ getAccessToken: () => null,
41
+ getDeviceCredential: () => null,
42
+ onTokensChanged: () => () => undefined,
43
+ setTokens: jest.fn(),
44
+ getCurrentAccountId: () => null,
45
+ };
46
+
47
+ const oxyServices = {
48
+ getAccessToken: jest.fn(() => null),
49
+ getBaseURL: jest.fn(() => 'http://test.invalid'),
50
+ onTokensChanged: jest.fn(() => () => undefined),
51
+ getFileDownloadUrl: jest.fn((id: string) => `https://cdn/${id}`),
52
+ } as unknown as OxyServices;
53
+
54
+ /**
55
+ * Every key the snapshot carries, and the whole set of them.
56
+ *
57
+ * An exact set rather than `not.toContain('accounts')` on purpose: it fails on
58
+ * ANY new field, not only on one spelled the way the old one was. The snapshot
59
+ * is a published contract that four surfaces render from, so growing it should
60
+ * be a deliberate edit here — and a flat list would come back under a new name
61
+ * (`rows`, `switchable`, `entries`) at least as readily as under the old one,
62
+ * which a name-specific check would wave through.
63
+ */
64
+ const SNAPSHOT_KEYS = [
65
+ 'activatingContextId',
66
+ 'activeContext',
67
+ 'commonsAvailability',
68
+ 'directory',
69
+ 'error',
70
+ 'loading',
71
+ 'removingContextId',
72
+ 'removingPrincipalId',
73
+ 'signIn',
74
+ 'view',
75
+ ];
76
+
77
+ describe('the account dialog surface after the flat list was retired', () => {
78
+ it('carries the server directory, and no flat account list beside it', () => {
79
+ const controller = createAccountDialogController({
80
+ oxyServices,
81
+ sessionClient: new SessionClient(host),
82
+ clientId: 'oxy_dk_test',
83
+ });
84
+
85
+ const snapshot = controller.getSnapshot();
86
+
87
+ // The absence half. `accounts` was the deduped union of the device's
88
+ // sign-ins and the CALLER's account graph — and a client holds one caller's
89
+ // graph and cannot enumerate another principal's, so on a device holding two
90
+ // people it answered with one person's accounts as though they were the
91
+ // device's.
92
+ expect(Object.keys(snapshot).sort()).toEqual(SNAPSHOT_KEYS);
93
+
94
+ // The positive control, in the same assertion and again here: a snapshot
95
+ // that stopped being built at all would satisfy "has no `accounts`" too.
96
+ expect(snapshot).toHaveProperty('directory');
97
+ expect(snapshot).toHaveProperty('activeContext');
98
+ });
99
+
100
+ it('switches on a context pair, and offers no account-id switch', () => {
101
+ const controller = createAccountDialogController({
102
+ oxyServices,
103
+ sessionClient: new SessionClient(host),
104
+ clientId: 'oxy_dk_test',
105
+ });
106
+
107
+ // `switchTo(accountId)` could not express WHICH person's route into a shared
108
+ // organization was being taken, so on a device where two people both reach
109
+ // one org it chose for the user. `activateContext(contextId)` names the
110
+ // pair, and `signOutContext` / `signOutPrincipal` are the two removals an
111
+ // account id likewise cannot name.
112
+ expect('switchTo' in controller).toBe(false);
113
+
114
+ expect(typeof controller.activateContext).toBe('function');
115
+ expect(typeof controller.signOutContext).toBe('function');
116
+ expect(typeof controller.signOutPrincipal).toBe('function');
117
+ });
118
+ });