@startsimpli/integrations 0.2.116 → 0.2.118
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/package.json +7 -7
- package/src/__tests__/briefing-compose.test.ts +102 -0
- package/src/corpus/briefing/compose.ts +83 -0
- package/src/corpus/briefing/index.ts +4 -0
- package/src/corpus/briefing/types.ts +62 -0
- package/src/corpus/index.ts +3 -0
- package/src/native/app/FoundryApp.tsx +2 -2
- package/src/native/app/__tests__/servicesForeground.test.ts +54 -0
- 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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.118",
|
|
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/auth": "^0.4.
|
|
54
|
-
"@startsimpli/
|
|
55
|
-
"@startsimpli/
|
|
53
|
+
"@startsimpli/auth": "^0.4.50",
|
|
54
|
+
"@startsimpli/utils": "^0.4.17",
|
|
55
|
+
"@startsimpli/ui": "^0.4.171"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
58
58
|
"react": {
|
|
@@ -98,10 +98,10 @@
|
|
|
98
98
|
"vitest": "^3.0.0",
|
|
99
99
|
"react-native": "0.85.3",
|
|
100
100
|
"react-native-safe-area-context": "~5.7.0",
|
|
101
|
-
"@startsimpli/llm": "0.4.
|
|
102
|
-
"@startsimpli/ui": "0.4.
|
|
101
|
+
"@startsimpli/llm": "0.4.30",
|
|
102
|
+
"@startsimpli/ui": "0.4.171",
|
|
103
103
|
"@startsimpli/ui-native": "0.1.14",
|
|
104
|
-
"@startsimpli/auth": "0.4.
|
|
104
|
+
"@startsimpli/auth": "0.4.50",
|
|
105
105
|
"@startsimpli/utils": "0.4.17"
|
|
106
106
|
},
|
|
107
107
|
"scripts": {
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { composeBriefing, localDate, type BriefingItem } from '../corpus/briefing';
|
|
4
|
+
|
|
5
|
+
const ME = 'user-me';
|
|
6
|
+
// 2026-11-05 09:00 in New York (14:00Z).
|
|
7
|
+
const NOW = Date.parse('2026-11-05T14:00:00Z');
|
|
8
|
+
const TZ = 'America/New_York';
|
|
9
|
+
|
|
10
|
+
const item = (over: Partial<BriefingItem> & { id: string }): BriefingItem => ({
|
|
11
|
+
title: `Item ${over.id}`,
|
|
12
|
+
status: 'open',
|
|
13
|
+
ownerSub: ME,
|
|
14
|
+
dueAt: '2026-11-05',
|
|
15
|
+
...over,
|
|
16
|
+
});
|
|
17
|
+
const compose = (items: BriefingItem[], over = {}) =>
|
|
18
|
+
composeBriefing(items, { ownerSub: ME, now: NOW, timeZone: TZ, ...over });
|
|
19
|
+
|
|
20
|
+
describe('composeBriefing', () => {
|
|
21
|
+
it('lists overdue, then in progress, then due today, each ordered by priority then date', () => {
|
|
22
|
+
const b = compose([
|
|
23
|
+
item({ id: 'today-hi', priority: 0 }),
|
|
24
|
+
item({ id: 'today-lo', priority: 3 }),
|
|
25
|
+
item({ id: 'prog', status: 'in_progress', dueAt: null, priority: 2 }),
|
|
26
|
+
item({ id: 'over-lo', dueAt: '2026-11-01', priority: 3 }),
|
|
27
|
+
item({ id: 'over-hi', dueAt: '2026-11-03', priority: 1 }),
|
|
28
|
+
]);
|
|
29
|
+
expect(b.items.map((i) => i.id)).toEqual(['over-hi', 'over-lo', 'prog', 'today-hi', 'today-lo']);
|
|
30
|
+
expect(b.items.map((i) => i.kind)).toEqual(['overdue', 'overdue', 'in_progress', 'due_today', 'due_today']);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('never includes done, dropped, or Linear completed/canceled items', () => {
|
|
34
|
+
const b = compose([
|
|
35
|
+
item({ id: 'done', status: 'done' }),
|
|
36
|
+
item({ id: 'dropped', status: 'dropped' }),
|
|
37
|
+
item({ id: 'lin-done', linearState: 'completed' }),
|
|
38
|
+
item({ id: 'lin-cancel', linearState: 'canceled' }),
|
|
39
|
+
item({ id: 'ok', linearState: 'started' }),
|
|
40
|
+
]);
|
|
41
|
+
expect(b.items.map((i) => i.id)).toEqual(['ok']);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('is owner scoped: other users (and unowned rows) are never included', () => {
|
|
45
|
+
const b = compose([item({ id: 'mine' }), item({ id: 'theirs', ownerSub: 'someone-else' }), item({ id: 'nobody', ownerSub: undefined })]);
|
|
46
|
+
expect(b.items.map((i) => i.id)).toEqual(['mine']);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('groups by project focus name, else Personal', () => {
|
|
50
|
+
const b = compose([item({ id: 'a', focusName: 'Tandem' }), item({ id: 'b' })]);
|
|
51
|
+
expect(b.items.map((i) => i.group)).toEqual(['Tandem', 'Personal']);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('caps at 8 spoken items and reports how many more', () => {
|
|
55
|
+
const items = Array.from({ length: 11 }, (_, n) => item({ id: `i${n}`, priority: n % 5 }));
|
|
56
|
+
const b = compose(items);
|
|
57
|
+
expect(b.items).toHaveLength(8);
|
|
58
|
+
expect(b.remaining).toBe(3);
|
|
59
|
+
expect(b.total).toBe(11);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('returns an explicit empty state', () => {
|
|
63
|
+
const b = compose([item({ id: 'later', dueAt: '2026-11-20' }), item({ id: 'undated', dueAt: null })]);
|
|
64
|
+
expect(b.empty).toBe(true);
|
|
65
|
+
expect(b.items).toEqual([]);
|
|
66
|
+
expect(b.counts).toEqual({ overdue: 0, in_progress: 0, due_today: 0 });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('returns the ordered item ids as the briefing context', () => {
|
|
70
|
+
const b = compose([item({ id: 'x', priority: 2 }), item({ id: 'y', priority: 1 })]);
|
|
71
|
+
expect(b.context.itemIds).toEqual(['y', 'x']);
|
|
72
|
+
expect(b.context.localDate).toBe('2026-11-05');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('carries the Linear identifier when linked', () => {
|
|
76
|
+
const b = compose([item({ id: 'l', linearIdentifier: 'LIN-123' }), item({ id: 'n' })]);
|
|
77
|
+
expect(b.items[0].linearIdentifier).toBe('LIN-123');
|
|
78
|
+
expect(b.items[1].linearIdentifier).toBeUndefined();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('uses the time zone, not UTC, for today (midnight boundary)', () => {
|
|
82
|
+
// 2026-11-06T02:00Z is still Nov 5 evening in New York, already Nov 6 in UTC.
|
|
83
|
+
const late = Date.parse('2026-11-06T02:00:00Z');
|
|
84
|
+
expect(localDate(late, TZ)).toBe('2026-11-05');
|
|
85
|
+
expect(localDate(late, 'UTC')).toBe('2026-11-06');
|
|
86
|
+
const ny = composeBriefing([item({ id: 't', dueAt: '2026-11-05' })], { ownerSub: ME, now: late, timeZone: TZ });
|
|
87
|
+
expect(ny.items[0].kind).toBe('due_today');
|
|
88
|
+
const utc = composeBriefing([item({ id: 't', dueAt: '2026-11-05' })], { ownerSub: ME, now: late, timeZone: 'UTC' });
|
|
89
|
+
expect(utc.items[0].kind).toBe('overdue');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('reads a full ISO due date in the user zone', () => {
|
|
93
|
+
// 2026-11-05T03:00Z is Nov 4 at 10pm in New York: overdue, not today.
|
|
94
|
+
const b = compose([item({ id: 'iso', dueAt: '2026-11-05T03:00:00Z' })]);
|
|
95
|
+
expect(b.items[0].kind).toBe('overdue');
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('keeps an in-progress item even when it has no date, and tolerates unknown status words', () => {
|
|
99
|
+
const b = compose([item({ id: 'p', status: 'in_progress', dueAt: null }), item({ id: 'weird', status: 'whatever' as never })]);
|
|
100
|
+
expect(b.items.map((i) => i.id)).toEqual(['p', 'weird']);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE BRIEFING CONTENT (bd startsim-nwc7t): what is on this person's plate today.
|
|
3
|
+
*
|
|
4
|
+
* PURE. No clock, no network, no zone database beyond `Intl`: the caller passes
|
|
5
|
+
* `now` and `timeZone`, so the same function runs on the server route, in the
|
|
6
|
+
* native app and in a test. Eligibility is one rule set: owned by the caller,
|
|
7
|
+
* not done / dropped, not completed or canceled in Linear, and either overdue,
|
|
8
|
+
* in progress, or due today in the CALLER'S zone.
|
|
9
|
+
*/
|
|
10
|
+
import type {
|
|
11
|
+
Briefing, BriefingEntry, BriefingItem, BriefingKind, BriefingOptions,
|
|
12
|
+
} from './types';
|
|
13
|
+
|
|
14
|
+
const FINISHED = new Set(['done', 'dropped']);
|
|
15
|
+
const LINEAR_FINISHED = new Set(['completed', 'canceled', 'cancelled']);
|
|
16
|
+
const DEFAULT_MAX_ITEMS = 8;
|
|
17
|
+
const KIND_RANK: Record<BriefingKind, number> = { overdue: 0, in_progress: 1, due_today: 2 };
|
|
18
|
+
|
|
19
|
+
/** `YYYY-MM-DD` of an instant in a zone. */
|
|
20
|
+
export function localDate(instant: number, timeZone = 'UTC'): string {
|
|
21
|
+
const parts = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
|
|
22
|
+
.formatToParts(new Date(instant));
|
|
23
|
+
const get = (type: string) => parts.find((p) => p.type === type)?.value ?? '';
|
|
24
|
+
return `${get('year')}-${get('month')}-${get('day')}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The calendar day a due value means: a bare date as written, an instant in the zone. */
|
|
28
|
+
function dueDate(dueAt: string | null | undefined, timeZone: string): string | null {
|
|
29
|
+
if (!dueAt) return null;
|
|
30
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(dueAt)) return dueAt;
|
|
31
|
+
const t = Date.parse(dueAt);
|
|
32
|
+
return Number.isNaN(t) ? null : localDate(t, timeZone);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function kindOf(item: BriefingItem, due: string | null, today: string): BriefingKind | null {
|
|
36
|
+
if (due && due < today) return 'overdue';
|
|
37
|
+
if (item.status === 'in_progress') return 'in_progress';
|
|
38
|
+
if (due === today) return 'due_today';
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function composeBriefing(items: BriefingItem[], options: BriefingOptions): Briefing {
|
|
43
|
+
const timeZone = options.timeZone ?? 'UTC';
|
|
44
|
+
const today = localDate(options.now, timeZone);
|
|
45
|
+
const max = options.maxItems ?? DEFAULT_MAX_ITEMS;
|
|
46
|
+
|
|
47
|
+
const eligible: BriefingEntry[] = [];
|
|
48
|
+
for (const item of items) {
|
|
49
|
+
if (!item.ownerSub || item.ownerSub !== options.ownerSub) continue;
|
|
50
|
+
if (FINISHED.has(item.status)) continue;
|
|
51
|
+
if (item.linearState && LINEAR_FINISHED.has(item.linearState.toLowerCase())) continue;
|
|
52
|
+
const due = dueDate(item.dueAt, timeZone);
|
|
53
|
+
const kind = kindOf(item, due, today);
|
|
54
|
+
if (!kind) continue;
|
|
55
|
+
eligible.push({
|
|
56
|
+
id: item.id,
|
|
57
|
+
title: item.title,
|
|
58
|
+
kind,
|
|
59
|
+
group: item.focusName?.trim() || 'Personal',
|
|
60
|
+
dueDate: due,
|
|
61
|
+
...(item.priority !== undefined ? { priority: item.priority } : {}),
|
|
62
|
+
...(item.linearIdentifier ? { linearIdentifier: item.linearIdentifier } : {}),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Array.sort is stable: equal rows keep the order they arrived in.
|
|
67
|
+
eligible.sort((a, b) =>
|
|
68
|
+
KIND_RANK[a.kind] - KIND_RANK[b.kind]
|
|
69
|
+
|| (a.priority ?? 99) - (b.priority ?? 99)
|
|
70
|
+
|| (a.dueDate ?? '9999').localeCompare(b.dueDate ?? '9999'));
|
|
71
|
+
|
|
72
|
+
const counts: Briefing['counts'] = { overdue: 0, in_progress: 0, due_today: 0 };
|
|
73
|
+
for (const entry of eligible) counts[entry.kind] += 1;
|
|
74
|
+
const spoken = eligible.slice(0, max);
|
|
75
|
+
return {
|
|
76
|
+
items: spoken,
|
|
77
|
+
remaining: eligible.length - spoken.length,
|
|
78
|
+
total: eligible.length,
|
|
79
|
+
counts,
|
|
80
|
+
empty: eligible.length === 0,
|
|
81
|
+
context: { itemIds: spoken.map((e) => e.id), localDate: today, timeZone },
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The briefing's input and output. The input is STRUCTURAL: a to-do from the
|
|
3
|
+
* tenant (a `Commitment`) or a Linear-synced item both fit, so the composer needs
|
|
4
|
+
* no mapping layer and no import of either type.
|
|
5
|
+
*/
|
|
6
|
+
export interface BriefingItem {
|
|
7
|
+
id: string;
|
|
8
|
+
title: string;
|
|
9
|
+
/** `open` | `in_progress` | `blocked` | `done` | `dropped`; other words are treated as open. */
|
|
10
|
+
status: string;
|
|
11
|
+
/** A date (`2026-11-05`) or a full ISO instant; the reader's zone decides which day an instant is. */
|
|
12
|
+
dueAt?: string | null;
|
|
13
|
+
/** 0 critical .. 4 backlog. Unset sorts last. */
|
|
14
|
+
priority?: number;
|
|
15
|
+
/** The member who owns it. Items without one are not anybody's briefing. */
|
|
16
|
+
ownerSub?: string;
|
|
17
|
+
/** The project (focus) it is filed under, by name. */
|
|
18
|
+
focusName?: string;
|
|
19
|
+
/** Linear's own state type when the item is synced (`started`, `completed`, `canceled`, ...). */
|
|
20
|
+
linearState?: string;
|
|
21
|
+
linearIdentifier?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type BriefingKind = 'overdue' | 'in_progress' | 'due_today';
|
|
25
|
+
|
|
26
|
+
export interface BriefingEntry {
|
|
27
|
+
id: string;
|
|
28
|
+
title: string;
|
|
29
|
+
kind: BriefingKind;
|
|
30
|
+
/** Project name, or `Personal`. */
|
|
31
|
+
group: string;
|
|
32
|
+
dueDate: string | null;
|
|
33
|
+
priority?: number;
|
|
34
|
+
linearIdentifier?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface BriefingOptions {
|
|
38
|
+
ownerSub: string;
|
|
39
|
+
now: number;
|
|
40
|
+
/** IANA zone of the person hearing it. Default UTC. */
|
|
41
|
+
timeZone?: string;
|
|
42
|
+
/** Items spoken before "and N more". Default 8. */
|
|
43
|
+
maxItems?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** What a voice reply is resolved against: the spoken order, and the day it was composed for. */
|
|
47
|
+
export interface BriefingContext {
|
|
48
|
+
itemIds: string[];
|
|
49
|
+
localDate: string;
|
|
50
|
+
timeZone: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface Briefing {
|
|
54
|
+
items: BriefingEntry[];
|
|
55
|
+
/** Eligible items beyond the spoken ones. */
|
|
56
|
+
remaining: number;
|
|
57
|
+
/** All eligible items. */
|
|
58
|
+
total: number;
|
|
59
|
+
counts: Record<BriefingKind, number>;
|
|
60
|
+
empty: boolean;
|
|
61
|
+
context: BriefingContext;
|
|
62
|
+
}
|
package/src/corpus/index.ts
CHANGED
|
@@ -272,3 +272,6 @@ export type {
|
|
|
272
272
|
AttrValue, CountGroup, CountQuery, CountRow, EntityFilters, EntityOrder, EntityPage, EntityQuery, FacetQuery, FilterReport,
|
|
273
273
|
FilterVerdict, RelationshipListQuery,
|
|
274
274
|
} from './entity-query';
|
|
275
|
+
|
|
276
|
+
// Daily briefing: what is on one person's plate today (bd startsim-kgkp1).
|
|
277
|
+
export * from './briefing';
|
|
@@ -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
|
+
});
|
|
@@ -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
|
},
|