@startsimpli/integrations 0.2.115 → 0.2.117
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.
- package/README.md +2 -0
- package/package.json +6 -6
- package/src/native/app/FoundryApp.tsx +2 -2
- package/src/native/app/__tests__/servicesForeground.test.ts +54 -0
- package/src/native/app/config/__tests__/validate.test.ts +8 -0
- package/src/native/app/config/types.ts +4 -0
- package/src/native/app/config/validate.ts +5 -2
- package/src/native/app/services.ts +6 -1
- package/src/native/recording/__tests__/staySignedIn.test.ts +131 -0
- package/src/native/recording/session.ts +45 -17
package/README.md
CHANGED
|
@@ -191,6 +191,8 @@ One command does step 1: `simpli ios new "Acme Go" --tenant-url https://acme.ai.
|
|
|
191
191
|
5. Check without a login: launch with `-tgFakeNotes list` (or a note id such as `n1`) to see the screens over `createFakeVoiceApi`.
|
|
192
192
|
6. `npx expo prebuild --platform ios`, then `npx expo run:ios --configuration Release` (Hermes). Signing and device install are per-Apple-team, see the template README.
|
|
193
193
|
|
|
194
|
+
App icon: `app.icon` in `foundry.config.json` is a path to a 1024x1024 opaque PNG (`<name>-dark.png` / `<name>-tinted.png` beside it become the iOS dark and tinted icons); `app.iconBackground` is a hex colour. With no `app.icon`, the build generates a colour field with a microphone, never a white square.
|
|
195
|
+
|
|
194
196
|
### Tabs: `FoundryTabsShell` and the shared corpus data layer (bd startsim-23np6.1)
|
|
195
197
|
|
|
196
198
|
Every Tandem web tab becomes an iOS tab from config. `NotesShell` is just the first preset.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.117",
|
|
4
4
|
"description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://startsimpli.com",
|
|
@@ -50,9 +50,9 @@
|
|
|
50
50
|
"react-native": ">=0.74.0",
|
|
51
51
|
"@startsimpli/ui-native": ">=0.1.12",
|
|
52
52
|
"react-native-safe-area-context": ">=4.0.0",
|
|
53
|
-
"@startsimpli/utils": "^0.4.17",
|
|
54
53
|
"@startsimpli/ui": "^0.4.170",
|
|
55
|
-
"@startsimpli/auth": "^0.4.
|
|
54
|
+
"@startsimpli/auth": "^0.4.50",
|
|
55
|
+
"@startsimpli/utils": "^0.4.17"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
58
58
|
"react": {
|
|
@@ -99,10 +99,10 @@
|
|
|
99
99
|
"react-native": "0.85.3",
|
|
100
100
|
"react-native-safe-area-context": "~5.7.0",
|
|
101
101
|
"@startsimpli/llm": "0.4.28",
|
|
102
|
-
"@startsimpli/
|
|
102
|
+
"@startsimpli/auth": "0.4.50",
|
|
103
103
|
"@startsimpli/ui-native": "0.1.14",
|
|
104
|
-
"@startsimpli/
|
|
105
|
-
"@startsimpli/
|
|
104
|
+
"@startsimpli/utils": "0.4.17",
|
|
105
|
+
"@startsimpli/ui": "0.4.170"
|
|
106
106
|
},
|
|
107
107
|
"scripts": {
|
|
108
108
|
"type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
|
|
@@ -117,8 +117,8 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
|
|
|
117
117
|
const sub = Linking.addEventListener('url', ({ url }) => services.deepLink.handle(url));
|
|
118
118
|
// Device-test hook: `-tgAutostop N`.
|
|
119
119
|
if (launch.autostop) services.deepLink.handle(`${config.app.scheme}://record?autostop=${launch.autostop}`);
|
|
120
|
-
services.onForeground();
|
|
121
|
-
const fg = AppState.addEventListener('change', (s) => { if (s === 'active') services.onForeground(); });
|
|
120
|
+
void services.onForeground();
|
|
121
|
+
const fg = AppState.addEventListener('change', (s) => { if (s === 'active') void services.onForeground(); });
|
|
122
122
|
return () => { off(); sub.remove(); fg.remove(); };
|
|
123
123
|
}, [services, launch, config]);
|
|
124
124
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createFoundryServices } from '../services';
|
|
3
|
+
import { createBanners } from '../banners';
|
|
4
|
+
import { validateFoundryApp } from '../config';
|
|
5
|
+
|
|
6
|
+
vi.mock('react-native', async () => ({
|
|
7
|
+
...(await import('../../../../../ui-native/test/rn-stub')),
|
|
8
|
+
AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
|
|
9
|
+
}));
|
|
10
|
+
|
|
11
|
+
// bd startsim-ib7f0: coming back to the app hours later renews the access token silently; no sign-in screen.
|
|
12
|
+
const NOW0 = 1_800_000_000_000;
|
|
13
|
+
const jwt = (expMs: number) => {
|
|
14
|
+
const exp = Math.floor(expMs / 1000);
|
|
15
|
+
const enc = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64');
|
|
16
|
+
return `${enc({ alg: 'HS256' })}.${enc({ exp, iat: exp - 1800 })}.sig`;
|
|
17
|
+
};
|
|
18
|
+
const res = (status: number, body: unknown = {}) => ({ ok: status < 400, status, json: async () => body }) as Response;
|
|
19
|
+
|
|
20
|
+
describe('services.onForeground', () => {
|
|
21
|
+
it('refreshes a stale access token and stays signed in', async () => {
|
|
22
|
+
let now = NOW0;
|
|
23
|
+
let refreshes = 0;
|
|
24
|
+
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
|
|
25
|
+
if (String(url).endsWith('/auth/token/refresh/')) { refreshes += 1; return res(200, { access: jwt(now + 1800_000), refresh: `R${refreshes}` }); }
|
|
26
|
+
return res(200, {});
|
|
27
|
+
}));
|
|
28
|
+
vi.spyOn(Date, 'now').mockImplementation(() => now);
|
|
29
|
+
const data: { refresh: string | null } = { refresh: 'R0' };
|
|
30
|
+
const files = new Map<string, string>();
|
|
31
|
+
const services = createFoundryServices({
|
|
32
|
+
config: (() => {
|
|
33
|
+
const v = validateFoundryApp({ app: { name: 'Acme Go' }, tenant: { url: 'https://acme.example.com' }, features: { recording: false } });
|
|
34
|
+
if (!v.ok) throw new Error('config');
|
|
35
|
+
return v.config;
|
|
36
|
+
})(),
|
|
37
|
+
device: {
|
|
38
|
+
tokenStorage: { getRefreshToken: async () => data.refresh, setRefreshToken: async (t: string) => { data.refresh = t; }, clear: async () => { data.refresh = null; } },
|
|
39
|
+
files: { exists: async (p: string) => files.has(p), read: async (p: string) => files.get(p) ?? '', write: async (p: string, v: string) => { files.set(p, v); } },
|
|
40
|
+
documentUri: (n: string) => `file:///${n}`,
|
|
41
|
+
} as never,
|
|
42
|
+
banners: createBanners(),
|
|
43
|
+
});
|
|
44
|
+
await services.session.restore();
|
|
45
|
+
expect(refreshes).toBe(1);
|
|
46
|
+
now += 6 * 3600_000;
|
|
47
|
+
await services.onForeground();
|
|
48
|
+
expect(refreshes).toBe(2);
|
|
49
|
+
expect(services.session.getState()).toBe('signedIn');
|
|
50
|
+
expect(data.refresh).toBe('R2');
|
|
51
|
+
vi.unstubAllGlobals();
|
|
52
|
+
vi.restoreAllMocks();
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -13,6 +13,14 @@ describe('validateFoundryApp', () => {
|
|
|
13
13
|
expect(c.maxVisibleTabs).toBe(5);
|
|
14
14
|
});
|
|
15
15
|
|
|
16
|
+
it('accepts an optional app icon path and background colour, and rejects bad ones by field', () => {
|
|
17
|
+
const c = resolveFoundryApp({ ...minimal, app: { name: 'Acme Go', icon: './assets/icon/icon.png', iconBackground: '#FF8A3D' } });
|
|
18
|
+
expect(c.app).toMatchObject({ icon: './assets/icon/icon.png', iconBackground: '#FF8A3D' });
|
|
19
|
+
expect(resolveFoundryApp(minimal).app).not.toHaveProperty('icon');
|
|
20
|
+
const r = validateFoundryApp({ ...minimal, app: { name: 'Acme Go', icon: 'icon.jpg', iconBackground: 'orange' } });
|
|
21
|
+
expect(r.ok ? [] : r.issues.map((i) => i.path)).toEqual(['app.icon', 'app.iconBackground']);
|
|
22
|
+
});
|
|
23
|
+
|
|
16
24
|
it('the auth app is the tenant slug: explicit, else the *.ai.startsimpli.com host, else the scheme', () => {
|
|
17
25
|
const auth = (input: object) => resolveFoundryApp(input).brand.authApp;
|
|
18
26
|
expect(auth({ app: { name: 'A Go' }, tenant: { url: 'http://localhost:4300', slug: 'hours' } })).toBe('hours');
|
|
@@ -73,6 +73,10 @@ export interface FoundryAppConfig {
|
|
|
73
73
|
/** URL scheme, `<scheme>://`. */
|
|
74
74
|
scheme: string;
|
|
75
75
|
bundleId: string;
|
|
76
|
+
/** Path to the app icon, a 1024x1024 opaque PNG, relative to the app directory. Optional `<name>-dark.png` and `<name>-tinted.png` beside it are the iOS dark / tinted icons. Unset: the build generates a colour field with a microphone. */
|
|
77
|
+
icon?: string;
|
|
78
|
+
/** Hex colour (`#RRGGBB`) of the generated default icon's field and the app's launch background. Unset: derived from the app name. */
|
|
79
|
+
iconBackground?: string;
|
|
76
80
|
};
|
|
77
81
|
brand: {
|
|
78
82
|
/** The Foundry's product name: Home title, sign-in title. */
|
|
@@ -63,7 +63,7 @@ export function validateFoundryApp(input: unknown, options: ValidateOptions = {}
|
|
|
63
63
|
|
|
64
64
|
// app
|
|
65
65
|
const app = section('app', true);
|
|
66
|
-
allowed(app, ['name', 'slug', 'scheme', 'bundleId'], 'app');
|
|
66
|
+
allowed(app, ['name', 'slug', 'scheme', 'bundleId', 'icon', 'iconBackground'], 'app');
|
|
67
67
|
let derived = { slug: '', scheme: '', bundleId: '' };
|
|
68
68
|
if (!str(app.name)) bad('app.name', 'is required (a display name, e.g. "Acme Go")');
|
|
69
69
|
else { try { derived = deriveAppNames(app.name); } catch (e) { bad('app.name', (e as Error).message); } }
|
|
@@ -74,6 +74,9 @@ export function validateFoundryApp(input: unknown, options: ValidateOptions = {}
|
|
|
74
74
|
if (scheme && !SCHEME.test(scheme)) bad('app.scheme', `"${scheme}" must be a URL scheme (lowercase letters, digits, + . -)`);
|
|
75
75
|
if (bundleId && !BUNDLE.test(bundleId)) bad('app.bundleId', `"${bundleId}" must look like com.example.app`);
|
|
76
76
|
|
|
77
|
+
if (app.icon !== undefined && (!str(app.icon) || !/\.png$/i.test(app.icon as string))) bad('app.icon', 'must be a path to a 1024x1024 PNG, e.g. "./assets/icon/icon.png"');
|
|
78
|
+
if (app.iconBackground !== undefined && !(typeof app.iconBackground === 'string' && /^#[0-9a-fA-F]{6}$/.test(app.iconBackground))) bad('app.iconBackground', 'must be a hex colour like "#FF8A3D"');
|
|
79
|
+
|
|
77
80
|
// brand
|
|
78
81
|
const brand = section('brand');
|
|
79
82
|
allowed(brand, ['name', 'tagline', 'authApp', 'logTag'], 'brand');
|
|
@@ -186,7 +189,7 @@ export function validateFoundryApp(input: unknown, options: ValidateOptions = {}
|
|
|
186
189
|
const resolvedBrandName = (brand.name as string | undefined) ?? (app.name as string);
|
|
187
190
|
const config: FoundryAppConfig = {
|
|
188
191
|
version: 1,
|
|
189
|
-
app: { name: app.name as string, slug, scheme, bundleId },
|
|
192
|
+
app: { name: app.name as string, slug, scheme, bundleId, ...(app.icon ? { icon: app.icon as string } : {}), ...(app.iconBackground ? { iconBackground: app.iconBackground as string } : {}) },
|
|
190
193
|
brand: {
|
|
191
194
|
name: resolvedBrandName,
|
|
192
195
|
tagline: (brand.tagline as string | undefined) ?? defaultBrandTagline(),
|
|
@@ -143,7 +143,12 @@ export function createFoundryServices(deps: { config: FoundryAppConfig; device:
|
|
|
143
143
|
if (recording) await recording.recoverAndDrain();
|
|
144
144
|
await deepLink.sessionReady();
|
|
145
145
|
},
|
|
146
|
-
|
|
146
|
+
/** App came to the foreground: renew a stale access token first (silently), then flush the upload queue. */
|
|
147
|
+
async onForeground() {
|
|
148
|
+
if (session.getState() !== 'signedIn') return;
|
|
149
|
+
await session.ensureFresh();
|
|
150
|
+
if (recording && session.getState() === 'signedIn') { void recording.queue.drain(); void recording.pending(); }
|
|
151
|
+
},
|
|
147
152
|
};
|
|
148
153
|
}
|
|
149
154
|
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createSession, type SecretStore } from '../session';
|
|
3
|
+
|
|
4
|
+
// bd startsim-ib7f0: the person stays signed in. Sign-in comes back ONLY when central rejects the refresh token.
|
|
5
|
+
|
|
6
|
+
const NOW0 = 1_800_000_000_000;
|
|
7
|
+
function jwt(expMs: number) {
|
|
8
|
+
const exp = Math.floor(expMs / 1000);
|
|
9
|
+
const enc = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64');
|
|
10
|
+
return `${enc({ alg: 'HS256' })}.${enc({ exp, iat: exp - 1800, userId: '1' })}.sig`;
|
|
11
|
+
}
|
|
12
|
+
const res = (status: number, body: unknown = {}) => ({ ok: status < 400, status, json: async () => body }) as Response;
|
|
13
|
+
|
|
14
|
+
function setup(opts: {
|
|
15
|
+
refresh?: (n: number) => Response | Promise<Response>;
|
|
16
|
+
api?: (auth: string, n: number) => Response;
|
|
17
|
+
readFails?: () => boolean;
|
|
18
|
+
initial?: string | null;
|
|
19
|
+
} = {}) {
|
|
20
|
+
const clock = { now: NOW0 };
|
|
21
|
+
const data: { refresh: string | null } = { refresh: opts.initial === undefined ? 'R0' : opts.initial };
|
|
22
|
+
const storage: SecretStore = {
|
|
23
|
+
getRefreshToken: async () => { if (opts.readFails?.()) throw new Error('errSecInteractionNotAllowed'); return data.refresh; },
|
|
24
|
+
setRefreshToken: async (t) => { data.refresh = t; },
|
|
25
|
+
clear: async () => { data.refresh = null; },
|
|
26
|
+
};
|
|
27
|
+
const n = { refresh: 0, api: 0 };
|
|
28
|
+
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
|
|
29
|
+
if (String(url).endsWith('/auth/token/refresh/')) {
|
|
30
|
+
n.refresh += 1;
|
|
31
|
+
return (opts.refresh ?? (() => res(200, { access: jwt(clock.now + 1800_000), refresh: `R${n.refresh}` })))(n.refresh);
|
|
32
|
+
}
|
|
33
|
+
n.api += 1;
|
|
34
|
+
return (opts.api ?? (() => res(200, { ok: 1 })))((init?.headers as Record<string, string>)?.Authorization ?? '', n.api);
|
|
35
|
+
});
|
|
36
|
+
const diag = { log: vi.fn() };
|
|
37
|
+
const session = createSession({ app: 'tandem', centralUrl: 'http://central', storage, fetch: fetchMock as never, diag, now: () => clock.now });
|
|
38
|
+
const states: string[] = [];
|
|
39
|
+
session.subscribe((s) => states.push(s));
|
|
40
|
+
return { session, clock, data, n, diag, states, fetchMock };
|
|
41
|
+
}
|
|
42
|
+
const events = (d: { log: ReturnType<typeof vi.fn> }, name: string) => d.log.mock.calls.filter((c) => c[0] === name).map((c) => c[1]);
|
|
43
|
+
|
|
44
|
+
describe('stay signed in', () => {
|
|
45
|
+
it('hours later: the stale access token is refreshed silently on foreground and the next request just works', async () => {
|
|
46
|
+
const s = setup();
|
|
47
|
+
await s.session.restore();
|
|
48
|
+
expect(s.session.getState()).toBe('signedIn');
|
|
49
|
+
s.clock.now += 5 * 3600_000;
|
|
50
|
+
await s.session.ensureFresh();
|
|
51
|
+
expect(s.n.refresh).toBe(2);
|
|
52
|
+
const out = await s.session.authorizedFetch('http://tandem/x');
|
|
53
|
+
expect(out.status).toBe(200);
|
|
54
|
+
expect(s.n.refresh).toBe(2); // no second refresh, no 401 round trip
|
|
55
|
+
expect(s.session.getState()).toBe('signedIn');
|
|
56
|
+
expect(s.states).toEqual(['signedIn']);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('foreground and an upload at the same moment share one rotation (single-flight)', async () => {
|
|
60
|
+
const s = setup();
|
|
61
|
+
await s.session.restore();
|
|
62
|
+
s.clock.now += 3600_000;
|
|
63
|
+
await Promise.all([s.session.ensureFresh(), s.session.authorizedFetch('http://tandem/a'), s.session.authorizedFetch('http://tandem/b')]);
|
|
64
|
+
expect(s.n.refresh).toBe(2);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('a 401 from the API refreshes once, retries, and stays signed in', async () => {
|
|
68
|
+
const s = setup({ api: (_a, n) => (n === 1 ? res(401) : res(200)) });
|
|
69
|
+
await s.session.restore();
|
|
70
|
+
expect((await s.session.authorizedFetch('http://tandem/x')).status).toBe(200);
|
|
71
|
+
expect(s.n.refresh).toBe(2);
|
|
72
|
+
expect(s.session.getState()).toBe('signedIn');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it.each([500, 503, 429])('central answering %i while refreshing does NOT sign out and keeps the token', async (status) => {
|
|
76
|
+
const s = setup({ refresh: (n) => (n === 1 ? res(200, { access: jwt(NOW0 + 1800_000), refresh: 'R1' }) : res(status)) });
|
|
77
|
+
await s.session.restore();
|
|
78
|
+
s.clock.now += 3 * 3600_000;
|
|
79
|
+
await expect(s.session.authorizedFetch('http://tandem/x')).rejects.toThrow();
|
|
80
|
+
expect(s.session.getState()).toBe('signedIn');
|
|
81
|
+
expect(s.data.refresh).toBe('R1');
|
|
82
|
+
expect(events(s.diag, 'auth.signed-out')).toEqual([]);
|
|
83
|
+
expect(events(s.diag, 'auth.refresh').at(-1)).toMatchObject({ ok: false, status });
|
|
84
|
+
// and it recovers on the next try
|
|
85
|
+
s.fetchMock.mockClear();
|
|
86
|
+
s.n.refresh = 0;
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('central rejecting the refresh token (401) is the ONLY thing that shows sign-in, with the reason logged', async () => {
|
|
90
|
+
const s = setup({ refresh: () => res(401, { detail: 'Token is blacklisted' }) });
|
|
91
|
+
await s.session.restore();
|
|
92
|
+
expect(s.session.getState()).toBe('signedOut');
|
|
93
|
+
expect(s.session.endedBy()).toBe('expired');
|
|
94
|
+
expect(s.data.refresh).toBeNull();
|
|
95
|
+
expect(events(s.diag, 'auth.signed-out')).toEqual([{ reason: 'refresh-rejected', status: 401 }]);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('an unreadable Keychain at launch is not signed out: the app opens and the next attempt retries', async () => {
|
|
99
|
+
let locked = true;
|
|
100
|
+
const s = setup({ readFails: () => locked });
|
|
101
|
+
await s.session.restore();
|
|
102
|
+
expect(s.session.getState()).toBe('signedIn');
|
|
103
|
+
expect(s.n.refresh).toBe(0);
|
|
104
|
+
expect(events(s.diag, 'auth.signed-out')).toEqual([]);
|
|
105
|
+
expect(events(s.diag, 'auth.refresh')).toEqual([{ ok: false, error: 'storage-unavailable', detail: 'Refresh token unreadable: errSecInteractionNotAllowed' }]);
|
|
106
|
+
locked = false;
|
|
107
|
+
expect((await s.session.authorizedFetch('http://tandem/x')).status).toBe(200);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('a truly empty Keychain is signed out, logged as no-token', async () => {
|
|
111
|
+
const s = setup({ initial: null });
|
|
112
|
+
await s.session.restore();
|
|
113
|
+
expect(s.session.getState()).toBe('signedOut');
|
|
114
|
+
expect(events(s.diag, 'auth.signed-out')).toEqual([{ reason: 'no-token' }]);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('signing out on purpose is logged as such', async () => {
|
|
118
|
+
const s = setup();
|
|
119
|
+
await s.session.restore();
|
|
120
|
+
await s.session.signOut();
|
|
121
|
+
expect(events(s.diag, 'auth.signed-out')).toEqual([{ reason: 'user' }]);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('ensureFresh never throws, even when central is down', async () => {
|
|
125
|
+
const s = setup({ refresh: (n) => (n === 1 ? res(200, { access: jwt(NOW0 + 1800_000), refresh: 'R1' }) : res(503)) });
|
|
126
|
+
await s.session.restore();
|
|
127
|
+
s.clock.now += 3600_000;
|
|
128
|
+
await expect(s.session.ensureFresh()).resolves.toBeUndefined();
|
|
129
|
+
expect(s.session.getState()).toBe('signedIn');
|
|
130
|
+
});
|
|
131
|
+
});
|
|
@@ -1,14 +1,17 @@
|
|
|
1
|
-
import { TokenAuthClient, type TokenStorage } from '@startsimpli/auth/token';
|
|
1
|
+
import { TokenAuthClient, TokenRefreshError, type TokenStorage } from '@startsimpli/auth/token';
|
|
2
2
|
|
|
3
3
|
export type SecretStore = TokenStorage;
|
|
4
4
|
export type SessionState = 'unknown' | 'signedOut' | 'signedIn';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Foundry sign-in on the shared token client. Only the refresh token is kept
|
|
8
|
-
* (in the Keychain); the password is used once and never stored.
|
|
9
|
-
*
|
|
8
|
+
* (in the Keychain); the password is used once and never stored.
|
|
9
|
+
*
|
|
10
|
+
* The person stays signed in. The sign-in screen comes back ONLY when central rejects the refresh token (revoked or
|
|
11
|
+
* expired) or the Keychain is genuinely empty. A central outage (5xx/429), no network or a Keychain that cannot be read
|
|
12
|
+
* right now keep the session and retry on the next request or foreground. Every sign-out is logged with its reason.
|
|
10
13
|
*/
|
|
11
|
-
export function createSession(deps: { centralUrl: string; storage: SecretStore; fetch?: typeof fetch; /** The app slug central auth knows (from the app config). */ app: string; /** Receives 'auth.refresh' (ok, status or error - never a token). */ diag?: { log(event: string, fields?: Record<string, unknown>): void }; /** Called after every authorized request: true when the server answered, false when the network failed. */ onNetwork?: (reachable: boolean) => void }) {
|
|
14
|
+
export function createSession(deps: { centralUrl: string; storage: SecretStore; fetch?: typeof fetch; /** The app slug central auth knows (from the app config). */ app: string; /** Receives 'auth.refresh' (ok, status or error - never a token). */ diag?: { log(event: string, fields?: Record<string, unknown>): void }; /** Called after every authorized request: true when the server answered, false when the network failed. */ onNetwork?: (reachable: boolean) => void; /** Clock (ms), injectable so tests can age the access token. */ now?: () => number }) {
|
|
12
15
|
const loggedFetch: typeof fetch = async (input, init) => {
|
|
13
16
|
const isRefresh = String(input).endsWith('/auth/token/refresh/');
|
|
14
17
|
try {
|
|
@@ -25,6 +28,7 @@ export function createSession(deps: { centralUrl: string; storage: SecretStore;
|
|
|
25
28
|
storage: deps.storage,
|
|
26
29
|
fetch: loggedFetch,
|
|
27
30
|
app: deps.app,
|
|
31
|
+
now: deps.now,
|
|
28
32
|
});
|
|
29
33
|
let state: SessionState = 'unknown';
|
|
30
34
|
/** Why the session ended: the server rejected the refresh token ('expired') or the person signed out. */
|
|
@@ -36,6 +40,28 @@ export function createSession(deps: { centralUrl: string; storage: SecretStore;
|
|
|
36
40
|
listeners.forEach((l) => l(state));
|
|
37
41
|
};
|
|
38
42
|
|
|
43
|
+
/** Classify a failed refresh. Returns true when it ended the session (and flipped to signedOut). */
|
|
44
|
+
async function handleFailure(e: unknown): Promise<boolean> {
|
|
45
|
+
const err = e instanceof TokenRefreshError ? e : null;
|
|
46
|
+
if (err?.rejected) {
|
|
47
|
+
ended = 'expired';
|
|
48
|
+
deps.diag?.log('auth.signed-out', { reason: 'refresh-rejected', status: err.status });
|
|
49
|
+
set('signedOut');
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
if (err?.missing) {
|
|
53
|
+
// First launch (nothing was ever stored) is just the sign-in screen; a token that vanished mid-session is an expiry.
|
|
54
|
+
if (state === 'signedIn') ended = 'expired';
|
|
55
|
+
deps.diag?.log('auth.signed-out', { reason: 'no-token' });
|
|
56
|
+
set('signedOut');
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
if (err?.storageUnavailable) {
|
|
60
|
+
deps.diag?.log('auth.refresh', { ok: false, error: 'storage-unavailable', detail: err.message });
|
|
61
|
+
}
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
39
65
|
return {
|
|
40
66
|
getState: () => state,
|
|
41
67
|
subscribe(listener: (s: SessionState) => void) {
|
|
@@ -54,20 +80,27 @@ export function createSession(deps: { centralUrl: string; storage: SecretStore;
|
|
|
54
80
|
set('signedIn');
|
|
55
81
|
},
|
|
56
82
|
async restore() {
|
|
57
|
-
if (!(await deps.storage.getRefreshToken())) return set('signedOut');
|
|
58
83
|
try {
|
|
59
84
|
await auth.refreshToken();
|
|
60
85
|
set('signedIn');
|
|
61
|
-
} catch {
|
|
62
|
-
//
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
86
|
+
} catch (e) {
|
|
87
|
+
// Nothing stored -> sign in. Rejected by central -> sign in again. Anything else keeps the session.
|
|
88
|
+
if (!(await handleFailure(e))) set('signedIn');
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
/** On app foreground: refresh a stale access token now so the first request of the session does not have to. Never throws. */
|
|
92
|
+
async ensureFresh() {
|
|
93
|
+
if (state !== 'signedIn') return;
|
|
94
|
+
try {
|
|
95
|
+
await auth.ensureFresh();
|
|
96
|
+
} catch (e) {
|
|
97
|
+
await handleFailure(e);
|
|
66
98
|
}
|
|
67
99
|
},
|
|
68
100
|
async signOut() {
|
|
69
101
|
await auth.logout();
|
|
70
102
|
ended = 'signOut';
|
|
103
|
+
deps.diag?.log('auth.signed-out', { reason: 'user' });
|
|
71
104
|
set('signedOut');
|
|
72
105
|
},
|
|
73
106
|
async authorizedFetch(url: string, init?: RequestInit) {
|
|
@@ -76,13 +109,8 @@ export function createSession(deps: { centralUrl: string; storage: SecretStore;
|
|
|
76
109
|
deps.onNetwork?.(true);
|
|
77
110
|
return res;
|
|
78
111
|
} catch (e) {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
set('signedOut');
|
|
82
|
-
} else {
|
|
83
|
-
// A rejected refresh clears the token (above); an intact token with a thrown request means the network is down.
|
|
84
|
-
deps.onNetwork?.(false);
|
|
85
|
-
}
|
|
112
|
+
// Signed out only for a rejected/missing refresh token; otherwise the request failed and the token is intact.
|
|
113
|
+
if (!(await handleFailure(e))) deps.onNetwork?.(false);
|
|
86
114
|
throw e;
|
|
87
115
|
}
|
|
88
116
|
},
|