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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,6 +20,7 @@ import org.json.JSONObject
20
20
  import java.io.File
21
21
  import java.security.MessageDigest
22
22
  import java.util.concurrent.atomic.AtomicBoolean
23
+ import java.util.concurrent.atomic.AtomicInteger
23
24
 
24
25
  private const val TAG = "ExpoMsalIntune"
25
26
  private const val AUTH_PREFS = "powerapps.native.auth"
@@ -28,6 +29,8 @@ private const val FORCE_ACCOUNT_SELECTION = "force_account_selection"
28
29
  class ExpoMsalIntuneModule : Module() {
29
30
 
30
31
  private var pca: IMultipleAccountPublicClientApplication? = null
32
+ private val initializationGeneration = AtomicInteger(0)
33
+ private val initializationLock = Any()
31
34
 
32
35
  override fun definition() = ModuleDefinition {
33
36
  Name("ExpoMsalIntune")
@@ -48,6 +51,9 @@ class ExpoMsalIntuneModule : Module() {
48
51
  // currentActivity is null during early JS startup.
49
52
  val appCtx = appContext.reactContext?.applicationContext
50
53
  ?: return@AsyncFunction promise.reject("E_NO_CONTEXT", "No application context available", null)
54
+ val generation = synchronized(initializationLock) {
55
+ initializationGeneration.incrementAndGet()
56
+ }
51
57
 
52
58
  val configJson = buildMsalConfigJson(
53
59
  clientId = clientId,
@@ -62,7 +68,7 @@ class ExpoMsalIntuneModule : Module() {
62
68
  // cache (overwriting each time). Using a fixed name avoids accumulating
63
69
  // temp files: deleteOnExit() is a no-op on Android since the JVM shutdown
64
70
  // hook never runs when the process is killed by the OS.
65
- val configFile = File(appCtx.cacheDir, "msal_config.json")
71
+ val configFile = File(appCtx.cacheDir, "msal_config_$generation.json")
66
72
  configFile.writeText(configJson.toString())
67
73
  Log.d(TAG, "initializeClient: config written, starting PCA creation")
68
74
 
@@ -116,17 +122,36 @@ class ExpoMsalIntuneModule : Module() {
116
122
 
117
123
  val timeoutRunnable = Runnable {
118
124
  if (settled.compareAndSet(false, true)) {
119
- Log.w(TAG, "initializeClient: PCA creation timed out after 8s — clearing cache and retrying")
120
- clearMsalCache()
125
+ val shouldRetry = synchronized(initializationLock) {
126
+ if (initializationGeneration.get() != generation) false
127
+ else {
128
+ Log.w(TAG, "initializeClient: PCA creation timed out after 8s — clearing cache and retrying")
129
+ clearMsalCache()
130
+ true
131
+ }
132
+ }
133
+ if (!shouldRetry) {
134
+ promise.reject("E_MSAL_INIT_SUPERSEDED", "MSAL initialization was superseded", null)
135
+ return@Runnable
136
+ }
121
137
  createPca(
122
138
  onSuccess = { app ->
123
139
  Log.d(TAG, "initializeClient: PCA onCreated after cache clear")
124
- pca = app
125
- promise.resolve(null)
140
+ val published = synchronized(initializationLock) {
141
+ if (initializationGeneration.get() != generation) false
142
+ else {
143
+ pca = app
144
+ configFile.copyTo(File(appCtx.cacheDir, "msal_config.json"), overwrite = true)
145
+ true
146
+ }
147
+ }
148
+ if (published) promise.resolve(null)
149
+ else promise.reject("E_MSAL_INIT_SUPERSEDED", "MSAL initialization was superseded", null)
126
150
  },
127
151
  onFailure = { ex ->
128
152
  Log.e(TAG, "initializeClient: PCA onError after cache clear: ${ex.message}")
129
- promise.reject("E_MSAL_INIT", ex.message, ex)
153
+ val code = if (initializationGeneration.get() == generation) "E_MSAL_INIT" else "E_MSAL_INIT_SUPERSEDED"
154
+ promise.reject(code, if (code == "E_MSAL_INIT") ex.message else "MSAL initialization was superseded", ex)
130
155
  }
131
156
  )
132
157
  }
@@ -137,14 +162,23 @@ class ExpoMsalIntuneModule : Module() {
137
162
  onSuccess = { app ->
138
163
  if (settled.compareAndSet(false, true)) {
139
164
  mainHandler.removeCallbacks(timeoutRunnable)
140
- pca = app
141
- promise.resolve(null)
165
+ val published = synchronized(initializationLock) {
166
+ if (initializationGeneration.get() != generation) false
167
+ else {
168
+ pca = app
169
+ configFile.copyTo(File(appCtx.cacheDir, "msal_config.json"), overwrite = true)
170
+ true
171
+ }
172
+ }
173
+ if (published) promise.resolve(null)
174
+ else promise.reject("E_MSAL_INIT_SUPERSEDED", "MSAL initialization was superseded", null)
142
175
  }
143
176
  },
144
177
  onFailure = { ex ->
145
178
  if (settled.compareAndSet(false, true)) {
146
179
  mainHandler.removeCallbacks(timeoutRunnable)
147
- promise.reject("E_MSAL_INIT", ex.message, ex)
180
+ val code = if (initializationGeneration.get() == generation) "E_MSAL_INIT" else "E_MSAL_INIT_SUPERSEDED"
181
+ promise.reject(code, if (code == "E_MSAL_INIT") ex.message else "MSAL initialization was superseded", ex)
148
182
  }
149
183
  }
150
184
  )
@@ -161,6 +195,7 @@ class ExpoMsalIntuneModule : Module() {
161
195
 
162
196
  val client = pca
163
197
  ?: return@AsyncFunction promise.reject("E_NOT_INIT", notInitMsg, null)
198
+ val generation = initializationGeneration.get()
164
199
  val activity = appContext.activityProvider?.currentActivity
165
200
  ?: return@AsyncFunction promise.reject("E_NO_ACTIVITY", "No activity available", null)
166
201
 
@@ -183,13 +218,25 @@ class ExpoMsalIntuneModule : Module() {
183
218
  }
184
219
  .withCallback(object : AuthenticationCallback {
185
220
  override fun onSuccess(result: IAuthenticationResult) {
221
+ if (initializationGeneration.get() != generation) {
222
+ promise.reject("E_MSAL_INTERACTIVE_SUPERSEDED", "MSAL interactive authentication was superseded", null)
223
+ return
224
+ }
186
225
  authPrefs.edit().remove(FORCE_ACCOUNT_SELECTION).apply()
187
226
  promise.resolve(serializeResult(result))
188
227
  }
189
228
  override fun onError(exception: MsalException) {
229
+ if (initializationGeneration.get() != generation) {
230
+ promise.reject("E_MSAL_INTERACTIVE_SUPERSEDED", "MSAL interactive authentication was superseded", null)
231
+ return
232
+ }
190
233
  promise.reject("E_MSAL_INTERACTIVE", exception.message, exception)
191
234
  }
192
235
  override fun onCancel() {
236
+ if (initializationGeneration.get() != generation) {
237
+ promise.reject("E_MSAL_INTERACTIVE_SUPERSEDED", "MSAL interactive authentication was superseded", null)
238
+ return
239
+ }
193
240
  promise.reject("E_MSAL_CANCELLED", "User cancelled sign-in", null)
194
241
  }
195
242
  })
@@ -481,9 +528,11 @@ class ExpoMsalIntuneModule : Module() {
481
528
  }
482
529
 
483
530
  mapOf(
531
+ "authContractVersion" to str("powerapps_auth_contract_version"),
484
532
  "clientId" to str("adal_client_id"),
485
533
  "redirectUri" to str("adal_redirect_uri"),
486
534
  "tenantId" to str("adal_tenant_id"),
535
+ "tenantMode" to str("powerapps_tenant_mode"),
487
536
  )
488
537
  }
489
538
 
@@ -45,6 +45,8 @@ 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 initializationGeneration: UInt64 = 0
49
+ private let initializationLock = NSLock()
48
50
  /// Stored at initializeClient time; controls which WebView type is used for
49
51
  /// interactive sign-in. true → WKWebView (no Info.plist URL scheme needed).
50
52
  /// false → ASWebAuthenticationSession (requires msauth.{bundleId}://auth scheme).
@@ -64,6 +66,10 @@ public class ExpoMsalIntuneModule: Module {
64
66
  // -----------------------------------------------------------------------
65
67
  AsyncFunction("initializeClient") {
66
68
  (clientId: String, authority: String, redirectUri: String, useEmbeddedWebView: Bool, useBroker: Bool) in
69
+ self.initializationLock.lock()
70
+ defer { self.initializationLock.unlock() }
71
+ self.initializationGeneration &+= 1
72
+ let generation = self.initializationGeneration
67
73
 
68
74
  guard let authorityURL = URL(string: authority) else {
69
75
  throw Self.nativeError(code: -1, message: "Invalid authority URL: \(authority)")
@@ -108,7 +114,11 @@ public class ExpoMsalIntuneModule: Module {
108
114
  // callback possible at runtime.
109
115
  MSALGlobalConfig.brokerAvailability = self.useBroker ? .auto : .none
110
116
  do {
111
- self.pca = try MSALPublicClientApplication(configuration: config)
117
+ let initializedPca = try MSALPublicClientApplication(configuration: config)
118
+ guard self.initializationGeneration == generation else {
119
+ throw MsalIntuneError.intuneError("MSAL initialization was superseded")
120
+ }
121
+ self.pca = initializedPca
112
122
  } catch let err as NSError {
113
123
  throw Self.nativeMsalError(
114
124
  code: msalInitErrorCode,
@@ -122,6 +132,9 @@ public class ExpoMsalIntuneModule: Module {
122
132
  // can recreate a PCA that shares this app's Keychain token cache. Mirrors
123
133
  // the Android module, which writes msal_config.json to the cache dir.
124
134
  // The geolocation reader expects flat keys: clientId / redirectUri / authority.
135
+ guard self.initializationGeneration == generation else {
136
+ throw MsalIntuneError.intuneError("MSAL initialization was superseded")
137
+ }
125
138
  Self.writeMsalConfig(
126
139
  clientId: clientId,
127
140
  redirectUri: iosRedirectUri,
@@ -138,6 +151,9 @@ public class ExpoMsalIntuneModule: Module {
138
151
  (scopes: [String], loginHint: String?, prompt: String?) async throws -> [String: Any] in
139
152
 
140
153
  guard let pca = self.pca else { throw MsalIntuneError.notInitialized }
154
+ self.initializationLock.lock()
155
+ let generation = self.initializationGeneration
156
+ self.initializationLock.unlock()
141
157
 
142
158
  return try await withCheckedThrowingContinuation { continuation in
143
159
  // topViewController() and pca.acquireToken() both require the main
@@ -173,6 +189,13 @@ public class ExpoMsalIntuneModule: Module {
173
189
  }
174
190
 
175
191
  pca.acquireToken(with: params) { result, error in
192
+ self.initializationLock.lock()
193
+ let isCurrentGeneration = self.initializationGeneration == generation
194
+ self.initializationLock.unlock()
195
+ guard isCurrentGeneration else {
196
+ continuation.resume(throwing: MsalIntuneError.intuneError("MSAL interactive authentication was superseded"))
197
+ return
198
+ }
176
199
  if let error = error as NSError? {
177
200
  continuation.resume(throwing: Self.nativeMsalError(
178
201
  code: msalInteractiveErrorCode,
@@ -358,9 +381,11 @@ public class ExpoMsalIntuneModule: Module {
358
381
  let info = Bundle.main.infoDictionary ?? [:]
359
382
  let mam = info["IntuneMAMSettings"] as? [String: Any] ?? [:]
360
383
  return [
384
+ "authContractVersion": mam["PowerAppsAuthContractVersion"] as? String ?? "",
361
385
  "clientId": mam["ADALClientId"] as? String ?? "",
362
386
  "redirectUri": mam["ADALRedirectUri"] as? String ?? "",
363
387
  "tenantId": mam["ADALTenantId"] as? String ?? "",
388
+ "tenantMode": mam["PowerAppsTenantMode"] as? String ?? "",
364
389
  ]
365
390
  }
366
391
 
@@ -482,10 +507,13 @@ public class ExpoMsalIntuneModule: Module {
482
507
  let str = String(data: data, encoding: .utf8) {
483
508
  claims = str
484
509
  }
510
+ let tenantId = account.accountClaims?["tid"] as? String
511
+ ?? account.tenantProfiles?.first?.tenantId
512
+ ?? ""
485
513
  return [
486
514
  "identifier": account.identifier ?? "",
487
515
  "username": account.username ?? "",
488
- "tenantId": account.tenantProfiles?.first?.tenantId ?? "",
516
+ "tenantId": tenantId,
489
517
  "claims": claims,
490
518
  ]
491
519
  }
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@0.4.0 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": "0.4.0",
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",
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