@leisuresaas/react-native 0.6.4 → 0.6.5-dev.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leisuresaas/react-native",
3
- "version": "0.6.4",
3
+ "version": "0.6.5-dev.1",
4
4
  "description": "React Native SDK for LeisureSaas: OAuth, Public Ads/App Config, Drive User Plane (publishable keys). Frontend-only — no Integration Key.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,35 @@
1
+ import { authGetItem, authSetItem } from "./auth-storage";
2
+
3
+ const deviceIdKey = "leisuresaas.device_id";
4
+ let cached = "";
5
+
6
+ function newId(): string {
7
+ return globalThis.crypto?.randomUUID?.() ?? `rn-${Date.now()}-${Math.random().toString(36).slice(2)}`;
8
+ }
9
+
10
+ /**
11
+ * A stable id for this app install, sent with sign-ins so the platform can tell devices apart
12
+ * (session limits, "signed-in devices"). Kept in secure storage; when storage is unavailable it
13
+ * lasts for the app run.
14
+ */
15
+ export async function appDeviceId(): Promise<string> {
16
+ if (cached) {
17
+ return cached;
18
+ }
19
+ try {
20
+ const stored = await authGetItem(deviceIdKey);
21
+ if (stored) {
22
+ cached = stored;
23
+ return cached;
24
+ }
25
+ } catch {
26
+ // storage unavailable: fall back to an id for this run
27
+ }
28
+ cached = newId();
29
+ try {
30
+ await authSetItem(deviceIdKey, cached);
31
+ } catch {
32
+ // keep the in-memory id
33
+ }
34
+ return cached;
35
+ }
package/src/errors.ts CHANGED
@@ -29,6 +29,11 @@ export const ErrorReason = {
29
29
  SubscriptionActiveOtherSource: "SUBSCRIPTION_ACTIVE_OTHER_SOURCE",
30
30
  // The token's workspace is no longer the user's active one: refresh the token, then retry.
31
31
  ActiveWorkspaceChanged: "ACTIVE_WORKSPACE_CHANGED",
32
+ // Sessions: signed out because the user signed in on another device / a sign-in refused because
33
+ // the product allows fewer devices / signed out from another device or by an operator.
34
+ SessionReplaced: "SESSION_REPLACED",
35
+ SessionLimitReached: "SESSION_LIMIT_REACHED",
36
+ SessionRevoked: "SESSION_REVOKED",
32
37
  // Drive uploads: the user's plan storage is used up / the product's storage is full / the file is
33
38
  // over the product's single-file limit.
34
39
  QuotaExceeded: "QUOTA_EXCEEDED",
package/src/index.ts CHANGED
@@ -95,8 +95,13 @@ export {
95
95
  requestProductPasswordReset,
96
96
  startPlatformAuthorize,
97
97
  unbindPlatformAccount,
98
+ heartbeat,
99
+ listSessions,
100
+ revokeSession,
101
+ startHeartbeat,
98
102
  } from "./public-auth";
99
- export type { AuthTokens, ProductAuthTokens, PublicAuthContext } from "./public-auth";
103
+ export type { AuthTokens, HeartbeatOptions, ProductAuthTokens, PublicAuthContext, UserSession } from "./public-auth";
104
+ export { appDeviceId } from "./device-id";
100
105
  export { getPublicAdsFeed, recordPublicAdEvents } from "./public-ads";
101
106
  export type { PublicAdsRequestContext } from "./public-ads";
102
107
  export { getPublicAppConfig } from "./public-app-config";
@@ -1,7 +1,9 @@
1
1
  import * as AuthSession from "expo-auth-session";
2
2
  import * as WebBrowser from "expo-web-browser";
3
+ import { AppState, type AppStateStatus } from "react-native";
3
4
 
4
5
  import { exchangeAuthorizationCode } from "./auth-session";
6
+ import { appDeviceId } from "./device-id";
5
7
  import { PlatformError } from "./errors";
6
8
  import { mobilePlatform } from "./platform";
7
9
  import { applyPublishableKeyHeaders } from "./publishable-key";
@@ -15,6 +17,9 @@ export type PublicAuthContext = {
15
17
  platform?: MobilePlatform | "web";
16
18
  bundleId?: string;
17
19
  origin?: string;
20
+ /** Your app's version and the device model, shown with the user's sessions. */
21
+ appVersion?: string;
22
+ deviceModel?: string;
18
23
  };
19
24
 
20
25
  export type AuthTokens = {
@@ -62,17 +67,25 @@ function authHeaders(ctx: PublicAuthContext, accessToken?: string): Record<strin
62
67
  return headers;
63
68
  }
64
69
 
70
+ async function deviceHeaders(ctx: PublicAuthContext): Promise<Record<string, string>> {
71
+ const headers: Record<string, string> = { "X-Device-Id": await appDeviceId() };
72
+ if (ctx.appVersion?.trim()) headers["X-App-Version"] = ctx.appVersion.trim();
73
+ if (ctx.deviceModel?.trim()) headers["X-Device-Model"] = ctx.deviceModel.trim();
74
+ return headers;
75
+ }
76
+
65
77
  async function publicAuthRequest<T>(
66
78
  ctx: PublicAuthContext,
67
79
  path: string,
68
80
  body?: unknown,
69
81
  accessToken?: string,
82
+ method: "GET" | "POST" = "POST",
70
83
  ): Promise<T> {
71
84
  const url = `${trimSlash(ctx.gatewayUrl)}/v1/public/auth${path}`;
72
85
  const res = await fetch(url, {
73
- method: "POST",
74
- headers: authHeaders(ctx, accessToken),
75
- body: body === undefined ? undefined : JSON.stringify(body),
86
+ method,
87
+ headers: { ...authHeaders(ctx, accessToken), ...(await deviceHeaders(ctx)) },
88
+ body: body === undefined || method === "GET" ? undefined : JSON.stringify(body),
76
89
  });
77
90
  const text = await res.text();
78
91
  if (!res.ok) {
@@ -210,6 +223,117 @@ export async function logout(
210
223
  await publicAuthRequest(ctx, "/logout", { refresh_token: refreshToken ?? "" }, accessToken);
211
224
  }
212
225
 
226
+ /** One of the user's signed-in devices. */
227
+ export type UserSession = {
228
+ id: string;
229
+ /** ios | android | web; empty when the app did not say. */
230
+ platform: string;
231
+ deviceId: string;
232
+ deviceModel: string;
233
+ appVersion: string;
234
+ createdUnix: number;
235
+ lastSeenUnix: number;
236
+ /** The session of this access token. */
237
+ current: boolean;
238
+ online: boolean;
239
+ };
240
+
241
+ type SessionJSON = {
242
+ id?: string;
243
+ platform?: string;
244
+ device_id?: string;
245
+ device_model?: string;
246
+ app_version?: string;
247
+ created_unix?: number;
248
+ last_seen_unix?: number;
249
+ current?: boolean;
250
+ online?: boolean;
251
+ };
252
+
253
+ /** Keeps this device online while the app is open but idle. Other signed-in calls also count. */
254
+ export async function heartbeat(ctx: PublicAuthContext, accessToken: string): Promise<{ lastSeenUnix: number }> {
255
+ const out = await publicAuthRequest<{ last_seen_unix?: number }>(ctx, "/heartbeat", {}, accessToken);
256
+ return { lastSeenUnix: out.last_seen_unix ?? 0 };
257
+ }
258
+
259
+ /** Lists the user's signed-in devices in this product, newest first. */
260
+ export async function listSessions(ctx: PublicAuthContext, accessToken: string): Promise<UserSession[]> {
261
+ const out = await publicAuthRequest<{ sessions?: SessionJSON[] }>(ctx, "/sessions", undefined, accessToken, "GET");
262
+ return (out.sessions ?? []).map((s) => ({
263
+ id: s.id ?? "",
264
+ platform: s.platform ?? "",
265
+ deviceId: s.device_id ?? "",
266
+ deviceModel: s.device_model ?? "",
267
+ appVersion: s.app_version ?? "",
268
+ createdUnix: s.created_unix ?? 0,
269
+ lastSeenUnix: s.last_seen_unix ?? 0,
270
+ current: s.current ?? false,
271
+ online: s.online ?? false,
272
+ }));
273
+ }
274
+
275
+ /** Signs out one of the user's devices ("sign out on other devices"). */
276
+ export async function revokeSession(ctx: PublicAuthContext, accessToken: string, sessionId: string): Promise<void> {
277
+ await publicAuthRequest(ctx, `/sessions/${encodeURIComponent(sessionId)}/revoke`, {}, accessToken);
278
+ }
279
+
280
+ export type HeartbeatOptions = {
281
+ /** Default 60000 ms. */
282
+ intervalMs?: number;
283
+ /**
284
+ * Called once when the session ended elsewhere: SESSION_REPLACED (signed in on another device) or
285
+ * SESSION_REVOKED (signed out from another device). Heartbeats stop; sign the user out.
286
+ */
287
+ onSessionEnded?: (reason: string) => void;
288
+ };
289
+
290
+ /**
291
+ * Sends a heartbeat now and every intervalMs while the app is in the foreground, so the user shows as
292
+ * online. Returns a function that stops it.
293
+ */
294
+ export function startHeartbeat(
295
+ ctx: PublicAuthContext,
296
+ getAccessToken: () => string | undefined | Promise<string | undefined>,
297
+ options: HeartbeatOptions = {},
298
+ ): () => void {
299
+ const intervalMs = options.intervalMs ?? 60_000;
300
+ let stopped = false;
301
+ let appState: AppStateStatus = AppState.currentState;
302
+
303
+ const beat = async () => {
304
+ if (stopped || appState !== "active") {
305
+ return;
306
+ }
307
+ const token = await getAccessToken();
308
+ if (!token) {
309
+ return;
310
+ }
311
+ try {
312
+ await heartbeat(ctx, token);
313
+ } catch (err) {
314
+ const reason = err instanceof PlatformError ? err.reason : "";
315
+ if (reason === "SESSION_REPLACED" || reason === "SESSION_REVOKED") {
316
+ stop();
317
+ options.onSessionEnded?.(reason);
318
+ }
319
+ }
320
+ };
321
+ const sub = AppState.addEventListener("change", (next) => {
322
+ appState = next;
323
+ if (next === "active") {
324
+ void beat();
325
+ }
326
+ });
327
+ const timer = setInterval(() => void beat(), intervalMs);
328
+ function stop() {
329
+ stopped = true;
330
+ clearInterval(timer);
331
+ sub.remove();
332
+ }
333
+ void beat();
334
+ return stop;
335
+ }
336
+
213
337
  export async function deleteAccount(ctx: PublicAuthContext, accessToken: string): Promise<void> {
214
338
  await publicAuthRequest(ctx, "/account/delete", {}, accessToken);
215
339
  }