@watchtowerobservability/activity-react-native 0.0.0-stage → 0.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.
- package/LICENSE +202 -0
- package/README.md +84 -2
- package/package.json +38 -4
- package/src/ActivityLog.tsx +230 -0
- package/src/EventDetail.tsx +99 -0
- package/src/Sheets.tsx +113 -0
- package/src/builtInStrings.ts +230 -0
- package/src/client.ts +179 -0
- package/src/index.ts +14 -0
- package/src/link.ts +17 -0
- package/src/live.ts +74 -0
- package/src/query.ts +36 -0
- package/src/sealed.ts +38 -0
- package/src/strings.ts +67 -0
- package/src/theme.ts +37 -0
- package/src/types.ts +65 -0
- package/src/useActivityLog.ts +181 -0
- package/src/verify.ts +164 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { filterKey, toQuery } from './query';
|
|
2
|
+
import type { ActivityEvent, Bucket, Facet, FeedPage, Filters, KeyValueStore, RateLimit, SavedView, SessionInfo } from './types';
|
|
3
|
+
import { verifyProof, verifyResponse, type Keys, type Proof, type Verdict, type VerifyPage } from './verify';
|
|
4
|
+
|
|
5
|
+
/** 404 = wrong, expired, revoked or foreign token; 429 carries `retryAfter` seconds; 409 on a proof = not sealed yet; 0 = offline. */
|
|
6
|
+
export class ActivityError extends Error {
|
|
7
|
+
constructor(readonly status: number, readonly retryAfter?: number, detail?: string) {
|
|
8
|
+
super(detail ?? (status === 0 ? 'offline' : `HTTP ${status}`));
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ClientOptions {
|
|
13
|
+
baseUrl: string;
|
|
14
|
+
/** Viewer token from your backend (`POST /v1/activity/sessions`) or an account token `wta_acct_...`. */
|
|
15
|
+
token: string;
|
|
16
|
+
/** Called once when a request answers 404 (expired or revoked token): return a fresh token, or null to give up. */
|
|
17
|
+
refreshToken?: () => Promise<string | null | undefined>;
|
|
18
|
+
/** Where the last feed page and local saved views live (pass AsyncStorage); default: memory. */
|
|
19
|
+
storage?: KeyValueStore;
|
|
20
|
+
fetch?: typeof fetch;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const memory = (): KeyValueStore => {
|
|
24
|
+
const m = new Map<string, string>();
|
|
25
|
+
return { getItem: async (k) => m.get(k) ?? null, setItem: async (k, v) => void m.set(k, v) };
|
|
26
|
+
};
|
|
27
|
+
const num = (h: Headers, n: string) => { const v = h.get(n); return v != null && v.trim() !== '' && !Number.isNaN(Number(v)) ? Number(v) : undefined; };
|
|
28
|
+
|
|
29
|
+
/** The viewer API: Bearer token in the header only, `ETag` revalidation, `RateLimit-*` headers, offline last page. */
|
|
30
|
+
export class ActivityClient {
|
|
31
|
+
readonly baseUrl: string;
|
|
32
|
+
token: string;
|
|
33
|
+
rateLimit: RateLimit = {};
|
|
34
|
+
refreshToken?: ClientOptions['refreshToken'];
|
|
35
|
+
readonly storage: KeyValueStore;
|
|
36
|
+
#fetch: typeof fetch;
|
|
37
|
+
#etags = new Map<string, { tag: string; body: string }>();
|
|
38
|
+
|
|
39
|
+
constructor(o: ClientOptions) {
|
|
40
|
+
this.baseUrl = o.baseUrl.replace(/\/+$/, '');
|
|
41
|
+
this.token = o.token;
|
|
42
|
+
this.refreshToken = o.refreshToken;
|
|
43
|
+
this.storage = o.storage ?? memory();
|
|
44
|
+
this.#fetch = o.fetch ?? ((...a) => fetch(...a));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
setToken(t: string) { this.token = t; this.#etags.clear(); }
|
|
48
|
+
|
|
49
|
+
/** One call; GETs revalidate with the remembered `ETag`. Returns the body text. */
|
|
50
|
+
async send(path: string, init: { method?: string; body?: string } = {}, retried = false): Promise<string> {
|
|
51
|
+
const url = this.baseUrl + path;
|
|
52
|
+
const get = !init.method || init.method === 'GET';
|
|
53
|
+
const cached = get ? this.#etags.get(url) : undefined;
|
|
54
|
+
const headers: Record<string, string> = { authorization: `Bearer ${this.token}`, accept: 'application/json' };
|
|
55
|
+
if (init.body) headers['content-type'] = 'application/json';
|
|
56
|
+
if (cached) headers['if-none-match'] = cached.tag;
|
|
57
|
+
let res: Response;
|
|
58
|
+
try { res = await this.#fetch(url, { method: init.method ?? 'GET', headers, body: init.body }); } catch { throw new ActivityError(0); }
|
|
59
|
+
this.rateLimit = {
|
|
60
|
+
limit: num(res.headers, 'ratelimit-limit') ?? this.rateLimit.limit,
|
|
61
|
+
remaining: num(res.headers, 'ratelimit-remaining') ?? this.rateLimit.remaining,
|
|
62
|
+
reset: num(res.headers, 'ratelimit-reset') ?? this.rateLimit.reset,
|
|
63
|
+
};
|
|
64
|
+
if (res.status === 304 && cached) return cached.body;
|
|
65
|
+
if (res.ok) {
|
|
66
|
+
const body = await res.text();
|
|
67
|
+
const tag = res.headers.get('etag');
|
|
68
|
+
if (get && tag) {
|
|
69
|
+
if (this.#etags.size > 64) this.#etags.clear();
|
|
70
|
+
this.#etags.set(url, { tag, body });
|
|
71
|
+
}
|
|
72
|
+
return body;
|
|
73
|
+
}
|
|
74
|
+
if (res.status === 404 && !retried && this.refreshToken) {
|
|
75
|
+
const t = await this.refreshToken().catch(() => null);
|
|
76
|
+
if (t && t !== this.token) { this.setToken(t); return this.send(path, init, true); }
|
|
77
|
+
}
|
|
78
|
+
let detail: string | undefined;
|
|
79
|
+
try { detail = (JSON.parse(await res.text()) as { detail?: string }).detail; } catch { /* not problem+json */ }
|
|
80
|
+
throw new ActivityError(res.status, res.status === 429 ? num(res.headers, 'retry-after') ?? this.rateLimit.reset ?? 60 : undefined, detail);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async get<T>(path: string): Promise<T> { return JSON.parse(await this.send(path)) as T; }
|
|
84
|
+
|
|
85
|
+
get #feedKey() { return `wta.feed:${this.baseUrl}`; }
|
|
86
|
+
|
|
87
|
+
/** One page of the account's events; the first page is cached and served offline (`offline: true`) when the filters match. */
|
|
88
|
+
async feed(f: Filters = {}, o: { cursor?: string | null; limit?: number } = {}): Promise<FeedPage> {
|
|
89
|
+
const q = toQuery(f);
|
|
90
|
+
q.set('limit', String(o.limit ?? 25));
|
|
91
|
+
if (o.cursor) q.set('cursor', o.cursor);
|
|
92
|
+
const key = `${filterKey(f)}&limit=${o.limit ?? 25}`;
|
|
93
|
+
try {
|
|
94
|
+
const body = await this.send(`/v1/activity/feed?${q}`);
|
|
95
|
+
if (!o.cursor) await this.storage.setItem(this.#feedKey, JSON.stringify({ key, body })).catch(() => {});
|
|
96
|
+
return JSON.parse(body) as FeedPage;
|
|
97
|
+
} catch (e) {
|
|
98
|
+
if (!(e instanceof ActivityError) || e.status !== 0 || o.cursor) throw e;
|
|
99
|
+
const c = JSON.parse((await this.storage.getItem(this.#feedKey).catch(() => null)) ?? '{}') as { key?: string; body?: string };
|
|
100
|
+
if (c.key !== key || !c.body) throw e;
|
|
101
|
+
return { ...(JSON.parse(c.body) as FeedPage), offline: true };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Distinct values of `field` (`action`, `actor`, `target_type`, `target`) under the other filters. */
|
|
106
|
+
async facets(field: string, f: Filters = {}): Promise<Facet[]> {
|
|
107
|
+
return (await this.get<{ data: Facet[] }>(`/v1/activity/feed/facets?field=${encodeURIComponent(field)}&${toQuery(f)}`)).data;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Events per UTC day (30 days unless `from` is set). */
|
|
111
|
+
async histogram(f: Filters = {}): Promise<Bucket[]> {
|
|
112
|
+
const q = toQuery(f);
|
|
113
|
+
q.set('bucket', 'day');
|
|
114
|
+
if (!q.has('from')) q.set('from', new Date(Date.now() - 30 * 864e5).toISOString());
|
|
115
|
+
return (await this.get<{ data: Bucket[] }>(`/v1/activity/feed/histogram?${q}`)).data;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
session(): Promise<SessionInfo> { return this.get('/v1/activity/session'); }
|
|
119
|
+
|
|
120
|
+
get #viewsKey() { return `wta.views:${this.baseUrl}`; }
|
|
121
|
+
|
|
122
|
+
/** Saved views: on the server for an account token (`remote`), in `storage` for a viewer session. */
|
|
123
|
+
async views(remote: boolean): Promise<SavedView[]> {
|
|
124
|
+
if (!remote) return JSON.parse((await this.storage.getItem(this.#viewsKey)) ?? '[]') as SavedView[];
|
|
125
|
+
const p = await this.get<{ data: (SavedView & { params: Record<string, string> | null })[] }>('/v1/activity/views');
|
|
126
|
+
return p.data.map((v) => ({ id: v.id, name: v.name, q: v.q ?? '', params: v.params ?? {} }));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async saveView(v: Omit<SavedView, 'id'>, remote: boolean): Promise<void> {
|
|
130
|
+
if (remote) return void (await this.send('/v1/activity/views', { method: 'POST', body: JSON.stringify({ name: v.name, q: v.q, params: v.params }) }));
|
|
131
|
+
const all = (await this.views(false)).filter((x) => x.name !== v.name);
|
|
132
|
+
await this.storage.setItem(this.#viewsKey, JSON.stringify([...all, { ...v, id: `local-${Date.now().toString(36)}` }]));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async deleteView(v: SavedView, remote: boolean): Promise<void> {
|
|
136
|
+
if (remote) return void (await this.send(`/v1/activity/views/${encodeURIComponent(v.id)}`, { method: 'DELETE' }));
|
|
137
|
+
await this.storage.setItem(this.#viewsKey, JSON.stringify((await this.views(false)).filter((x) => x.id !== v.id)));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The filtered events as `csv`, `ndjson` or `ocsf` text (capability `export`; recorded in the account's log). */
|
|
141
|
+
export(f: Filters = {}, format = 'csv'): Promise<string> {
|
|
142
|
+
const q = toQuery(f);
|
|
143
|
+
q.set('format', format);
|
|
144
|
+
return this.send(`/v1/activity/feed/export?${q}`);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The value behind a tokenised IP or email (capability `reveal`; every reveal is an audited access event). */
|
|
148
|
+
async reveal(token: string): Promise<string> {
|
|
149
|
+
return (JSON.parse(await this.send('/v1/activity/reveal', { method: 'POST', body: JSON.stringify({ token }) })) as { value: string }).value;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** One event by permalink: the feed read at that instant (`from = at`, `to = at + 1 ms`), or null. */
|
|
153
|
+
async event(id: string, at: string): Promise<ActivityEvent | null> {
|
|
154
|
+
const t = Date.parse(at);
|
|
155
|
+
const q = new URLSearchParams({ from: new Date(t).toISOString(), to: new Date(t + 1).toISOString(), limit: '100' });
|
|
156
|
+
return (await this.get<FeedPage>(`/v1/activity/feed?${q}`)).data.find((e) => e.id === id) ?? null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async #keys(project: string): Promise<Keys> {
|
|
160
|
+
return (await this.get<{ keys?: Keys }>(`/v1/activity/keys?project=${encodeURIComponent(project)}`).catch(() => ({ keys: [] }))).keys ?? [];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Fetch every verify page (at most 50 x 2000 rows) and the project keys, then check them on the device. */
|
|
164
|
+
async verifyChain(): Promise<Verdict> {
|
|
165
|
+
let page = await this.get<VerifyPage>('/v1/activity/feed/verify?limit=2000');
|
|
166
|
+
const all = { ...page, data: [...page.data] };
|
|
167
|
+
for (let n = 0; page.next_cursor && n < 50; n++) {
|
|
168
|
+
page = await this.get<VerifyPage>(`/v1/activity/feed/verify?limit=2000&from_seq=${encodeURIComponent(page.next_cursor)}`);
|
|
169
|
+
all.data.push(...page.data);
|
|
170
|
+
}
|
|
171
|
+
return verifyResponse(all, await this.#keys(all.project));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** One event's Merkle inclusion proof, checked on the device (409 until its hour is signed). */
|
|
175
|
+
async proveEvent(id: string): Promise<Verdict> {
|
|
176
|
+
const p = await this.get<Proof>(`/v1/activity/feed/proof?event_id=${encodeURIComponent(id)}`);
|
|
177
|
+
return verifyProof(p, await this.#keys(p.project), id);
|
|
178
|
+
}
|
|
179
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export { ActivityLog, type ActivityLogProps } from './ActivityLog';
|
|
2
|
+
export { EventDetail } from './EventDetail';
|
|
3
|
+
export { ActivityClient, ActivityError, type ClientOptions } from './client';
|
|
4
|
+
export { useActivityLog, type ActivityLogState, type VerifyState } from './useActivityLog';
|
|
5
|
+
export { pickStrings, fmt, headline } from './strings';
|
|
6
|
+
export { tokenize, removeTerm, chipText, toQuery, isRtl, type Term } from './query';
|
|
7
|
+
export { resolveColors, isDark, type Appearance, type Colors } from './theme';
|
|
8
|
+
export { BUILT_IN_STRINGS } from './builtInStrings';
|
|
9
|
+
export * from './verify';
|
|
10
|
+
export { SseParser, openStream, nextStep, newCount } from './live';
|
|
11
|
+
export { openSealed, revealTokens } from './sealed';
|
|
12
|
+
export { eventLink, parseLink } from './link';
|
|
13
|
+
export { relTime, fmtDate } from './strings';
|
|
14
|
+
export type * from './types';
|
package/src/link.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Event permalinks, the same parameters as the web element (`#wta-event=<id>&wta-at=<occurred_at>`), so one link
|
|
2
|
+
// works on the hosted page and in the app. `base` is your app's URL (custom scheme or universal/app link).
|
|
3
|
+
|
|
4
|
+
export function eventLink(base: string, e: { id: string; occurred_at: string }): string {
|
|
5
|
+
const p = `wta-event=${encodeURIComponent(e.id)}&wta-at=${encodeURIComponent(e.occurred_at)}`;
|
|
6
|
+
return base.includes('#') ? `${base}&${p}` : `${base}#${p}`;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** `{id, at}` from a link (fragment first, then query), or null. */
|
|
10
|
+
export function parseLink(url: string): { id: string; at: string } | null {
|
|
11
|
+
for (const part of [url.split('#')[1] ?? '', (url.split('#')[0] ?? '').split('?')[1] ?? '']) {
|
|
12
|
+
const q = new URLSearchParams(part);
|
|
13
|
+
const id = q.get('wta-event'), at = q.get('wta-at');
|
|
14
|
+
if (id && at && !Number.isNaN(Date.parse(at))) return { id, at };
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
package/src/live.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Live updates: `GET /v1/activity/feed/stream` (server-sent events). `new` carries `{count, latest_received_at}`;
|
|
2
|
+
// `end` carries `expired`, `revoked`, `max_duration` or `error`. React Native's fetch has no streaming body, so the
|
|
3
|
+
// stream is read with XMLHttpRequest progress events (incremental `responseText`).
|
|
4
|
+
import { ActivityError } from './client';
|
|
5
|
+
|
|
6
|
+
/** Line-at-a-time SSE parser: returns `{event, data}` on the blank line that ends an event. */
|
|
7
|
+
export class SseParser {
|
|
8
|
+
#event = '';
|
|
9
|
+
#data: string[] = [];
|
|
10
|
+
#buf = '';
|
|
11
|
+
/** Feed raw text; returns the events it completed. */
|
|
12
|
+
push(chunk: string): { event: string; data: string }[] {
|
|
13
|
+
this.#buf += chunk;
|
|
14
|
+
const out: { event: string; data: string }[] = [];
|
|
15
|
+
let i;
|
|
16
|
+
while ((i = this.#buf.indexOf('\n')) >= 0) {
|
|
17
|
+
const line = this.#buf.slice(0, i).replace(/\r$/, '');
|
|
18
|
+
this.#buf = this.#buf.slice(i + 1);
|
|
19
|
+
if (line === '') {
|
|
20
|
+
if (this.#data.length) out.push({ event: this.#event || 'message', data: this.#data.join('\n') });
|
|
21
|
+
this.#event = ''; this.#data = [];
|
|
22
|
+
} else if (line.startsWith('event:')) this.#event = line.slice(6).trim();
|
|
23
|
+
else if (line.startsWith('data:')) this.#data.push(line.slice(5).trim());
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** New events in one `new` message. */
|
|
30
|
+
export const newCount = (data: string): number => { try { return Number(JSON.parse(data).count) || 0; } catch { return 0; } };
|
|
31
|
+
|
|
32
|
+
/** What to do after a stream ended: wait `delay` seconds, refresh the token first, or stop. */
|
|
33
|
+
export function nextStep(outcome: { end?: string; error?: ActivityError }, backoff: number): { delay: number; refresh: boolean; stop: boolean; backoff: number } {
|
|
34
|
+
const e = outcome.error;
|
|
35
|
+
if (outcome.end === 'expired' || outcome.end === 'revoked' || e?.status === 404) return { delay: 0, refresh: true, stop: false, backoff: 1 };
|
|
36
|
+
if (e?.status === 429) return { delay: e.retryAfter ?? 60, refresh: false, stop: false, backoff };
|
|
37
|
+
if (e || outcome.end === 'error' || !outcome.end) return { delay: backoff, refresh: false, stop: false, backoff: Math.min(backoff * 2, 30) };
|
|
38
|
+
return { delay: 1, refresh: false, stop: false, backoff: 1 }; // max_duration: reconnect at once
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type Xhr = Pick<XMLHttpRequest, 'open' | 'setRequestHeader' | 'send' | 'abort' | 'readyState' | 'status' | 'responseText' | 'getResponseHeader'>
|
|
42
|
+
& { onprogress: unknown; onreadystatechange: unknown; onerror: unknown; onload: unknown };
|
|
43
|
+
|
|
44
|
+
/** One stream connection; resolves with the `end` reason ('' when the connection closed without one). */
|
|
45
|
+
export function openStream(url: string, token: string, onNew: (n: number) => void, make: () => Xhr = () => new XMLHttpRequest() as unknown as Xhr): { done: Promise<string>; abort: () => void } {
|
|
46
|
+
const x = make();
|
|
47
|
+
const p = new SseParser();
|
|
48
|
+
let seen = 0, end = '';
|
|
49
|
+
const done = new Promise<string>((resolve, reject) => {
|
|
50
|
+
const read = () => {
|
|
51
|
+
const t = x.responseText ?? '';
|
|
52
|
+
for (const ev of p.push(t.slice(seen))) {
|
|
53
|
+
if (ev.event === 'new') onNew(newCount(ev.data));
|
|
54
|
+
if (ev.event === 'end') end = ev.data;
|
|
55
|
+
}
|
|
56
|
+
seen = t.length;
|
|
57
|
+
};
|
|
58
|
+
x.onreadystatechange = () => {
|
|
59
|
+
if (x.readyState === 2 && x.status >= 400) {
|
|
60
|
+
const ra = Number(x.getResponseHeader('retry-after'));
|
|
61
|
+
reject(new ActivityError(x.status, Number.isFinite(ra) && ra > 0 ? ra : undefined));
|
|
62
|
+
x.abort();
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
x.onprogress = read;
|
|
66
|
+
x.onload = () => { read(); resolve(end); };
|
|
67
|
+
x.onerror = () => reject(new ActivityError(0));
|
|
68
|
+
x.open('GET', url);
|
|
69
|
+
x.setRequestHeader('authorization', `Bearer ${token}`);
|
|
70
|
+
x.setRequestHeader('accept', 'text/event-stream');
|
|
71
|
+
x.send();
|
|
72
|
+
});
|
|
73
|
+
return { done, abort: () => x.abort() };
|
|
74
|
+
}
|
package/src/query.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Filters } from './types';
|
|
2
|
+
|
|
3
|
+
// Search chips: a small tokenizer over the qualifier syntax the feed's `q` accepts (the server parses it).
|
|
4
|
+
const KEYS = 'action actor actor_email target target_type outcome severity country operation ip created occurred'.split(' ');
|
|
5
|
+
|
|
6
|
+
export interface Term { raw: string; key?: string; value: string; neg: boolean }
|
|
7
|
+
|
|
8
|
+
/** Whitespace-separated terms; double quotes group (`actor:"Ada L"`); `-key:value` negates. */
|
|
9
|
+
export function tokenize(q: string): Term[] {
|
|
10
|
+
const out: Term[] = [];
|
|
11
|
+
for (const [raw, neg, k, v, quoted] of q.matchAll(/(-?)([a-z_]+:)?("([^"]*)"?|\S+)/g)) {
|
|
12
|
+
const key = k?.slice(0, -1);
|
|
13
|
+
out.push(key && KEYS.includes(key) ? { raw: raw!, key, value: quoted ?? v!, neg: neg === '-' } : { raw: raw!, value: raw!, neg: false });
|
|
14
|
+
}
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const removeTerm = (q: string, i: number) => tokenize(q).filter((_, j) => j !== i).map((t) => t.raw).join(' ');
|
|
19
|
+
export const chipText = (t: Term, not = 'not') => (t.key ? `${t.neg ? not + ' ' : ''}${t.key}: ${t.value}` : t.value);
|
|
20
|
+
export const isRtl = (locale?: string | null) => /^(ar|he|fa|ur|ps|sd|yi|dv|ckb)\b/i.test(locale ?? '');
|
|
21
|
+
|
|
22
|
+
export const RANGES: Record<string, number> = { '24h': 864e5, '7d': 6048e5, '30d': 2592e6 };
|
|
23
|
+
|
|
24
|
+
/** Filters -> feed query; a quick range resolves to `from` at call time. Empty values are dropped. */
|
|
25
|
+
export function toQuery(f: Filters, now = Date.now()): URLSearchParams {
|
|
26
|
+
const q = new URLSearchParams();
|
|
27
|
+
const quick = f.range ? RANGES[f.range] : undefined;
|
|
28
|
+
for (const [k, v] of Object.entries(f)) if (v && k !== 'range' && !(quick && (k === 'from' || k === 'to'))) q.set(k, String(v).trim());
|
|
29
|
+
if (quick) q.set('from', new Date(now - quick).toISOString());
|
|
30
|
+
return q;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Stable cache key of a filter set (the quick range unresolved). */
|
|
34
|
+
export const filterKey = (f: Filters) => Object.entries(f).filter(([, v]) => v).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}=${v}`).join('&');
|
|
35
|
+
|
|
36
|
+
export const isFiltered = (f: Filters) => Object.entries(f).some(([k, v]) => v && k !== 'order');
|
package/src/sealed.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { gcm } from '@noble/ciphers/aes.js';
|
|
2
|
+
|
|
3
|
+
// Client-sealed values: `{"$wt_cse": kid, alg: "A256GCM", iv, ct}` envelopes (standard base64; `ct` ends with the
|
|
4
|
+
// 16-byte tag), AES-256-GCM with the UTF-8 dotted path as AAD (`metadata.ssn`, `changes.0.old`). The key stays in the
|
|
5
|
+
// app and never reaches Watchtower; an envelope that does not open stays as it is.
|
|
6
|
+
|
|
7
|
+
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
8
|
+
export function b64(s: string): Uint8Array {
|
|
9
|
+
const out: number[] = [];
|
|
10
|
+
let buf = 0, n = 0;
|
|
11
|
+
for (const c of s.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '')) {
|
|
12
|
+
const v = B64.indexOf(c);
|
|
13
|
+
if (v < 0) return new Uint8Array();
|
|
14
|
+
buf = ((buf << 6) | v) & 0xffffff; n += 6;
|
|
15
|
+
if (n >= 8) { n -= 8; out.push((buf >> n) & 0xff); }
|
|
16
|
+
}
|
|
17
|
+
return new Uint8Array(out);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Opens the envelopes under `v` (at dotted `path` from the event root) with the base64 AES-256 `key`. */
|
|
21
|
+
export function openSealed(v: unknown, key: string, path: string): unknown {
|
|
22
|
+
if (!v || typeof v !== 'object') return v;
|
|
23
|
+
if (Array.isArray(v)) return v.map((x, i) => openSealed(x, key, `${path}.${i}`));
|
|
24
|
+
const o = v as Record<string, unknown>;
|
|
25
|
+
if (typeof o.$wt_cse === 'string') {
|
|
26
|
+
try {
|
|
27
|
+
const pt = gcm(b64(key), b64(String(o.iv)), new TextEncoder().encode(path)).decrypt(b64(String(o.ct)));
|
|
28
|
+
return JSON.parse(new TextDecoder().decode(pt));
|
|
29
|
+
} catch { return v; }
|
|
30
|
+
}
|
|
31
|
+
return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, openSealed(x, key, `${path}.${k}`)]));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const hasSealed = (v: unknown) => v != null && JSON.stringify(v).includes('$wt_cse');
|
|
35
|
+
|
|
36
|
+
/** Tokenised IP (2001:db8::/32) or email (@token.invalid) values of an event, for `POST /v1/activity/reveal`. */
|
|
37
|
+
export const revealTokens = (ip: string | undefined, email: string | undefined) =>
|
|
38
|
+
[ip, email].filter((v): v is string => !!v && /^2001:db8:|@token\.invalid$/.test(v));
|
package/src/strings.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { BUILT_IN_STRINGS } from './builtInStrings';
|
|
2
|
+
import type { ActivityEvent, Strings, Theme } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* UI copy for a locale: built-in en < built-in language ("pt") < built-in exact ("pt-BR") < theme "default" <
|
|
6
|
+
* theme language < theme exact locale < app overrides. A flat theme map (every value a string) counts as "default".
|
|
7
|
+
*/
|
|
8
|
+
export function pickStrings(strings: Theme['strings'], locale: string | undefined, overrides: Strings = {}): Strings {
|
|
9
|
+
const s = strings ?? {};
|
|
10
|
+
const flat = Object.values(s).some((v) => typeof v === 'string');
|
|
11
|
+
const map = (flat ? { default: s } : s) as Record<string, Strings | undefined>;
|
|
12
|
+
const chain = locale ? [locale.split('-')[0]!, locale] : [];
|
|
13
|
+
const out: Strings = { ...BUILT_IN_STRINGS.en };
|
|
14
|
+
for (const l of chain) Object.assign(out, BUILT_IN_STRINGS[l]);
|
|
15
|
+
for (const l of ['default', ...chain]) Object.assign(out, map[l]);
|
|
16
|
+
return Object.assign(out, overrides);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Fill `{n}` style placeholders of a UI string. */
|
|
20
|
+
export const fmt = (s: string, vars: Record<string, string | number>) => s.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));
|
|
21
|
+
|
|
22
|
+
/** Dotted path into an event; `target` falls back to `targets[0]`. */
|
|
23
|
+
export function field(ev: unknown, path: string): unknown {
|
|
24
|
+
let v: any = ev;
|
|
25
|
+
for (const k of path.split('.')) {
|
|
26
|
+
const next = v != null && typeof v === 'object' ? v[k] : undefined;
|
|
27
|
+
v = next === undefined && k === 'target' ? v?.targets?.[0] : next;
|
|
28
|
+
}
|
|
29
|
+
return v;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function text(ev: unknown, path: string): string {
|
|
33
|
+
const v = field(ev, path);
|
|
34
|
+
return v == null || typeof v === 'object' ? '' : String(v);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The row headline: the theme's action label template, else "<actor> <action> <target>". */
|
|
38
|
+
export function headline(ev: ActivityEvent, theme: Theme | undefined, s: Strings): string {
|
|
39
|
+
const target = ev.target ?? ev.targets?.[0];
|
|
40
|
+
const e = {
|
|
41
|
+
...ev,
|
|
42
|
+
actor: { ...ev.actor, name: ev.actor.name || (ev.actor.type === 'anonymous' ? s.anonymous : ev.actor.id) },
|
|
43
|
+
target: target && { ...target, name: target.name || target.id },
|
|
44
|
+
};
|
|
45
|
+
const tpl = theme?.actions?.[ev.action]?.label ?? '{actor.name} ' + ev.action + (target ? ' {target.name}' : '');
|
|
46
|
+
return tpl.replace(/\{([\w.]+)\}/g, (_, p: string) => text(e, p));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const show = (v: unknown) => (v == null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
50
|
+
|
|
51
|
+
/** "5 min ago" from the string table (the same steps on every platform); future times read as "just now". */
|
|
52
|
+
export function relTime(iso: string, s: Strings, now = Date.now()): string {
|
|
53
|
+
const sec = Math.max(0, Math.floor((now - Date.parse(iso)) / 1000));
|
|
54
|
+
const day = Math.floor(sec / 86400);
|
|
55
|
+
const [k, n] = sec < 5 ? ['relNow', 0] : sec < 60 ? ['relSec', sec] : sec < 3600 ? ['relMin', Math.floor(sec / 60)] : sec < 86400 ? ['relHour', Math.floor(sec / 3600)]
|
|
56
|
+
: day < 30 ? ['relDay', day] : day < 365 ? ['relMonth', Math.floor(day / 30)] : ['relYear', Math.floor(day / 365)];
|
|
57
|
+
return fmt(s[k as string]!, { n });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Intl date in the session's locale and time zone; an unknown zone falls back to the device's. */
|
|
61
|
+
export function fmtDate(iso: string, locale?: string, timeZone?: string, o: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'medium' }): string {
|
|
62
|
+
try {
|
|
63
|
+
return new Intl.DateTimeFormat(locale, { ...o, timeZone }).format(new Date(iso));
|
|
64
|
+
} catch {
|
|
65
|
+
try { return new Intl.DateTimeFormat(locale, o).format(new Date(iso)); } catch { return iso; }
|
|
66
|
+
}
|
|
67
|
+
}
|
package/src/theme.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Palette, Strings, Theme } from './types';
|
|
2
|
+
|
|
3
|
+
/** App-side overrides on top of the project theme from the feed. */
|
|
4
|
+
export interface Appearance {
|
|
5
|
+
accent?: string;
|
|
6
|
+
/** Force light or dark; default: the theme's `colorScheme`, then the device. */
|
|
7
|
+
colorScheme?: 'light' | 'dark';
|
|
8
|
+
palette?: Palette;
|
|
9
|
+
paletteDark?: Palette;
|
|
10
|
+
radius?: number;
|
|
11
|
+
density?: 'compact' | 'comfortable';
|
|
12
|
+
/** Overrides the session's locale (BCP 47). */
|
|
13
|
+
locale?: string;
|
|
14
|
+
/** Copy overrides by key (see builtInStrings.ts). */
|
|
15
|
+
strings?: Strings;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Colors { bg: string; fg: string; muted: string; accent: string; border: string; danger: string; radius: number; compact: boolean }
|
|
19
|
+
|
|
20
|
+
const LIGHT: Required<Palette> = { bg: '#ffffff', fg: '#1a1a1a', muted: '#666666', accent: '#2563eb', border: '#e3e3e3', danger: '#c0392b' };
|
|
21
|
+
const DARK: Required<Palette> = { bg: '#111111', fg: '#f2f2f2', muted: '#a0a0a0', accent: '#60a5fa', border: '#333333', danger: '#f87171' };
|
|
22
|
+
// Only plain colors reach native styles (no CSS functions or url()).
|
|
23
|
+
const color = (v: unknown): v is string => typeof v === 'string' && /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|[a-z]+)$/i.test(v.trim());
|
|
24
|
+
|
|
25
|
+
export function isDark(theme: Theme | undefined, a: Appearance, device: string | null | undefined): boolean {
|
|
26
|
+
const s = a.colorScheme ?? theme?.colorScheme ?? 'system';
|
|
27
|
+
return s === 'dark' || (s === 'system' && device === 'dark');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function resolveColors(theme: Theme | undefined, a: Appearance, dark: boolean): Colors {
|
|
31
|
+
const layers = [dark ? DARK : LIGHT, theme?.palette, dark ? theme?.paletteDark : undefined, a.palette, dark ? a.paletteDark : undefined];
|
|
32
|
+
const out = { ...(dark ? DARK : LIGHT) };
|
|
33
|
+
for (const p of layers) for (const [k, v] of Object.entries(p ?? {})) if (color(v)) out[k as keyof Palette] = v;
|
|
34
|
+
if (a.accent && color(a.accent)) out.accent = a.accent;
|
|
35
|
+
const r = typeof theme?.radius === 'number' ? theme.radius : parseFloat(String(theme?.radius ?? ''));
|
|
36
|
+
return { ...out, radius: a.radius ?? (Number.isFinite(r) ? r : 8), compact: (a.density ?? theme?.density) === 'compact' };
|
|
37
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Wire shapes of the viewer API (`GET /v1/activity/feed` and friends), same as the web element's.
|
|
2
|
+
export interface Palette { bg?: string; fg?: string; muted?: string; accent?: string; border?: string; danger?: string }
|
|
3
|
+
export interface ActionStyle { label?: string; icon?: string; tone?: string }
|
|
4
|
+
export type Strings = Record<string, string>;
|
|
5
|
+
/** The project's activity theme as the feed returns it. Every key is optional. */
|
|
6
|
+
export interface Theme {
|
|
7
|
+
brandName?: string; logoUrl?: string; logoDarkUrl?: string;
|
|
8
|
+
colorScheme?: 'system' | 'light' | 'dark';
|
|
9
|
+
palette?: Palette; paletteDark?: Palette;
|
|
10
|
+
radius?: string | number;
|
|
11
|
+
density?: 'compact' | 'comfortable';
|
|
12
|
+
/** Per-locale map with a "default" entry; a flat map is read as "default". */
|
|
13
|
+
strings?: Record<string, Strings | string>;
|
|
14
|
+
actions?: Record<string, ActionStyle>;
|
|
15
|
+
detailFields?: string[];
|
|
16
|
+
showIp?: boolean; showMetadata?: boolean; showLocation?: boolean; showImpersonation?: boolean;
|
|
17
|
+
hideAccessEvents?: boolean;
|
|
18
|
+
environmentLabel?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface Target { type: string; id: string; name?: string }
|
|
21
|
+
export interface ActivityEvent {
|
|
22
|
+
id: string;
|
|
23
|
+
account_id: string;
|
|
24
|
+
actor: { id: string; name?: string; type?: string; email?: string; url?: string };
|
|
25
|
+
on_behalf_of?: { id: string; name?: string };
|
|
26
|
+
credential?: { type: string; id?: string; fingerprint?: string };
|
|
27
|
+
action: string;
|
|
28
|
+
target?: Target;
|
|
29
|
+
targets?: Target[];
|
|
30
|
+
changes?: { field: string; old?: unknown; new?: unknown }[];
|
|
31
|
+
context?: { ip?: string; user_agent?: string; request_id?: string; session_id?: string; country?: string };
|
|
32
|
+
outcome?: 'success' | 'failure' | 'denied';
|
|
33
|
+
severity?: 'info' | 'notice' | 'warning' | 'critical';
|
|
34
|
+
metadata?: Record<string, unknown>;
|
|
35
|
+
ip?: string;
|
|
36
|
+
signed_by?: string;
|
|
37
|
+
trace_id?: string;
|
|
38
|
+
occurred_at: string;
|
|
39
|
+
received_at?: string;
|
|
40
|
+
}
|
|
41
|
+
export interface FeedPage {
|
|
42
|
+
data: ActivityEvent[];
|
|
43
|
+
next_cursor?: string | null;
|
|
44
|
+
theme?: Theme;
|
|
45
|
+
locale?: string | null;
|
|
46
|
+
time_zone?: string | null;
|
|
47
|
+
capabilities?: string[];
|
|
48
|
+
/** Set by the client: served from the offline cache. */
|
|
49
|
+
offline?: boolean;
|
|
50
|
+
}
|
|
51
|
+
/** Feed filters; every key maps 1:1 to a `/v1/activity/feed` query parameter. `range`: 24h, 7d or 30d. */
|
|
52
|
+
export interface Filters {
|
|
53
|
+
q?: string; action?: string; actor_id?: string; target_type?: string; target_id?: string;
|
|
54
|
+
outcome?: string; severity?: string; range?: string; from?: string; to?: string; order?: string;
|
|
55
|
+
}
|
|
56
|
+
export interface Facet { value: string; label?: string; count: number }
|
|
57
|
+
export interface Bucket { at: string; count: number }
|
|
58
|
+
export interface SavedView { id: string; name: string; q: string; params: Record<string, string> }
|
|
59
|
+
export interface SessionInfo {
|
|
60
|
+
account_id: string; capabilities: string[]; locale?: string | null; time_zone?: string | null;
|
|
61
|
+
expires_at?: string | null; credential: 'session' | 'account_token';
|
|
62
|
+
}
|
|
63
|
+
export interface RateLimit { limit?: number; remaining?: number; reset?: number }
|
|
64
|
+
/** AsyncStorage-compatible key-value store (pass `@react-native-async-storage/async-storage`). */
|
|
65
|
+
export interface KeyValueStore { getItem(k: string): Promise<string | null>; setItem(k: string, v: string): Promise<void> }
|