@qafka/react-native-cms 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,245 @@
1
- # Temporary Holding Version
1
+ # @qafka/react-native-cms
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Kodlama ajanları için: [`AGENTS.md`](./AGENTS.md) (kurulum, imzalar, kurallar, tüm dışa aktarımlar).
4
+
5
+ QafkaCMS'in React Native **runtime** SDK'sı. Consumer app içinde çalışır; uygulama raw REST yerine bu sanctioned client'a konuşur (attestation zorunlu+native).
6
+
7
+ > **Faz 1 Foundation** (QFK2-E22). Runtime view-config renderer + CMS-driven UI component'leri → QFK2-E45.
8
+
9
+ ## Katmanlar
10
+
11
+ | Katman | Sorumluluk |
12
+ |---|---|
13
+ | `AuthClient` | register / login / refresh / logout / magic-link (end-user JWT) |
14
+ | `ContentClient` | content CRUD + filter + cursor pagination + locale (`?locale=`) |
15
+ | `AttestationManager` | iOS App Attest / Android Key Attestation → device session token |
16
+ | secure `storage` | Keychain / EncryptedSharedPreferences (kendi native modülümüz) |
17
+ | `ContentChangeHub` | içerik canlı güncelleme: `useContent(c, params, { live: true })` — koleksiyonda değişiklik sinyali açıkken tek SSE bağlantısı (polling yedek), veri taşımaz, kendi yetkisiyle yeniden çeker (`client.contentChanges`) |
18
+ | `ConfigSyncClient` | config **polling** (varsayılan) + REST snapshot; SSE version-watch `{ live: true }` ile opt-in (translations/theme/nav) |
19
+ | `LanguageManager` | aktif dil + persist + `t()` (locales/i18n config domain) — `useLocale`/`useTranslation` |
20
+ | `QafkaCmsProvider` + hooks | Client paylaşımı + boot lifecycle + reactive query cache (TTL/persist/boot-prefetch) + auth→cache + locale→cache reset — `useContent`/`useQuery`/`useMutation`/`useAuth`/`useLocale`/`useTranslation`/`useQafkaCms` |
21
+
22
+ ## Güven eksenleri
23
+
24
+ Her istek koşullu olarak şu başlıkları taşır:
25
+
26
+ - `Authorization: Bearer <accessToken>` — **end-user kimliği** (E7 JWT)
27
+ - `X-Session-Token: <sessionToken>` — **cihaz güveni** (E22 attestation)
28
+ - `X-Project-Key: <qpk_…>` — **proje kimliği** (publishable key; panelden üretilir). `Authorization: Bearer` taşımayan (anonim / token'sız) isteklerde ve attestation el sıkışmasında (her zaman) gönderilir; Bearer varsa eklenmez. SSE (`live: true`) aynı kuralı izler.
29
+ - `X-Project-Id: <uuid>` — **proje kimliği (mobil)**: panelden kopyalanan, gizli olmayan proje id'si. Her istekte ve attestation el sıkışmasında gönderilir; sunucu bunun yanında cihaz kanıtı ister: release'te `X-Session-Token`, dev'de projeye bağlı TEST anahtarı (`x-api-key`, yalnız dev-bypass'ta gönderilir).
30
+ - `X-Project-Slug: <slug>` — opsiyonel proje etiketi (kimlik doğrulamaz)
31
+
32
+ Mobilde `projectId` yeterlidir; `publishableKey` artık opsiyoneldir (web / mevcut kurulumlar). İkisi de yoksa `createClient` `QafkaCMS: projectId is required (or a publishableKey qpk_…)` hatası fırlatır; verilen `publishableKey` yine `qpk_` ile başlamalıdır. `projectId` dev'de `devConfig` içindeki TEST anahtarını da seçer; CLI'sız yol: `apiKey: __DEV__ ? process.env.EXPO_PUBLIC_QAFKA_TEST_KEY : undefined` (`.env.local`, Release paketine girmez). Push kullanmayan uygulama yalnız `@qafka/react-native-cms/expo-plugin/withQafkaCmsAttestation` plugin'ini ekler. Sunucu hata kodları (`PROJECT_REQUIRED`, `ATTESTATION_REQUIRED`, `APP_NOT_REGISTERED`, `PROJECT_MISMATCH`) iOS anahtarının yeniden üretilmesini asla tetiklemez. Sunucu bu kodları RFC 7807 hata gövdesinin `code` alanında döner (`{ type, title, status, detail, code }`).
33
+
34
+ > **Yükseltme notu:** `projectId` artık release build'lerde de `X-Project-Id` başlığı olarak her isteğe eklenir ve sunucu onu proje kimliği olarak doğrular. Değer, panelde görünen projenin id'si (UUID) olmalıdır. `projectId`'yi yalnız dev config seçicisi olarak başka bir değerle (slug, takma ad vb.) kullanan uygulamalar bunu düzeltmelidir: yanlış değer publishable key ile birlikte `400` (`X-Project-Id does not match the project key`), anahtarsız `401 ATTESTATION_REQUIRED` alır.
35
+
36
+ ## Kendi HTTP istemcinle kullanma
37
+
38
+ SDK'nın taşıdığı proje + kanıt başlıklarını kendi `fetch`/axios istemcine ekleyebilirsin:
39
+
40
+ ```ts
41
+ const proof = await cms.getRequestHeaders(); // attestation hazır değilse bir kez başlatır
42
+ // release: { 'X-Project-Id', 'X-Session-Token' } · dev-bypass: { 'X-Project-Id', 'x-api-key' }
43
+ // publishableKey ile kurulduysa X-Project-Key de gelir; projectSlug varsa X-Project-Slug
44
+ const res = await fetch(`${apiUrl}/v1/end-user/content/posts`, {
45
+ headers: { ...proof, Authorization: `Bearer ${accessToken}` },
46
+ });
47
+
48
+ // Yalnız 401 ATTESTATION_SESSION_EXPIRED (oturum doldu) ya da 429 + X-Token-Refresh-Required aldıysan, bir kez:
49
+ const fresh = await cms.refreshRequestHeaders();
50
+ // ATTESTATION_REQUIRED (kanıt yok/yanlış), APP_NOT_REGISTERED, PROJECT_MISMATCH, DEVICE_NOT_TRUSTED, ATTESTATION_REVOKED: yeniden deneme, göster.
51
+ ```
52
+
53
+ `Authorization`, `Content-Type` ve `Accept-Language` dönmez; onları sen eklersin.
54
+
55
+ ## Kullanım
56
+
57
+ ```ts
58
+ import { createClient } from '@qafka/react-native-cms';
59
+
60
+ const cms = createClient({ apiUrl: 'https://api.qafkacms.com', projectId: '<panelden proje id (UUID)>' });
61
+ await cms.initialize(); // session hydrate + device attestation
62
+
63
+ await cms.auth.login({ email, password });
64
+ const { docs } = await cms.content.list('posts', { filter: { status: { _eq: 'active' } }, limit: 20 });
65
+
66
+ const theme = cms.createConfigSync('theme', { primary: '#000' }); // polling (varsayılan)
67
+ await theme.start();
68
+ theme.subscribe((t) => applyTheme(t));
69
+
70
+ // Sadece gerçekten saniye-altı push gereken domain için SSE aç (örn. kill-switch):
71
+ // cms.createConfigSync('feature_flags', { flags: {} }, { live: true });
72
+ ```
73
+
74
+ ### External identity provider
75
+
76
+ Kendi kimlik sağlayıcınız (Firebase, Auth0, ...) varsa:
77
+
78
+ ```ts
79
+ const cms = createClient({ projectId, externalTokenProvider: async () => myAuth.getFreshToken() }); // oturum bittiyse null
80
+ const { endUser, created } = await cms.auth.signInWithExternalToken(idpToken);
81
+ await cms.auth.linkExternal(idpToken); // giriş yapmış üyeye bağla -> { endUser }
82
+ await cms.auth.unlinkExternal(); // -> { endUser }
83
+ ```
84
+
85
+ Dış oturumda refresh token yoktur; CMS access token süresi dolunca ve uygulama yeniden açılınca `externalTokenProvider` çağrılır (`null` dönerse oturum kapanır). `logout()` yalnız yerelde temizler. Hata kodları `ProblemError.raw.code`: 401 `INVALID_EXTERNAL_TOKEN`/`IDENTITY_DEACTIVATED`/`ACCOUNT_DEACTIVATED`; 403 `EXTERNAL_AUTH_DISABLED`/`EXTERNAL_SIGNUP_DISABLED`/`INTERNAL_AUTH_DISABLED`; 409 `IDENTITY_IN_USE`/`ACCOUNT_EXISTS_LINK_REQUIRED`/`LAST_SIGN_IN_METHOD`; 502 `EXTERNAL_PROVIDER_UNAVAILABLE`.
86
+
87
+ > **Transport (E56):** config domain'leri varsayılan **polling** ile senkronlanır — saniye-altı tazelik gerektirmediği için her domain'e kalıcı SSE bağlantısı açmak 300k ölçekte gereksiz pahalı. SSE yalnız `{ live: true }` ile, gerçekten anlık push gereken tek bir domain için. Backend tarafında published-config okumaları kısa-TTL cache'lenir + publish'te invalidate edilir (publish thundering herd koruması).
88
+ >
89
+ > **Poll aralığı** varsayılan ~60s; tek yerden `createClient({ configPollIntervalMs: 60_000 })` ile yönetilir (SDK-managed `locales`/`i18n` dahil). Developer her çağrıda yazmaz. Güvenli bir **tabanın (30s) altına inemez** — verilen daha küçük değer yukarı clamp'lenir (hem `configPollIntervalMs` hem per-domain `pollIntervalMs`). Daha hızlı gerekiyorsa polling değil, `live: true` (SSE).
90
+ >
91
+ > **Poll verimliliği (E56):** Her tick'te tam payload değil — önce ucuz `/config/:domain/version` çekilir; **yalnız versiyon arttığında** snapshot indirilir (değişmemiş translations KB'ı boşuna inmez). App **arka plana geçince polling durur**, foreground'a dönünce yeniden başlar + hemen bir versiyon kontrolü yapar (RN `AppState`; `createClient({ appState })` ile override edilebilir). İlk poll'a **jitter** uygulanır — restart/foreground sonrası tüm cihazların aynı anda poll etmesini dağıtır.
92
+
93
+ ## React Provider + hooks
94
+
95
+ İmperatif `createClient` hâlâ çekirdek; üstüne **reactive** bir katman var. App `createClient`'ı kurar (deps DI elde kalır), Provider'a `client` geçer; Provider `initialize()`'ı (token hydrate + attestation) sahiplenir, boot'ta seçili API'leri ısıtır ve reactive query cache'i sağlar.
96
+
97
+ ```tsx
98
+ import { createClient, QafkaCmsProvider, useContent } from '@qafka/react-native-cms';
99
+
100
+ const client = createClient({ apiUrl: 'https://api.qafkacms.com', projectId: '<proje id>' });
101
+
102
+ export function Root() {
103
+ return (
104
+ <QafkaCmsProvider
105
+ client={client}
106
+ prefetch={[
107
+ // boot'ta Promise.all ile ısıtılır; gate:true olanlar fallback arkasında beklenir
108
+ { key: ['content', 'categories', {}], gate: true, ttl: '1h', persist: true,
109
+ fetch: (c) => c.content.list('categories') },
110
+ { key: ['content', 'banners', {}], ttl: '10m', persist: true,
111
+ fetch: (c) => c.content.list('banners') }, // fire-and-forget
112
+ ]}
113
+ fallback={<Splash />} // gate:true bitene dek; yoksa render-through
114
+ >
115
+ <App />
116
+ </QafkaCmsProvider>
117
+ );
118
+ }
119
+
120
+ function Categories() {
121
+ // 'categories' prefetch+persist edildi → anında; bayatsa arkada revalidate
122
+ const { data, isLoading, isFetching, refetch } = useContent('categories', undefined, { ttl: '1h' });
123
+ // useQuery(key, (client) => …) ile herhangi bir çağrıyı da cache'leyebilirsin
124
+ }
125
+ ```
126
+
127
+ Sıralama ve ilişki: `sort` (en çok 3 anahtar, `-` = azalan) ve `expand` (RELATION alanını tek seviye satır içine alır).
128
+
129
+ ```tsx
130
+ const { data: malls } = useContent('shopping_malls', { sort: ['order'], expand: ['city'] });
131
+ const { data: mall } = useContentItem('shopping_malls', id, { expand: ['city'] });
132
+ // imperatif: client.content.list('stores', { sort: '-created_at', page: 2 })
133
+ ```
134
+
135
+ Sıralı liste `page` ile sayfalanır; `sort` + `cursor` birlikte backend'de 400 döner. Parametreler cache anahtarına girer (expand'li ve expand'siz okuma ayrı tutulur). `useContentItem` imzası: `(collection, id, params?, options?)`.
136
+
137
+ Cache davranışı: **in-flight dedupe** · **TTL freshness** (taze veride ağ yok) · **stale-while-revalidate** · **stale-on-error** (hata olunca eski veri durur) · **epoch ile race koruması** · opsiyonel **persist** (timestamp'le → restart'ta TTL korunur). Motor `useSyncExternalStore` + paylaşılan `QueryCache`; aynı key'i mount eden tüm ekranlar tek entry'yi paylaşır.
138
+
139
+ Lifecycle: `useQafkaCms()` → `{ status: 'initializing'|'ready'|'error', error, retry, clearCache }`. Provider `initialize()`'ı sahiplendiği için **ayrıca `client.initialize()` çağırma**.
140
+
141
+ Auth: `useAuth()` → `{ isAuthenticated, userId, roles }`, login/refresh/logout'ta reactive (her istekte `Authorization: Bearer` otomatik iliştirilir + transparan refresh, concurrent istekler tek `/refresh`'e coalesce edilir).
142
+
143
+ ```tsx
144
+ import { useAuth } from '@qafka/react-native-cms';
145
+ function Gate() {
146
+ const { isAuthenticated, roles } = useAuth();
147
+ return isAuthenticated ? <Home premium={roles.includes('premium')} /> : <Login />;
148
+ }
149
+ ```
150
+
151
+ **Login/logout'ta cache otomatik resetlenir** — kimlik değişince önceki kullanıcının server-scoped verisi sızmasın diye cache temizlenir (login'de mount'lu sorgular yeni token'la refetch eder; token refresh aynı kimlik olduğundan cache'e dokunmaz). Manuel reset gerekirse `useQafkaCms().clearCache()`.
152
+
153
+ Persist: `persist: true` query'leri, config-sync anlık görüntüleri ve kayıtlı dil varsayılan olarak SDK'nın **kendi secure store'una** (Keychain / EncryptedSharedPreferences, token'larla aynı) yazılır; o zaman persist'i **küçük/nadir değişen referans datası** için kullan (categories, config). Düz bir depo verirsen (`createClient({ ..., cacheStorage: AsyncStorage })` ya da MMKV sarmalayıcısı, QFK2-T471) bunların hepsi ve (kendi `storage`'ı verilmemişse) içerik paketi oraya gider; oturum verisi (refresh token, unlock token, attestation, cihaz kimliği) secure store'da kalır. Secure store'daki eski kopyalar ilk okunuşta düz depoya taşınır, geçişte önbellek ve dil kaybolmaz. Sadece persist'lenenler yazılır, gerisi bellekte state.
154
+
155
+ ## Yazma — `useMutation`
156
+
157
+ Yazma çağrıları + otomatik (prefix-bazlı) invalidation:
158
+
159
+ ```tsx
160
+ import { useMutation, useContent } from '@qafka/react-native-cms';
161
+
162
+ function Posts() {
163
+ const { data } = useContent('posts');
164
+ const create = useMutation(
165
+ (client, vars: { title: string }) => client.content.create('posts', vars),
166
+ { invalidate: [['content', 'posts']] }, // başarıda 'posts' query'lerini prefix'le tazele
167
+ );
168
+ // await create.mutate({ title: 'Merhaba' }); → create.isPending / .error / .data / .reset()
169
+ }
170
+ ```
171
+
172
+ `invalidate` key'leri **prefix** eşleşir (react-query gibi): `['content','posts']` tüm `content.list('posts', …)` varyantlarını tazeler — mount'lu ekran anında revalidate, mount'suz olan bir sonraki açılışta refetch. Manuel kontrol/optimistik için `useQafkaCmsCache()` (`invalidate` / `invalidateByPrefix` / `setData` / `refetch`).
173
+
174
+ ## i18n & Aktif dil (E55)
175
+
176
+ UI çevirileri (`i18n` config domain) + desteklenen diller (`locales` config domain) SDK-managed config-sync ile çekilir; `LanguageManager` aktif dili tutar (SDK'nın önbellek deposuna persist: `cacheStorage` verildiyse o, yoksa secure store) ve app geneline yayar. Aktif dil:
177
+
178
+ - her content isteğine **`?locale=`** query olarak iliştirilir → CMS o dilde içerik döner,
179
+ - ayrıca **`Accept-Language`** header olarak gider (backend önceliği: `?locale=` > `Accept-Language` > proje `defaultLocale`),
180
+ - `useTranslation().t()` ile UI string'lerini çözer (fallback: aktif → default → key; `{{param}}` interpolation).
181
+
182
+ Dil değişince content cache otomatik invalidate olur — mount'lu sorgular yeni dilde refetch eder.
183
+
184
+ ```tsx
185
+ import { useTranslation, useLocale } from '@qafka/react-native-cms';
186
+
187
+ function Screen() {
188
+ const { t, locale, setLocale } = useTranslation();
189
+ return (
190
+ <>
191
+ <Text>{t('greeting', { name: 'Ada' })}</Text> {/* "Merhaba Ada" */}
192
+ <Button title="EN" onPress={() => setLocale('en')} />
193
+ </>
194
+ );
195
+ }
196
+
197
+ function LanguagePicker() {
198
+ // availableLocales = `locales` config domain; setLocale persist eder + app-wide yayar
199
+ const { locale, availableLocales, defaultLocale, setLocale } = useLocale();
200
+ }
201
+ ```
202
+
203
+ İmperatif (hook'suz) kullanım:
204
+
205
+ ```ts
206
+ await cms.language.setLanguage('tr');
207
+ cms.language.t('greeting');
208
+ const { docs } = await cms.content.list('posts'); // ambient 'tr' → ?locale=tr
209
+ const fr = await cms.content.list('posts', { locale: 'fr' }); // bu istek için override
210
+ ```
211
+
212
+ ### Cold-start / build-time embed (E58)
213
+
214
+ Storage boş + network yokken (ilk kurulum) `t('key')` ham anahtarı göstermesin diye, en güncel çeviriler **build'e gömülebilir**. `qafka cms config pull` published config'i `qafkacms/{i18n,locales}.json`'a (`{ version, data }`, **commit'lenir**) yazar; `createClient`'a verirsin:
215
+
216
+ ```ts
217
+ const cms = createClient({
218
+ apiUrl, publishableKey,
219
+ bootstrap: {
220
+ i18n: require('./qafkacms/i18n.json'),
221
+ locales: require('./qafkacms/locales.json'),
222
+ },
223
+ });
224
+ ```
225
+
226
+ İlk frame'de gömülü çeviri görünür; runtime backend daha yeniyse **versiyona göre** yükseltir (gömülü version backend'le aynıysa snapshot çekilmez). `qafka cms config check` build öncesi gömülü config eskiyse **uyarır** (non-blocking; runtime nasılsa günceller), `--fix` ile pull eder.
227
+
228
+ ## Bağımlılık politikası
229
+
230
+ Production peer dependency yalnızca `react` + `react-native`. Third-party JS ~sıfır. Secure storage ve attestation kendi native modüllerimiz (`ios/`, `android/`); AsyncStorage/MMKV/keychain-lib yok. Native kod kardeş ürün Qafka'dan adapte (QFK2-Q6 = A).
231
+
232
+ Reactive katman da sıfır-bağımlılık: `useSyncExternalStore` (React 18+ peer) + kendi `QueryCache`'imiz (react-query/zustand yok). Query persist'i varsayılan olarak SDK'nın mevcut native storage'ına yazılır — ek bağımlılık yok; büyük önbellek için uygulama kendi AsyncStorage / MMKV'sini `cacheStorage` olarak verebilir (opsiyonel, SDK bağımlılık eklemez).
233
+
234
+ ## Geliştirme
235
+
236
+ ```
237
+ pnpm --filter @qafka/react-native-cms test # jest (react-native mock'lu)
238
+ pnpm --filter @qafka/react-native-cms typecheck
239
+ pnpm --filter @qafka/react-native-cms build # dist + .d.ts (tsup; core + react gömülü)
240
+ pnpm -r test # tüm workspace (core, react, react-native)
241
+ ```
242
+
243
+ Repo bir pnpm workspace'tir (QFK2-E73): bu paket `packages/react-native`; platformdan bağımsız kod dahili `packages/core` (`@qafka/cms-core`) ve `packages/react` (`@qafka/cms-react`) paketlerinde, build'de `dist/`'e gömülür (yayın `package.json`'unda `dependencies` yok). npm yayını `packages/react-native` içinden yapılır (`npm publish`; `prepublishOnly` build + typecheck + test çalıştırır).
244
+
245
+ > Native iOS/Android cihaz e2e (gerçek attestation→session token) bu pakette derlenmez — Xcode/Gradle + fiziksel cihaz gerektirir; ayrı QA adımı.
@@ -0,0 +1,41 @@
1
+ apply plugin: 'com.android.library'
2
+ apply plugin: 'kotlin-android'
3
+
4
+ def safeExtGet(prop, fallback) {
5
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
6
+ }
7
+
8
+ android {
9
+ namespace "com.qafkacms"
10
+ compileSdkVersion safeExtGet('compileSdkVersion', 34)
11
+
12
+ defaultConfig {
13
+ minSdkVersion safeExtGet('minSdkVersion', 24)
14
+ targetSdkVersion safeExtGet('targetSdkVersion', 34)
15
+ }
16
+
17
+ compileOptions {
18
+ sourceCompatibility JavaVersion.toVersion(safeExtGet('javaVersion', 17))
19
+ targetCompatibility JavaVersion.toVersion(safeExtGet('javaVersion', 17))
20
+ }
21
+
22
+ kotlinOptions {
23
+ jvmTarget = safeExtGet('javaVersion', 17).toString()
24
+ }
25
+ }
26
+
27
+ repositories {
28
+ google()
29
+ mavenCentral()
30
+ }
31
+
32
+ dependencies {
33
+ implementation 'com.facebook.react:react-android'
34
+ implementation 'androidx.security:security-crypto:1.1.0-alpha06'
35
+ // E57 — FCM token collection. Bundled by the SDK so the host app needs NO
36
+ // Firebase setup (no google-services.json / plugin): the module initializes a
37
+ // secondary FirebaseApp programmatically from the tenant's sender config.
38
+ // Gradle dedupes to one artifact if the host also depends on it; align via the
39
+ // Firebase BoM in the host if a version conflict surfaces (OQ4).
40
+ implementation 'com.google.firebase:firebase-messaging:24.1.0'
41
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,21 @@
1
+ package com.qafkacms
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+ import com.qafkacms.attestation.QafkaCmsAttestationModule
8
+ import com.qafkacms.push.QafkaCmsPushModule
9
+ import com.qafkacms.storage.QafkaCmsStorageModule
10
+
11
+ class QafkaCmsPackage : ReactPackage {
12
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
13
+ listOf(
14
+ QafkaCmsAttestationModule(reactContext),
15
+ QafkaCmsStorageModule(reactContext),
16
+ QafkaCmsPushModule(reactContext),
17
+ )
18
+
19
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> =
20
+ emptyList()
21
+ }
@@ -0,0 +1,92 @@
1
+ package com.qafkacms.attestation
2
+
3
+ import android.os.Build
4
+ import android.security.keystore.KeyGenParameterSpec
5
+ import android.security.keystore.KeyProperties
6
+ import android.util.Base64
7
+ import com.facebook.react.bridge.*
8
+ import java.security.KeyPairGenerator
9
+ import java.security.KeyStore
10
+ import java.security.cert.Certificate
11
+
12
+ class QafkaCmsAttestationModule(reactContext: ReactApplicationContext) :
13
+ ReactContextBaseJavaModule(reactContext) {
14
+
15
+ override fun getName(): String = "QafkaCmsAttestation"
16
+
17
+ override fun getConstants(): MutableMap<String, Any> {
18
+ val context = reactApplicationContext
19
+ val bundleId = context.packageName ?: ""
20
+ val appVersion = try {
21
+ context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: ""
22
+ } catch (e: Exception) {
23
+ ""
24
+ }
25
+ val deviceModel = "${Build.MANUFACTURER} ${Build.MODEL}".trim()
26
+ return mutableMapOf(
27
+ "bundleId" to bundleId,
28
+ "appVersion" to appVersion,
29
+ "deviceModel" to deviceModel,
30
+ )
31
+ }
32
+
33
+ @ReactMethod
34
+ fun isSupported(promise: Promise) {
35
+ // Key Attestation requires Android 8.0+ (API 26) for hardware-backed
36
+ promise.resolve(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
37
+ }
38
+
39
+ @ReactMethod
40
+ fun generateKeyPair(alias: String, challengeBase64: String, promise: Promise) {
41
+ try {
42
+ val challenge = Base64.decode(challengeBase64, Base64.DEFAULT)
43
+
44
+ // Delete existing key if any
45
+ val keyStore = KeyStore.getInstance("AndroidKeyStore")
46
+ keyStore.load(null)
47
+ if (keyStore.containsAlias(alias)) {
48
+ keyStore.deleteEntry(alias)
49
+ }
50
+
51
+ val keyPairGenerator = KeyPairGenerator.getInstance(
52
+ KeyProperties.KEY_ALGORITHM_EC,
53
+ "AndroidKeyStore"
54
+ )
55
+
56
+ val builder = KeyGenParameterSpec.Builder(alias,
57
+ KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY
58
+ )
59
+ .setDigests(KeyProperties.DIGEST_SHA256)
60
+ .setAttestationChallenge(challenge)
61
+
62
+ keyPairGenerator.initialize(builder.build())
63
+ keyPairGenerator.generateKeyPair()
64
+
65
+ promise.resolve(null)
66
+ } catch (e: Exception) {
67
+ promise.reject("KEY_GEN_FAILED", e.message, e)
68
+ }
69
+ }
70
+
71
+ @ReactMethod
72
+ fun getAttestationCertChain(alias: String, promise: Promise) {
73
+ try {
74
+ val keyStore = KeyStore.getInstance("AndroidKeyStore")
75
+ keyStore.load(null)
76
+
77
+ val chain: Array<Certificate> = keyStore.getCertificateChain(alias)
78
+ ?: throw Exception("No certificate chain found for alias: $alias")
79
+
80
+ val result = Arguments.createArray()
81
+ for (cert in chain) {
82
+ val encoded = cert.encoded
83
+ val base64 = Base64.encodeToString(encoded, Base64.NO_WRAP)
84
+ result.pushString(base64)
85
+ }
86
+
87
+ promise.resolve(result)
88
+ } catch (e: Exception) {
89
+ promise.reject("CERT_CHAIN_FAILED", e.message, e)
90
+ }
91
+ }
92
+ }
@@ -0,0 +1,162 @@
1
+ package com.qafkacms.push
2
+
3
+ import android.Manifest
4
+ import android.content.pm.PackageManager
5
+ import android.os.Build
6
+ import androidx.core.app.NotificationManagerCompat
7
+ import androidx.core.content.ContextCompat
8
+ import com.facebook.react.bridge.Arguments
9
+ import com.facebook.react.bridge.Promise
10
+ import com.facebook.react.bridge.ReactApplicationContext
11
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
12
+ import com.facebook.react.bridge.ReactMethod
13
+ import com.facebook.react.bridge.ReadableMap
14
+ import com.facebook.react.modules.core.PermissionAwareActivity
15
+ import com.facebook.react.modules.core.PermissionListener
16
+ import com.google.firebase.FirebaseApp
17
+ import com.google.firebase.FirebaseOptions
18
+ import com.google.firebase.messaging.FirebaseMessaging
19
+
20
+ /**
21
+ * Native push token collection (E57) — Android via FCM, with NO host-app
22
+ * Firebase setup. The SDK bundles `firebase-messaging` and initializes a
23
+ * **secondary** [FirebaseApp] from the tenant's public client config (delivered
24
+ * over config-sync), so the host's own default FirebaseApp (if any) is untouched
25
+ * and no `google-services.json` is required. The module never subclasses
26
+ * `FirebaseMessagingService` — it only *reads* a token (receiving messages is out
27
+ * of scope for E57), so it cannot collide with the host's messaging service.
28
+ */
29
+ class QafkaCmsPushModule(private val reactContext: ReactApplicationContext) :
30
+ ReactContextBaseJavaModule(reactContext), PermissionListener {
31
+
32
+ override fun getName(): String = "QafkaCmsPush"
33
+
34
+ private var permissionPromise: Promise? = null
35
+
36
+ // ── permission ──────────────────────────────────────────────────────────
37
+
38
+ @ReactMethod
39
+ fun getPermissionStatus(promise: Promise) {
40
+ promise.resolve(currentPermissionStatus())
41
+ }
42
+
43
+ private fun currentPermissionStatus(): String {
44
+ // Android 13+ gates notifications behind the POST_NOTIFICATIONS runtime
45
+ // permission; below 13 they're on unless the user disabled them.
46
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
47
+ val granted = ContextCompat.checkSelfPermission(
48
+ reactContext, Manifest.permission.POST_NOTIFICATIONS
49
+ ) == PackageManager.PERMISSION_GRANTED
50
+ if (granted) "granted" else "undetermined"
51
+ } else {
52
+ if (NotificationManagerCompat.from(reactContext).areNotificationsEnabled()) {
53
+ "granted"
54
+ } else {
55
+ "denied"
56
+ }
57
+ }
58
+ }
59
+
60
+ @ReactMethod
61
+ fun requestPermission(promise: Promise) {
62
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
63
+ promise.resolve(currentPermissionStatus())
64
+ return
65
+ }
66
+ if (ContextCompat.checkSelfPermission(
67
+ reactContext, Manifest.permission.POST_NOTIFICATIONS
68
+ ) == PackageManager.PERMISSION_GRANTED
69
+ ) {
70
+ promise.resolve("granted")
71
+ return
72
+ }
73
+ val activity = reactContext.currentActivity
74
+ if (activity !is PermissionAwareActivity) {
75
+ promise.reject(
76
+ "NO_ACTIVITY",
77
+ "No PermissionAwareActivity available to request notification permission",
78
+ )
79
+ return
80
+ }
81
+ permissionPromise = promise
82
+ activity.requestPermissions(
83
+ arrayOf(Manifest.permission.POST_NOTIFICATIONS),
84
+ PERMISSION_REQUEST_CODE,
85
+ this,
86
+ )
87
+ }
88
+
89
+ override fun onRequestPermissionsResult(
90
+ requestCode: Int,
91
+ permissions: Array<String>,
92
+ grantResults: IntArray,
93
+ ): Boolean {
94
+ if (requestCode != PERMISSION_REQUEST_CODE) return false
95
+ val granted = grantResults.isNotEmpty() &&
96
+ grantResults[0] == PackageManager.PERMISSION_GRANTED
97
+ permissionPromise?.resolve(if (granted) "granted" else "denied")
98
+ permissionPromise = null
99
+ return true
100
+ }
101
+
102
+ // ── token ───────────────────────────────────────────────────────────────
103
+
104
+ @ReactMethod
105
+ fun getToken(androidConfig: ReadableMap?, promise: Promise) {
106
+ if (androidConfig == null) {
107
+ promise.reject(
108
+ "NO_CONFIG",
109
+ "Android FCM client config required (apiKey/appId/senderId/projectId)",
110
+ )
111
+ return
112
+ }
113
+ try {
114
+ val app = secondaryApp(androidConfig)
115
+ app.get(FirebaseMessaging::class.java).token.addOnCompleteListener { task ->
116
+ if (task.isSuccessful) {
117
+ promise.resolve(task.result)
118
+ } else {
119
+ promise.reject(
120
+ "TOKEN_FAILED",
121
+ task.exception?.message ?: "FCM getToken failed",
122
+ task.exception,
123
+ )
124
+ }
125
+ }
126
+ } catch (e: Exception) {
127
+ promise.reject("TOKEN_FAILED", e.message, e)
128
+ }
129
+ }
130
+
131
+ /** Initialize (or reuse) a named secondary FirebaseApp scoped to the tenant's sender. */
132
+ private fun secondaryApp(config: ReadableMap): FirebaseApp {
133
+ FirebaseApp.getApps(reactContext).firstOrNull { it.name == APP_NAME }?.let { return it }
134
+ val options = FirebaseOptions.Builder()
135
+ .setApiKey(requireField(config, "apiKey"))
136
+ .setApplicationId(requireField(config, "appId"))
137
+ .setGcmSenderId(requireField(config, "senderId"))
138
+ .setProjectId(requireField(config, "projectId"))
139
+ .build()
140
+ return FirebaseApp.initializeApp(reactContext, options, APP_NAME)
141
+ }
142
+
143
+ private fun requireField(map: ReadableMap, key: String): String =
144
+ map.getString(key) ?: throw IllegalArgumentException("Missing FCM config field: $key")
145
+
146
+ // ── device info ───────────────────────────────────────────────────────────
147
+
148
+ @ReactMethod
149
+ fun getDeviceInfo(promise: Promise) {
150
+ val info = Arguments.createMap().apply {
151
+ putString("osVersion", "Android ${Build.VERSION.RELEASE}")
152
+ putString("model", Build.MODEL ?: "")
153
+ putString("brand", Build.MANUFACTURER ?: "")
154
+ }
155
+ promise.resolve(info)
156
+ }
157
+
158
+ companion object {
159
+ private const val APP_NAME = "qafkacms"
160
+ private const val PERMISSION_REQUEST_CODE = 7357
161
+ }
162
+ }
@@ -0,0 +1,80 @@
1
+ package com.qafkacms.storage
2
+
3
+ import android.content.SharedPreferences
4
+ import androidx.security.crypto.EncryptedSharedPreferences
5
+ import androidx.security.crypto.MasterKey
6
+ import com.facebook.react.bridge.Arguments
7
+ import com.facebook.react.bridge.Promise
8
+ import com.facebook.react.bridge.ReactApplicationContext
9
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
10
+ import com.facebook.react.bridge.ReactMethod
11
+ import com.facebook.react.bridge.ReadableArray
12
+
13
+ class QafkaCmsStorageModule(reactContext: ReactApplicationContext) :
14
+ ReactContextBaseJavaModule(reactContext) {
15
+
16
+ override fun getName(): String = "QafkaCmsStorage"
17
+
18
+ private val prefs: SharedPreferences by lazy {
19
+ val masterKey = MasterKey.Builder(reactApplicationContext)
20
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
21
+ .build()
22
+
23
+ EncryptedSharedPreferences.create(
24
+ reactApplicationContext,
25
+ FILE_NAME,
26
+ masterKey,
27
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
28
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
29
+ )
30
+ }
31
+
32
+ @ReactMethod
33
+ fun getItem(key: String, promise: Promise) {
34
+ try {
35
+ val value = prefs.getString(key, null)
36
+ promise.resolve(value)
37
+ } catch (e: Exception) {
38
+ promise.reject("STORAGE_READ_FAILED", e.message, e)
39
+ }
40
+ }
41
+
42
+ @ReactMethod
43
+ fun setItem(key: String, value: String, promise: Promise) {
44
+ try {
45
+ prefs.edit().putString(key, value).apply()
46
+ promise.resolve(null)
47
+ } catch (e: Exception) {
48
+ promise.reject("STORAGE_WRITE_FAILED", e.message, e)
49
+ }
50
+ }
51
+
52
+ @ReactMethod
53
+ fun removeItem(key: String, promise: Promise) {
54
+ try {
55
+ prefs.edit().remove(key).apply()
56
+ promise.resolve(null)
57
+ } catch (e: Exception) {
58
+ promise.reject("STORAGE_DELETE_FAILED", e.message, e)
59
+ }
60
+ }
61
+
62
+ @ReactMethod
63
+ fun multiRemove(keys: ReadableArray, promise: Promise) {
64
+ try {
65
+ val editor = prefs.edit()
66
+ for (i in 0 until keys.size()) {
67
+ val key = keys.getString(i) ?: continue
68
+ editor.remove(key)
69
+ }
70
+ editor.apply()
71
+ promise.resolve(null)
72
+ } catch (e: Exception) {
73
+ promise.reject("STORAGE_DELETE_FAILED", e.message, e)
74
+ }
75
+ }
76
+
77
+ companion object {
78
+ private const val FILE_NAME = "qafkacms_secure_prefs"
79
+ }
80
+ }
package/app.plugin.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./expo-plugin/withQafkaCms');