@oxyhq/core 1.11.24 → 2.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.
Files changed (150) hide show
  1. package/README.md +5 -6
  2. package/dist/cjs/.tsbuildinfo +1 -1
  3. package/dist/cjs/AuthManager.js +678 -4
  4. package/dist/cjs/AuthManagerTypes.js +13 -0
  5. package/dist/cjs/CrossDomainAuth.js +45 -3
  6. package/dist/cjs/OxyServices.base.js +16 -0
  7. package/dist/cjs/i18n/locales/ar-SA.json +83 -0
  8. package/dist/cjs/i18n/locales/ca-ES.json +83 -0
  9. package/dist/cjs/i18n/locales/de-DE.json +83 -0
  10. package/dist/cjs/i18n/locales/en-US.json +83 -0
  11. package/dist/cjs/i18n/locales/es-ES.json +99 -4
  12. package/dist/cjs/i18n/locales/fr-FR.json +83 -0
  13. package/dist/cjs/i18n/locales/it-IT.json +83 -0
  14. package/dist/cjs/i18n/locales/ja-JP.json +83 -0
  15. package/dist/cjs/i18n/locales/ko-KR.json +83 -0
  16. package/dist/cjs/i18n/locales/locales/ar-SA.json +83 -1
  17. package/dist/cjs/i18n/locales/locales/ca-ES.json +83 -1
  18. package/dist/cjs/i18n/locales/locales/de-DE.json +83 -1
  19. package/dist/cjs/i18n/locales/locales/en-US.json +83 -0
  20. package/dist/cjs/i18n/locales/locales/es-ES.json +99 -4
  21. package/dist/cjs/i18n/locales/locales/fr-FR.json +83 -1
  22. package/dist/cjs/i18n/locales/locales/it-IT.json +83 -1
  23. package/dist/cjs/i18n/locales/locales/ja-JP.json +200 -117
  24. package/dist/cjs/i18n/locales/locales/ko-KR.json +83 -1
  25. package/dist/cjs/i18n/locales/locales/pt-PT.json +83 -1
  26. package/dist/cjs/i18n/locales/locales/zh-CN.json +83 -1
  27. package/dist/cjs/i18n/locales/pt-PT.json +83 -0
  28. package/dist/cjs/i18n/locales/zh-CN.json +83 -0
  29. package/dist/cjs/index.js +121 -57
  30. package/dist/cjs/mixins/OxyServices.auth.js +235 -0
  31. package/dist/cjs/mixins/OxyServices.fedcm.js +36 -0
  32. package/dist/cjs/mixins/OxyServices.popup.js +61 -1
  33. package/dist/cjs/mixins/OxyServices.user.js +18 -0
  34. package/dist/cjs/utils/accountUtils.js +64 -1
  35. package/dist/cjs/utils/coldBoot.js +71 -0
  36. package/dist/cjs/utils/fapiAutoDetect.js +88 -0
  37. package/dist/esm/.tsbuildinfo +1 -1
  38. package/dist/esm/AuthManager.js +678 -4
  39. package/dist/esm/AuthManagerTypes.js +12 -0
  40. package/dist/esm/CrossDomainAuth.js +45 -3
  41. package/dist/esm/OxyServices.base.js +16 -0
  42. package/dist/esm/i18n/locales/ar-SA.json +83 -0
  43. package/dist/esm/i18n/locales/ca-ES.json +83 -0
  44. package/dist/esm/i18n/locales/de-DE.json +83 -0
  45. package/dist/esm/i18n/locales/en-US.json +83 -0
  46. package/dist/esm/i18n/locales/es-ES.json +99 -4
  47. package/dist/esm/i18n/locales/fr-FR.json +83 -0
  48. package/dist/esm/i18n/locales/it-IT.json +83 -0
  49. package/dist/esm/i18n/locales/ja-JP.json +83 -0
  50. package/dist/esm/i18n/locales/ko-KR.json +83 -0
  51. package/dist/esm/i18n/locales/locales/ar-SA.json +83 -1
  52. package/dist/esm/i18n/locales/locales/ca-ES.json +83 -1
  53. package/dist/esm/i18n/locales/locales/de-DE.json +83 -1
  54. package/dist/esm/i18n/locales/locales/en-US.json +83 -0
  55. package/dist/esm/i18n/locales/locales/es-ES.json +99 -4
  56. package/dist/esm/i18n/locales/locales/fr-FR.json +83 -1
  57. package/dist/esm/i18n/locales/locales/it-IT.json +83 -1
  58. package/dist/esm/i18n/locales/locales/ja-JP.json +200 -117
  59. package/dist/esm/i18n/locales/locales/ko-KR.json +83 -1
  60. package/dist/esm/i18n/locales/locales/pt-PT.json +83 -1
  61. package/dist/esm/i18n/locales/locales/zh-CN.json +83 -1
  62. package/dist/esm/i18n/locales/pt-PT.json +83 -0
  63. package/dist/esm/i18n/locales/zh-CN.json +83 -0
  64. package/dist/esm/index.js +74 -26
  65. package/dist/esm/mixins/OxyServices.auth.js +235 -0
  66. package/dist/esm/mixins/OxyServices.fedcm.js +36 -0
  67. package/dist/esm/mixins/OxyServices.popup.js +61 -1
  68. package/dist/esm/mixins/OxyServices.user.js +18 -0
  69. package/dist/esm/utils/accountUtils.js +61 -0
  70. package/dist/esm/utils/coldBoot.js +68 -0
  71. package/dist/esm/utils/fapiAutoDetect.js +85 -0
  72. package/dist/types/.tsbuildinfo +1 -1
  73. package/dist/types/AuthManager.d.ts +243 -3
  74. package/dist/types/AuthManagerTypes.d.ts +68 -0
  75. package/dist/types/CrossDomainAuth.d.ts +23 -0
  76. package/dist/types/OxyServices.base.d.ts +14 -0
  77. package/dist/types/OxyServices.d.ts +7 -0
  78. package/dist/types/index.d.ts +31 -17
  79. package/dist/types/mixins/OxyServices.analytics.d.ts +1 -0
  80. package/dist/types/mixins/OxyServices.appData.d.ts +1 -0
  81. package/dist/types/mixins/OxyServices.assets.d.ts +4 -1
  82. package/dist/types/mixins/OxyServices.auth.d.ts +73 -1
  83. package/dist/types/mixins/OxyServices.contacts.d.ts +1 -0
  84. package/dist/types/mixins/OxyServices.developer.d.ts +1 -0
  85. package/dist/types/mixins/OxyServices.devices.d.ts +1 -0
  86. package/dist/types/mixins/OxyServices.features.d.ts +2 -5
  87. package/dist/types/mixins/OxyServices.fedcm.d.ts +34 -0
  88. package/dist/types/mixins/OxyServices.karma.d.ts +1 -0
  89. package/dist/types/mixins/OxyServices.language.d.ts +1 -0
  90. package/dist/types/mixins/OxyServices.location.d.ts +1 -0
  91. package/dist/types/mixins/OxyServices.managedAccounts.d.ts +1 -0
  92. package/dist/types/mixins/OxyServices.payment.d.ts +1 -0
  93. package/dist/types/mixins/OxyServices.popup.d.ts +40 -0
  94. package/dist/types/mixins/OxyServices.privacy.d.ts +1 -0
  95. package/dist/types/mixins/OxyServices.redirect.d.ts +1 -0
  96. package/dist/types/mixins/OxyServices.security.d.ts +1 -0
  97. package/dist/types/mixins/OxyServices.topics.d.ts +1 -0
  98. package/dist/types/mixins/OxyServices.user.d.ts +16 -1
  99. package/dist/types/mixins/OxyServices.utility.d.ts +1 -0
  100. package/dist/types/models/interfaces.d.ts +98 -0
  101. package/dist/types/models/session.d.ts +8 -0
  102. package/dist/types/utils/accountUtils.d.ts +33 -0
  103. package/dist/types/utils/coldBoot.d.ts +102 -0
  104. package/dist/types/utils/fapiAutoDetect.d.ts +37 -0
  105. package/package.json +9 -18
  106. package/src/AuthManager.ts +776 -7
  107. package/src/AuthManagerTypes.ts +72 -0
  108. package/src/CrossDomainAuth.ts +54 -3
  109. package/src/OxyServices.base.ts +17 -0
  110. package/src/OxyServices.ts +7 -0
  111. package/src/__tests__/authManager.cookiePath.test.ts +339 -0
  112. package/src/__tests__/authManager.security.test.ts +342 -0
  113. package/src/__tests__/crossDomainAuth.test.ts +191 -0
  114. package/src/i18n/locales/ar-SA.json +83 -1
  115. package/src/i18n/locales/ca-ES.json +83 -1
  116. package/src/i18n/locales/de-DE.json +83 -1
  117. package/src/i18n/locales/en-US.json +83 -0
  118. package/src/i18n/locales/es-ES.json +99 -4
  119. package/src/i18n/locales/fr-FR.json +83 -1
  120. package/src/i18n/locales/it-IT.json +83 -1
  121. package/src/i18n/locales/ja-JP.json +200 -117
  122. package/src/i18n/locales/ko-KR.json +83 -1
  123. package/src/i18n/locales/pt-PT.json +83 -1
  124. package/src/i18n/locales/zh-CN.json +83 -1
  125. package/src/index.ts +309 -112
  126. package/src/mixins/OxyServices.auth.ts +268 -1
  127. package/src/mixins/OxyServices.fedcm.ts +63 -0
  128. package/src/mixins/OxyServices.popup.ts +79 -1
  129. package/src/mixins/OxyServices.user.ts +33 -1
  130. package/src/mixins/__tests__/popup.test.ts +307 -0
  131. package/src/mixins/__tests__/sessionBaseUrl.test.ts +61 -0
  132. package/src/models/interfaces.ts +116 -0
  133. package/src/models/session.ts +8 -0
  134. package/src/utils/__tests__/coldBoot.test.ts +226 -0
  135. package/src/utils/__tests__/fapiAutoDetect.test.ts +93 -0
  136. package/src/utils/accountUtils.ts +84 -0
  137. package/src/utils/coldBoot.ts +136 -0
  138. package/src/utils/fapiAutoDetect.ts +82 -0
  139. package/dist/cjs/crypto/index.js +0 -22
  140. package/dist/cjs/shared/index.js +0 -70
  141. package/dist/cjs/utils/index.js +0 -26
  142. package/dist/esm/crypto/index.js +0 -13
  143. package/dist/esm/shared/index.js +0 -31
  144. package/dist/esm/utils/index.js +0 -7
  145. package/dist/types/crypto/index.d.ts +0 -11
  146. package/dist/types/shared/index.d.ts +0 -28
  147. package/dist/types/utils/index.d.ts +0 -6
  148. package/src/crypto/index.ts +0 -30
  149. package/src/shared/index.ts +0 -82
  150. package/src/utils/index.ts +0 -21
@@ -0,0 +1,226 @@
1
+ import {
2
+ runColdBoot,
3
+ type ColdBootStep,
4
+ type ColdBootStepResult,
5
+ } from '../coldBoot';
6
+
7
+ interface TestSession {
8
+ readonly userId: string;
9
+ }
10
+
11
+ function sessionStep(
12
+ id: string,
13
+ userId: string,
14
+ onRun?: () => void
15
+ ): ColdBootStep<TestSession> {
16
+ return {
17
+ id,
18
+ run: async (): Promise<ColdBootStepResult<TestSession>> => {
19
+ onRun?.();
20
+ return { kind: 'session', session: { userId } };
21
+ },
22
+ };
23
+ }
24
+
25
+ function skipStep(id: string, onRun?: () => void): ColdBootStep<TestSession> {
26
+ return {
27
+ id,
28
+ run: async (): Promise<ColdBootStepResult<TestSession>> => {
29
+ onRun?.();
30
+ return { kind: 'skip' };
31
+ },
32
+ };
33
+ }
34
+
35
+ describe('runColdBoot', () => {
36
+ it('returns the first session and short-circuits remaining steps', async () => {
37
+ const ranLater = jest.fn();
38
+ const outcome = await runColdBoot<TestSession>({
39
+ steps: [
40
+ skipStep('first'),
41
+ sessionStep('winner', 'u-123'),
42
+ sessionStep('later', 'u-999', ranLater),
43
+ ],
44
+ });
45
+
46
+ expect(outcome).toEqual({
47
+ kind: 'session',
48
+ via: 'winner',
49
+ session: { userId: 'u-123' },
50
+ });
51
+ expect(ranLater).not.toHaveBeenCalled();
52
+ });
53
+
54
+ it('outcome.via is the winning step id', async () => {
55
+ const outcome = await runColdBoot<TestSession>({
56
+ steps: [skipStep('a'), skipStep('b'), sessionStep('c', 'u-7')],
57
+ });
58
+
59
+ expect(outcome.kind).toBe('session');
60
+ if (outcome.kind === 'session') {
61
+ expect(outcome.via).toBe('c');
62
+ expect(outcome.session).toEqual({ userId: 'u-7' });
63
+ }
64
+ });
65
+
66
+ it('returns unauthenticated when every step skips', async () => {
67
+ const outcome = await runColdBoot<TestSession>({
68
+ steps: [skipStep('a'), skipStep('b'), skipStep('c')],
69
+ });
70
+
71
+ expect(outcome).toEqual({ kind: 'unauthenticated' });
72
+ });
73
+
74
+ it('returns unauthenticated for an empty step list', async () => {
75
+ const outcome = await runColdBoot<TestSession>({ steps: [] });
76
+ expect(outcome).toEqual({ kind: 'unauthenticated' });
77
+ });
78
+
79
+ it('skips a disabled step WITHOUT calling its run()', async () => {
80
+ const disabledRun = jest.fn();
81
+ const outcome = await runColdBoot<TestSession>({
82
+ steps: [
83
+ {
84
+ id: 'disabled',
85
+ enabled: () => false,
86
+ run: async (): Promise<ColdBootStepResult<TestSession>> => {
87
+ disabledRun();
88
+ return { kind: 'session', session: { userId: 'should-not-run' } };
89
+ },
90
+ },
91
+ sessionStep('enabled', 'u-ok'),
92
+ ],
93
+ });
94
+
95
+ expect(disabledRun).not.toHaveBeenCalled();
96
+ expect(outcome).toEqual({
97
+ kind: 'session',
98
+ via: 'enabled',
99
+ session: { userId: 'u-ok' },
100
+ });
101
+ });
102
+
103
+ it('runs an enabled:()=>true step', async () => {
104
+ const outcome = await runColdBoot<TestSession>({
105
+ steps: [
106
+ {
107
+ id: 'gated',
108
+ enabled: () => true,
109
+ run: async (): Promise<ColdBootStepResult<TestSession>> => ({
110
+ kind: 'session',
111
+ session: { userId: 'u-gated' },
112
+ }),
113
+ },
114
+ ],
115
+ });
116
+
117
+ expect(outcome).toEqual({
118
+ kind: 'session',
119
+ via: 'gated',
120
+ session: { userId: 'u-gated' },
121
+ });
122
+ });
123
+
124
+ it('reports a thrown run() via onStepError and continues to the next step', async () => {
125
+ const onStepError = jest.fn();
126
+ const boom = new Error('run exploded');
127
+ const outcome = await runColdBoot<TestSession>({
128
+ steps: [
129
+ {
130
+ id: 'throws',
131
+ run: async (): Promise<ColdBootStepResult<TestSession>> => {
132
+ throw boom;
133
+ },
134
+ },
135
+ sessionStep('recovers', 'u-after-throw'),
136
+ ],
137
+ onStepError,
138
+ });
139
+
140
+ expect(onStepError).toHaveBeenCalledTimes(1);
141
+ expect(onStepError).toHaveBeenCalledWith('throws', boom);
142
+ expect(outcome).toEqual({
143
+ kind: 'session',
144
+ via: 'recovers',
145
+ session: { userId: 'u-after-throw' },
146
+ });
147
+ });
148
+
149
+ it('treats a thrown enabled() as disabled, reports via onStepError, and continues', async () => {
150
+ const onStepError = jest.fn();
151
+ const enabledThrew = new Error('enabled exploded');
152
+ const guardedRun = jest.fn();
153
+ const outcome = await runColdBoot<TestSession>({
154
+ steps: [
155
+ {
156
+ id: 'enabled-throws',
157
+ enabled: () => {
158
+ throw enabledThrew;
159
+ },
160
+ run: async (): Promise<ColdBootStepResult<TestSession>> => {
161
+ guardedRun();
162
+ return { kind: 'session', session: { userId: 'should-not-run' } };
163
+ },
164
+ },
165
+ sessionStep('next', 'u-next'),
166
+ ],
167
+ onStepError,
168
+ });
169
+
170
+ expect(guardedRun).not.toHaveBeenCalled();
171
+ expect(onStepError).toHaveBeenCalledTimes(1);
172
+ expect(onStepError).toHaveBeenCalledWith('enabled-throws', enabledThrew);
173
+ expect(outcome).toEqual({
174
+ kind: 'session',
175
+ via: 'next',
176
+ session: { userId: 'u-next' },
177
+ });
178
+ });
179
+
180
+ it('returns unauthenticated when all steps error and reports each', async () => {
181
+ const onStepError = jest.fn();
182
+ const outcome = await runColdBoot<TestSession>({
183
+ steps: [
184
+ {
185
+ id: 'a',
186
+ run: async (): Promise<ColdBootStepResult<TestSession>> => {
187
+ throw new Error('a');
188
+ },
189
+ },
190
+ {
191
+ id: 'b',
192
+ enabled: () => {
193
+ throw new Error('b');
194
+ },
195
+ run: async (): Promise<ColdBootStepResult<TestSession>> => ({
196
+ kind: 'skip',
197
+ }),
198
+ },
199
+ ],
200
+ onStepError,
201
+ });
202
+
203
+ expect(outcome).toEqual({ kind: 'unauthenticated' });
204
+ expect(onStepError).toHaveBeenCalledTimes(2);
205
+ });
206
+
207
+ it('does not require onStepError to be provided when a step throws', async () => {
208
+ const outcome = await runColdBoot<TestSession>({
209
+ steps: [
210
+ {
211
+ id: 'throws',
212
+ run: async (): Promise<ColdBootStepResult<TestSession>> => {
213
+ throw new Error('no observer');
214
+ },
215
+ },
216
+ sessionStep('ok', 'u-ok'),
217
+ ],
218
+ });
219
+
220
+ expect(outcome).toEqual({
221
+ kind: 'session',
222
+ via: 'ok',
223
+ session: { userId: 'u-ok' },
224
+ });
225
+ });
226
+ });
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Auto-detect of `auth.<rp-apex>` from `window.location` for the Clerk-style
3
+ * multi-domain FAPI setup. The IdP backend independently derives `iss` and
4
+ * the FedCM manifest from the request host, so the only contract the SDK
5
+ * needs to honour is: build URLs against the same host the page is on,
6
+ * one subdomain over.
7
+ *
8
+ * Ported verbatim from packages/auth-sdk/__tests__/utils/fapiAutoDetect.test.ts
9
+ * plus multi-part-TLD bail-out cases that are unique to the core copy's
10
+ * MULTIPART_TLDS guard.
11
+ */
12
+
13
+ import { autoDetectAuthWebUrl } from '../fapiAutoDetect';
14
+
15
+ function loc(hostname: string, protocol = 'https:'): Pick<Location, 'hostname' | 'protocol'> {
16
+ return { hostname, protocol };
17
+ }
18
+
19
+ describe('autoDetectAuthWebUrl', () => {
20
+ describe('returns auth.<apex> for public hostnames', () => {
21
+ it('derives from the apex itself', () => {
22
+ expect(autoDetectAuthWebUrl(loc('mention.earth'))).toBe('https://auth.mention.earth');
23
+ });
24
+
25
+ it('strips one leading subdomain', () => {
26
+ expect(autoDetectAuthWebUrl(loc('www.mention.earth'))).toBe('https://auth.mention.earth');
27
+ expect(autoDetectAuthWebUrl(loc('app.alia.onl'))).toBe('https://auth.alia.onl');
28
+ });
29
+
30
+ it('strips multiple leading subdomains down to the last two labels', () => {
31
+ // The heuristic is "last two labels" — fine for our use case because
32
+ // the IdP itself validates the request host. Deeply-nested hostnames
33
+ // resolve to the trailing two-label apex.
34
+ expect(autoDetectAuthWebUrl(loc('deep.app.homiio.com'))).toBe('https://auth.homiio.com');
35
+ });
36
+
37
+ it('honours the request protocol so dev http stays http', () => {
38
+ expect(autoDetectAuthWebUrl(loc('staging.example.test', 'http:'))).toBe(
39
+ 'http://auth.example.test'
40
+ );
41
+ });
42
+ });
43
+
44
+ describe('returns current origin when already on the IdP', () => {
45
+ it('keeps everything same-origin instead of hopping to a sibling IdP', () => {
46
+ expect(autoDetectAuthWebUrl(loc('auth.mention.earth'))).toBe('https://auth.mention.earth');
47
+ expect(autoDetectAuthWebUrl(loc('auth.oxy.so'))).toBe('https://auth.oxy.so');
48
+ });
49
+ });
50
+
51
+ describe('returns undefined where auto-detect would be wrong', () => {
52
+ it('skips localhost and 127.0.0.1 (dev)', () => {
53
+ expect(autoDetectAuthWebUrl(loc('localhost', 'http:'))).toBeUndefined();
54
+ expect(autoDetectAuthWebUrl(loc('127.0.0.1', 'http:'))).toBeUndefined();
55
+ });
56
+
57
+ it('skips IPv4 literals', () => {
58
+ expect(autoDetectAuthWebUrl(loc('192.168.1.10'))).toBeUndefined();
59
+ expect(autoDetectAuthWebUrl(loc('10.0.0.1'))).toBeUndefined();
60
+ });
61
+
62
+ it('skips IPv6 literals (bracketed)', () => {
63
+ expect(autoDetectAuthWebUrl(loc('[::1]'))).toBeUndefined();
64
+ });
65
+
66
+ it('skips single-label hostnames', () => {
67
+ expect(autoDetectAuthWebUrl(loc('intranet'))).toBeUndefined();
68
+ });
69
+
70
+ it('skips unknown protocols', () => {
71
+ expect(autoDetectAuthWebUrl({ hostname: 'mention.earth', protocol: 'file:' })).toBeUndefined();
72
+ expect(autoDetectAuthWebUrl({ hostname: 'mention.earth', protocol: 'ftp:' })).toBeUndefined();
73
+ });
74
+
75
+ it('skips empty/missing hostnames', () => {
76
+ expect(autoDetectAuthWebUrl(loc(''))).toBeUndefined();
77
+ });
78
+
79
+ it('returns undefined when no location is available (SSR / non-browser)', () => {
80
+ expect(autoDetectAuthWebUrl(undefined)).toBeUndefined();
81
+ });
82
+ });
83
+
84
+ describe('bails out on multi-part public suffixes (would derive an attacker-registrable apex)', () => {
85
+ it('does not derive auth.co.uk from a two-label co.uk host', () => {
86
+ expect(autoDetectAuthWebUrl(loc('foo.co.uk'))).toBeUndefined();
87
+ });
88
+
89
+ it('does not derive auth.com.au from a two-label com.au host', () => {
90
+ expect(autoDetectAuthWebUrl(loc('shop.com.au'))).toBeUndefined();
91
+ });
92
+ });
93
+ });
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { translate } from '../i18n';
7
+ import type { RefreshAllAccount } from '../models/interfaces';
7
8
 
8
9
  export interface QuickAccount {
9
10
  sessionId: string;
@@ -12,6 +13,19 @@ export interface QuickAccount {
12
13
  displayName: string;
13
14
  avatar?: string;
14
15
  avatarUrl?: string;
16
+ /**
17
+ * Device-local account slot index, 0..N-1 (Google-style multi-account).
18
+ * Mirrors the server's `oxy_rt_${authuser}` cookie slot. Optional so that
19
+ * pre-multi-account QuickAccounts (sessionId-only, non-cookie auth on RN)
20
+ * remain valid; web flows always populate it after `refreshAllSessions`.
21
+ */
22
+ authuser?: number;
23
+ /**
24
+ * Account's preferred Bloom color preset (e.g. `"blue"`, `"oxy"`). Drives
25
+ * per-account theming in the account chooser. `null` / `undefined` means
26
+ * the account has no preference and the base theme should be used.
27
+ */
28
+ color?: string | null;
15
29
  }
16
30
 
17
31
  /** Minimal user shape accepted by display-name helpers. Avoids importing the full User type. */
@@ -147,3 +161,73 @@ export const createQuickAccount = (
147
161
  avatarUrl,
148
162
  };
149
163
  };
164
+
165
+ /**
166
+ * Merge a fresh `/auth/refresh-all` snapshot into an existing QuickAccount
167
+ * list, preserving any cached fields (`avatarUrl`) for slots that didn't
168
+ * change. The fresh response is canonical: the resulting list contains EXACTLY
169
+ * the slots present in `fresh`, sorted by `authuser` ascending. Stale stored
170
+ * accounts that no longer appear in `fresh` are dropped (the server already
171
+ * authoritatively cleared the corresponding cookie).
172
+ *
173
+ * @param stored Previously persisted QuickAccount list (any order).
174
+ * @param fresh Server's authoritative refresh-all response.
175
+ * @returns Canonical merged list, sorted by `authuser` asc.
176
+ */
177
+ export const mergeAccountsFromRefreshAll = (
178
+ stored: QuickAccount[] | undefined,
179
+ fresh: RefreshAllAccount[],
180
+ ): QuickAccount[] => {
181
+ const storedByAuthuser = new Map<number, QuickAccount>();
182
+ if (stored) {
183
+ for (const account of stored) {
184
+ if (typeof account.authuser === 'number') {
185
+ storedByAuthuser.set(account.authuser, account);
186
+ }
187
+ }
188
+ }
189
+
190
+ const merged: QuickAccount[] = fresh.map((entry) => {
191
+ const previous = storedByAuthuser.get(entry.authuser);
192
+ // `entry.user` is null on the SDK legacy-fallback path; preserve any
193
+ // previously cached identity for that slot rather than overwriting
194
+ // it with blanks, and let the AuthManager's getCurrentUser() hydration
195
+ // refresh it on the next snapshot.
196
+ const wireUser = entry.user;
197
+ const username = wireUser?.username ?? previous?.username ?? '';
198
+ const displayName = getAccountDisplayName({
199
+ name: wireUser?.name,
200
+ username,
201
+ });
202
+ const avatar = wireUser?.avatar ?? previous?.avatar ?? undefined;
203
+ const avatarUrl =
204
+ previous && previous.avatar === avatar ? previous.avatarUrl : undefined;
205
+ return {
206
+ sessionId: entry.sessionId,
207
+ userId: wireUser?.id ?? previous?.userId,
208
+ username,
209
+ displayName,
210
+ avatar,
211
+ avatarUrl,
212
+ authuser: entry.authuser,
213
+ color: wireUser?.color ?? previous?.color ?? null,
214
+ };
215
+ });
216
+
217
+ merged.sort((a, b) => {
218
+ const aIdx = a.authuser ?? Number.POSITIVE_INFINITY;
219
+ const bIdx = b.authuser ?? Number.POSITIVE_INFINITY;
220
+ return aIdx - bIdx;
221
+ });
222
+
223
+ return merged;
224
+ };
225
+
226
+ /**
227
+ * Return the account's preferred Bloom color preset, or `null` if it has no
228
+ * preference. Centralises the `color ?? null` normalisation so consumers can
229
+ * drive per-account theming without duplicating the nullish-handling.
230
+ */
231
+ export const getAccountColor = (account: QuickAccount): string | null => {
232
+ return account.color ?? null;
233
+ };
@@ -0,0 +1,136 @@
1
+ /**
2
+ * coldBoot — a pure, ordered, short-circuit runner for "cold boot"
3
+ * authentication resolution.
4
+ *
5
+ * On a fresh page load / app launch the SDK may have several ways to recover an
6
+ * existing session (silent FedCM, a persisted refresh token, a cross-domain
7
+ * claim, an explicit popup flow, …). They must be attempted in a *deterministic
8
+ * order*, and the FIRST one that yields a session wins — every later step is
9
+ * skipped. This module encodes exactly that contract and nothing else.
10
+ *
11
+ * Design constraints (all enforced):
12
+ * - PURE: no DOM, no `navigator`, no `window`, no React, no platform globals.
13
+ * - NO module-level mutable state. Every call to {@link runColdBoot} is fully
14
+ * self-contained, so it is safe under bundler re-evaluation (e.g. the Metro
15
+ * web bundle, which is precisely why the FedCM silent-SSO guard had to live
16
+ * in consumers rather than a core singleton).
17
+ * - Architecture-agnostic: both candidate cross-domain SSO designs consume
18
+ * this same primitive; it knows nothing about HOW a step resolves a session.
19
+ *
20
+ * A step is skipped (without running) when its `enabled` predicate returns
21
+ * false. Any thrown error — from either `enabled` or `run` — is reported via
22
+ * `onStepError` and treated as a non-fatal skip, so one broken recovery path
23
+ * can never prevent a later, healthy one from succeeding.
24
+ */
25
+
26
+ /**
27
+ * A successful step result carrying the recovered session.
28
+ */
29
+ export interface ColdBootSession<S> {
30
+ readonly kind: 'session';
31
+ readonly session: S;
32
+ }
33
+
34
+ /**
35
+ * A step result indicating this step has nothing to contribute; the runner
36
+ * should fall through to the next step.
37
+ */
38
+ export interface ColdBootSkip {
39
+ readonly kind: 'skip';
40
+ }
41
+
42
+ /**
43
+ * The result of running a single cold-boot step.
44
+ */
45
+ export type ColdBootStepResult<S> = ColdBootSession<S> | ColdBootSkip;
46
+
47
+ /**
48
+ * A single ordered cold-boot recovery step.
49
+ */
50
+ export interface ColdBootStep<S> {
51
+ /** Stable identifier; surfaced as {@link ColdBootOutcome.via} on success. */
52
+ readonly id: string;
53
+ /**
54
+ * Optional gate. When provided and it returns `false`, `run` is NOT called
55
+ * and the runner moves to the next step. A throw is treated as disabled
56
+ * (and reported via `onStepError`).
57
+ */
58
+ readonly enabled?: () => boolean;
59
+ /**
60
+ * Attempts to recover a session. Resolve with `{ kind: 'session' }` to win
61
+ * the cold boot, or `{ kind: 'skip' }` to defer to the next step. A throw is
62
+ * treated as a skip (and reported via `onStepError`).
63
+ */
64
+ readonly run: () => Promise<ColdBootStepResult<S>>;
65
+ }
66
+
67
+ /**
68
+ * The terminal outcome of a cold boot: either the winning step's session
69
+ * (with the step `id` it came from), or `unauthenticated` if every step
70
+ * skipped, was disabled, or errored.
71
+ */
72
+ export type ColdBootOutcome<S> =
73
+ | { readonly kind: 'session'; readonly via: string; readonly session: S }
74
+ | { readonly kind: 'unauthenticated' };
75
+
76
+ /**
77
+ * Options for {@link runColdBoot}.
78
+ */
79
+ export interface RunColdBootOptions<S> {
80
+ /** Ordered steps; evaluated front to back, first session wins. */
81
+ readonly steps: ReadonlyArray<ColdBootStep<S>>;
82
+ /**
83
+ * Optional observer invoked whenever a step's `enabled` or `run` throws.
84
+ * Receives the offending step `id` and the thrown value. Must not throw;
85
+ * the runner does not guard against an observer that itself throws.
86
+ */
87
+ readonly onStepError?: (id: string, error: unknown) => void;
88
+ }
89
+
90
+ /**
91
+ * Run the ordered cold-boot steps and resolve to the first recovered session,
92
+ * or `unauthenticated` if none recovers one.
93
+ *
94
+ * Semantics:
95
+ * 1. Iterate `steps` in order.
96
+ * 2. If a step has an `enabled` predicate, call it inside try/catch:
97
+ * - throw → report via `onStepError(id, err)` → treat as disabled → continue.
98
+ * - returns false → continue (skip, `run` not called).
99
+ * 3. Otherwise await `step.run()` inside try/catch:
100
+ * - throw → report via `onStepError(id, err)` → continue.
101
+ * - `{ kind: 'session' }` → return `{ kind: 'session', via: step.id, session }`.
102
+ * - `{ kind: 'skip' }` → continue.
103
+ * 4. After the loop with no winner → `{ kind: 'unauthenticated' }`.
104
+ */
105
+ export async function runColdBoot<S>(
106
+ options: RunColdBootOptions<S>
107
+ ): Promise<ColdBootOutcome<S>> {
108
+ const { steps, onStepError } = options;
109
+
110
+ for (const step of steps) {
111
+ if (step.enabled) {
112
+ let isEnabled: boolean;
113
+ try {
114
+ isEnabled = step.enabled();
115
+ } catch (error) {
116
+ onStepError?.(step.id, error);
117
+ continue;
118
+ }
119
+ if (!isEnabled) continue;
120
+ }
121
+
122
+ let result: ColdBootStepResult<S>;
123
+ try {
124
+ result = await step.run();
125
+ } catch (error) {
126
+ onStepError?.(step.id, error);
127
+ continue;
128
+ }
129
+
130
+ if (result.kind === 'session') {
131
+ return { kind: 'session', via: step.id, session: result.session };
132
+ }
133
+ }
134
+
135
+ return { kind: 'unauthenticated' };
136
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Auto-detect the FAPI (IdP) URL from the current browser hostname.
3
+ *
4
+ * This is the canonical cross-domain IdP-resolution primitive for the Oxy
5
+ * ecosystem. Both candidate cross-domain SSO designs derive `auth.<rp-apex>`
6
+ * through this helper; do not fork it.
7
+ *
8
+ * Clerk-style multi-domain SSO depends on the IdP being reachable on a
9
+ * subdomain of the RP's own apex (e.g. `auth.mention.earth` CNAMEd to the
10
+ * central Oxy IdP). That way every FedCM endpoint, the session cookie,
11
+ * and any popup/redirect target are same-site with the RP — the only way
12
+ * to get first-party cookies in Safari ITP and Firefox Total Cookie
13
+ * Protection.
14
+ *
15
+ * This helper computes `https://auth.<rp-apex>` from
16
+ * `window.location.hostname` so a consuming app doesn't have to pass
17
+ * `authWebUrl` explicitly. Returns `undefined` for environments where
18
+ * auto-detection would be wrong:
19
+ *
20
+ * - SSR / non-browser (no `window`).
21
+ * - `localhost`, `127.0.0.1`, IPv4/IPv6 literals.
22
+ * - Hostnames with fewer than two labels.
23
+ * - Hostnames whose trailing two labels form a known multi-part public
24
+ * suffix (e.g. `co.uk`), where the naive `labels.slice(-2)` apex would be
25
+ * an attacker-registrable suffix like `auth.co.uk` rather than the real
26
+ * registrable domain.
27
+ *
28
+ * When the page is already loaded ON the IdP itself (`auth.<anything>`),
29
+ * the helper returns the current origin so the SDK keeps everything
30
+ * same-origin instead of hopping to a different IdP host.
31
+ *
32
+ * The IdP backend independently derives `iss`, `provider_urls`, and the
33
+ * `fedcm.json` icon URLs from the request host
34
+ * (`packages/auth/server/index.ts`), so an honest CNAME pair is all that
35
+ * is required for end-to-end FedCM correctness — no per-RP config.
36
+ */
37
+
38
+ /**
39
+ * Known multi-part public suffixes where the registrable domain is the LAST
40
+ * THREE labels, not two. Deriving an apex from `labels.slice(-2)` against any
41
+ * of these would yield an attacker-registrable suffix (e.g. `auth.co.uk`),
42
+ * so we bail out instead.
43
+ *
44
+ * This is intentionally a small, explicit allow-list rather than the full
45
+ * Public Suffix List — it covers the suffixes the Oxy ecosystem's RPs use.
46
+ * Any multi-part-TLD RP MUST extend this set (or wire in a proper PSL check)
47
+ * before relying on this helper, otherwise auto-detection silently bails to
48
+ * `undefined` and the consumer must pass `authWebUrl` explicitly.
49
+ */
50
+ const MULTIPART_TLDS: ReadonlySet<string> = new Set([
51
+ 'co.uk',
52
+ 'com.au',
53
+ 'co.jp',
54
+ 'co.nz',
55
+ 'com.br',
56
+ 'co.za',
57
+ 'com.mx',
58
+ 'co.in',
59
+ 'co.kr',
60
+ 'com.sg',
61
+ ]);
62
+
63
+ export function autoDetectAuthWebUrl(
64
+ location: Pick<Location, 'hostname' | 'protocol'> | undefined =
65
+ typeof window !== 'undefined' ? window.location : undefined
66
+ ): string | undefined {
67
+ if (!location) return undefined;
68
+ const { hostname, protocol } = location;
69
+ if (!hostname) return undefined;
70
+ if (protocol !== 'https:' && protocol !== 'http:') return undefined;
71
+ if (hostname === 'localhost' || hostname === '127.0.0.1') return undefined;
72
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) return undefined;
73
+ if (hostname.startsWith('[')) return undefined;
74
+ if (hostname.startsWith('auth.')) {
75
+ return `${protocol}//${hostname}`;
76
+ }
77
+ const labels = hostname.split('.');
78
+ if (labels.length < 2) return undefined;
79
+ if (MULTIPART_TLDS.has(labels.slice(-2).join('.'))) return undefined;
80
+ const apex = labels.slice(-2).join('.');
81
+ return `${protocol}//auth.${apex}`;
82
+ }
@@ -1,22 +0,0 @@
1
- "use strict";
2
- /**
3
- * Oxy Crypto Module
4
- *
5
- * Provides cryptographic identity management for the Oxy ecosystem.
6
- * Handles key generation, secure storage, digital signatures, and recovery phrases.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.default = exports.RecoveryPhraseService = exports.SignatureService = exports.IdentityPersistError = exports.IdentityAlreadyExistsError = exports.KeyManager = void 0;
10
- // Import polyfills first - this ensures Buffer is available for bip39 and other libraries
11
- require("./polyfill");
12
- var keyManager_1 = require("./keyManager");
13
- Object.defineProperty(exports, "KeyManager", { enumerable: true, get: function () { return keyManager_1.KeyManager; } });
14
- Object.defineProperty(exports, "IdentityAlreadyExistsError", { enumerable: true, get: function () { return keyManager_1.IdentityAlreadyExistsError; } });
15
- Object.defineProperty(exports, "IdentityPersistError", { enumerable: true, get: function () { return keyManager_1.IdentityPersistError; } });
16
- var signatureService_1 = require("./signatureService");
17
- Object.defineProperty(exports, "SignatureService", { enumerable: true, get: function () { return signatureService_1.SignatureService; } });
18
- var recoveryPhrase_1 = require("./recoveryPhrase");
19
- Object.defineProperty(exports, "RecoveryPhraseService", { enumerable: true, get: function () { return recoveryPhrase_1.RecoveryPhraseService; } });
20
- // Re-export for convenience
21
- var keyManager_2 = require("./keyManager");
22
- Object.defineProperty(exports, "default", { enumerable: true, get: function () { return keyManager_2.KeyManager; } });