@quatronic/sdk 0.10.1-test.b120025 → 0.10.1-test.ca61122

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.
@@ -1,6 +1,39 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
 
4
+ interface ServerResolverOptions {
5
+ /** The Qore portal, e.g. `https://portal.qore.app`. Baked into the build. */
6
+ portalUrl: string;
7
+ /** The tenant's slug in the portal. Baked into the build. */
8
+ tenant: string;
9
+ /** This app's module slug in the portal. Baked into the build. */
10
+ module: string;
11
+ /** The portal environment this build belongs to (`stag`, `acc`, `prod`). */
12
+ env: string;
13
+ /**
14
+ * A fixed server for local development (`EXPO_PUBLIC_SERVER_URL` in
15
+ * `mobile/.env.local`). When set, the portal is never asked.
16
+ */
17
+ override?: string;
18
+ }
19
+ interface ServerResolver {
20
+ /** The server's origin, without a trailing slash. Throws `ServerUnavailable` when there is none to give. */
21
+ origin(): Promise<string>;
22
+ /**
23
+ * Report that a request to `failed` did not reach a server (a network error,
24
+ * not an error status). The next `origin()` asks the portal again, at most
25
+ * once a minute; while the portal cannot answer, the old origin stays.
26
+ */
27
+ reportUnreachable(failed: string): void;
28
+ /** The origin known right now, or null before the first answer. Synchronous, for Sentry's trace targets. */
29
+ current(): string | null;
30
+ }
31
+ /** No server is known for this build: the portal does not answer and nothing is cached. */
32
+ declare class ServerUnavailable extends Error {
33
+ readonly reason: "not_found" | "unreachable" | "invalid";
34
+ constructor(reason: "not_found" | "unreachable" | "invalid");
35
+ }
36
+
4
37
  /** What `/api/auth/me` answers to a bearer caller. */
5
38
  interface Me {
6
39
  sub: string;
@@ -20,8 +53,14 @@ type LoginResult = {
20
53
  detail?: string;
21
54
  };
22
55
  interface MobileAuthOptions {
23
- /** The app's own Next server, e.g. `https://shop.acme.qore.app`. The device talks to nothing else. */
24
- serverUrl: string;
56
+ /**
57
+ * Where the app's own Next server is, asked by environment from the portal
58
+ * (`createServerResolver`). The device talks to nothing else. Set this or
59
+ * `serverUrl`.
60
+ */
61
+ server?: ServerResolver;
62
+ /** A fixed server origin instead, e.g. `https://shop.acme.qore.app`. */
63
+ serverUrl?: string;
25
64
  /** Sent as `X-Qore-App-Version` on every request, so server logs say which build called. */
26
65
  appVersion?: string;
27
66
  }
@@ -34,6 +73,7 @@ interface MobileAuth {
34
73
  openPasswordReset(locale: string): Promise<void>;
35
74
  /** Whether a token is stored. Says nothing about whether the server still accepts it. */
36
75
  hasSession(): Promise<boolean>;
76
+ /** The server's origin as known right now; empty before the first answer. */
37
77
  readonly serverUrl: string;
38
78
  }
39
79
 
@@ -108,4 +148,4 @@ declare function Can({ permission, children, fallback }: {
108
148
  fallback?: ReactNode;
109
149
  }): react.JSX.Element;
110
150
 
111
- export { ApiError as A, Can as C, type LoginFailure as L, type MobileAuthOptions as M, QoreAuthProvider as Q, type SignedOutNotice as S, Unauthenticated as U, type MobileAuth as a, type AuthContextValue as b, type AuthStatus as c, type LoginResult as d, type Me as e, type QoreAuthProviderProps as f, useCan as g, useMe as h, useAuth as u };
151
+ export { ApiError as A, Can as C, type LoginFailure as L, type MobileAuthOptions as M, QoreAuthProvider as Q, type ServerResolverOptions as S, Unauthenticated as U, type MobileAuth as a, type ServerResolver as b, type AuthContextValue as c, type AuthStatus as d, type LoginResult as e, type Me as f, type QoreAuthProviderProps as g, ServerUnavailable as h, type SignedOutNotice as i, useCan as j, useMe as k, useAuth as u };
@@ -1,8 +1,14 @@
1
- import { M as MobileAuthOptions, a as MobileAuth } from '../../context-B_u-vpkw.js';
2
- export { A as ApiError, b as AuthContextValue, c as AuthStatus, C as Can, L as LoginFailure, d as LoginResult, e as Me, Q as QoreAuthProvider, f as QoreAuthProviderProps, S as SignedOutNotice, U as Unauthenticated, u as useAuth, g as useCan, h as useMe } from '../../context-B_u-vpkw.js';
1
+ import { M as MobileAuthOptions, a as MobileAuth, S as ServerResolverOptions, b as ServerResolver } from '../../context-CuTHogIX.js';
2
+ export { A as ApiError, c as AuthContextValue, d as AuthStatus, C as Can, L as LoginFailure, e as LoginResult, f as Me, Q as QoreAuthProvider, g as QoreAuthProviderProps, h as ServerUnavailable, i as SignedOutNotice, U as Unauthenticated, u as useAuth, j as useCan, k as useMe } from '../../context-CuTHogIX.js';
3
3
  import 'react';
4
4
 
5
5
  /** The device auth client for the app's own server. Create it once, at module scope. */
6
6
  declare function createMobileAuth(opts: MobileAuthOptions): MobileAuth;
7
+ /**
8
+ * Where this build's server is: asks the portal once, keeps the answer in
9
+ * secure storage, and asks again when that host stops answering. Pass it to
10
+ * `createMobileAuth({ server })` and its `current` to `qoreSentryInit`.
11
+ */
12
+ declare function createServerResolver(opts: ServerResolverOptions): ServerResolver;
7
13
 
8
- export { MobileAuth, MobileAuthOptions, createMobileAuth };
14
+ export { MobileAuth, MobileAuthOptions, ServerResolver, ServerResolverOptions, createMobileAuth, createServerResolver };
@@ -10,6 +10,111 @@ import {
10
10
  Unauthenticated
11
11
  } from "../../chunk-YXIYI7R2.js";
12
12
 
13
+ // src/expo/core/url.ts
14
+ function queryParam(url, name) {
15
+ const query = url.split("#", 1)[0].split("?")[1];
16
+ if (!query) return null;
17
+ for (const pair of query.split("&")) {
18
+ const i = pair.indexOf("=");
19
+ const key = i < 0 ? pair : pair.slice(0, i);
20
+ if (safeDecode(key) !== name) continue;
21
+ return i < 0 ? "" : safeDecode(pair.slice(i + 1).replace(/\+/g, " "));
22
+ }
23
+ return null;
24
+ }
25
+ function safeDecode(s) {
26
+ try {
27
+ return decodeURIComponent(s);
28
+ } catch {
29
+ return s;
30
+ }
31
+ }
32
+ function normalizeOrigin(serverUrl) {
33
+ return serverUrl.replace(/\/+$/, "");
34
+ }
35
+
36
+ // src/expo/core/server.ts
37
+ var ServerUnavailable = class extends Error {
38
+ constructor(reason) {
39
+ super(`No server known for this app (${reason})`);
40
+ this.reason = reason;
41
+ this.name = "ServerUnavailable";
42
+ }
43
+ reason;
44
+ };
45
+ var REASK_INTERVAL_MS = 6e4;
46
+ var HTTPS_ORIGIN = /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/i;
47
+ function storageKey(tenant, module, env) {
48
+ return `qore.server.${tenant}.${module}.${env}`;
49
+ }
50
+ function fixedServer(origin) {
51
+ const o = normalizeOrigin(origin);
52
+ return { origin: async () => o, reportUnreachable: () => void 0, current: () => o };
53
+ }
54
+ function createServerResolverWith(platform, opts) {
55
+ if (opts.override) return fixedServer(opts.override);
56
+ const now = platform.now ?? Date.now;
57
+ const key = storageKey(opts.tenant, opts.module, opts.env);
58
+ const discoveryUrl = `${normalizeOrigin(opts.portalUrl)}/api/public/mobile/v1/modules/${encodeURIComponent(opts.tenant)}/${encodeURIComponent(opts.module)}/origin?env=${encodeURIComponent(opts.env)}`;
59
+ let known = null;
60
+ let loaded = false;
61
+ let stale = false;
62
+ let lastAsk = -Infinity;
63
+ let inflight = null;
64
+ async function ask() {
65
+ lastAsk = now();
66
+ let res;
67
+ try {
68
+ res = await platform.fetch(discoveryUrl, { headers: { accept: "application/json" } });
69
+ } catch {
70
+ throw new ServerUnavailable("unreachable");
71
+ }
72
+ if (res.status === 404) throw new ServerUnavailable("not_found");
73
+ if (!res.ok) throw new ServerUnavailable("unreachable");
74
+ const body = await res.json().catch(() => null);
75
+ const origin = typeof body?.origin === "string" ? normalizeOrigin(body.origin) : "";
76
+ if (!HTTPS_ORIGIN.test(origin)) throw new ServerUnavailable("invalid");
77
+ return origin;
78
+ }
79
+ async function resolve() {
80
+ if (!loaded) {
81
+ known = await platform.store.get(key).catch(() => null);
82
+ loaded = true;
83
+ }
84
+ if (known && !stale) return known;
85
+ try {
86
+ const origin = await ask();
87
+ stale = false;
88
+ if (origin !== known) {
89
+ known = origin;
90
+ await platform.store.set(key, origin).catch(() => void 0);
91
+ }
92
+ return origin;
93
+ } catch (e) {
94
+ if (known) {
95
+ stale = false;
96
+ return known;
97
+ }
98
+ throw e;
99
+ }
100
+ }
101
+ return {
102
+ origin() {
103
+ if (known && !stale) return Promise.resolve(known);
104
+ inflight ??= resolve().finally(() => {
105
+ inflight = null;
106
+ });
107
+ return inflight;
108
+ },
109
+ reportUnreachable(failed) {
110
+ if (normalizeOrigin(failed) !== known) return;
111
+ if (now() - lastAsk < REASK_INTERVAL_MS) return;
112
+ stale = true;
113
+ },
114
+ current: () => known
115
+ };
116
+ }
117
+
13
118
  // src/expo/core/pkce.ts
14
119
  var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
15
120
  function base64url(bytes) {
@@ -38,34 +143,14 @@ async function createPkce(crypto) {
38
143
  return { verifier, challenge };
39
144
  }
40
145
 
41
- // src/expo/core/url.ts
42
- function queryParam(url, name) {
43
- const query = url.split("#", 1)[0].split("?")[1];
44
- if (!query) return null;
45
- for (const pair of query.split("&")) {
46
- const i = pair.indexOf("=");
47
- const key = i < 0 ? pair : pair.slice(0, i);
48
- if (safeDecode(key) !== name) continue;
49
- return i < 0 ? "" : safeDecode(pair.slice(i + 1).replace(/\+/g, " "));
50
- }
51
- return null;
52
- }
53
- function safeDecode(s) {
54
- try {
55
- return decodeURIComponent(s);
56
- } catch {
57
- return s;
58
- }
59
- }
60
- function normalizeOrigin(serverUrl) {
61
- return serverUrl.replace(/\/+$/, "");
62
- }
63
-
64
146
  // src/expo/auth/client.ts
65
147
  var TOKEN_KEY = "qore.session";
66
148
  var SERVER_REASONS = /* @__PURE__ */ new Set(["cancelled", "expired", "no_app_access", "identity_mismatch", "failed"]);
149
+ function noServer() {
150
+ throw new Error("createMobileAuth needs `server` or `serverUrl`");
151
+ }
67
152
  function createMobileAuthWith(platform, opts) {
68
- const origin = normalizeOrigin(opts.serverUrl);
153
+ const server = opts.server ?? (opts.serverUrl ? fixedServer(opts.serverUrl) : noServer());
69
154
  const versionHeader = opts.appVersion ? { "x-qore-app-version": opts.appVersion } : void 0;
70
155
  function headers(init, token) {
71
156
  const h = new Headers(init);
@@ -77,7 +162,7 @@ function createMobileAuthWith(platform, opts) {
77
162
  if (!path.startsWith("/") || path.startsWith("//")) throw new Error(`apiFetch takes a path on the app's own server, got "${path}"`);
78
163
  const token = await platform.store.get(TOKEN_KEY);
79
164
  if (!token) throw new Unauthenticated();
80
- const res = await platform.fetch(`${origin}${path}`, { ...init, headers: headers(init.headers, token) });
165
+ const res = await send(path, { ...init, headers: headers(init.headers, token) });
81
166
  if (res.status === 401) {
82
167
  await platform.store.delete(TOKEN_KEY);
83
168
  throw new Unauthenticated();
@@ -89,7 +174,21 @@ function createMobileAuthWith(platform, opts) {
89
174
  if (res.status === 204) return void 0;
90
175
  return await res.json();
91
176
  }
177
+ async function send(path, init) {
178
+ const origin = await server.origin();
179
+ try {
180
+ return await platform.fetch(`${origin}${path}`, init);
181
+ } catch (e) {
182
+ server.reportUnreachable(origin);
183
+ const method = (init.method ?? "GET").toUpperCase();
184
+ if (method !== "GET" && method !== "HEAD") throw e;
185
+ const next = await server.origin().catch(() => origin);
186
+ if (next === origin) throw e;
187
+ return platform.fetch(`${next}${path}`, init);
188
+ }
189
+ }
92
190
  async function login(locale) {
191
+ const origin = await server.origin();
93
192
  const { verifier, challenge } = await createPkce(platform);
94
193
  const returnUrl = platform.returnUrl();
95
194
  const url = `${origin}/api/auth/mobile/login?challenge=${encodeURIComponent(challenge)}&redirect=${encodeURIComponent(returnUrl)}&locale=${encodeURIComponent(locale)}`;
@@ -107,6 +206,7 @@ function createMobileAuthWith(platform, opts) {
107
206
  body: JSON.stringify({ code, verifier })
108
207
  });
109
208
  } catch {
209
+ server.reportUnreachable(origin);
110
210
  return { ok: false, reason: "failed", detail: "network" };
111
211
  }
112
212
  const body = await res.json().catch(() => null);
@@ -121,9 +221,10 @@ function createMobileAuthWith(platform, opts) {
121
221
  const token = await platform.store.get(TOKEN_KEY);
122
222
  await platform.store.delete(TOKEN_KEY);
123
223
  if (!token) return;
124
- await platform.fetch(`${origin}/api/auth/mobile/logout`, { method: "POST", headers: headers(void 0, token) }).catch(() => void 0);
224
+ await send("/api/auth/mobile/logout", { method: "POST", headers: headers(void 0, token) }).catch(() => void 0);
125
225
  }
126
226
  async function openPasswordReset(locale) {
227
+ const origin = await server.origin();
127
228
  await platform.openBrowser(`${origin}/api/auth/mobile/reset-password?locale=${encodeURIComponent(locale)}`);
128
229
  }
129
230
  return {
@@ -132,7 +233,9 @@ function createMobileAuthWith(platform, opts) {
132
233
  apiFetch,
133
234
  openPasswordReset,
134
235
  hasSession: async () => await platform.store.get(TOKEN_KEY) !== null,
135
- serverUrl: origin
236
+ get serverUrl() {
237
+ return server.current() ?? "";
238
+ }
136
239
  };
137
240
  }
138
241
 
@@ -164,12 +267,17 @@ var nativeAuthPlatform = {
164
267
  function createMobileAuth(opts) {
165
268
  return createMobileAuthWith(nativeAuthPlatform, opts);
166
269
  }
270
+ function createServerResolver(opts) {
271
+ return createServerResolverWith({ store: nativeAuthPlatform.store, fetch: nativeAuthPlatform.fetch }, opts);
272
+ }
167
273
  export {
168
274
  ApiError,
169
275
  Can,
170
276
  QoreAuthProvider,
277
+ ServerUnavailable,
171
278
  Unauthenticated,
172
279
  createMobileAuth,
280
+ createServerResolver,
173
281
  useAuth,
174
282
  useCan,
175
283
  useMe
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/expo/core/pkce.ts","../../../src/expo/core/url.ts","../../../src/expo/auth/client.ts","../../../src/expo/auth/native.ts","../../../src/expo/auth/index.ts"],"sourcesContent":["const ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n\n/** base64url without padding; no dependency on a global `btoa`. */\nexport function base64url(bytes: Uint8Array): string {\n let out = \"\"\n let i = 0\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!\n out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]! + ALPHABET[n & 63]!\n }\n const rest = bytes.length - i\n if (rest === 1) {\n const n = bytes[i]! << 16\n out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]!\n } else if (rest === 2) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)\n out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]!\n }\n return out\n}\n\n/** Standard base64 (as a SHA-256 digest comes back) to base64url without padding. */\nexport function base64ToUrl(b64: string): string {\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")\n}\n\nexport interface PkceCrypto {\n randomBytes(n: number): Uint8Array\n sha256Base64(input: string): Promise<string>\n}\n\n/** A 43-character verifier and its S256 challenge (RFC 7636). */\nexport async function createPkce(crypto: PkceCrypto): Promise<{ verifier: string; challenge: string }> {\n const verifier = base64url(crypto.randomBytes(32))\n const challenge = base64ToUrl(await crypto.sha256Base64(verifier))\n return { verifier, challenge }\n}\n","// URL helpers that do not rely on React Native's partial `URL` polyfill.\n\n/** The first value of query parameter `name` in `url`, decoded; null when absent. */\nexport function queryParam(url: string, name: string): string | null {\n const query = url.split(\"#\", 1)[0]!.split(\"?\")[1]\n if (!query) return null\n for (const pair of query.split(\"&\")) {\n const i = pair.indexOf(\"=\")\n const key = i < 0 ? pair : pair.slice(0, i)\n if (safeDecode(key) !== name) continue\n return i < 0 ? \"\" : safeDecode(pair.slice(i + 1).replace(/\\+/g, \" \"))\n }\n return null\n}\n\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s)\n } catch {\n return s\n }\n}\n\n/** `serverUrl` without trailing slashes. */\nexport function normalizeOrigin(serverUrl: string): string {\n return serverUrl.replace(/\\/+$/, \"\")\n}\n","// The device half of mobile sign-in. The server half is\n// `createAuthRouteHandlers({ mobile })` in `@quatronic/sdk/next/auth`; change\n// both together. This file imports no React Native module: `native.ts` builds\n// the platform from the real peers, tests hand in a fake one.\nimport { ApiError, Unauthenticated } from \"../core/errors\"\nimport { createPkce, type PkceCrypto } from \"../core/pkce\"\nimport { normalizeOrigin, queryParam } from \"../core/url\"\n\n/** Where the session token lives: the platform keystore, never AsyncStorage. */\nexport const TOKEN_KEY = \"qore.session\"\n\nexport interface AuthPlatform extends PkceCrypto {\n store: {\n get(key: string): Promise<string | null>\n set(key: string, value: string): Promise<void>\n delete(key: string): Promise<void>\n }\n /** The app's own return URL: `exp://…/--/auth/return` in Expo Go, `<scheme>://auth/return` in a build. */\n returnUrl(): string\n /** Opens the system browser on `url` and resolves with the URL it was sent back to, or null when the user closed it. */\n openAuthSession(url: string, returnUrl: string): Promise<string | null>\n openBrowser(url: string): Promise<void>\n fetch: typeof fetch\n}\n\n/** What `/api/auth/me` answers to a bearer caller. */\nexport interface Me {\n sub: string\n email: string | null\n name: string | null\n organizationAlias: string | null\n roles: string[]\n permissions: string[]\n}\n\n/** Why a login did not produce a session. The server sends all but `cancelled` and `failed` itself. */\nexport type LoginFailure = \"cancelled\" | \"expired\" | \"no_app_access\" | \"identity_mismatch\" | \"failed\"\n\nexport type LoginResult = { ok: true } | { ok: false; reason: LoginFailure; detail?: string }\n\nconst SERVER_REASONS: ReadonlySet<string> = new Set([\"cancelled\", \"expired\", \"no_app_access\", \"identity_mismatch\", \"failed\"])\n\nexport interface MobileAuthOptions {\n /** The app's own Next server, e.g. `https://shop.acme.qore.app`. The device talks to nothing else. */\n serverUrl: string\n /** Sent as `X-Qore-App-Version` on every request, so server logs say which build called. */\n appVersion?: string\n}\n\nexport interface MobileAuth {\n login(locale: string): Promise<LoginResult>\n logout(): Promise<void>\n /** Fetch a route of the app's own server (`/api/...`) with the session token. Throws `Unauthenticated` on 401 (the token is cleared), `ApiError` on any other error status. */\n apiFetch<T>(path: string, init?: RequestInit): Promise<T>\n /** Keycloak's \"forgot password\" page in the system browser. Keycloak mails the link; nothing comes back to the app. */\n openPasswordReset(locale: string): Promise<void>\n /** Whether a token is stored. Says nothing about whether the server still accepts it. */\n hasSession(): Promise<boolean>\n readonly serverUrl: string\n}\n\nexport function createMobileAuthWith(platform: AuthPlatform, opts: MobileAuthOptions): MobileAuth {\n const origin = normalizeOrigin(opts.serverUrl)\n const versionHeader = opts.appVersion ? { \"x-qore-app-version\": opts.appVersion } : undefined\n\n function headers(init?: HeadersInit, token?: string): Headers {\n const h = new Headers(init)\n if (versionHeader) h.set(\"x-qore-app-version\", versionHeader[\"x-qore-app-version\"])\n if (token) h.set(\"authorization\", `Bearer ${token}`)\n return h\n }\n\n async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {\n // A relative path only: the token is for the app's own server and nobody else.\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) throw new Error(`apiFetch takes a path on the app's own server, got \"${path}\"`)\n const token = await platform.store.get(TOKEN_KEY)\n if (!token) throw new Unauthenticated()\n const res = await platform.fetch(`${origin}${path}`, { ...init, headers: headers(init.headers, token) })\n if (res.status === 401) {\n await platform.store.delete(TOKEN_KEY)\n throw new Unauthenticated()\n }\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: unknown } | null\n throw new ApiError(res.status, typeof body?.error === \"string\" ? body.error : null)\n }\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n }\n\n async function login(locale: string): Promise<LoginResult> {\n const { verifier, challenge } = await createPkce(platform)\n const returnUrl = platform.returnUrl()\n const url =\n `${origin}/api/auth/mobile/login?challenge=${encodeURIComponent(challenge)}` +\n `&redirect=${encodeURIComponent(returnUrl)}&locale=${encodeURIComponent(locale)}`\n const back = await platform.openAuthSession(url, returnUrl)\n if (back === null) return { ok: false, reason: \"cancelled\" }\n\n const error = queryParam(back, \"error\")\n if (error !== null) return { ok: false, reason: SERVER_REASONS.has(error) ? (error as LoginFailure) : \"failed\", detail: error }\n const code = queryParam(back, \"code\")\n if (!code) return { ok: false, reason: \"failed\", detail: \"no_code\" }\n\n let res: Response\n try {\n res = await platform.fetch(`${origin}/api/auth/mobile/redeem`, {\n method: \"POST\",\n headers: headers({ \"content-type\": \"application/json\" }),\n body: JSON.stringify({ code, verifier }),\n })\n } catch {\n return { ok: false, reason: \"failed\", detail: \"network\" }\n }\n const body = (await res.json().catch(() => null)) as { token?: unknown; error?: unknown } | null\n if (!res.ok || typeof body?.token !== \"string\") {\n const detail = typeof body?.error === \"string\" ? body.error : `http_${res.status}`\n // The code lives a minute; a slow redeem is an expired login, not a broken one.\n return { ok: false, reason: detail === \"invalid_grant\" ? \"expired\" : \"failed\", detail }\n }\n await platform.store.set(TOKEN_KEY, body.token)\n return { ok: true }\n }\n\n async function logout(): Promise<void> {\n const token = await platform.store.get(TOKEN_KEY)\n await platform.store.delete(TOKEN_KEY)\n if (!token) return\n // Best effort: the local token is already gone, which is what signs the device out.\n await platform.fetch(`${origin}/api/auth/mobile/logout`, { method: \"POST\", headers: headers(undefined, token) }).catch(() => undefined)\n }\n\n async function openPasswordReset(locale: string): Promise<void> {\n await platform.openBrowser(`${origin}/api/auth/mobile/reset-password?locale=${encodeURIComponent(locale)}`)\n }\n\n return {\n login,\n logout,\n apiFetch,\n openPasswordReset,\n hasSession: async () => (await platform.store.get(TOKEN_KEY)) !== null,\n serverUrl: origin,\n }\n}\n","// The only file of `expo/auth` that imports React Native peers.\nimport * as Crypto from \"expo-crypto\"\nimport * as Linking from \"expo-linking\"\nimport * as SecureStore from \"expo-secure-store\"\nimport * as WebBrowser from \"expo-web-browser\"\nimport type { AuthPlatform } from \"./client\"\n\nexport const nativeAuthPlatform: AuthPlatform = {\n randomBytes: (n) => Crypto.getRandomBytes(n),\n sha256Base64: (input) =>\n Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, input, { encoding: Crypto.CryptoEncoding.BASE64 }),\n store: {\n get: (key) => SecureStore.getItemAsync(key),\n set: (key, value) => SecureStore.setItemAsync(key, value),\n delete: (key) => SecureStore.deleteItemAsync(key),\n },\n returnUrl: () => Linking.createURL(\"auth/return\"),\n openAuthSession: async (url, returnUrl) => {\n const result = await WebBrowser.openAuthSessionAsync(url, returnUrl)\n return result.type === \"success\" ? result.url : null\n },\n openBrowser: async (url) => {\n await WebBrowser.openBrowserAsync(url)\n },\n fetch: (input, init) => fetch(input, init),\n}\n","// @quatronic/sdk/expo/auth — sign-in for a Qore mobile app (React Native / Expo).\n// Runs on the device. Its server counterpart is `@quatronic/sdk/next/auth`\n// with `mobile` set; see docs/surfaces.md. Never import this from `src/`.\nimport { createMobileAuthWith, type MobileAuth, type MobileAuthOptions } from \"./client\"\nimport { nativeAuthPlatform } from \"./native\"\n\n/** The device auth client for the app's own server. Create it once, at module scope. */\nexport function createMobileAuth(opts: MobileAuthOptions): MobileAuth {\n return createMobileAuthWith(nativeAuthPlatform, opts)\n}\n\nexport { ApiError, Unauthenticated } from \"../core/errors\"\nexport type { LoginFailure, LoginResult, Me, MobileAuth, MobileAuthOptions } from \"./client\"\nexport { Can, QoreAuthProvider, useAuth, useCan, useMe } from \"./context\"\nexport type { AuthContextValue, AuthStatus, QoreAuthProviderProps, SignedOutNotice } from \"./context\"\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAM,WAAW;AAGV,SAAS,UAAU,OAA2B;AACnD,MAAI,MAAM;AACV,MAAI,IAAI;AACR,SAAO,IAAI,IAAI,MAAM,QAAQ,KAAK,GAAG;AACnC,UAAM,IAAK,MAAM,CAAC,KAAM,KAAO,MAAM,IAAI,CAAC,KAAM,IAAK,MAAM,IAAI,CAAC;AAChE,WAAO,SAAU,KAAK,KAAM,EAAE,IAAK,SAAU,KAAK,KAAM,EAAE,IAAK,SAAU,KAAK,IAAK,EAAE,IAAK,SAAS,IAAI,EAAE;AAAA,EAC3G;AACA,QAAM,OAAO,MAAM,SAAS;AAC5B,MAAI,SAAS,GAAG;AACd,UAAM,IAAI,MAAM,CAAC,KAAM;AACvB,WAAO,SAAU,KAAK,KAAM,EAAE,IAAK,SAAU,KAAK,KAAM,EAAE;AAAA,EAC5D,WAAW,SAAS,GAAG;AACrB,UAAM,IAAK,MAAM,CAAC,KAAM,KAAO,MAAM,IAAI,CAAC,KAAM;AAChD,WAAO,SAAU,KA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,QAAW,KAAK,EAAE,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,EACxI;AAEA,iBAAe,kBAAkB,QAA+B;AAC9D,UAAM,SAAS,YAAY,GAAG,MAAM,0CAA0C,mBAAmB,MAAM,CAAC,EAAE;AAAA,EAC5G;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY,YAAa,MAAM,SAAS,MAAM,IAAI,SAAS,MAAO;AAAA,IAClE,WAAW;AAAA,EACb;AACF;;;AC/IA,YAAY,YAAY;AACxB,YAAY,aAAa;AACzB,YAAY,iBAAiB;AAC7B,YAAY,gBAAgB;AAGrB,IAAM,qBAAmC;AAAA,EAC9C,aAAa,CAAC,MAAa,sBAAe,CAAC;AAAA,EAC3C,cAAc,CAAC,UACN,yBAAyB,6BAAsB,QAAQ,OAAO,EAAE,UAAiB,sBAAe,OAAO,CAAC;AAAA,EACjH,OAAO;AAAA,IACL,KAAK,CAAC,QAAoB,yBAAa,GAAG;AAAA,IAC1C,KAAK,CAAC,KAAK,UAAsB,yBAAa,KAAK,KAAK;AAAA,IACxD,QAAQ,CAAC,QAAoB,4BAAgB,GAAG;AAAA,EAClD;AAAA,EACA,WAAW,MAAc,kBAAU,aAAa;AAAA,EAChD,iBAAiB,OAAO,KAAK,cAAc;AACzC,UAAM,SAAS,MAAiB,gCAAqB,KAAK,SAAS;AACnE,WAAO,OAAO,SAAS,YAAY,OAAO,MAAM;AAAA,EAClD;AAAA,EACA,aAAa,OAAO,QAAQ;AAC1B,UAAiB,4BAAiB,GAAG;AAAA,EACvC;AAAA,EACA,OAAO,CAAC,OAAO,SAAS,MAAM,OAAO,IAAI;AAC3C;;;AClBO,SAAS,iBAAiB,MAAqC;AACpE,SAAO,qBAAqB,oBAAoB,IAAI;AACtD;","names":[]}
1
+ {"version":3,"sources":["../../../src/expo/core/url.ts","../../../src/expo/core/server.ts","../../../src/expo/core/pkce.ts","../../../src/expo/auth/client.ts","../../../src/expo/auth/native.ts","../../../src/expo/auth/index.ts"],"sourcesContent":["// URL helpers that do not rely on React Native's partial `URL` polyfill.\n\n/** The first value of query parameter `name` in `url`, decoded; null when absent. */\nexport function queryParam(url: string, name: string): string | null {\n const query = url.split(\"#\", 1)[0]!.split(\"?\")[1]\n if (!query) return null\n for (const pair of query.split(\"&\")) {\n const i = pair.indexOf(\"=\")\n const key = i < 0 ? pair : pair.slice(0, i)\n if (safeDecode(key) !== name) continue\n return i < 0 ? \"\" : safeDecode(pair.slice(i + 1).replace(/\\+/g, \" \"))\n }\n return null\n}\n\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s)\n } catch {\n return s\n }\n}\n\n/** `serverUrl` without trailing slashes. */\nexport function normalizeOrigin(serverUrl: string): string {\n return serverUrl.replace(/\\/+$/, \"\")\n}\n","// Which server a mobile build talks to. One build serves one environment, but\n// its JS bundle is the same in every environment (an over-the-air update is\n// republished from one to the next), so the server's address cannot be baked\n// in. The bundle carries the portal's address and its tenant and module slugs\n// instead, all the same everywhere, and asks the portal which origin serves this module in\n// this environment. The answer is cached on the device and only asked again\n// when the cached host stops answering: a custom domain bound later moves the\n// app along without a new build or update.\n//\n// Pure: the platform (storage, fetch) is handed in. `expo/auth` builds it from\n// the real peers.\nimport { normalizeOrigin } from \"./url\"\n\nexport interface ServerResolverPlatform {\n store: {\n get(key: string): Promise<string | null>\n set(key: string, value: string): Promise<void>\n }\n fetch: typeof fetch\n /** Milliseconds since the epoch; tests freeze it. */\n now?: () => number\n}\n\nexport interface ServerResolverOptions {\n /** The Qore portal, e.g. `https://portal.qore.app`. Baked into the build. */\n portalUrl: string\n /** The tenant's slug in the portal. Baked into the build. */\n tenant: string\n /** This app's module slug in the portal. Baked into the build. */\n module: string\n /** The portal environment this build belongs to (`stag`, `acc`, `prod`). */\n env: string\n /**\n * A fixed server for local development (`EXPO_PUBLIC_SERVER_URL` in\n * `mobile/.env.local`). When set, the portal is never asked.\n */\n override?: string\n}\n\nexport interface ServerResolver {\n /** The server's origin, without a trailing slash. Throws `ServerUnavailable` when there is none to give. */\n origin(): Promise<string>\n /**\n * Report that a request to `failed` did not reach a server (a network error,\n * not an error status). The next `origin()` asks the portal again, at most\n * once a minute; while the portal cannot answer, the old origin stays.\n */\n reportUnreachable(failed: string): void\n /** The origin known right now, or null before the first answer. Synchronous, for Sentry's trace targets. */\n current(): string | null\n}\n\n/** No server is known for this build: the portal does not answer and nothing is cached. */\nexport class ServerUnavailable extends Error {\n constructor(readonly reason: \"not_found\" | \"unreachable\" | \"invalid\") {\n super(`No server known for this app (${reason})`)\n this.name = \"ServerUnavailable\"\n }\n}\n\n/** Minimum time between two re-asks after an unreachable host, so a server outage does not turn into a portal storm. */\nconst REASK_INTERVAL_MS = 60_000\n\n// A regex, not `new URL`: React Native's URL polyfill is partial.\nconst HTTPS_ORIGIN = /^https:\\/\\/[a-z0-9.-]+(?::\\d{1,5})?$/i\n\nexport function storageKey(tenant: string, module: string, env: string): string {\n return `qore.server.${tenant}.${module}.${env}`\n}\n\n/** A resolver that always answers `origin`; what a fixed `serverUrl` becomes. */\nexport function fixedServer(origin: string): ServerResolver {\n const o = normalizeOrigin(origin)\n return { origin: async () => o, reportUnreachable: () => undefined, current: () => o }\n}\n\nexport function createServerResolverWith(platform: ServerResolverPlatform, opts: ServerResolverOptions): ServerResolver {\n if (opts.override) return fixedServer(opts.override)\n const now = platform.now ?? Date.now\n const key = storageKey(opts.tenant, opts.module, opts.env)\n const discoveryUrl =\n `${normalizeOrigin(opts.portalUrl)}/api/public/mobile/v1/modules/${encodeURIComponent(opts.tenant)}/${encodeURIComponent(opts.module)}` +\n `/origin?env=${encodeURIComponent(opts.env)}`\n\n let known: string | null = null\n let loaded = false\n let stale = false\n let lastAsk = -Infinity\n let inflight: Promise<string> | null = null\n\n async function ask(): Promise<string> {\n lastAsk = now()\n let res: Response\n try {\n res = await platform.fetch(discoveryUrl, { headers: { accept: \"application/json\" } })\n } catch {\n throw new ServerUnavailable(\"unreachable\")\n }\n if (res.status === 404) throw new ServerUnavailable(\"not_found\")\n if (!res.ok) throw new ServerUnavailable(\"unreachable\")\n const body = (await res.json().catch(() => null)) as { origin?: unknown } | null\n const origin = typeof body?.origin === \"string\" ? normalizeOrigin(body.origin) : \"\"\n // The answer becomes the only host the session token is sent to: anything\n // but a plain https origin is refused rather than trusted.\n if (!HTTPS_ORIGIN.test(origin)) throw new ServerUnavailable(\"invalid\")\n return origin\n }\n\n async function resolve(): Promise<string> {\n if (!loaded) {\n known = await platform.store.get(key).catch(() => null)\n loaded = true\n }\n if (known && !stale) return known\n try {\n const origin = await ask()\n stale = false\n if (origin !== known) {\n known = origin\n await platform.store.set(key, origin).catch(() => undefined)\n }\n return origin\n } catch (e) {\n // The portal is down or says nothing: keep using the host we had.\n if (known) {\n stale = false\n return known\n }\n throw e\n }\n }\n\n return {\n origin() {\n if (known && !stale) return Promise.resolve(known)\n inflight ??= resolve().finally(() => {\n inflight = null\n })\n return inflight\n },\n reportUnreachable(failed) {\n if (normalizeOrigin(failed) !== known) return\n if (now() - lastAsk < REASK_INTERVAL_MS) return\n stale = true\n },\n current: () => known,\n }\n}\n","const ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n\n/** base64url without padding; no dependency on a global `btoa`. */\nexport function base64url(bytes: Uint8Array): string {\n let out = \"\"\n let i = 0\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!\n out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]! + ALPHABET[n & 63]!\n }\n const rest = bytes.length - i\n if (rest === 1) {\n const n = bytes[i]! << 16\n out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]!\n } else if (rest === 2) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)\n out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]!\n }\n return out\n}\n\n/** Standard base64 (as a SHA-256 digest comes back) to base64url without padding. */\nexport function base64ToUrl(b64: string): string {\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")\n}\n\nexport interface PkceCrypto {\n randomBytes(n: number): Uint8Array\n sha256Base64(input: string): Promise<string>\n}\n\n/** A 43-character verifier and its S256 challenge (RFC 7636). */\nexport async function createPkce(crypto: PkceCrypto): Promise<{ verifier: string; challenge: string }> {\n const verifier = base64url(crypto.randomBytes(32))\n const challenge = base64ToUrl(await crypto.sha256Base64(verifier))\n return { verifier, challenge }\n}\n","// The device half of mobile sign-in. The server half is\n// `createAuthRouteHandlers({ mobile })` in `@quatronic/sdk/next/auth`; change\n// both together. This file imports no React Native module: `native.ts` builds\n// the platform from the real peers, tests hand in a fake one.\nimport { ApiError, Unauthenticated } from \"../core/errors\"\nimport { createPkce, type PkceCrypto } from \"../core/pkce\"\nimport { fixedServer, type ServerResolver } from \"../core/server\"\nimport { queryParam } from \"../core/url\"\n\n/** Where the session token lives: the platform keystore, never AsyncStorage. */\nexport const TOKEN_KEY = \"qore.session\"\n\nexport interface AuthPlatform extends PkceCrypto {\n store: {\n get(key: string): Promise<string | null>\n set(key: string, value: string): Promise<void>\n delete(key: string): Promise<void>\n }\n /** The app's own return URL: `exp://…/--/auth/return` in Expo Go, `<scheme>://auth/return` in a build. */\n returnUrl(): string\n /** Opens the system browser on `url` and resolves with the URL it was sent back to, or null when the user closed it. */\n openAuthSession(url: string, returnUrl: string): Promise<string | null>\n openBrowser(url: string): Promise<void>\n fetch: typeof fetch\n}\n\n/** What `/api/auth/me` answers to a bearer caller. */\nexport interface Me {\n sub: string\n email: string | null\n name: string | null\n organizationAlias: string | null\n roles: string[]\n permissions: string[]\n}\n\n/** Why a login did not produce a session. The server sends all but `cancelled` and `failed` itself. */\nexport type LoginFailure = \"cancelled\" | \"expired\" | \"no_app_access\" | \"identity_mismatch\" | \"failed\"\n\nexport type LoginResult = { ok: true } | { ok: false; reason: LoginFailure; detail?: string }\n\nconst SERVER_REASONS: ReadonlySet<string> = new Set([\"cancelled\", \"expired\", \"no_app_access\", \"identity_mismatch\", \"failed\"])\n\nexport interface MobileAuthOptions {\n /**\n * Where the app's own Next server is, asked by environment from the portal\n * (`createServerResolver`). The device talks to nothing else. Set this or\n * `serverUrl`.\n */\n server?: ServerResolver\n /** A fixed server origin instead, e.g. `https://shop.acme.qore.app`. */\n serverUrl?: string\n /** Sent as `X-Qore-App-Version` on every request, so server logs say which build called. */\n appVersion?: string\n}\n\nexport interface MobileAuth {\n login(locale: string): Promise<LoginResult>\n logout(): Promise<void>\n /** Fetch a route of the app's own server (`/api/...`) with the session token. Throws `Unauthenticated` on 401 (the token is cleared), `ApiError` on any other error status. */\n apiFetch<T>(path: string, init?: RequestInit): Promise<T>\n /** Keycloak's \"forgot password\" page in the system browser. Keycloak mails the link; nothing comes back to the app. */\n openPasswordReset(locale: string): Promise<void>\n /** Whether a token is stored. Says nothing about whether the server still accepts it. */\n hasSession(): Promise<boolean>\n /** The server's origin as known right now; empty before the first answer. */\n readonly serverUrl: string\n}\n\nfunction noServer(): never {\n throw new Error(\"createMobileAuth needs `server` or `serverUrl`\")\n}\n\nexport function createMobileAuthWith(platform: AuthPlatform, opts: MobileAuthOptions): MobileAuth {\n const server: ServerResolver = opts.server ?? (opts.serverUrl ? fixedServer(opts.serverUrl) : noServer())\n const versionHeader = opts.appVersion ? { \"x-qore-app-version\": opts.appVersion } : undefined\n\n function headers(init?: HeadersInit, token?: string): Headers {\n const h = new Headers(init)\n if (versionHeader) h.set(\"x-qore-app-version\", versionHeader[\"x-qore-app-version\"])\n if (token) h.set(\"authorization\", `Bearer ${token}`)\n return h\n }\n\n async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {\n // A relative path only: the token is for the app's own server and nobody else.\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) throw new Error(`apiFetch takes a path on the app's own server, got \"${path}\"`)\n const token = await platform.store.get(TOKEN_KEY)\n if (!token) throw new Unauthenticated()\n const res = await send(path, { ...init, headers: headers(init.headers, token) })\n if (res.status === 401) {\n await platform.store.delete(TOKEN_KEY)\n throw new Unauthenticated()\n }\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: unknown } | null\n throw new ApiError(res.status, typeof body?.error === \"string\" ? body.error : null)\n }\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n }\n\n /**\n * One request to the app's server. A request that reaches no server reports\n * the host as unreachable; when that moves the app to another host, a read\n * is sent once more there. A write is not: it may have arrived.\n */\n async function send(path: string, init: RequestInit): Promise<Response> {\n const origin = await server.origin()\n try {\n return await platform.fetch(`${origin}${path}`, init)\n } catch (e) {\n server.reportUnreachable(origin)\n const method = (init.method ?? \"GET\").toUpperCase()\n if (method !== \"GET\" && method !== \"HEAD\") throw e\n const next = await server.origin().catch(() => origin)\n if (next === origin) throw e\n return platform.fetch(`${next}${path}`, init)\n }\n }\n\n async function login(locale: string): Promise<LoginResult> {\n const origin = await server.origin()\n const { verifier, challenge } = await createPkce(platform)\n const returnUrl = platform.returnUrl()\n const url =\n `${origin}/api/auth/mobile/login?challenge=${encodeURIComponent(challenge)}` +\n `&redirect=${encodeURIComponent(returnUrl)}&locale=${encodeURIComponent(locale)}`\n const back = await platform.openAuthSession(url, returnUrl)\n if (back === null) return { ok: false, reason: \"cancelled\" }\n\n const error = queryParam(back, \"error\")\n if (error !== null) return { ok: false, reason: SERVER_REASONS.has(error) ? (error as LoginFailure) : \"failed\", detail: error }\n const code = queryParam(back, \"code\")\n if (!code) return { ok: false, reason: \"failed\", detail: \"no_code\" }\n\n let res: Response\n try {\n res = await platform.fetch(`${origin}/api/auth/mobile/redeem`, {\n method: \"POST\",\n headers: headers({ \"content-type\": \"application/json\" }),\n body: JSON.stringify({ code, verifier }),\n })\n } catch {\n server.reportUnreachable(origin)\n return { ok: false, reason: \"failed\", detail: \"network\" }\n }\n const body = (await res.json().catch(() => null)) as { token?: unknown; error?: unknown } | null\n if (!res.ok || typeof body?.token !== \"string\") {\n const detail = typeof body?.error === \"string\" ? body.error : `http_${res.status}`\n // The code lives a minute; a slow redeem is an expired login, not a broken one.\n return { ok: false, reason: detail === \"invalid_grant\" ? \"expired\" : \"failed\", detail }\n }\n await platform.store.set(TOKEN_KEY, body.token)\n return { ok: true }\n }\n\n async function logout(): Promise<void> {\n const token = await platform.store.get(TOKEN_KEY)\n await platform.store.delete(TOKEN_KEY)\n if (!token) return\n // Best effort: the local token is already gone, which is what signs the device out.\n await send(\"/api/auth/mobile/logout\", { method: \"POST\", headers: headers(undefined, token) }).catch(() => undefined)\n }\n\n async function openPasswordReset(locale: string): Promise<void> {\n const origin = await server.origin()\n await platform.openBrowser(`${origin}/api/auth/mobile/reset-password?locale=${encodeURIComponent(locale)}`)\n }\n\n return {\n login,\n logout,\n apiFetch,\n openPasswordReset,\n hasSession: async () => (await platform.store.get(TOKEN_KEY)) !== null,\n get serverUrl() {\n return server.current() ?? \"\"\n },\n }\n}\n","// The only file of `expo/auth` that imports React Native peers.\nimport * as Crypto from \"expo-crypto\"\nimport * as Linking from \"expo-linking\"\nimport * as SecureStore from \"expo-secure-store\"\nimport * as WebBrowser from \"expo-web-browser\"\nimport type { AuthPlatform } from \"./client\"\n\nexport const nativeAuthPlatform: AuthPlatform = {\n randomBytes: (n) => Crypto.getRandomBytes(n),\n sha256Base64: (input) =>\n Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, input, { encoding: Crypto.CryptoEncoding.BASE64 }),\n store: {\n get: (key) => SecureStore.getItemAsync(key),\n set: (key, value) => SecureStore.setItemAsync(key, value),\n delete: (key) => SecureStore.deleteItemAsync(key),\n },\n returnUrl: () => Linking.createURL(\"auth/return\"),\n openAuthSession: async (url, returnUrl) => {\n const result = await WebBrowser.openAuthSessionAsync(url, returnUrl)\n return result.type === \"success\" ? result.url : null\n },\n openBrowser: async (url) => {\n await WebBrowser.openBrowserAsync(url)\n },\n fetch: (input, init) => fetch(input, init),\n}\n","// @quatronic/sdk/expo/auth — sign-in for a Qore mobile app (React Native / Expo).\n// Runs on the device. Its server counterpart is `@quatronic/sdk/next/auth`\n// with `mobile` set; see docs/surfaces.md. Never import this from `src/`.\nimport { createServerResolverWith, type ServerResolver, type ServerResolverOptions } from \"../core/server\"\nimport { createMobileAuthWith, type MobileAuth, type MobileAuthOptions } from \"./client\"\nimport { nativeAuthPlatform } from \"./native\"\n\n/** The device auth client for the app's own server. Create it once, at module scope. */\nexport function createMobileAuth(opts: MobileAuthOptions): MobileAuth {\n return createMobileAuthWith(nativeAuthPlatform, opts)\n}\n\n/**\n * Where this build's server is: asks the portal once, keeps the answer in\n * secure storage, and asks again when that host stops answering. Pass it to\n * `createMobileAuth({ server })` and its `current` to `qoreSentryInit`.\n */\nexport function createServerResolver(opts: ServerResolverOptions): ServerResolver {\n return createServerResolverWith({ store: nativeAuthPlatform.store, fetch: nativeAuthPlatform.fetch }, opts)\n}\n\nexport { ApiError, Unauthenticated } from \"../core/errors\"\nexport { ServerUnavailable } from \"../core/server\"\nexport type { ServerResolver, ServerResolverOptions } from \"../core/server\"\nexport type { LoginFailure, LoginResult, Me, MobileAuth, MobileAuthOptions } from \"./client\"\nexport { Can, QoreAuthProvider, useAuth, useCan, useMe } from \"./context\"\nexport type { AuthContextValue, AuthStatus, QoreAuthProviderProps, SignedOutNotice } from \"./context\"\n"],"mappings":";;;;;;;;;;;;;AAGO,SAAS,WAAW,KAAa,MAA6B;AACnE,QAAM,QAAQ,IAAI,MAAM,KAAK,CAAC,EAAE,CAAC,EAAG,MAAM,GAAG,EAAE,CAAC;AAChD,MAAI,CAAC,MAAO,QAAO;AACnB,aAAW,QAAQ,MAAM,MAAM,GAAG,GAAG;AACnC,UAAM,IAAI,KAAK,QAAQ,GAAG;AAC1B,UAAM,MAAM,IAAI,IAAI,OAAO,KAAK,MAAM,GAAG,CAAC;AAC1C,QAAI,WAAW,GAAG,MAAM,K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,UAAiB,sBAAe,OAAO,CAAC;AAAA,EACjH,OAAO;AAAA,IACL,KAAK,CAAC,QAAoB,yBAAa,GAAG;AAAA,IAC1C,KAAK,CAAC,KAAK,UAAsB,yBAAa,KAAK,KAAK;AAAA,IACxD,QAAQ,CAAC,QAAoB,4BAAgB,GAAG;AAAA,EAClD;AAAA,EACA,WAAW,MAAc,kBAAU,aAAa;AAAA,EAChD,iBAAiB,OAAO,KAAK,cAAc;AACzC,UAAM,SAAS,MAAiB,gCAAqB,KAAK,SAAS;AACnE,WAAO,OAAO,SAAS,YAAY,OAAO,MAAM;AAAA,EAClD;AAAA,EACA,aAAa,OAAO,QAAQ;AAC1B,UAAiB,4BAAiB,GAAG;AAAA,EACvC;AAAA,EACA,OAAO,CAAC,OAAO,SAAS,MAAM,OAAO,IAAI;AAC3C;;;ACjBO,SAAS,iBAAiB,MAAqC;AACpE,SAAO,qBAAqB,oBAAoB,IAAI;AACtD;AAOO,SAAS,qBAAqB,MAA6C;AAChF,SAAO,yBAAyB,EAAE,OAAO,mBAAmB,OAAO,OAAO,mBAAmB,MAAM,GAAG,IAAI;AAC5G;","names":[]}
@@ -1,10 +1,16 @@
1
1
  interface MobileConfigInput {
2
- /** `EXPO_PUBLIC_SERVER_URL`: the app's own server. */
3
- serverUrl: string;
2
+ /** `extra.qorePortalUrl`: the Qore portal, which says where this app's server is. */
3
+ portalUrl: string;
4
+ /** `extra.qoreTenant`: the tenant's slug in the portal. */
5
+ tenant: string;
6
+ /** `extra.qoreModule`: this app's module slug in the portal. */
7
+ module: string;
4
8
  /** `EXPO_PUBLIC_SENTRY_DSN`; empty turns Sentry off. */
5
9
  sentryDsn: string;
6
- /** `EXPO_PUBLIC_QORE_ENV`. */
10
+ /** The environment this build belongs to, from `qoreEnvFrom`. */
7
11
  qoreEnv: string;
12
+ /** `EXPO_PUBLIC_SERVER_URL`: a fixed server for local development. Optional. */
13
+ serverUrl?: string;
8
14
  }
9
15
  interface ConfigProblem {
10
16
  key: string;
@@ -12,5 +18,21 @@ interface ConfigProblem {
12
18
  }
13
19
  /** Empty when the build can run. */
14
20
  declare function checkConfig(c: MobileConfigInput): ConfigProblem[];
21
+ interface QoreEnvSources {
22
+ /** `Updates.channel`: the build profile's channel. Null in Expo Go and dev builds. */
23
+ channel?: string | null;
24
+ /** `Application.applicationId`: the installed app id, `<base>.<suffix>` outside prod. */
25
+ applicationId?: string | null;
26
+ /** The prod app id, with no suffix (`extra.qoreBaseAppId`). */
27
+ baseApplicationId?: string | null;
28
+ /** When nothing native says it: an `EXPO_PUBLIC_QORE_ENV` for local development, else `stag`. */
29
+ fallback?: string;
30
+ }
31
+ /**
32
+ * The portal environment this build belongs to, read from the native build
33
+ * rather than the bundle: the channel first, then the app id's suffix
34
+ * (no suffix is prod).
35
+ */
36
+ declare function qoreEnvFrom(s: QoreEnvSources): string;
15
37
 
16
- export { type ConfigProblem, type MobileConfigInput, checkConfig };
38
+ export { type ConfigProblem, type MobileConfigInput, type QoreEnvSources, checkConfig, qoreEnvFrom };
@@ -1,17 +1,35 @@
1
1
  // src/expo/config/index.ts
2
2
  function checkConfig(c) {
3
3
  const problems = [];
4
- if (!isOrigin(c.serverUrl)) problems.push({ key: "EXPO_PUBLIC_SERVER_URL", problem: "must be an https:// origin" });
4
+ if (c.serverUrl && !isOrigin(c.serverUrl))
5
+ problems.push({ key: "EXPO_PUBLIC_SERVER_URL", problem: "must be an https:// origin, or unset to ask the portal" });
6
+ if (!c.serverUrl) {
7
+ if (!isOrigin(c.portalUrl)) problems.push({ key: "qorePortalUrl", problem: "must be an https:// origin" });
8
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(c.tenant)) problems.push({ key: "qoreTenant", problem: "must be the tenant's slug" });
9
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(c.module)) problems.push({ key: "qoreModule", problem: "must be the module's slug" });
10
+ }
5
11
  if (c.sentryDsn && !/^https:\/\/\S+$/i.test(c.sentryDsn))
6
12
  problems.push({ key: "EXPO_PUBLIC_SENTRY_DSN", problem: "must be an https:// DSN, or empty to turn Sentry off" });
7
13
  if (!/^[a-z][a-z0-9-]*$/.test(c.qoreEnv))
8
- problems.push({ key: "EXPO_PUBLIC_QORE_ENV", problem: "must be an environment name such as staging" });
14
+ problems.push({ key: "EXPO_PUBLIC_QORE_ENV", problem: "must be an environment name such as stag" });
9
15
  return problems;
10
16
  }
17
+ var CHANNEL_ENV = { staging: "stag", production: "prod" };
18
+ function qoreEnvFrom(s) {
19
+ if (s.channel) return CHANNEL_ENV[s.channel] ?? s.channel;
20
+ const id = s.applicationId;
21
+ const base = s.baseApplicationId;
22
+ if (id && base) {
23
+ if (id === base) return "prod";
24
+ if (id.startsWith(`${base}.`)) return id.slice(base.length + 1);
25
+ }
26
+ return s.fallback || "stag";
27
+ }
11
28
  function isOrigin(raw) {
12
29
  return /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?\/*$/i.test(raw);
13
30
  }
14
31
  export {
15
- checkConfig
32
+ checkConfig,
33
+ qoreEnvFrom
16
34
  };
17
35
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/expo/config/index.ts"],"sourcesContent":["// @quatronic/sdk/expo/config — checks the mobile app's public config. The web\n// app refuses to boot on a bad env; a phone shows the problems on screen,\n// since nobody reads its log. Pure: no React Native import.\n\nexport interface MobileConfigInput {\n /** `EXPO_PUBLIC_SERVER_URL`: the app's own server. */\n serverUrl: string\n /** `EXPO_PUBLIC_SENTRY_DSN`; empty turns Sentry off. */\n sentryDsn: string\n /** `EXPO_PUBLIC_QORE_ENV`. */\n qoreEnv: string\n}\n\nexport interface ConfigProblem {\n key: string\n problem: string\n}\n\n/** Empty when the build can run. */\nexport function checkConfig(c: MobileConfigInput): ConfigProblem[] {\n const problems: ConfigProblem[] = []\n if (!isOrigin(c.serverUrl)) problems.push({ key: \"EXPO_PUBLIC_SERVER_URL\", problem: \"must be an https:// origin\" })\n if (c.sentryDsn && !/^https:\\/\\/\\S+$/i.test(c.sentryDsn))\n problems.push({ key: \"EXPO_PUBLIC_SENTRY_DSN\", problem: \"must be an https:// DSN, or empty to turn Sentry off\" })\n if (!/^[a-z][a-z0-9-]*$/.test(c.qoreEnv))\n problems.push({ key: \"EXPO_PUBLIC_QORE_ENV\", problem: \"must be an environment name such as staging\" })\n return problems\n}\n\n// A regex, not `new URL`: React Native's URL polyfill is partial.\nfunction isOrigin(raw: string): boolean {\n return /^https:\\/\\/[a-z0-9.-]+(?::\\d{1,5})?\\/*$/i.test(raw)\n}\n"],"mappings":";AAmBO,SAAS,YAAY,GAAuC;AACjE,QAAM,WAA4B,CAAC;AACnC,MAAI,CAAC,SAAS,EAAE,SAAS,EAAG,UAAS,KAAK,EAAE,KAAK,0BAA0B,SAAS,6BAA6B,CAAC;AAClH,MAAI,EAAE,aAAa,CAAC,mBAAmB,KAAK,EAAE,SAAS;AACrD,aAAS,KAAK,EAAE,KAAK,0BAA0B,SAAS,uDAAuD,CAAC;AAClH,MAAI,CAAC,oBAAoB,KAAK,EAAE,OAAO;AACrC,aAAS,KAAK,EAAE,KAAK,wBAAwB,SAAS,8CAA8C,CAAC;AACvG,SAAO;AACT;AAGA,SAAS,SAAS,KAAsB;AACtC,SAAO,2CAA2C,KAAK,GAAG;AAC5D;","names":[]}
1
+ {"version":3,"sources":["../../../src/expo/config/index.ts"],"sourcesContent":["// @quatronic/sdk/expo/config — checks the mobile app's public config. The web\n// app refuses to boot on a bad env; a phone shows the problems on screen,\n// since nobody reads its log. Pure: no React Native import.\n//\n// One JS bundle serves every environment (an over-the-air update is\n// republished from one to the next), so nothing here is per environment: the\n// build carries the portal's address and its tenant and module slugs, the environment comes\n// from the native build (`qoreEnvFrom`), and the server from the portal\n// (`expo/auth` `createServerResolver`).\n\nexport interface MobileConfigInput {\n /** `extra.qorePortalUrl`: the Qore portal, which says where this app's server is. */\n portalUrl: string\n /** `extra.qoreTenant`: the tenant's slug in the portal. */\n tenant: string\n /** `extra.qoreModule`: this app's module slug in the portal. */\n module: string\n /** `EXPO_PUBLIC_SENTRY_DSN`; empty turns Sentry off. */\n sentryDsn: string\n /** The environment this build belongs to, from `qoreEnvFrom`. */\n qoreEnv: string\n /** `EXPO_PUBLIC_SERVER_URL`: a fixed server for local development. Optional. */\n serverUrl?: string\n}\n\nexport interface ConfigProblem {\n key: string\n problem: string\n}\n\n/** Empty when the build can run. */\nexport function checkConfig(c: MobileConfigInput): ConfigProblem[] {\n const problems: ConfigProblem[] = []\n if (c.serverUrl && !isOrigin(c.serverUrl))\n problems.push({ key: \"EXPO_PUBLIC_SERVER_URL\", problem: \"must be an https:// origin, or unset to ask the portal\" })\n // Without an override the portal is the only way to find the server.\n if (!c.serverUrl) {\n if (!isOrigin(c.portalUrl)) problems.push({ key: \"qorePortalUrl\", problem: \"must be an https:// origin\" })\n if (!/^[a-z0-9][a-z0-9-]*$/.test(c.tenant)) problems.push({ key: \"qoreTenant\", problem: \"must be the tenant's slug\" })\n if (!/^[a-z0-9][a-z0-9-]*$/.test(c.module)) problems.push({ key: \"qoreModule\", problem: \"must be the module's slug\" })\n }\n if (c.sentryDsn && !/^https:\\/\\/\\S+$/i.test(c.sentryDsn))\n problems.push({ key: \"EXPO_PUBLIC_SENTRY_DSN\", problem: \"must be an https:// DSN, or empty to turn Sentry off\" })\n if (!/^[a-z][a-z0-9-]*$/.test(c.qoreEnv))\n problems.push({ key: \"EXPO_PUBLIC_QORE_ENV\", problem: \"must be an environment name such as stag\" })\n return problems\n}\n\n/** EAS channel names that differ from the portal's environment names. */\nconst CHANNEL_ENV: Readonly<Record<string, string>> = { staging: \"stag\", production: \"prod\" }\n\nexport interface QoreEnvSources {\n /** `Updates.channel`: the build profile's channel. Null in Expo Go and dev builds. */\n channel?: string | null\n /** `Application.applicationId`: the installed app id, `<base>.<suffix>` outside prod. */\n applicationId?: string | null\n /** The prod app id, with no suffix (`extra.qoreBaseAppId`). */\n baseApplicationId?: string | null\n /** When nothing native says it: an `EXPO_PUBLIC_QORE_ENV` for local development, else `stag`. */\n fallback?: string\n}\n\n/**\n * The portal environment this build belongs to, read from the native build\n * rather than the bundle: the channel first, then the app id's suffix\n * (no suffix is prod).\n */\nexport function qoreEnvFrom(s: QoreEnvSources): string {\n if (s.channel) return CHANNEL_ENV[s.channel] ?? s.channel\n const id = s.applicationId\n const base = s.baseApplicationId\n if (id && base) {\n if (id === base) return \"prod\"\n if (id.startsWith(`${base}.`)) return id.slice(base.length + 1)\n }\n return s.fallback || \"stag\"\n}\n\n// A regex, not `new URL`: React Native's URL polyfill is partial.\nfunction isOrigin(raw: string): boolean {\n return /^https:\\/\\/[a-z0-9.-]+(?::\\d{1,5})?\\/*$/i.test(raw)\n}\n"],"mappings":";AA+BO,SAAS,YAAY,GAAuC;AACjE,QAAM,WAA4B,CAAC;AACnC,MAAI,EAAE,aAAa,CAAC,SAAS,EAAE,SAAS;AACtC,aAAS,KAAK,EAAE,KAAK,0BAA0B,SAAS,yDAAyD,CAAC;AAEpH,MAAI,CAAC,EAAE,WAAW;AAChB,QAAI,CAAC,SAAS,EAAE,SAAS,EAAG,UAAS,KAAK,EAAE,KAAK,iBAAiB,SAAS,6BAA6B,CAAC;AACzG,QAAI,CAAC,uBAAuB,KAAK,EAAE,MAAM,EAAG,UAAS,KAAK,EAAE,KAAK,cAAc,SAAS,4BAA4B,CAAC;AACrH,QAAI,CAAC,uBAAuB,KAAK,EAAE,MAAM,EAAG,UAAS,KAAK,EAAE,KAAK,cAAc,SAAS,4BAA4B,CAAC;AAAA,EACvH;AACA,MAAI,EAAE,aAAa,CAAC,mBAAmB,KAAK,EAAE,SAAS;AACrD,aAAS,KAAK,EAAE,KAAK,0BAA0B,SAAS,uDAAuD,CAAC;AAClH,MAAI,CAAC,oBAAoB,KAAK,EAAE,OAAO;AACrC,aAAS,KAAK,EAAE,KAAK,wBAAwB,SAAS,2CAA2C,CAAC;AACpG,SAAO;AACT;AAGA,IAAM,cAAgD,EAAE,SAAS,QAAQ,YAAY,OAAO;AAkBrF,SAAS,YAAY,GAA2B;AACrD,MAAI,EAAE,QAAS,QAAO,YAAY,EAAE,OAAO,KAAK,EAAE;AAClD,QAAM,KAAK,EAAE;AACb,QAAM,OAAO,EAAE;AACf,MAAI,MAAM,MAAM;AACd,QAAI,OAAO,KAAM,QAAO;AACxB,QAAI,GAAG,WAAW,GAAG,IAAI,GAAG,EAAG,QAAO,GAAG,MAAM,KAAK,SAAS,CAAC;AAAA,EAChE;AACA,SAAO,EAAE,YAAY;AACvB;AAGA,SAAS,SAAS,KAAsB;AACtC,SAAO,2CAA2C,KAAK,GAAG;AAC5D;","names":[]}
@@ -5,8 +5,12 @@ interface MobileSentryConfig {
5
5
  dsn: string;
6
6
  /** The Qore environment name, the same as the server's `QORE_ENV`, so phone and server filter together. */
7
7
  environment: string;
8
- /** The app's own server. Trace headers go there and nowhere else. */
9
- serverUrl: string;
8
+ /**
9
+ * The app's own server. Trace headers go there and nowhere else. A function
10
+ * is asked on every request: pass `server.current` of a `ServerResolver`,
11
+ * whose answer is not known yet when Sentry starts.
12
+ */
13
+ serverUrl: string | (() => string | null);
10
14
  /** Defaults to `<slug>@<version>+<build>` from the app config. */
11
15
  release?: string;
12
16
  }
@@ -22,13 +22,20 @@ var tagSpan = (s) => {
22
22
  scrubbed.data = { ...scrubbed.data, ...APP_TAG };
23
23
  return scrubbed;
24
24
  };
25
- var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
25
+ var PRODUCTION = /* @__PURE__ */ new Set(["prod", "production"]);
26
+ function isOnServer(url, origin) {
27
+ if (!origin) return false;
28
+ const o = origin.replace(/\/+$/, "");
29
+ if (!url.startsWith(o)) return false;
30
+ const next = url.charAt(o.length);
31
+ return next === "" || next === "/" || next === "?" || next === "#";
32
+ }
26
33
  function releaseName(slug, version, build) {
27
34
  return `${slug || "app"}@${version || "0.0.0"}${build ? `+${build}` : ""}`;
28
35
  }
29
36
  function buildMobileOptions(cfg) {
30
- const production = cfg.environment === "production";
31
- const origin = cfg.serverUrl.replace(/\/+$/, "");
37
+ const production = PRODUCTION.has(cfg.environment);
38
+ const server = cfg.serverUrl;
32
39
  return {
33
40
  dsn: cfg.dsn,
34
41
  environment: cfg.environment,
@@ -36,8 +43,8 @@ function buildMobileOptions(cfg) {
36
43
  // Who it was is the Keycloak subject (setTelemetryUser), never a name or address.
37
44
  sendDefaultPii: false,
38
45
  dataCollection: { urlQueryParams: { deny: [...SECRET_PARAMS] } },
39
- // The origin plus a path boundary, so `https://app.example` does not match `https://app.example.evil`.
40
- tracePropagationTargets: [new RegExp(`^${escapeRe(origin)}(?:[/?#]|$)`)],
46
+ // A function target: Sentry asks it per request, so it follows the resolver.
47
+ tracePropagationTargets: [(url) => isOnServer(url, typeof server === "string" ? server : server())],
41
48
  tracesSampleRate: production ? 0.1 : 1,
42
49
  enableLogs: true,
43
50
  // Logs are what the app says through `log`, not whatever reaches console.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/expo/sentry/index.ts","../../../src/expo/sentry/options.ts"],"sourcesContent":["// @quatronic/sdk/expo/sentry — errors, traces, logs and masked Replay for a\n// Qore mobile app, into the module's Sentry project with tag app=mobile.\n// Runs on the device; the web counterpart is `@quatronic/sdk/next/sentry`.\nimport * as Sentry from \"@sentry/react-native\"\nimport Constants from \"expo-constants\"\nimport { useEffect, type ComponentType } from \"react\"\nimport { buildMobileOptions, NAVIGATION_OPTIONS, releaseName, REPLAY_OPTIONS, type MobileSentryConfig } from \"./options\"\n\n// Created at import, as Sentry requires, and registered by useNavigationTelemetry.\n// Sentry's expoRouterIntegration looks for a module Expo Router 58 no longer\n// ships and then does nothing, so the container is registered by hand.\nconst navigation = Sentry.reactNavigationIntegration({ ...NAVIGATION_OPTIONS })\nlet enabled = false\n\n/** Call once, at the top of the root layout module, before anything renders. No DSN, no Sentry. */\nexport function qoreSentryInit(cfg: MobileSentryConfig): void {\n if (!cfg.dsn || enabled) return\n enabled = true\n const release = cfg.release ?? releaseName(Constants.expoConfig?.slug, Constants.expoConfig?.version, Constants.nativeBuildVersion)\n Sentry.init({\n ...buildMobileOptions({ ...cfg, release }),\n // Replay is native only: Expo Go skips it, a development or store build records.\n integrations: [navigation, Sentry.mobileReplayIntegration({ ...REPLAY_OPTIONS })],\n })\n}\n\n/** On sign-in and sign-out: the Keycloak subject only, as on the server. Pass it to `QoreAuthProvider`'s `onUserChange`. */\nexport function setTelemetryUser(sub: string | null): void {\n if (enabled) Sentry.setUser(sub ? { id: sub } : null)\n}\n\n/**\n * In the root layout, with Expo Router's `useNavigationContainerRef()`: one\n * transaction per screen, tab switches included, which the screen's API calls\n * hang under.\n */\nexport function useNavigationTelemetry(navigationRef: unknown): void {\n useEffect(() => {\n if (enabled && navigationRef) navigation.registerNavigationContainer(navigationRef)\n }, [navigationRef])\n}\n\n/** Wrap the root layout's default export: catches render errors and adds touch breadcrumbs. */\nexport function wrap<P extends object>(component: ComponentType<P>): ComponentType<P> {\n return Sentry.wrap(component)\n}\n\nexport { releaseName } from \"./options\"\nexport type { MobileSentryConfig } from \"./options\"\n","// Pure half of `expo/sentry`: the init options, unit-tested in Node.\nimport { SECRET_PARAMS, scrubEvent, scrubLog, scrubSpan } from \"../../sentry-core/scrub\"\n\nexport interface MobileSentryConfig {\n /** The module's Sentry DSN (public by design). Empty turns Sentry off. */\n dsn: string\n /** The Qore environment name, the same as the server's `QORE_ENV`, so phone and server filter together. */\n environment: string\n /** The app's own server. Trace headers go there and nowhere else. */\n serverUrl: string\n /** Defaults to `<slug>@<version>+<build>` from the app config. */\n release?: string\n}\n\n/** Tells phone events from server ones in the shared project. */\nconst APP_TAG = { app: \"mobile\" } as const\n\n// The scope's tags reach errors and transactions only: Sentry Logs and child\n// spans never see them, so those carry the tag as an attribute.\nconst tagLog = <L extends Parameters<typeof scrubLog>[0]>(l: L): L => {\n const scrubbed = scrubLog(l)\n scrubbed.attributes = { ...scrubbed.attributes, ...APP_TAG }\n return scrubbed\n}\nconst tagSpan = <S extends Parameters<typeof scrubSpan>[0]>(s: S): S => {\n const scrubbed = scrubSpan(s)\n scrubbed.data = { ...scrubbed.data, ...APP_TAG }\n return scrubbed\n}\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\n/** `<slug>@<version>+<build>`; the build is left off when unknown (Expo Go). */\nexport function releaseName(slug: string | undefined, version: string | undefined, build: string | null | undefined): string {\n return `${slug || \"app\"}@${version || \"0.0.0\"}${build ? `+${build}` : \"\"}`\n}\n\n/**\n * Everything `Sentry.init` gets except the integrations, which need the\n * native module. Scrubbing is the server's (`sentry-core/scrub`), so the\n * phone and the server redact the same things.\n */\nexport function buildMobileOptions(cfg: MobileSentryConfig & { release: string }) {\n const production = cfg.environment === \"production\"\n const origin = cfg.serverUrl.replace(/\\/+$/, \"\")\n return {\n dsn: cfg.dsn,\n environment: cfg.environment,\n release: cfg.release,\n // Who it was is the Keycloak subject (setTelemetryUser), never a name or address.\n sendDefaultPii: false,\n dataCollection: { urlQueryParams: { deny: [...SECRET_PARAMS] } },\n // The origin plus a path boundary, so `https://app.example` does not match `https://app.example.evil`.\n tracePropagationTargets: [new RegExp(`^${escapeRe(origin)}(?:[/?#]|$)`)],\n tracesSampleRate: production ? 0.1 : 1,\n enableLogs: true,\n // Logs are what the app says through `log`, not whatever reaches console.\n enableAutoConsoleLogs: false,\n replaysSessionSampleRate: production ? 0.1 : 1,\n replaysOnErrorSampleRate: 1,\n initialScope: { tags: { ...APP_TAG } },\n beforeSend: scrubEvent,\n beforeSendTransaction: scrubEvent,\n beforeSendLog: tagLog,\n beforeSendSpan: tagSpan,\n }\n}\n\n/**\n * The navigation integration's options. With Sentry's default\n * (`ignoreEmptyBackNavigationTransactions: true`) a navigation to a route it\n * has seen before is dropped when nothing hangs under it — which is exactly a\n * switch back to a tab that is already mounted, so tab switches never showed up.\n */\nexport const NAVIGATION_OPTIONS = {\n ignoreEmptyBackNavigationTransactions: false,\n // `(tabs)/explore`, not `explore`: the route file, so two screens with one name stay apart.\n useFullPathsForNavigationRoutes: true,\n enableTimeToInitialDisplay: true,\n} as const\n\n/** Session Replay records shapes only: every text, image and vector is masked on the phone. Never unmask by default. */\nexport const REPLAY_OPTIONS = { maskAllText: true, maskAllImages: true, maskAllVectors: true } as const\n"],"mappings":";;;;;;;;AAGA,YAAY,YAAY;AACxB,OAAO,eAAe;AACtB,SAAS,iBAAqC;;;ACU9C,IAAM,UAAU,EAAE,KAAK,SAAS;AAIhC,IAAM,SAAS,CAA2C,MAAY;AACpE,QAAM,WAAW,SAAS,CAAC;AAC3B,WAAS,aAAa,EAAE,GAAG,SAAS,YAAY,GAAG,QAAQ;AAC3D,SAAO;AACT;AACA,IAAM,UAAU,CAA4C,MAAY;AACtE,QAAM,WAAW,UAAU,CAAC;AAC5B,WAAS,OAAO,EAAE,GAAG,SAAS,MAAM,GAAG,QAAQ;AAC/C,SAAO;AACT;AAEA,IAAM,WAAW,CAAC,MAAc,EAAE,QAAQ,uBAAuB,MAAM;AAGhE,SAAS,YAAY,MAA0B,SAA6B,OAA0C;AAC3H,SAAO,GAAG,QAAQ,KAAK,IAAI,WAAW,OAAO,GAAG,QAAQ,IAAI,KAAK,KAAK,EAAE;AAC1E;AAOO,SAAS,mBAAmB,KAA+C;AAChF,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,SAAS,IAAI,UAAU,QAAQ,QAAQ,EAAE;AAC/C,SAAO;AAAA,IACL,KAAK,IAAI;AAAA,IACT,aAAa,IAAI;AAAA,IACjB,SAAS,IAAI;AAAA;AAAA,IAEb,gBAAgB;AAAA,IAChB,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,CAAC,GAAG,aAAa,EAAE,EAAE;AAAA;AAAA,IAE/D,yBAAyB,CAAC,IAAI,OAAO,IAAI,SAAS,MAAM,CAAC,aAAa,CAAC;AAAA,IACvE,kBAAkB,aAAa,MAAM;AAAA,IACrC,YAAY;AAAA;AAAA,IAEZ,uBAAuB;AAAA,IACvB,0BAA0B,aAAa,MAAM;AAAA,IAC7C,0BAA0B;AAAA,IAC1B,cAAc,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE;AAAA,IACrC,YAAY;AAAA,IACZ,uBAAuB;AAAA,IACvB,eAAe;AAAA,IACf,gBAAgB;AAAA,EAClB;AACF;AAQO,IAAM,qBAAqB;AAAA,EAChC,uCAAuC;AAAA;AAAA,EAEvC,iCAAiC;AAAA,EACjC,4BAA4B;AAC9B;AAGO,IAAM,iBAAiB,EAAE,aAAa,MAAM,eAAe,MAAM,gBAAgB,KAAK;;;ADvE7F,IAAM,aAAoB,kCAA2B,EAAE,GAAG,mBAAmB,CAAC;AAC9E,IAAI,UAAU;AAGP,SAAS,eAAe,KAA+B;AAC5D,MAAI,CAAC,IAAI,OAAO,QAAS;AACzB,YAAU;AACV,QAAM,UAAU,IAAI,WAAW,YAAY,UAAU,YAAY,MAAM,UAAU,YAAY,SAAS,UAAU,kBAAkB;AAClI,EAAO,YAAK;AAAA,IACV,GAAG,mBAAmB,EAAE,GAAG,KAAK,QAAQ,CAAC;AAAA;AAAA,IAEzC,cAAc,CAAC,YAAmB,+BAAwB,EAAE,GAAG,eAAe,CAAC,CAAC;AAAA,EAClF,CAAC;AACH;AAGO,SAAS,iBAAiB,KAA0B;AACzD,MAAI,QAAS,CAAO,eAAQ,MAAM,EAAE,IAAI,IAAI,IAAI,IAAI;AACtD;AAOO,SAAS,uBAAuB,eAA8B;AACnE,YAAU,MAAM;AACd,QAAI,WAAW,cAAe,YAAW,4BAA4B,aAAa;AAAA,EACpF,GAAG,CAAC,aAAa,CAAC;AACpB;AAGO,SAASA,MAAuB,WAA+C;AACpF,SAAc,YAAK,SAAS;AAC9B;","names":["wrap"]}
1
+ {"version":3,"sources":["../../../src/expo/sentry/index.ts","../../../src/expo/sentry/options.ts"],"sourcesContent":["// @quatronic/sdk/expo/sentry — errors, traces, logs and masked Replay for a\n// Qore mobile app, into the module's Sentry project with tag app=mobile.\n// Runs on the device; the web counterpart is `@quatronic/sdk/next/sentry`.\nimport * as Sentry from \"@sentry/react-native\"\nimport Constants from \"expo-constants\"\nimport { useEffect, type ComponentType } from \"react\"\nimport { buildMobileOptions, NAVIGATION_OPTIONS, releaseName, REPLAY_OPTIONS, type MobileSentryConfig } from \"./options\"\n\n// Created at import, as Sentry requires, and registered by useNavigationTelemetry.\n// Sentry's expoRouterIntegration looks for a module Expo Router 58 no longer\n// ships and then does nothing, so the container is registered by hand.\nconst navigation = Sentry.reactNavigationIntegration({ ...NAVIGATION_OPTIONS })\nlet enabled = false\n\n/** Call once, at the top of the root layout module, before anything renders. No DSN, no Sentry. */\nexport function qoreSentryInit(cfg: MobileSentryConfig): void {\n if (!cfg.dsn || enabled) return\n enabled = true\n const release = cfg.release ?? releaseName(Constants.expoConfig?.slug, Constants.expoConfig?.version, Constants.nativeBuildVersion)\n Sentry.init({\n ...buildMobileOptions({ ...cfg, release }),\n // Replay is native only: Expo Go skips it, a development or store build records.\n integrations: [navigation, Sentry.mobileReplayIntegration({ ...REPLAY_OPTIONS })],\n })\n}\n\n/** On sign-in and sign-out: the Keycloak subject only, as on the server. Pass it to `QoreAuthProvider`'s `onUserChange`. */\nexport function setTelemetryUser(sub: string | null): void {\n if (enabled) Sentry.setUser(sub ? { id: sub } : null)\n}\n\n/**\n * In the root layout, with Expo Router's `useNavigationContainerRef()`: one\n * transaction per screen, tab switches included, which the screen's API calls\n * hang under.\n */\nexport function useNavigationTelemetry(navigationRef: unknown): void {\n useEffect(() => {\n if (enabled && navigationRef) navigation.registerNavigationContainer(navigationRef)\n }, [navigationRef])\n}\n\n/** Wrap the root layout's default export: catches render errors and adds touch breadcrumbs. */\nexport function wrap<P extends object>(component: ComponentType<P>): ComponentType<P> {\n return Sentry.wrap(component)\n}\n\nexport { releaseName } from \"./options\"\nexport type { MobileSentryConfig } from \"./options\"\n","// Pure half of `expo/sentry`: the init options, unit-tested in Node.\nimport { SECRET_PARAMS, scrubEvent, scrubLog, scrubSpan } from \"../../sentry-core/scrub\"\n\nexport interface MobileSentryConfig {\n /** The module's Sentry DSN (public by design). Empty turns Sentry off. */\n dsn: string\n /** The Qore environment name, the same as the server's `QORE_ENV`, so phone and server filter together. */\n environment: string\n /**\n * The app's own server. Trace headers go there and nowhere else. A function\n * is asked on every request: pass `server.current` of a `ServerResolver`,\n * whose answer is not known yet when Sentry starts.\n */\n serverUrl: string | (() => string | null)\n /** Defaults to `<slug>@<version>+<build>` from the app config. */\n release?: string\n}\n\n/** Tells phone events from server ones in the shared project. */\nconst APP_TAG = { app: \"mobile\" } as const\n\n// The scope's tags reach errors and transactions only: Sentry Logs and child\n// spans never see them, so those carry the tag as an attribute.\nconst tagLog = <L extends Parameters<typeof scrubLog>[0]>(l: L): L => {\n const scrubbed = scrubLog(l)\n scrubbed.attributes = { ...scrubbed.attributes, ...APP_TAG }\n return scrubbed\n}\nconst tagSpan = <S extends Parameters<typeof scrubSpan>[0]>(s: S): S => {\n const scrubbed = scrubSpan(s)\n scrubbed.data = { ...scrubbed.data, ...APP_TAG }\n return scrubbed\n}\n\n/** The portal calls production `prod`; the starter used to say `production`. */\nconst PRODUCTION: ReadonlySet<string> = new Set([\"prod\", \"production\"])\n\n/** `url` is on `origin`, with a path boundary, so `https://app.example` does not match `https://app.example.evil`. */\nfunction isOnServer(url: string, origin: string | null): boolean {\n if (!origin) return false\n const o = origin.replace(/\\/+$/, \"\")\n if (!url.startsWith(o)) return false\n const next = url.charAt(o.length)\n return next === \"\" || next === \"/\" || next === \"?\" || next === \"#\"\n}\n\n/** `<slug>@<version>+<build>`; the build is left off when unknown (Expo Go). */\nexport function releaseName(slug: string | undefined, version: string | undefined, build: string | null | undefined): string {\n return `${slug || \"app\"}@${version || \"0.0.0\"}${build ? `+${build}` : \"\"}`\n}\n\n/**\n * Everything `Sentry.init` gets except the integrations, which need the\n * native module. Scrubbing is the server's (`sentry-core/scrub`), so the\n * phone and the server redact the same things.\n */\nexport function buildMobileOptions(cfg: MobileSentryConfig & { release: string }) {\n const production = PRODUCTION.has(cfg.environment)\n const server = cfg.serverUrl\n return {\n dsn: cfg.dsn,\n environment: cfg.environment,\n release: cfg.release,\n // Who it was is the Keycloak subject (setTelemetryUser), never a name or address.\n sendDefaultPii: false,\n dataCollection: { urlQueryParams: { deny: [...SECRET_PARAMS] } },\n // A function target: Sentry asks it per request, so it follows the resolver.\n tracePropagationTargets: [(url: string) => isOnServer(url, typeof server === \"string\" ? server : server())],\n tracesSampleRate: production ? 0.1 : 1,\n enableLogs: true,\n // Logs are what the app says through `log`, not whatever reaches console.\n enableAutoConsoleLogs: false,\n replaysSessionSampleRate: production ? 0.1 : 1,\n replaysOnErrorSampleRate: 1,\n initialScope: { tags: { ...APP_TAG } },\n beforeSend: scrubEvent,\n beforeSendTransaction: scrubEvent,\n beforeSendLog: tagLog,\n beforeSendSpan: tagSpan,\n }\n}\n\n/**\n * The navigation integration's options. With Sentry's default\n * (`ignoreEmptyBackNavigationTransactions: true`) a navigation to a route it\n * has seen before is dropped when nothing hangs under it — which is exactly a\n * switch back to a tab that is already mounted, so tab switches never showed up.\n */\nexport const NAVIGATION_OPTIONS = {\n ignoreEmptyBackNavigationTransactions: false,\n // `(tabs)/explore`, not `explore`: the route file, so two screens with one name stay apart.\n useFullPathsForNavigationRoutes: true,\n enableTimeToInitialDisplay: true,\n} as const\n\n/** Session Replay records shapes only: every text, image and vector is masked on the phone. Never unmask by default. */\nexport const REPLAY_OPTIONS = { maskAllText: true, maskAllImages: true, maskAllVectors: true } as const\n"],"mappings":";;;;;;;;AAGA,YAAY,YAAY;AACxB,OAAO,eAAe;AACtB,SAAS,iBAAqC;;;ACc9C,IAAM,UAAU,EAAE,KAAK,SAAS;AAIhC,IAAM,SAAS,CAA2C,MAAY;AACpE,QAAM,WAAW,SAAS,CAAC;AAC3B,WAAS,aAAa,EAAE,GAAG,SAAS,YAAY,GAAG,QAAQ;AAC3D,SAAO;AACT;AACA,IAAM,UAAU,CAA4C,MAAY;AACtE,QAAM,WAAW,UAAU,CAAC;AAC5B,WAAS,OAAO,EAAE,GA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