@watchtowerobservability/activity-react-native 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # Watchtower Activity for React Native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Native React Native components that show each end user the activity of their own account, from the Watchtower
4
+ hosted activity log. Built from `View`, `Text`, `SectionList` and `Modal`: no WebView, no native module to link.
5
+
6
+ - Feed with infinite scroll, pull to refresh and day sections
7
+ - Search with the Watchtower query language (`action:invoice.* -outcome:denied actor:"Ada L"`), with removable chips
8
+ - Filters from server facets (action, actor, target type), outcome, severity, time range, order
9
+ - Event sheet with details, context, changes (before/after), targets, credential and metadata (selectable text)
10
+ - Saved views (on the server for account tokens, in your storage for viewer sessions)
11
+ - Export (CSV) through the system share sheet, or your own `onExport`
12
+ - Verify badge: the hash chain and the Ed25519-signed checkpoint are re-checked on the device (@noble/hashes,
13
+ @noble/curves; React Native has no WebCrypto); per event Merkle inclusion proofs
14
+ - The project theme from the feed (palette, dark palette, radius, density, action labels, strings) plus overrides
15
+ - Dark mode, font scaling, VoiceOver/TalkBack roles, labels and hints
16
+ - Built-in copy in en, de, fr, es, ja, pt-BR and ar (right to left); the theme and the app can override any string
17
+ - Token refresh callback, `ETag` revalidation, `RateLimit-*` headers, the last page cached for offline use
18
+ - Live updates over the feed stream (`/v1/activity/feed/stream`, SSE): an "N new events" button, reconnect with
19
+ backoff, token refresh on expiry, paused while the app is in the background
20
+ - Reveal of tokenised IPs and emails (`POST /v1/activity/reveal`, capability `reveal`, audited) and on-device opening
21
+ of client-sealed values (`$wt_cse`, AES-256-GCM, the key never leaves the app)
22
+ - Event permalinks (`#wta-event=<id>&wta-at=<occurred_at>`, the same as the web element) to open from a deep link
23
+ and to share
24
+ - Times in the session's time zone and locale; relative ("5 min ago") or absolute, the viewer's choice is kept
25
+
26
+ React Native 0.74 or later (Hermes `TextEncoder` and `Intl`).
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ npm i @watchtowerobservability/activity-react-native
32
+ npm i @react-native-async-storage/async-storage # optional: offline page and local views survive restarts
33
+ ```
34
+
35
+ ## Use
36
+
37
+ Your backend mints a short-lived viewer token for the signed-in user (`POST /v1/activity/sessions`, or the server
38
+ SDK's `createSession`). Never ship a project API key in the app.
39
+
40
+ ```tsx
41
+ import AsyncStorage from '@react-native-async-storage/async-storage';
42
+ import { ActivityClient, ActivityLog } from '@watchtowerobservability/activity-react-native';
43
+
44
+ const client = new ActivityClient({
45
+ baseUrl: 'https://api.watchtower.example',
46
+ token: viewerToken,
47
+ refreshToken: () => myBackend.mintViewerToken(), // once per request that answers 404
48
+ storage: AsyncStorage,
49
+ });
50
+
51
+ <ActivityLog client={client} appearance={{ accent: '#4f46e5', locale: 'de' }} />
52
+ ```
53
+
54
+ `appearance` overrides the project theme: `accent`, `colorScheme`, `palette`, `paletteDark`, `radius`, `density`,
55
+ `locale` and `strings` (any key of `src/builtInStrings.ts`). `onExport(text, format)` replaces the share sheet,
56
+ for example to write a file with `expo-file-system`.
57
+
58
+ For your own UI, use the `useActivityLog(client)` hook (events, filters, facets, views, verify state and actions)
59
+ or the `ActivityClient` alone (`feed`, `facets`, `histogram`, `views`, `export`, `verifyChain`, `proveEvent`).
60
+
61
+ ## Live updates, reveal, sealed values and permalinks
62
+
63
+ - **Live**: `<ActivityLog client={c} live />` streams while `AppState` is active (an XHR streaming reader, no native module). The stream counts new events; tapping the button reloads. It reconnects with backoff (1 s doubling
64
+ to 30 s, `Retry-After` on 429), asks `refreshToken` when the session expires or is revoked, and stops when no new
65
+ token comes. One stream per session (the API answers 409 to a second).
66
+ - **Reveal**: when the session has the `reveal` capability and the event carries a tokenised IP (`2001:db8::/32`)
67
+ or email (`@token.invalid`), the event sheet shows "Reveal". Every reveal is recorded in the account's log.
68
+ - **Sealed values**: pass `sealKey` (base64 AES-256) to open `$wt_cse` envelopes in metadata and changes on the device (AAD = the dotted path; `@noble/ciphers`). Without it, sealed values show as their envelopes.
69
+ - **Permalinks**: set `linkBase="myapp://activity"` to get "Share link" / "Copy link" in the event sheet (`onShareLink` receives the URL, default the share sheet). Pass an incoming deep link as `link` (from `Linking`); `eventLink`/`parseLink` build and read links.
70
+
71
+ ## Example
72
+
73
+ `example/App.tsx`.
74
+
75
+ ## Test
76
+
77
+ ```sh
78
+ npm install
79
+ npm run typecheck
80
+ npm test
81
+ ```
82
+
83
+ ## License
84
+
85
+ Apache-2.0
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@watchtowerobservability/activity-react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Watchtower hosted activity log: native React Native viewer components (no WebView)",
5
+ "license": "Apache-2.0",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "react-native": "src/index.ts",
9
+ "files": [
10
+ "src"
11
+ ],
12
+ "scripts": {
13
+ "typecheck": "tsc --noEmit -p tsconfig.json",
14
+ "test": "vitest run"
15
+ },
16
+ "dependencies": {
17
+ "@noble/ciphers": "^2.0.0",
18
+ "@noble/curves": "^2.0.0",
19
+ "@noble/hashes": "^2.0.0"
20
+ },
21
+ "peerDependencies": {
22
+ "react": ">=18",
23
+ "react-native": ">=0.74"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "22.15.0",
27
+ "@types/react": "^19.0.0",
28
+ "typescript": "5.7.2",
29
+ "vitest": "5.0.5"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/watchtowerobservability/watchtower-activity-react-native.git"
34
+ },
35
+ "homepage": "https://github.com/watchtowerobservability/watchtower-activity-react-native#readme",
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "registry": "https://registry.npmjs.org/"
39
+ }
40
+ }
@@ -0,0 +1,230 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { ActivityIndicator, Pressable, RefreshControl, SectionList, Share, StyleSheet, Text, TextInput, View, useColorScheme, type ViewStyle } from 'react-native';
3
+ import { ActivityClient, type ClientOptions } from './client';
4
+ import { EventDetail } from './EventDetail';
5
+ import { chipText, isFiltered, isRtl, tokenize, removeTerm } from './query';
6
+ import { FiltersSheet, ViewsSheet } from './Sheets';
7
+ import { eventLink, parseLink } from './link';
8
+ import { fmt, fmtDate, headline, pickStrings, relTime } from './strings';
9
+ import { isDark, resolveColors, type Appearance, type Colors } from './theme';
10
+ import type { ActivityEvent, Filters } from './types';
11
+ import { useActivityLog, type ActivityLogState } from './useActivityLog';
12
+
13
+ export interface ActivityLogProps {
14
+ /** A client you hold (to share it or call it yourself), or the options to make one. */
15
+ client?: ActivityClient;
16
+ options?: ClientOptions;
17
+ appearance?: Appearance;
18
+ filters?: Filters;
19
+ pageSize?: number;
20
+ /** Receives the export text; default: the system share sheet. Write it to a file with your file library if needed. */
21
+ onExport?: (text: string, format: string) => void;
22
+ /** Open the feed stream: "N new events" while the app is in the foreground. */
23
+ live?: boolean;
24
+ /** Base64 AES-256 key that opens client-sealed (`$wt_cse`) values on the device; it never leaves the app. */
25
+ sealKey?: string;
26
+ /** Your app's URL for event permalinks (e.g. `myapp://activity`); enables "Share link" in the event sheet. */
27
+ linkBase?: string;
28
+ /** Receives a permalink to share; default: the system share sheet. */
29
+ onShareLink?: (url: string, event: ActivityEvent) => void;
30
+ /** A permalink to open (from your deep-link handler); the event sheet opens on it. */
31
+ link?: string | null;
32
+ style?: ViewStyle;
33
+ }
34
+
35
+ /** The end user's account activity log: search, filters, saved views, export, verify badge and an event sheet. */
36
+ export function ActivityLog(p: ActivityLogProps) {
37
+ const client = useMemo(() => p.client ?? new ActivityClient(p.options!), [p.client, p.options]);
38
+ const a = p.appearance ?? {};
39
+ const st = useActivityLog(client, a, p.filters, p.pageSize, p.live);
40
+ const device = useColorScheme();
41
+ const c = resolveColors(st.theme, a, isDark(st.theme, a, device));
42
+ const [open, setOpen] = useState<ActivityEvent | null>(null);
43
+ const [sheet, setSheet] = useState<'filters' | 'views' | null>(null);
44
+ const [q, setQ] = useState(p.filters?.q ?? '');
45
+ const s = st.strings, rtl = isRtl(st.locale);
46
+ useEffect(() => {
47
+ const l = p.link ? parseLink(p.link) : null;
48
+ if (l) void st.openEvent(l.id, l.at).then((e) => e && setOpen(e));
49
+ }, [p.link]); // eslint-disable-line react-hooks/exhaustive-deps
50
+ const share = p.linkBase || p.onShareLink ? (e: ActivityEvent) => {
51
+ const url = eventLink(p.linkBase ?? '', e);
52
+ if (p.onShareLink) p.onShareLink(url, e); else void Share.share({ message: url }).catch(() => {});
53
+ } : undefined;
54
+ const sections = useMemo(() => {
55
+ const m = new Map<string, ActivityEvent[]>();
56
+ for (const e of st.events) {
57
+ const k = fmtDate(e.occurred_at, st.locale, st.timeZone, { dateStyle: 'full' });
58
+ (m.get(k) ?? m.set(k, []).get(k)!).push(e);
59
+ }
60
+ return [...m].map(([title, data]) => ({ title, data }));
61
+ }, [st.events, st.locale, st.timeZone]);
62
+ const exportNow = async () => {
63
+ st.setNote(s.exporting!);
64
+ const t = await st.exportText('csv');
65
+ if (t == null) return;
66
+ st.setNote(null);
67
+ if (p.onExport) p.onExport(t, 'csv'); else await Share.share({ message: t, title: 'activity.csv' }).catch(() => {});
68
+ };
69
+ // a title set by the theme or the app wins, then the brand name, then the built-in (translated) title
70
+ const custom = s.title !== pickStrings(undefined, st.locale).title;
71
+ const title = custom ? s.title : st.theme?.brandName ?? s.title;
72
+
73
+ return (
74
+ <View style={[{ flex: 1, backgroundColor: c.bg, direction: rtl ? 'rtl' : 'ltr' }, p.style]}>
75
+ {st.theme?.environmentLabel ? <Text accessibilityRole="text" style={x.env}>{st.theme.environmentLabel}</Text> : null}
76
+ <View style={x.header}>
77
+ <Text accessibilityRole="header" style={[x.title, { color: c.fg }]}>{title}</Text>
78
+ {st.can('verify') ? <VerifyBadge st={st} c={c} /> : null}
79
+ <HeaderButton c={c} label={s.filters!} onPress={() => setSheet('filters')} />
80
+ <HeaderButton c={c} label={s.views!} onPress={() => { setSheet('views'); void st.loadViews(); }} />
81
+ {st.can('export') ? <HeaderButton c={c} label={s.export!} onPress={() => void exportNow()} /> : null}
82
+ </View>
83
+ <TextInput
84
+ value={q} onChangeText={setQ} onSubmitEditing={() => st.setFilters({ ...st.filters, q })} placeholder={s.search} placeholderTextColor={c.muted}
85
+ accessibilityLabel={s.search} autoCorrect={false} autoCapitalize="none" returnKeyType="search"
86
+ style={[x.search, { color: c.fg, borderColor: c.border, borderRadius: c.radius, textAlign: rtl ? 'right' : 'left' }]}
87
+ />
88
+ <Chips st={st} c={c} onChange={setQ} />
89
+ {st.histogram.length > 1 ? <Sparkline st={st} c={c} /> : null}
90
+ {st.fresh ? (
91
+ <Pressable accessibilityRole="button" onPress={st.clearFresh} style={[x.fresh, { backgroundColor: c.accent, borderRadius: c.radius }]}>
92
+ <Text style={{ color: '#fff', fontWeight: '600' }}>{fmt(s.newEvents!, { n: st.fresh })}</Text>
93
+ </Pressable>
94
+ ) : null}
95
+ {st.offline ? <Text style={[x.note, { color: c.muted }]}>{s.offline}</Text> : null}
96
+ {st.note ? <Text accessibilityLiveRegion="polite" onPress={() => st.setNote(null)} style={[x.note, { color: c.muted }]}>{st.note}</Text> : null}
97
+ <SectionList
98
+ sections={sections}
99
+ keyExtractor={(e) => e.id}
100
+ renderSectionHeader={({ section }) => <Text accessibilityRole="header" style={[x.day, { color: c.muted, backgroundColor: c.bg }]}>{section.title}</Text>}
101
+ renderItem={({ item }) => <Row e={item} st={st} c={c} onPress={() => setOpen(item)} />}
102
+ onEndReached={st.loadMore}
103
+ onEndReachedThreshold={0.5}
104
+ refreshControl={<RefreshControl refreshing={st.loading && st.events.length > 0} onRefresh={st.reload} tintColor={c.accent} />}
105
+ ListFooterComponent={<Footer st={st} c={c} clear={() => { setQ(''); st.setFilters({}); }} />}
106
+ />
107
+ <EventDetail event={open} st={st} c={c} onClose={() => setOpen(null)} sealKey={p.sealKey} onShare={share} />
108
+ <FiltersSheet visible={sheet === 'filters'} st={st} c={c} onClose={() => setSheet(null)} />
109
+ <ViewsSheet visible={sheet === 'views'} st={st} c={c} onClose={() => setSheet(null)} onApply={(v) => setQ(v.q)} />
110
+ </View>
111
+ );
112
+ }
113
+
114
+ function HeaderButton({ c, label, onPress }: { c: Colors; label: string; onPress: () => void }) {
115
+ return (
116
+ <Pressable accessibilityRole="button" accessibilityLabel={label} onPress={onPress} hitSlop={8} style={x.hb}>
117
+ <Text style={{ color: c.accent, fontSize: 15 }}>{label}</Text>
118
+ </Pressable>
119
+ );
120
+ }
121
+
122
+ function Chips({ st, c, onChange }: { st: ActivityLogState; c: Colors; onChange: (q: string) => void }) {
123
+ const terms = tokenize(st.filters.q ?? '');
124
+ if (!terms.length) return null;
125
+ return (
126
+ <View style={x.chips}>
127
+ {terms.map((t, i) => {
128
+ const label = chipText(t, st.strings.not);
129
+ return (
130
+ <Pressable key={`${i}:${t.raw}`} accessibilityRole="button" accessibilityLabel={`${st.strings.removeFilter} ${label}`}
131
+ onPress={() => { const q = removeTerm(st.filters.q ?? '', i); onChange(q); st.setFilters({ ...st.filters, q }); }}
132
+ style={[x.chip, { borderColor: c.border }]}>
133
+ <Text style={{ color: c.fg, fontSize: 12 }}>{label} ×</Text>
134
+ </Pressable>
135
+ );
136
+ })}
137
+ </View>
138
+ );
139
+ }
140
+
141
+ function Row({ e, st, c, onPress }: { e: ActivityEvent; st: ActivityLogState; c: Colors; onPress: () => void }) {
142
+ const s = st.strings, t = st.theme;
143
+ const tone = t?.actions?.[e.action]?.tone ?? (e.severity === 'critical' || e.outcome === 'denied' || e.outcome === 'failure' ? 'danger' : '');
144
+ const line = headline(e, t, s);
145
+ const abs = fmtDate(e.occurred_at, st.locale, st.timeZone);
146
+ const badges = [
147
+ e.on_behalf_of && t?.showImpersonation !== false ? s.viaSupport : null,
148
+ e.outcome && e.outcome !== 'success' ? e.outcome : null,
149
+ e.severity === 'warning' || e.severity === 'critical' ? e.severity : null,
150
+ ].filter((b): b is string => !!b);
151
+ return (
152
+ <Pressable accessibilityRole="button" accessibilityLabel={[line, ...badges, abs].join(', ')} accessibilityHint={s.rowHint}
153
+ onPress={onPress} style={[x.row, { borderColor: c.border, paddingVertical: c.compact ? 6 : 12 }]}>
154
+ <View style={{ flex: 1 }}>
155
+ <Text style={{ color: tone === 'danger' ? c.danger : c.fg, fontSize: 15, fontWeight: '500' }}>{line}</Text>
156
+ {badges.length ? <View style={x.badges}>{badges.map((b) => <Text key={b} style={[x.badge, { color: c.danger, borderColor: c.border }]}>{b}</Text>)}</View> : null}
157
+ {t?.showIp && (e.context?.ip ?? e.ip) ? <Text style={{ color: c.muted, fontSize: 12 }}>{e.context?.ip ?? e.ip}</Text> : null}
158
+ {t?.showLocation && e.context?.country ? <Text style={{ color: c.muted, fontSize: 12 }}>{e.context.country}</Text> : null}
159
+ </View>
160
+ <Text style={{ color: c.muted, fontSize: 12 }}>{st.time === 'relative' ? relTime(e.occurred_at, s) : fmtDate(e.occurred_at, st.locale, st.timeZone)}</Text>
161
+ </Pressable>
162
+ );
163
+ }
164
+
165
+ function Footer({ st, c, clear }: { st: ActivityLogState; c: Colors; clear: () => void }) {
166
+ const s = st.strings;
167
+ if (st.error) {
168
+ return (
169
+ <View accessibilityRole="alert" style={x.center}>
170
+ <Text style={{ color: c.danger }}>{st.error}</Text>
171
+ <HeaderButton c={c} label={s.retry!} onPress={st.events.length ? st.loadMore : st.reload} />
172
+ </View>
173
+ );
174
+ }
175
+ if (st.loading) return <ActivityIndicator style={x.center} color={c.accent} accessibilityLabel={s.loading} />;
176
+ if (st.events.length) return null;
177
+ const filtered = isFiltered(st.filters);
178
+ return (
179
+ <View style={x.center}>
180
+ <Text style={{ color: c.muted }}>{filtered ? s.noMatch : s.emptyState}</Text>
181
+ {filtered ? <HeaderButton c={c} label={s.clearFilters!} onPress={clear} /> : null}
182
+ </View>
183
+ );
184
+ }
185
+
186
+ function VerifyBadge({ st, c }: { st: ActivityLogState; c: Colors }) {
187
+ const s = st.strings, v = st.verify;
188
+ const [label, color] = v.state === 'running' ? [s.verifying!, c.muted]
189
+ : v.state === 'idle' ? [s.verify!, c.accent]
190
+ : v.verdict.ok && v.verdict.signature !== false ? [v.verdict.signature ? s.verifiedBadge! : s.unverifiedBadge!, v.verdict.signature ? '#15803d' : c.muted]
191
+ : [s.tamperedBadge!, c.danger];
192
+ const full = v.state !== 'done' ? label
193
+ : v.verdict.ok && v.verdict.signature ? fmt(s.verified!, { n: v.verdict.checked })
194
+ : v.verdict.ok && v.verdict.signature === null ? fmt(s.verifiedHashes!, { n: v.verdict.checked })
195
+ : fmt(s.tampered!, { n: v.verdict.firstBadSeq ?? '?' });
196
+ return (
197
+ <Pressable accessibilityRole="button" accessibilityLabel={full} accessibilityState={{ busy: v.state === 'running' }}
198
+ disabled={v.state === 'running'} onPress={() => void st.verifyChain()} style={[x.vb, { borderColor: color }]}>
199
+ <Text style={{ color, fontSize: 12, fontWeight: '600' }}>{label}</Text>
200
+ </Pressable>
201
+ );
202
+ }
203
+
204
+ function Sparkline({ st, c }: { st: ActivityLogState; c: Colors }) {
205
+ const top = Math.max(1, ...st.histogram.map((b) => b.count));
206
+ return (
207
+ <View accessible accessibilityLabel={st.histogram.map((b) => `${b.at.slice(0, 10)}: ${b.count}`).join(', ')} style={x.spark}>
208
+ {st.histogram.map((b) => <View key={b.at} style={{ flex: 1, marginHorizontal: 0.5, height: `${Math.max(4, (b.count / top) * 100)}%`, backgroundColor: c.accent, opacity: 0.6 }} />)}
209
+ </View>
210
+ );
211
+ }
212
+
213
+ const x = StyleSheet.create({
214
+ env: { backgroundColor: '#fef3c7', color: '#78350f', fontWeight: '600', textAlign: 'center', padding: 4 },
215
+ header: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, paddingTop: 12, paddingBottom: 8, gap: 12 },
216
+ title: { flex: 1, fontSize: 20, fontWeight: '600' },
217
+ hb: { paddingVertical: 4 },
218
+ search: { marginHorizontal: 16, borderWidth: StyleSheet.hairlineWidth, paddingHorizontal: 10, paddingVertical: 8, fontSize: 15 },
219
+ chips: { flexDirection: 'row', flexWrap: 'wrap', gap: 6, paddingHorizontal: 16, paddingTop: 8 },
220
+ chip: { borderWidth: StyleSheet.hairlineWidth, borderRadius: 12, paddingHorizontal: 8, paddingVertical: 3 },
221
+ note: { paddingHorizontal: 16, paddingTop: 6, fontSize: 13 },
222
+ day: { paddingHorizontal: 16, paddingTop: 14, paddingBottom: 4, fontSize: 12, fontWeight: '600', textTransform: 'uppercase' },
223
+ row: { flexDirection: 'row', gap: 12, paddingHorizontal: 16, borderBottomWidth: StyleSheet.hairlineWidth },
224
+ badges: { flexDirection: 'row', gap: 6, marginTop: 4 },
225
+ badge: { fontSize: 11, borderWidth: StyleSheet.hairlineWidth, borderRadius: 9, paddingHorizontal: 6 },
226
+ center: { alignItems: 'center', padding: 24, gap: 8 },
227
+ vb: { borderWidth: 1, borderRadius: 10, paddingHorizontal: 8, paddingVertical: 2 },
228
+ fresh: { alignSelf: 'center', paddingHorizontal: 14, paddingVertical: 6, marginTop: 8 },
229
+ spark: { flexDirection: 'row', alignItems: 'flex-end', height: 24, marginHorizontal: 16, marginTop: 8 },
230
+ });