@microsoft/power-apps-native-auth 0.3.8 → 1.0.2

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
@@ -20,10 +20,61 @@ npm run setup --workspace @microsoft/power-apps-native-auth
20
20
 
21
21
  ## Peer dependencies
22
22
 
23
- - `expo` >= 55.0.17
24
- - `expo-modules-core` >= 55.0.23
25
- - `react-native` >= 0.83.4
26
- - `@expo/config-plugins` >= 55.0.8
23
+ - `expo` >= 57.0.21
24
+ - `expo-modules-core` >= 57.0.17
25
+ - `react-native` >= 0.86.3 and < 0.87
26
+ - `@expo/config-plugins` >= 57.0.9
27
+
28
+ ### iOS build requirements
29
+
30
+ The Expo 57 target uses Xcode 26.4 (macOS Tahoe 26.2 or later) and iOS 17
31
+ or later. SDK setup pins [Intune iOS SDK 21.8.0](https://github.com/microsoftconnect/ms-intune-app-sdk-ios/releases/tag/21.8.0),
32
+ whose published Swift interface was built with Swift 6.2.4. Intune 21.9.0
33
+ was built with Swift 6.3.3 and is not assumed compatible with the selected
34
+ Xcode 26.4 / Swift 6.3 toolchain without a separate build validation.
35
+ Intune 20.x targets Xcode 16 and must not be reused
36
+ with this build. MSAL is pinned to CocoaPods version `2.16.0`, whose upstream
37
+ source tag is available. The `2.16.1` podspec references an unavailable source
38
+ tag and fails on clean installs; do not replace the pin with a floating 2.x
39
+ constraint. Authentication and MAM are not disabled by pre-release diagnostics.
40
+
41
+ Run `npm run setup:ios --workspace @microsoft/power-apps-native-auth` before
42
+ installing pods. Setup replaces an older cached SDK and records the new version
43
+ only after both frameworks have been installed. Overrides through the first
44
+ argument or `INTUNE_IOS_SDK_VERSION` must be exact 21.x versions and require
45
+ their own native compatibility validation; they are not automatic upgrades.
46
+
47
+ Selecting a supported SDK and passing setup tests do not certify a native
48
+ build. Simulator/device launch, sign-in, broker return and MAM behavior still
49
+ need validation with the selected Xcode toolchain.
50
+
51
+ ### SDK setup script responsibilities
52
+
53
+ [`scripts/setup-ios-frameworks.js`](scripts/setup-ios-frameworks.js) is run by
54
+ native-build developers/CI before CocoaPods and wrapping. It downloads the
55
+ selected framework release into the auth package's ignored `ios/Frameworks/`
56
+ directory; it is not part of `/check-updates` or a running customer's app.
57
+
58
+ | Function | Purpose and safety boundary |
59
+ |---|---|
60
+ | `assertSupportedVersion` | Require an exact supported 21.x SDK version; reject incompatible families/ranges rather than selecting a floating release |
61
+ | `frameworksPresent` | Check both required framework directories, not just a version marker |
62
+ | `isInstalled` | Reuse a matching installation only when its sentinel and both frameworks agree |
63
+ | `download` | Download the selected archive with bounded redirects/timeout; propagate transport/HTTP failures |
64
+ | `installFrameworks` | Require both extracted framework directories, invalidate the old success marker, copy both frameworks, then record the version |
65
+ | `main` | Select explicit/environment/default version, use valid cached contents or download/extract/install, and remove its own temporary directory |
66
+
67
+ The runtime fingerprint includes this script's complete source because its SDK
68
+ pin selects native binaries. These function notes live here to avoid changing
69
+ that fingerprint merely to add comments to the script. Changing its implementation
70
+ or selected SDK still requires intentional native compatibility preparation and
71
+ rebuilt binaries.
72
+
73
+ Android fingerprinting likewise includes the complete
74
+ [`scripts/setup-android-sdk.js`](scripts/setup-android-sdk.js) source and excludes
75
+ its downloaded `android/libs/` contents, including the version marker. Running
76
+ SDK setup must not change compatibility metadata; changing the setup pin still
77
+ does. Authored Android sources and Gradle declarations remain fingerprinted.
27
78
 
28
79
  ## Usage
29
80
 
@@ -1,11 +1,11 @@
1
1
  buildscript {
2
- ext.kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : '1.9.0'
2
+ ext.kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : '2.1.20'
3
3
  repositories {
4
4
  mavenCentral()
5
5
  google()
6
6
  }
7
7
  dependencies {
8
- classpath("com.android.tools.build:gradle:8.1.1")
8
+ classpath("com.android.tools.build:gradle:8.12.0")
9
9
  classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
10
10
  }
11
11
  }
@@ -18,11 +18,11 @@ def safeExtGet(prop, fallback) {
18
18
  }
19
19
 
20
20
  android {
21
- compileSdkVersion safeExtGet('compileSdkVersion', 35)
21
+ compileSdkVersion safeExtGet('compileSdkVersion', 36)
22
22
 
23
23
  defaultConfig {
24
24
  minSdkVersion safeExtGet('minSdkVersion', 26)
25
- targetSdkVersion safeExtGet('targetSdkVersion', 35)
25
+ targetSdkVersion safeExtGet('targetSdkVersion', 36)
26
26
  }
27
27
 
28
28
  compileOptions {
@@ -57,8 +57,10 @@ dependencies {
57
57
  implementation project(':expo-modules-core')
58
58
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
59
59
 
60
- // MSAL Android — latest: 6.0.1 (com.microsoft.identity.client:msal on Maven Central)
61
- implementation 'com.microsoft.identity.client:msal:6.+'
60
+ // MSAL Android (com.microsoft.identity.client:msal on Maven Central).
61
+ // SDL requires 8.0.3 or later. 8.x needs minSdk 24, AGP 8.10+ and compileSdk 36,
62
+ // all provided by the Expo SDK 57 / React Native 0.86 root project.
63
+ implementation 'com.microsoft.identity.client:msal:8.6.0'
62
64
 
63
65
  // Microsoft Intune MAM SDK for Android.
64
66
  // NOT published to any public Maven feed — downloaded from GitHub by
@@ -19,7 +19,10 @@ import org.json.JSONArray
19
19
  import org.json.JSONObject
20
20
  import java.io.File
21
21
  import java.security.MessageDigest
22
+ import java.net.URI
23
+ import java.util.UUID
22
24
  import java.util.concurrent.atomic.AtomicBoolean
25
+ import java.util.concurrent.atomic.AtomicInteger
23
26
 
24
27
  private const val TAG = "ExpoMsalIntune"
25
28
  private const val AUTH_PREFS = "powerapps.native.auth"
@@ -28,6 +31,10 @@ private const val FORCE_ACCOUNT_SELECTION = "force_account_selection"
28
31
  class ExpoMsalIntuneModule : Module() {
29
32
 
30
33
  private var pca: IMultipleAccountPublicClientApplication? = null
34
+ @Volatile private var currentAuthority: String? = null
35
+ @Volatile private var authorityTenantId: String? = null
36
+ private val initializationGeneration = AtomicInteger(0)
37
+ private val initializationLock = Any()
31
38
 
32
39
  override fun definition() = ModuleDefinition {
33
40
  Name("ExpoMsalIntune")
@@ -48,6 +55,9 @@ class ExpoMsalIntuneModule : Module() {
48
55
  // currentActivity is null during early JS startup.
49
56
  val appCtx = appContext.reactContext?.applicationContext
50
57
  ?: return@AsyncFunction promise.reject("E_NO_CONTEXT", "No application context available", null)
58
+ val generation = synchronized(initializationLock) {
59
+ initializationGeneration.incrementAndGet()
60
+ }
51
61
 
52
62
  val configJson = buildMsalConfigJson(
53
63
  clientId = clientId,
@@ -62,7 +72,7 @@ class ExpoMsalIntuneModule : Module() {
62
72
  // cache (overwriting each time). Using a fixed name avoids accumulating
63
73
  // temp files: deleteOnExit() is a no-op on Android since the JVM shutdown
64
74
  // hook never runs when the process is killed by the OS.
65
- val configFile = File(appCtx.cacheDir, "msal_config.json")
75
+ val configFile = File(appCtx.cacheDir, "msal_config_$generation.json")
66
76
  configFile.writeText(configJson.toString())
67
77
  Log.d(TAG, "initializeClient: config written, starting PCA creation")
68
78
 
@@ -116,17 +126,38 @@ class ExpoMsalIntuneModule : Module() {
116
126
 
117
127
  val timeoutRunnable = Runnable {
118
128
  if (settled.compareAndSet(false, true)) {
119
- Log.w(TAG, "initializeClient: PCA creation timed out after 8s — clearing cache and retrying")
120
- clearMsalCache()
129
+ val shouldRetry = synchronized(initializationLock) {
130
+ if (initializationGeneration.get() != generation) false
131
+ else {
132
+ Log.w(TAG, "initializeClient: PCA creation timed out after 8s — clearing cache and retrying")
133
+ clearMsalCache()
134
+ true
135
+ }
136
+ }
137
+ if (!shouldRetry) {
138
+ promise.reject("E_MSAL_INIT_SUPERSEDED", "MSAL initialization was superseded", null)
139
+ return@Runnable
140
+ }
121
141
  createPca(
122
142
  onSuccess = { app ->
123
143
  Log.d(TAG, "initializeClient: PCA onCreated after cache clear")
124
- pca = app
125
- promise.resolve(null)
144
+ val published = synchronized(initializationLock) {
145
+ if (initializationGeneration.get() != generation) false
146
+ else {
147
+ pca = app
148
+ currentAuthority = authority
149
+ authorityTenantId = tenantIdFromAuthority(authority)
150
+ configFile.copyTo(File(appCtx.cacheDir, "msal_config.json"), overwrite = true)
151
+ true
152
+ }
153
+ }
154
+ if (published) promise.resolve(null)
155
+ else promise.reject("E_MSAL_INIT_SUPERSEDED", "MSAL initialization was superseded", null)
126
156
  },
127
157
  onFailure = { ex ->
128
158
  Log.e(TAG, "initializeClient: PCA onError after cache clear: ${ex.message}")
129
- promise.reject("E_MSAL_INIT", ex.message, ex)
159
+ val code = if (initializationGeneration.get() == generation) "E_MSAL_INIT" else "E_MSAL_INIT_SUPERSEDED"
160
+ promise.reject(code, if (code == "E_MSAL_INIT") ex.message else "MSAL initialization was superseded", ex)
130
161
  }
131
162
  )
132
163
  }
@@ -137,14 +168,25 @@ class ExpoMsalIntuneModule : Module() {
137
168
  onSuccess = { app ->
138
169
  if (settled.compareAndSet(false, true)) {
139
170
  mainHandler.removeCallbacks(timeoutRunnable)
140
- pca = app
141
- promise.resolve(null)
171
+ val published = synchronized(initializationLock) {
172
+ if (initializationGeneration.get() != generation) false
173
+ else {
174
+ pca = app
175
+ currentAuthority = authority
176
+ authorityTenantId = tenantIdFromAuthority(authority)
177
+ configFile.copyTo(File(appCtx.cacheDir, "msal_config.json"), overwrite = true)
178
+ true
179
+ }
180
+ }
181
+ if (published) promise.resolve(null)
182
+ else promise.reject("E_MSAL_INIT_SUPERSEDED", "MSAL initialization was superseded", null)
142
183
  }
143
184
  },
144
185
  onFailure = { ex ->
145
186
  if (settled.compareAndSet(false, true)) {
146
187
  mainHandler.removeCallbacks(timeoutRunnable)
147
- promise.reject("E_MSAL_INIT", ex.message, ex)
188
+ val code = if (initializationGeneration.get() == generation) "E_MSAL_INIT" else "E_MSAL_INIT_SUPERSEDED"
189
+ promise.reject(code, if (code == "E_MSAL_INIT") ex.message else "MSAL initialization was superseded", ex)
148
190
  }
149
191
  }
150
192
  )
@@ -161,6 +203,7 @@ class ExpoMsalIntuneModule : Module() {
161
203
 
162
204
  val client = pca
163
205
  ?: return@AsyncFunction promise.reject("E_NOT_INIT", notInitMsg, null)
206
+ val generation = initializationGeneration.get()
164
207
  val activity = appContext.activityProvider?.currentActivity
165
208
  ?: return@AsyncFunction promise.reject("E_NO_ACTIVITY", "No activity available", null)
166
209
 
@@ -183,13 +226,25 @@ class ExpoMsalIntuneModule : Module() {
183
226
  }
184
227
  .withCallback(object : AuthenticationCallback {
185
228
  override fun onSuccess(result: IAuthenticationResult) {
229
+ if (initializationGeneration.get() != generation) {
230
+ promise.reject("E_MSAL_INTERACTIVE_SUPERSEDED", "MSAL interactive authentication was superseded", null)
231
+ return
232
+ }
186
233
  authPrefs.edit().remove(FORCE_ACCOUNT_SELECTION).apply()
187
234
  promise.resolve(serializeResult(result))
188
235
  }
189
236
  override fun onError(exception: MsalException) {
237
+ if (initializationGeneration.get() != generation) {
238
+ promise.reject("E_MSAL_INTERACTIVE_SUPERSEDED", "MSAL interactive authentication was superseded", null)
239
+ return
240
+ }
190
241
  promise.reject("E_MSAL_INTERACTIVE", exception.message, exception)
191
242
  }
192
243
  override fun onCancel() {
244
+ if (initializationGeneration.get() != generation) {
245
+ promise.reject("E_MSAL_INTERACTIVE_SUPERSEDED", "MSAL interactive authentication was superseded", null)
246
+ return
247
+ }
193
248
  promise.reject("E_MSAL_CANCELLED", "User cancelled sign-in", null)
194
249
  }
195
250
  })
@@ -220,7 +275,7 @@ class ExpoMsalIntuneModule : Module() {
220
275
  val params = AcquireTokenSilentParameters.Builder()
221
276
  .withScopes(scopes)
222
277
  .forAccount(account)
223
- .fromAuthority(account.authority)
278
+ .fromAuthority(currentAuthority ?: account.authority)
224
279
  .forceRefresh(forceRefresh)
225
280
  .withCallback(object : SilentAuthenticationCallback {
226
281
  override fun onSuccess(result: IAuthenticationResult) {
@@ -400,7 +455,7 @@ class ExpoMsalIntuneModule : Module() {
400
455
  // the async RemoveAccountCallback deadlocks under Bridgeless, leaving
401
456
  // isLoading=true after signout so the loading spinner never clears.
402
457
  try {
403
- Log.d(TAG, "signOut: removing account ${account.id}")
458
+ Log.d(TAG, "signOut: removing account")
404
459
  client.removeAccount(account)
405
460
  Log.d(TAG, "signOut: account removed successfully")
406
461
  promise.resolve(null)
@@ -481,9 +536,11 @@ class ExpoMsalIntuneModule : Module() {
481
536
  }
482
537
 
483
538
  mapOf(
539
+ "authContractVersion" to str("powerapps_auth_contract_version"),
484
540
  "clientId" to str("adal_client_id"),
485
541
  "redirectUri" to str("adal_redirect_uri"),
486
542
  "tenantId" to str("adal_tenant_id"),
543
+ "tenantMode" to str("powerapps_tenant_mode"),
487
544
  )
488
545
  }
489
546
 
@@ -531,6 +588,11 @@ class ExpoMsalIntuneModule : Module() {
531
588
 
532
589
  private val notInitMsg = "ExpoMsalIntune: call initializeClient() before acquiring tokens"
533
590
 
591
+ private fun tenantIdFromAuthority(authority: String): String? {
592
+ val authoritySegment = runCatching { URI(authority).path.trim('/').substringAfterLast('/') }.getOrNull()
593
+ return authoritySegment?.takeIf { runCatching { UUID.fromString(it) }.isSuccess }
594
+ }
595
+
534
596
  private fun findAccount(
535
597
  client: IMultipleAccountPublicClientApplication,
536
598
  identifier: String
@@ -543,21 +605,45 @@ class ExpoMsalIntuneModule : Module() {
543
605
  }
544
606
  }
545
607
 
546
- private fun serializeAccount(account: IAccount): Map<String, Any> {
608
+ private fun serializeAccount(account: IAccount, resultTenantId: String? = null): Map<String, Any> {
547
609
  val claims = try {
548
610
  val claimsMap = account.claims ?: emptyMap<String, Any>()
549
611
  JSONObject(claimsMap).toString()
550
612
  } catch (e: Exception) {
551
613
  "{}"
552
614
  }
615
+ val tenantId = resultTenantId?.takeIf { it.isNotBlank() }
616
+ ?: configuredTenantIdForAccount(account)
617
+ ?: account.tenantId?.takeIf { it.isNotBlank() }
618
+ ?: homeTenantIdForAccount(account)
619
+ ?: ""
553
620
  return mapOf(
554
621
  "identifier" to (account.id ?: ""),
555
622
  "username" to (account.username ?: ""),
556
- "tenantId" to (account.tenantId ?: ""),
623
+ "tenantId" to tenantId,
557
624
  "claims" to claims,
558
625
  )
559
626
  }
560
627
 
628
+ private fun configuredTenantIdForAccount(account: IAccount): String? {
629
+ val configuredTenantId = authorityTenantId ?: return null
630
+ val claimsTenantId = account.claims?.get("tid") as? String
631
+ val matchesAccount = account.tenantId?.equals(configuredTenantId, ignoreCase = true) == true
632
+ || claimsTenantId?.equals(configuredTenantId, ignoreCase = true) == true
633
+ || homeTenantIdForAccount(account)?.equals(configuredTenantId, ignoreCase = true) == true
634
+ || (account as? IMultiTenantAccount)?.tenantProfiles?.keys.orEmpty()
635
+ .any { it.equals(configuredTenantId, ignoreCase = true) }
636
+ return configuredTenantId.takeIf { matchesAccount }
637
+ }
638
+
639
+ private fun homeTenantIdForAccount(account: IAccount): String? {
640
+ val homeAccountId = account.id ?: return null
641
+ val separatorIndex = homeAccountId.lastIndexOf('.')
642
+ if (separatorIndex < 0 || separatorIndex == homeAccountId.lastIndex) return null
643
+ val tenantId = homeAccountId.substring(separatorIndex + 1)
644
+ return tenantId.takeIf { runCatching { UUID.fromString(it) }.isSuccess }
645
+ }
646
+
561
647
  private fun serializeResult(result: IAuthenticationResult): Map<String, Any> {
562
648
  return mapOf(
563
649
  "accessToken" to result.accessToken,
@@ -566,7 +652,7 @@ class ExpoMsalIntuneModule : Module() {
566
652
  "idToken" to (result.account.idToken ?: ""),
567
653
  "expiresOn" to result.expiresOn.time,
568
654
  "scopes" to result.scope.toList(),
569
- "account" to serializeAccount(result.account),
655
+ "account" to serializeAccount(result.account, result.tenantId),
570
656
  )
571
657
  }
572
658
 
@@ -7,19 +7,16 @@ Pod::Spec.new do |s|
7
7
  s.author = 'Microsoft'
8
8
  s.homepage = 'https://github.com/microsoft/pa-wrap-tools'
9
9
  s.license = { :type => 'MIT' }
10
- s.platforms = { :ios => '14.0' }
10
+ s.platforms = { :ios => '17.0' }
11
11
  s.source = { :path => '.' }
12
12
  s.static_framework = true
13
13
 
14
14
  s.dependency 'ExpoModulesCore'
15
- # MSAL iOS — latest: 2.10.0
16
- s.dependency 'MSAL', '~> 2.10'
15
+ s.dependency 'MSAL', '2.16.0'
17
16
 
18
- # IntuneMAMSwift iOS 20.9.2 (Xcode 16 compatible; 21.x requires Xcode 26)
17
+ # IntuneMAMSwift iOS 21.8.0 requires Xcode 26 and iOS 17+.
19
18
  # Vendored locally because IntuneMAMSwift is not published to the public CocoaPods CDN.
20
- # To upgrade: download the new release from
21
- # https://github.com/microsoftconnect/ms-intune-app-sdk-ios/releases
22
- # and replace the contents of ios/Frameworks/.
19
+ # Run npm run setup:ios after changing the version in scripts/setup-ios-frameworks.js.
23
20
  s.vendored_frameworks = 'Frameworks/IntuneMAMSwift.xcframework',
24
21
  'Frameworks/IntuneMAMSwiftStub.xcframework'
25
22
 
@@ -45,6 +45,9 @@ extension MsalIntuneError: LocalizedError {
45
45
  public class ExpoMsalIntuneModule: Module {
46
46
  private static let forceAccountSelectionKey = "powerapps.native.auth.forceAccountSelection"
47
47
  private var pca: MSALPublicClientApplication?
48
+ private var authorityTenantId: String?
49
+ private var initializationGeneration: UInt64 = 0
50
+ private let initializationLock = NSLock()
48
51
  /// Stored at initializeClient time; controls which WebView type is used for
49
52
  /// interactive sign-in. true → WKWebView (no Info.plist URL scheme needed).
50
53
  /// false → ASWebAuthenticationSession (requires msauth.{bundleId}://auth scheme).
@@ -64,6 +67,10 @@ public class ExpoMsalIntuneModule: Module {
64
67
  // -----------------------------------------------------------------------
65
68
  AsyncFunction("initializeClient") {
66
69
  (clientId: String, authority: String, redirectUri: String, useEmbeddedWebView: Bool, useBroker: Bool) in
70
+ self.initializationLock.lock()
71
+ defer { self.initializationLock.unlock() }
72
+ self.initializationGeneration &+= 1
73
+ let generation = self.initializationGeneration
67
74
 
68
75
  guard let authorityURL = URL(string: authority) else {
69
76
  throw Self.nativeError(code: -1, message: "Invalid authority URL: \(authority)")
@@ -108,7 +115,12 @@ public class ExpoMsalIntuneModule: Module {
108
115
  // callback possible at runtime.
109
116
  MSALGlobalConfig.brokerAvailability = self.useBroker ? .auto : .none
110
117
  do {
111
- self.pca = try MSALPublicClientApplication(configuration: config)
118
+ let initializedPca = try MSALPublicClientApplication(configuration: config)
119
+ guard self.initializationGeneration == generation else {
120
+ throw MsalIntuneError.intuneError("MSAL initialization was superseded")
121
+ }
122
+ self.pca = initializedPca
123
+ self.authorityTenantId = Self.tenantId(fromAuthorityURL: authorityURL)
112
124
  } catch let err as NSError {
113
125
  throw Self.nativeMsalError(
114
126
  code: msalInitErrorCode,
@@ -122,6 +134,9 @@ public class ExpoMsalIntuneModule: Module {
122
134
  // can recreate a PCA that shares this app's Keychain token cache. Mirrors
123
135
  // the Android module, which writes msal_config.json to the cache dir.
124
136
  // The geolocation reader expects flat keys: clientId / redirectUri / authority.
137
+ guard self.initializationGeneration == generation else {
138
+ throw MsalIntuneError.intuneError("MSAL initialization was superseded")
139
+ }
125
140
  Self.writeMsalConfig(
126
141
  clientId: clientId,
127
142
  redirectUri: iosRedirectUri,
@@ -138,6 +153,9 @@ public class ExpoMsalIntuneModule: Module {
138
153
  (scopes: [String], loginHint: String?, prompt: String?) async throws -> [String: Any] in
139
154
 
140
155
  guard let pca = self.pca else { throw MsalIntuneError.notInitialized }
156
+ self.initializationLock.lock()
157
+ let generation = self.initializationGeneration
158
+ self.initializationLock.unlock()
141
159
 
142
160
  return try await withCheckedThrowingContinuation { continuation in
143
161
  // topViewController() and pca.acquireToken() both require the main
@@ -173,6 +191,13 @@ public class ExpoMsalIntuneModule: Module {
173
191
  }
174
192
 
175
193
  pca.acquireToken(with: params) { result, error in
194
+ self.initializationLock.lock()
195
+ let isCurrentGeneration = self.initializationGeneration == generation
196
+ self.initializationLock.unlock()
197
+ guard isCurrentGeneration else {
198
+ continuation.resume(throwing: MsalIntuneError.intuneError("MSAL interactive authentication was superseded"))
199
+ return
200
+ }
176
201
  if let error = error as NSError? {
177
202
  continuation.resume(throwing: Self.nativeMsalError(
178
203
  code: msalInteractiveErrorCode,
@@ -358,9 +383,11 @@ public class ExpoMsalIntuneModule: Module {
358
383
  let info = Bundle.main.infoDictionary ?? [:]
359
384
  let mam = info["IntuneMAMSettings"] as? [String: Any] ?? [:]
360
385
  return [
386
+ "authContractVersion": mam["PowerAppsAuthContractVersion"] as? String ?? "",
361
387
  "clientId": mam["ADALClientId"] as? String ?? "",
362
388
  "redirectUri": mam["ADALRedirectUri"] as? String ?? "",
363
389
  "tenantId": mam["ADALTenantId"] as? String ?? "",
390
+ "tenantMode": mam["PowerAppsTenantMode"] as? String ?? "",
364
391
  ]
365
392
  }
366
393
 
@@ -398,6 +425,14 @@ public class ExpoMsalIntuneModule: Module {
398
425
  )
399
426
  }
400
427
 
428
+ private static func tenantId(fromAuthorityURL authorityUrl: URL) -> String? {
429
+ guard let authoritySegment = authorityUrl.pathComponents.last,
430
+ UUID(uuidString: authoritySegment) != nil else {
431
+ return nil
432
+ }
433
+ return authoritySegment
434
+ }
435
+
401
436
  private func cacheOperationsPca() throws -> MSALPublicClientApplication? {
402
437
  if let pca {
403
438
  return pca
@@ -475,21 +510,38 @@ public class ExpoMsalIntuneModule: Module {
475
510
  return account
476
511
  }
477
512
 
478
- private func serializeAccount(_ account: MSALAccount) -> [String: Any] {
513
+ private func serializeAccount(_ account: MSALAccount, resultTenantId: String? = nil) -> [String: Any] {
479
514
  var claims: String = "{}"
480
515
  if let rawClaims = account.accountClaims,
481
516
  let data = try? JSONSerialization.data(withJSONObject: rawClaims),
482
517
  let str = String(data: data, encoding: .utf8) {
483
518
  claims = str
484
519
  }
520
+ let tenantId = resultTenantId
521
+ ?? configuredTenantId(for: account)
522
+ ?? account.accountClaims?["tid"] as? String
523
+ ?? account.homeAccountId?.tenantId
524
+ ?? account.tenantProfiles?.first(where: { $0.isHomeTenantProfile })?.tenantId
525
+ ?? ""
485
526
  return [
486
527
  "identifier": account.identifier ?? "",
487
528
  "username": account.username ?? "",
488
- "tenantId": account.tenantProfiles?.first?.tenantId ?? "",
529
+ "tenantId": tenantId,
489
530
  "claims": claims,
490
531
  ]
491
532
  }
492
533
 
534
+ private func configuredTenantId(for account: MSALAccount) -> String? {
535
+ guard let configuredTenantId = authorityTenantId else { return nil }
536
+ let claimsTenantId = account.accountClaims?["tid"] as? String
537
+ let matchesAccount = claimsTenantId?.caseInsensitiveCompare(configuredTenantId) == .orderedSame
538
+ || account.homeAccountId?.tenantId?.caseInsensitiveCompare(configuredTenantId) == .orderedSame
539
+ || account.tenantProfiles?.contains(where: {
540
+ $0.tenantId?.caseInsensitiveCompare(configuredTenantId) == .orderedSame
541
+ }) == true
542
+ return matchesAccount ? configuredTenantId : nil
543
+ }
544
+
493
545
  private func serializeResult(_ result: MSALResult) -> [String: Any] {
494
546
  let expiresOn = result.expiresOn.map { $0.timeIntervalSince1970 * 1000 } ?? 0
495
547
  return [
@@ -497,7 +549,7 @@ public class ExpoMsalIntuneModule: Module {
497
549
  "idToken": result.idToken ?? "",
498
550
  "expiresOn": expiresOn,
499
551
  "scopes": result.scopes,
500
- "account": serializeAccount(result.account),
552
+ "account": serializeAccount(result.account, resultTenantId: result.tenantProfile.tenantId),
501
553
  ]
502
554
  }
503
555
 
package/lib/NOTICE.txt CHANGED
@@ -2,4 +2,4 @@ NOTICES
2
2
 
3
3
  This repository incorporates material as listed below or described in the code.
4
4
 
5
- @microsoft/power-apps-native-auth@0.3.8 has no production third-party dependencies.
5
+ @microsoft/power-apps-native-auth@1.0.2 has no production third-party dependencies.
@@ -84,9 +84,11 @@ export interface NativeExpoMsalIntuneModule {
84
84
  * when the returned clientId is empty or still contains a placeholder tag.
85
85
  */
86
86
  getWrapConfig(): {
87
+ authContractVersion: string;
87
88
  clientId: string;
88
89
  redirectUri: string;
89
90
  tenantId: string;
91
+ tenantMode: string;
90
92
  };
91
93
  }
92
94
  declare const ExpoMsalIntuneModule: NativeExpoMsalIntuneModule;
@@ -106,9 +106,11 @@ export declare function computeMsalRedirectUri(): string;
106
106
  * ```
107
107
  */
108
108
  export declare function getWrapConfig(): {
109
+ authContractVersion: string;
109
110
  clientId: string;
110
111
  redirectUri: string;
111
112
  tenantId: string;
113
+ tenantMode: string;
112
114
  };
113
115
  export default PublicClientApplication;
114
116
  /**
@@ -84,9 +84,11 @@ export interface NativeExpoMsalIntuneModule {
84
84
  * when the returned clientId is empty or still contains a placeholder tag.
85
85
  */
86
86
  getWrapConfig(): {
87
+ authContractVersion: string;
87
88
  clientId: string;
88
89
  redirectUri: string;
89
90
  tenantId: string;
91
+ tenantMode: string;
90
92
  };
91
93
  }
92
94
  declare const ExpoMsalIntuneModule: NativeExpoMsalIntuneModule;
@@ -106,9 +106,11 @@ export declare function computeMsalRedirectUri(): string;
106
106
  * ```
107
107
  */
108
108
  export declare function getWrapConfig(): {
109
+ authContractVersion: string;
109
110
  clientId: string;
110
111
  redirectUri: string;
111
112
  tenantId: string;
113
+ tenantMode: string;
112
114
  };
113
115
  export default PublicClientApplication;
114
116
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/power-apps-native-auth",
3
- "version": "0.3.8",
3
+ "version": "1.0.2",
4
4
  "description": "Expo native module: MSAL authentication + Microsoft Intune MAM for iOS and Android",
5
5
  "author": "Microsoft Corporation",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -40,20 +40,19 @@
40
40
  "prepack": "bob build && node ../../scripts/package-build/notices.js",
41
41
  "build": "bob build && node ../../scripts/package-build/notices.js",
42
42
  "type-check": "tsc --noEmit",
43
+ "test": "node --test test/*.test.js",
43
44
  "setup:ios": "node scripts/setup-ios-frameworks.js",
44
45
  "setup:android": "node scripts/setup-android-sdk.js",
45
46
  "setup": "npm run setup:ios && npm run setup:android"
46
47
  },
47
48
  "peerDependencies": {
48
- "@expo/config-plugins": ">=55.0.8",
49
- "expo": ">=55.0.17",
50
- "expo-modules-core": ">=55.0.23",
51
- "react-native": ">=0.83.4"
49
+ "@expo/config-plugins": ">=57.0.9",
50
+ "expo": ">=57.0.21",
51
+ "react-native": ">=0.86.3 <0.87"
52
52
  },
53
53
  "devDependencies": {
54
- "@microsoft/power-apps-cli": "0.15.3",
55
- "expo-modules-core": "55.0.25",
56
- "typescript": "5.9.3"
54
+ "expo-modules-core": "57.0.19",
55
+ "typescript": "6.0.3"
57
56
  },
58
57
  "keywords": [
59
58
  "expo",
package/plugin/index.js CHANGED
@@ -444,6 +444,8 @@ const WRAP_PLACEHOLDER_STRINGS = [
444
444
  // For typical customer setups the app owner's tenant equals the AAD app
445
445
  // registration tenant, which is what MSAL's authority URL requires.
446
446
  { name: 'adal_tenant_id', value: 'ADAL_TENANT_ID_TAG' },
447
+ { name: 'powerapps_auth_contract_version', value: '2' },
448
+ { name: 'powerapps_tenant_mode', value: 'POWERAPPS_TENANT_MODE_TAG' },
447
449
  ];
448
450
 
449
451
  function withWrapStringPlaceholders(config) {
@@ -465,6 +467,9 @@ function withWrapStringPlaceholders(config) {
465
467
  if (name === 'adal_tenant_id' && process.env.ADAL_TENANT_ID) {
466
468
  return { name, value: process.env.ADAL_TENANT_ID };
467
469
  }
470
+ if (name === 'powerapps_tenant_mode' && process.env.POWERAPPS_TENANT_MODE) {
471
+ return { name, value: process.env.POWERAPPS_TENANT_MODE };
472
+ }
468
473
  return { name, value };
469
474
  });
470
475
 
@@ -22,6 +22,7 @@ function withIntuneMAMSettings(config) {
22
22
  return withInfoPlist(config, (mod) => {
23
23
  const clientId = process.env.ADAL_CLIENT_ID;
24
24
  const tenantId = process.env.ADAL_TENANT_ID;
25
+ const tenantMode = process.env.POWERAPPS_TENANT_MODE;
25
26
  const redirectUri = process.env.IOS_ADAL_REDIRECT_URI;
26
27
  const bundleId = config.ios?.bundleIdentifier;
27
28
  const isDevBuild = process.env.DEV_CLIENT === 'true' ||
@@ -38,6 +39,8 @@ function withIntuneMAMSettings(config) {
38
39
  ADALRedirectUri: redirectUri ?? `msauth.${bundleId}://auth`,
39
40
  ADALTenantId: tenantId ?? '',
40
41
  ADALAuthority: `https://login.microsoftonline.com/${tenantId ?? ''}`,
42
+ PowerAppsAuthContractVersion: '2',
43
+ PowerAppsTenantMode: tenantMode ?? 'single',
41
44
  };
42
45
  } else {
43
46
  // Release build without env vars (wrap pipeline base IPA).
@@ -48,6 +51,8 @@ function withIntuneMAMSettings(config) {
48
51
  ADALClientId: 'ADAL_CLIENT_ID_TAG',
49
52
  ADALRedirectUri: 'ADAL_REDIRECT_URI_TAG',
50
53
  ADALTenantId: 'ADAL_TENANT_ID_TAG',
54
+ PowerAppsAuthContractVersion: '2',
55
+ PowerAppsTenantMode: 'POWERAPPS_TENANT_MODE_TAG',
51
56
  };
52
57
  }
53
58
 
@@ -14,94 +14,109 @@
14
14
  const https = require('https');
15
15
  const fs = require('fs');
16
16
  const path = require('path');
17
- const { execSync } = require('child_process');
17
+ const { execFileSync } = require('child_process');
18
+ const { pipeline } = require('stream/promises');
18
19
  const os = require('os');
19
20
 
20
- const DEFAULT_VERSION = '20.9.2';
21
- const version = process.argv[2] || process.env.INTUNE_IOS_SDK_VERSION || DEFAULT_VERSION;
22
-
21
+ const DEFAULT_VERSION = '21.8.0';
23
22
  const REPO = 'microsoftconnect/ms-intune-app-sdk-ios';
24
- const DOWNLOAD_URL = `https://github.com/${REPO}/archive/refs/tags/${version}.zip`;
25
-
26
23
  const FRAMEWORKS = ['IntuneMAMSwift.xcframework', 'IntuneMAMSwiftStub.xcframework'];
27
24
 
28
- const frameworksDir = path.join(__dirname, '..', 'ios', 'Frameworks');
29
- const sentinelPath = path.join(frameworksDir, '.sdk-version');
30
- const tmpZip = path.join(os.tmpdir(), `intune-ios-sdk-${version}.zip`);
31
- const tmpExtract = path.join(os.tmpdir(), `intune-ios-sdk-${version}`);
32
-
33
- // Check if already present
34
- const currentVersion = fs.existsSync(sentinelPath)
35
- ? fs.readFileSync(sentinelPath, 'utf8').trim()
36
- : null;
37
- const allPresent = currentVersion === version
38
- && FRAMEWORKS.every(f => fs.existsSync(path.join(frameworksDir, f)));
39
- if (allPresent) {
40
- console.log(`✅ IntuneMAMSwift ${version} xcframeworks already present in ios/Frameworks/`);
41
- process.exit(0);
25
+ function assertSupportedVersion(version) {
26
+ if (typeof version !== 'string' || !/^21\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(version)) {
27
+ throw new Error('This Xcode 26 build requires an exact Intune iOS SDK 21.x version (for example 21.8.0); SDK 20.x targets Xcode 16.');
28
+ }
42
29
  }
43
30
 
44
- fs.mkdirSync(frameworksDir, { recursive: true });
31
+ function frameworksPresent(directory) {
32
+ return FRAMEWORKS.every(framework =>
33
+ fs.existsSync(path.join(directory, framework))
34
+ && fs.statSync(path.join(directory, framework)).isDirectory());
35
+ }
45
36
 
46
- console.log(`⬇️ Downloading IntuneMAMSwift ${version} from GitHub...`);
47
- console.log(` ${DOWNLOAD_URL}`);
37
+ function isInstalled(frameworksDir, version) {
38
+ assertSupportedVersion(version);
39
+ const sentinelPath = path.join(frameworksDir, '.sdk-version');
40
+ return fs.existsSync(sentinelPath)
41
+ && fs.readFileSync(sentinelPath, 'utf8').trim() === version
42
+ && frameworksPresent(frameworksDir);
43
+ }
48
44
 
49
- function download(url, dest, redirects = 0) {
45
+ async function download(url, dest, redirects = 0) {
50
46
  if (redirects > 5) throw new Error('Too many redirects');
51
47
  return new Promise((resolve, reject) => {
52
- const file = fs.createWriteStream(dest);
53
- https.get(url, (res) => {
48
+ const request = https.get(url, (res) => {
54
49
  if (res.statusCode === 301 || res.statusCode === 302) {
55
- file.close();
56
- fs.unlinkSync(dest);
57
- download(res.headers.location, dest, redirects + 1).then(resolve).catch(reject);
50
+ res.resume();
51
+ if (!res.headers.location) {
52
+ reject(new Error(`Missing redirect location from ${url}`));
53
+ return;
54
+ }
55
+ download(new URL(res.headers.location, url), dest, redirects + 1).then(resolve, reject);
58
56
  return;
59
57
  }
60
58
  if (res.statusCode !== 200) {
59
+ res.resume();
61
60
  reject(new Error(`HTTP ${res.statusCode} from ${url}`));
62
61
  return;
63
62
  }
64
- res.pipe(file);
65
- file.on('finish', () => file.close(resolve));
66
- }).on('error', (err) => {
67
- fs.unlinkSync(dest);
68
- reject(err);
69
- });
63
+ const file = fs.createWriteStream(dest);
64
+ pipeline(res, file).then(resolve, reject);
65
+ }).on('error', reject);
66
+ request.setTimeout(60000, () => request.destroy(new Error('Intune SDK download timed out')));
70
67
  });
71
68
  }
72
69
 
73
- (async () => {
74
- try {
75
- await download(DOWNLOAD_URL, tmpZip);
76
- console.log('📦 Extracting...');
77
-
78
- execSync(`unzip -q -o "${tmpZip}" -d "${tmpExtract}"`, { stdio: 'inherit' });
79
-
80
- const extractedRoot = path.join(tmpExtract, `ms-intune-app-sdk-ios-${version}`);
81
-
82
- for (const framework of FRAMEWORKS) {
83
- const src = path.join(extractedRoot, framework);
84
- const dest = path.join(frameworksDir, framework);
85
- if (!fs.existsSync(src)) {
86
- throw new Error(`Expected ${framework} not found in the release archive at ${src}`);
87
- }
88
- if (fs.existsSync(dest)) {
89
- execSync(`rm -rf "${dest}"`);
90
- }
91
- execSync(`cp -R "${src}" "${dest}"`);
92
- console.log(`✅ Copied ${framework}`);
93
- }
70
+ function installFrameworks(extractedRoot, frameworksDir, version) {
71
+ assertSupportedVersion(version);
72
+ if (!frameworksPresent(extractedRoot)) {
73
+ throw new Error(`Expected both Intune xcframework directories in the release archive at ${extractedRoot}`);
74
+ }
75
+ fs.mkdirSync(frameworksDir, { recursive: true });
76
+ const sentinelPath = path.join(frameworksDir, '.sdk-version');
77
+ // A partial copy must never leave a successful installation marker.
78
+ fs.rmSync(sentinelPath, { force: true });
79
+ for (const framework of FRAMEWORKS) {
80
+ const dest = path.join(frameworksDir, framework);
81
+ fs.rmSync(dest, { recursive: true, force: true });
82
+ fs.cpSync(path.join(extractedRoot, framework), dest, { recursive: true, verbatimSymlinks: true });
83
+ console.log(`✅ Copied ${framework}`);
84
+ }
85
+ fs.writeFileSync(sentinelPath, version + '\n', 'utf8');
86
+ }
94
87
 
95
- fs.writeFileSync(sentinelPath, version + '\n', 'utf8');
88
+ async function main() {
89
+ const version = process.argv[2] || process.env.INTUNE_IOS_SDK_VERSION || DEFAULT_VERSION;
90
+ assertSupportedVersion(version);
91
+ const frameworksDir = path.join(__dirname, '..', 'ios', 'Frameworks');
92
+ if (isInstalled(frameworksDir, version)) {
93
+ console.log(`✅ IntuneMAMSwift ${version} xcframeworks already present in ios/Frameworks/`);
94
+ return;
95
+ }
96
96
 
97
- // Cleanup
98
- fs.unlinkSync(tmpZip);
99
- execSync(`rm -rf "${tmpExtract}"`);
97
+ const downloadUrl = `https://github.com/${REPO}/archive/refs/tags/${version}.zip`;
98
+ const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'intune-ios-sdk-'));
99
+ try {
100
+ const tmpZip = path.join(temporaryDirectory, 'sdk.zip');
101
+ console.log(`⬇️ Downloading IntuneMAMSwift ${version} from GitHub...`);
102
+ console.log(` ${downloadUrl}`);
103
+ await download(downloadUrl, tmpZip);
104
+ console.log('📦 Extracting...');
105
+ execFileSync('unzip', ['-q', tmpZip, '-d', temporaryDirectory], { stdio: 'inherit' });
106
+ installFrameworks(path.join(temporaryDirectory, `ms-intune-app-sdk-ios-${version}`), frameworksDir, version);
100
107
 
101
108
  console.log(`\n✅ IntuneMAMSwift ${version} xcframeworks installed to ios/Frameworks/`);
102
109
  console.log(' You can now run: npx expo run:ios\n');
103
- } catch (err) {
104
- console.error(`\n❌ setup:ios failed: ${err.message}`);
105
- process.exit(1);
110
+ } finally {
111
+ fs.rmSync(temporaryDirectory, { recursive: true, force: true });
106
112
  }
107
- })();
113
+ }
114
+
115
+ module.exports = { DEFAULT_VERSION, FRAMEWORKS, assertSupportedVersion, isInstalled, installFrameworks };
116
+
117
+ if (require.main === module) {
118
+ main().catch(err => {
119
+ console.error(`\n❌ setup:ios failed: ${err.message}`);
120
+ process.exitCode = 1;
121
+ });
122
+ }