@proxze/kyc-react-native 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.
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProxzeKycSession = void 0;
4
+ const client_1 = require("./client");
5
+ const queue_1 = require("./queue");
6
+ const storage_1 = require("./storage");
7
+ const nightWindow_1 = require("./nightWindow");
8
+ // Read from the manifest so the version reported to the server never drifts
9
+ // from the published one (resolves to the package root from both src/ and dist/).
10
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
11
+ const SDK_VERSION = require('../package.json').version;
12
+ const FLUSH_INTERVAL_MS = 60000;
13
+ /**
14
+ * Orchestrates one verification on the device:
15
+ *
16
+ * bootstrap → consent → permissions → (optional address pin) → fence
17
+ * registration → night tracking → evidence uploads → done.
18
+ *
19
+ * Night tracking is dual-mode, matching the service's HYBRID evaluator:
20
+ * geofence enter/exit transitions arrive from the OS whenever they happen,
21
+ * and a scheduler requests position samples on the 30-minute marks inside
22
+ * the 12AM–5AM window plus one morning check after it closes. Whichever
23
+ * signals survive the device's battery policies, the server can score.
24
+ */
25
+ class ProxzeKycSession {
26
+ constructor(options) {
27
+ var _a, _b;
28
+ this.state = 'idle';
29
+ this.client = new client_1.ProxzeKycClient({
30
+ baseUrl: options.baseUrl,
31
+ sessionToken: options.sessionToken,
32
+ });
33
+ this.storage = (_a = options.storage) !== null && _a !== void 0 ? _a : (0, storage_1.defaultStorage)();
34
+ this.events = (_b = options.events) !== null && _b !== void 0 ? _b : {};
35
+ this.deviceId = options.deviceId;
36
+ if (options.adapter) {
37
+ this.adapter = options.adapter;
38
+ }
39
+ else {
40
+ // Deferred so simply constructing a session never throws on a missing
41
+ // optional peer — only starting tracking needs the location stack.
42
+ this.adapterFactory = () => {
43
+ const { BackgroundGeolocationAdapter,
44
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
45
+ } = require('./location/backgroundGeolocationAdapter');
46
+ return new BackgroundGeolocationAdapter();
47
+ };
48
+ }
49
+ }
50
+ getState() {
51
+ return this.state;
52
+ }
53
+ getSession() {
54
+ return this.session;
55
+ }
56
+ /** Fetch server-side state and derive the local step. */
57
+ async bootstrap() {
58
+ var _a, _b;
59
+ const session = await this.client.getSession();
60
+ this.session = session;
61
+ (_b = (_a = this.events).onSessionUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, session);
62
+ if (session.consentRequired)
63
+ this.setState('awaiting_consent');
64
+ else if (session.addressConfirmationRequired)
65
+ this.setState('awaiting_address_pin');
66
+ else
67
+ this.setState('awaiting_permissions');
68
+ return session;
69
+ }
70
+ /** Record NDPR consent. Must precede any location work. */
71
+ async grantConsent(consentVersion) {
72
+ var _a;
73
+ await this.client.grantConsent(consentVersion, this.deviceId);
74
+ await this.refresh();
75
+ this.setState(((_a = this.session) === null || _a === void 0 ? void 0 : _a.addressConfirmationRequired)
76
+ ? 'awaiting_address_pin'
77
+ : 'awaiting_permissions');
78
+ }
79
+ /**
80
+ * Re-centre the fence on the customer's pin — required when the declared
81
+ * address geocoded too coarsely for a 100m fence.
82
+ */
83
+ async confirmAddress(pin) {
84
+ await this.client.confirmAddress({
85
+ lat: pin.lat,
86
+ lng: pin.lng,
87
+ accuracyM: pin.accuracyM,
88
+ });
89
+ await this.refresh();
90
+ this.setState('awaiting_permissions');
91
+ }
92
+ /**
93
+ * Request permissions, register the fence and begin the night loop.
94
+ *
95
+ * Returns the granted permission state so the app can route the customer:
96
+ * `denied` → explain and re-prompt; `precise: false` → walk them to
97
+ * settings (approximate location cannot confirm a 100m fence);
98
+ * `granted_when_in_use` → warn that overnight confirmation is unlikely.
99
+ * Tracking starts on anything better than an outright denial — degraded
100
+ * signals still feed the server's hybrid evaluator.
101
+ */
102
+ async startTracking() {
103
+ if (!this.session)
104
+ await this.bootstrap();
105
+ const session = this.session;
106
+ if (session.consentRequired) {
107
+ throw new Error('Consent must be granted before tracking starts');
108
+ }
109
+ if (!session.geofence) {
110
+ throw new Error('Session has no geofence — confirm the address first');
111
+ }
112
+ const adapter = this.resolveAdapter();
113
+ const permission = await adapter.requestPermissions();
114
+ if (permission.grade === 'denied') {
115
+ this.emitError(new Error('Location permission denied'));
116
+ return permission;
117
+ }
118
+ this.queue = new queue_1.OfflineEventQueue(this.storage, session.kycId);
119
+ await adapter.registerGeofence(session.geofence);
120
+ await this.client.acknowledgeGeofence().catch(() => undefined);
121
+ this.unsubscribe = adapter.onEvent((event) => {
122
+ void this.handleEvent(event);
123
+ });
124
+ await adapter.start();
125
+ this.scheduleNextSample();
126
+ this.flushTimer = setInterval(() => void this.flushQueue(), FLUSH_INTERVAL_MS);
127
+ this.setState('tracking');
128
+ return permission;
129
+ }
130
+ /** Stop monitoring and clear the fence (verification finished or abandoned). */
131
+ async stopTracking() {
132
+ var _a;
133
+ if (this.sampleTimer)
134
+ clearTimeout(this.sampleTimer);
135
+ if (this.flushTimer)
136
+ clearInterval(this.flushTimer);
137
+ this.sampleTimer = undefined;
138
+ this.flushTimer = undefined;
139
+ (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
140
+ this.unsubscribe = undefined;
141
+ if (this.adapter) {
142
+ await this.adapter.clearGeofence().catch(() => undefined);
143
+ await this.adapter.stop().catch(() => undefined);
144
+ }
145
+ if (this.state === 'tracking')
146
+ this.setState('stopped');
147
+ }
148
+ /** NDPR — stops collection immediately, server-side and locally. */
149
+ async withdrawConsent() {
150
+ await this.client.withdrawConsent();
151
+ await this.stopTracking();
152
+ }
153
+ async uploadUtilityBill(file, documentType) {
154
+ const result = await this.client.uploadUtilityBill(file, documentType);
155
+ await this.refresh().catch(() => undefined);
156
+ return result;
157
+ }
158
+ async uploadVideo(file, meta) {
159
+ const result = await this.client.uploadVideo(file, meta);
160
+ await this.refresh().catch(() => undefined);
161
+ return result;
162
+ }
163
+ /** Restart the window after a missed night (FLOW-03). */
164
+ async restart() {
165
+ const result = await this.client.restart();
166
+ await this.refresh().catch(() => undefined);
167
+ return result;
168
+ }
169
+ async refresh() {
170
+ var _a, _b;
171
+ const session = await this.client.getSession();
172
+ this.session = session;
173
+ (_b = (_a = this.events).onSessionUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, session);
174
+ return session;
175
+ }
176
+ /**
177
+ * Tracking health for a status screen or support tooling: what the OS is
178
+ * actually letting us do, and whether events are reaching the server.
179
+ */
180
+ async diagnostics() {
181
+ var _a, _b;
182
+ let permission = null;
183
+ try {
184
+ permission = await this.resolveAdapter().checkPermissions();
185
+ }
186
+ catch {
187
+ /* adapter not available yet */
188
+ }
189
+ return {
190
+ state: this.state,
191
+ permission,
192
+ queuedEvents: this.queue ? await this.queue.size() : 0,
193
+ sessionStatus: (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : null,
194
+ };
195
+ }
196
+ // ---------------------------------------------------------------------------
197
+ resolveAdapter() {
198
+ if (!this.adapter)
199
+ this.adapter = this.adapterFactory();
200
+ return this.adapter;
201
+ }
202
+ async handleEvent(event) {
203
+ if (!this.queue)
204
+ return;
205
+ // Re-label a generic sample by when it happened: inside the window it is a
206
+ // ping the evaluator counts; in the grace slot it is the morning check.
207
+ let type = event.type;
208
+ if (type === 'ping' && (0, nightWindow_1.isInMorningCheckSlot)(event.recordedAt)) {
209
+ type = 'morning_check';
210
+ }
211
+ await this.queue.enqueue({ ...event, type });
212
+ // Transitions matter to the verdict — try to deliver them promptly rather
213
+ // than waiting out the flush interval. Failure is fine; the queue holds it.
214
+ if (type !== 'heartbeat')
215
+ void this.flushQueue();
216
+ }
217
+ scheduleNextSample() {
218
+ const delay = Math.max((0, nightWindow_1.msUntilNextSample)(), 15000);
219
+ this.sampleTimer = setTimeout(async () => {
220
+ try {
221
+ if (this.adapter &&
222
+ ((0, nightWindow_1.isWithinNightWindow)(new Date()) || (0, nightWindow_1.isInMorningCheckSlot)(new Date()))) {
223
+ const position = await this.adapter.getCurrentPosition();
224
+ await this.handleEvent(position);
225
+ }
226
+ }
227
+ catch {
228
+ /* position unavailable — the fence transitions still cover us */
229
+ }
230
+ finally {
231
+ if (this.state === 'tracking')
232
+ this.scheduleNextSample();
233
+ }
234
+ }, delay);
235
+ }
236
+ async flushQueue() {
237
+ var _a;
238
+ if (!this.queue)
239
+ return;
240
+ try {
241
+ const result = await this.queue.flush(this.client, {
242
+ platform: detectPlatform(),
243
+ sdkVersion: SDK_VERSION,
244
+ deviceId: this.deviceId,
245
+ });
246
+ if (result.sent > 0)
247
+ await this.refresh().catch(() => undefined);
248
+ const status = (_a = this.session) === null || _a === void 0 ? void 0 : _a.status;
249
+ if (status && status !== 'initiated' && status !== 'in_progress') {
250
+ await this.stopTracking();
251
+ this.setState('completed');
252
+ }
253
+ }
254
+ catch (err) {
255
+ if (err instanceof client_1.ProxzeKycError && err.isSessionClosed) {
256
+ // Decision issued or token expired — stop cleanly, keep the queue for
257
+ // the audit trail rather than hammering a closed session.
258
+ await this.stopTracking();
259
+ this.setState('completed');
260
+ return;
261
+ }
262
+ this.emitError(err);
263
+ }
264
+ }
265
+ setState(state) {
266
+ var _a, _b;
267
+ if (this.state === state)
268
+ return;
269
+ this.state = state;
270
+ (_b = (_a = this.events).onStateChange) === null || _b === void 0 ? void 0 : _b.call(_a, state);
271
+ }
272
+ emitError(error) {
273
+ var _a, _b;
274
+ (_b = (_a = this.events).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
275
+ }
276
+ }
277
+ exports.ProxzeKycSession = ProxzeKycSession;
278
+ const detectPlatform = () => {
279
+ try {
280
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
281
+ const { Platform } = require('react-native');
282
+ return (Platform === null || Platform === void 0 ? void 0 : Platform.OS) === 'ios' || (Platform === null || Platform === void 0 ? void 0 : Platform.OS) === 'android'
283
+ ? Platform.OS
284
+ : undefined;
285
+ }
286
+ catch {
287
+ return undefined;
288
+ }
289
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Persistence for the offline event queue.
3
+ *
4
+ * AsyncStorage is the default when the host app has it installed; anything
5
+ * implementing the three methods works (MMKV, SQLite wrappers, secure storage).
6
+ * The in-memory fallback keeps the SDK functional in tests and in apps that
7
+ * haven't added a storage lib yet — events then survive offline periods but
8
+ * not a process kill, which is degraded, not broken.
9
+ */
10
+ export interface StorageAdapter {
11
+ getItem(key: string): Promise<string | null>;
12
+ setItem(key: string, value: string): Promise<void>;
13
+ removeItem(key: string): Promise<void>;
14
+ }
15
+ export declare const memoryStorage: () => StorageAdapter;
16
+ /** `@react-native-async-storage/async-storage` when present, else memory. */
17
+ export declare const defaultStorage: () => StorageAdapter;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultStorage = exports.memoryStorage = void 0;
4
+ const memoryStorage = () => {
5
+ const store = new Map();
6
+ return {
7
+ async getItem(key) {
8
+ var _a;
9
+ return (_a = store.get(key)) !== null && _a !== void 0 ? _a : null;
10
+ },
11
+ async setItem(key, value) {
12
+ store.set(key, value);
13
+ },
14
+ async removeItem(key) {
15
+ store.delete(key);
16
+ },
17
+ };
18
+ };
19
+ exports.memoryStorage = memoryStorage;
20
+ /** `@react-native-async-storage/async-storage` when present, else memory. */
21
+ const defaultStorage = () => {
22
+ var _a;
23
+ try {
24
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
25
+ const asyncStorage = require('@react-native-async-storage/async-storage');
26
+ const impl = (_a = asyncStorage === null || asyncStorage === void 0 ? void 0 : asyncStorage.default) !== null && _a !== void 0 ? _a : asyncStorage;
27
+ if (impl === null || impl === void 0 ? void 0 : impl.getItem)
28
+ return impl;
29
+ }
30
+ catch {
31
+ /* optional peer not installed */
32
+ }
33
+ return (0, exports.memoryStorage)();
34
+ };
35
+ exports.defaultStorage = defaultStorage;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Wire types for the `/v2/sdk/*` surface of proxze-kyc-service.
3
+ *
4
+ * Field names mirror the HTTP contract verbatim (camelCase) — one file to
5
+ * diff against the service's serializers when the API changes.
6
+ */
7
+ export type KycStatus = 'initiated' | 'in_progress' | 'partial' | 'verified' | 'failed' | 'cancelled';
8
+ export type LocationEventType = 'enter' | 'exit' | 'dwell' | 'ping' | 'morning_check' | 'heartbeat';
9
+ export interface GeofenceConfig {
10
+ lat: number;
11
+ lng: number;
12
+ radiusM: number;
13
+ }
14
+ export interface SdkSession {
15
+ kycId: string;
16
+ status: KycStatus;
17
+ customerName: string;
18
+ declaredAddress: string;
19
+ expiresAt: string;
20
+ consentRequired: boolean;
21
+ /** True when the geocode was too coarse — ask the customer to drop a pin. */
22
+ addressConfirmationRequired: boolean;
23
+ geofence: GeofenceConfig | null;
24
+ requirements: {
25
+ utilityBill: {
26
+ required: boolean;
27
+ status: string;
28
+ acceptedTypes: string[];
29
+ maxSizeBytes: number;
30
+ };
31
+ video: {
32
+ required: boolean;
33
+ status: string;
34
+ daysRecorded: number;
35
+ };
36
+ nights: {
37
+ required: number;
38
+ confirmed: number;
39
+ missed: number;
40
+ };
41
+ };
42
+ restartsRemaining: number;
43
+ nightWindow: {
44
+ startHour: number;
45
+ endHour: number;
46
+ timezone: string;
47
+ };
48
+ }
49
+ export interface LocationEventInput {
50
+ /** Client-generated id; the server dedupes on it, so replays are safe. */
51
+ clientEventId: string;
52
+ type: LocationEventType;
53
+ lat?: number;
54
+ lng?: number;
55
+ accuracyM?: number;
56
+ /** Device timestamp, ISO 8601. */
57
+ recordedAt: string;
58
+ isMocked?: boolean;
59
+ batteryLevel?: number;
60
+ isCharging?: boolean;
61
+ }
62
+ export interface IngestResponse {
63
+ accepted: number;
64
+ duplicates: number;
65
+ rejected: number;
66
+ sessionStatus: KycStatus;
67
+ }
68
+ export interface ConsentResponse {
69
+ consented: boolean;
70
+ grantedAt: string;
71
+ }
72
+ export interface ConfirmAddressResponse {
73
+ geofence: GeofenceConfig;
74
+ }
75
+ export interface BillUploadResponse {
76
+ documentId: string;
77
+ documentType: string;
78
+ documentDate: string | null;
79
+ ocrConfidence: number | null;
80
+ matchScore: number | null;
81
+ matchStatus: 'MATCH' | 'PARTIAL' | 'MISMATCH' | null;
82
+ status: string;
83
+ rejectionReason: string | null;
84
+ canRetry: boolean;
85
+ }
86
+ export interface VideoUploadResponse {
87
+ videoId: string;
88
+ dayNumber: number;
89
+ status: string;
90
+ withinGeofence: boolean;
91
+ distanceFromAddressM: number | null;
92
+ livenessStatus: string;
93
+ rejectionReason: string | null;
94
+ }
95
+ export interface RestartResponse {
96
+ kycId: string;
97
+ restartCount: number;
98
+ restartsRemaining: number;
99
+ status: KycStatus;
100
+ }
101
+ /** A file as React Native's fetch/FormData understands it. */
102
+ export interface RNFile {
103
+ uri: string;
104
+ name: string;
105
+ type: string;
106
+ }
107
+ export interface VideoMeta {
108
+ dayNumber: number;
109
+ durationSec: number;
110
+ lat?: number;
111
+ lng?: number;
112
+ accuracyM?: number;
113
+ recordedAt: string;
114
+ isMocked?: boolean;
115
+ }
116
+ export type UtilityDocumentType = 'electricity_bill' | 'water_bill' | 'cable_bill' | 'tenancy_agreement';
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ /**
3
+ * Wire types for the `/v2/sdk/*` surface of proxze-kyc-service.
4
+ *
5
+ * Field names mirror the HTTP contract verbatim (camelCase) — one file to
6
+ * diff against the service's serializers when the API changes.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@proxze/kyc-react-native",
3
+ "version": "0.1.0",
4
+ "description": "Proxze Enterprise Address KYC SDK for React Native — passive geofence night verification, consent, evidence upload.",
5
+ "author": "Sage Grey Technologies Limited",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "keywords": [
8
+ "react-native",
9
+ "kyc",
10
+ "address-verification",
11
+ "geofence",
12
+ "geolocation",
13
+ "proxze"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Sage-Grey-Technologies/proxze-kyc-react-native.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/Sage-Grey-Technologies/proxze-kyc-react-native/issues"
21
+ },
22
+ "homepage": "https://github.com/Sage-Grey-Technologies/proxze-kyc-react-native#readme",
23
+ "main": "dist/index.js",
24
+ "types": "dist/index.d.ts",
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
35
+ "typecheck": "tsc --noEmit -p tsconfig.json",
36
+ "test": "jest",
37
+ "prepack": "yarn build",
38
+ "prepublishOnly": "yarn typecheck && yarn test"
39
+ },
40
+ "peerDependencies": {
41
+ "react": ">=17.0.0",
42
+ "react-native": ">=0.70.0",
43
+ "react-native-background-geolocation": ">=4.0.0",
44
+ "@react-native-async-storage/async-storage": ">=1.17.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "react-native-background-geolocation": {
48
+ "optional": true
49
+ },
50
+ "@react-native-async-storage/async-storage": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "devDependencies": {
55
+ "@types/jest": "^29.5.14",
56
+ "@types/react": "^18.3.0",
57
+ "jest": "^29.7.0",
58
+ "react": "^18.3.1",
59
+ "ts-jest": "^29.2.5",
60
+ "typescript": "^5.7.3"
61
+ },
62
+ "jest": {
63
+ "preset": "ts-jest",
64
+ "testEnvironment": "node",
65
+ "testMatch": [
66
+ "**/__tests__/**/*.spec.ts"
67
+ ]
68
+ }
69
+ }