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

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.
@@ -22,6 +22,8 @@ import java.security.MessageDigest
22
22
  import java.util.concurrent.atomic.AtomicBoolean
23
23
 
24
24
  private const val TAG = "ExpoMsalIntune"
25
+ private const val AUTH_PREFS = "powerapps.native.auth"
26
+ private const val FORCE_ACCOUNT_SELECTION = "force_account_selection"
25
27
 
26
28
  class ExpoMsalIntuneModule : Module() {
27
29
 
@@ -162,15 +164,26 @@ class ExpoMsalIntuneModule : Module() {
162
164
  val activity = appContext.activityProvider?.currentActivity
163
165
  ?: return@AsyncFunction promise.reject("E_NO_ACTIVITY", "No activity available", null)
164
166
 
167
+ val authPrefs = activity.applicationContext.getSharedPreferences(
168
+ AUTH_PREFS,
169
+ android.content.Context.MODE_PRIVATE,
170
+ )
171
+ val effectivePrompt = if (authPrefs.getBoolean(FORCE_ACCOUNT_SELECTION, false)) {
172
+ "select_account"
173
+ } else {
174
+ prompt
175
+ }
176
+
165
177
  val params = AcquireTokenParameters.Builder()
166
178
  .startAuthorizationFromActivity(activity)
167
179
  .withScopes(scopes)
168
180
  .apply {
169
181
  loginHint?.let { withLoginHint(it) }
170
- prompt?.let { withPrompt(mapPrompt(it)) }
182
+ effectivePrompt?.let { withPrompt(mapPrompt(it)) }
171
183
  }
172
184
  .withCallback(object : AuthenticationCallback {
173
185
  override fun onSuccess(result: IAuthenticationResult) {
186
+ authPrefs.edit().remove(FORCE_ACCOUNT_SELECTION).apply()
174
187
  promise.resolve(serializeResult(result))
175
188
  }
176
189
  override fun onError(exception: MsalException) {
@@ -251,6 +264,121 @@ class ExpoMsalIntuneModule : Module() {
251
264
  }
252
265
  }
253
266
 
267
+ AsyncFunction("clearAccounts") { promise: Promise ->
268
+ val client = pca
269
+ ?: return@AsyncFunction promise.reject("E_NOT_INIT", notInitMsg, null)
270
+
271
+ try {
272
+ val accounts = client.accounts
273
+ Log.d(TAG, "clearAccounts: removing ${accounts.size} account(s)")
274
+ accounts.forEach { client.removeAccount(it) }
275
+ promise.resolve(null)
276
+ } catch (e: MsalException) {
277
+ Log.e(TAG, "clearAccounts: MsalException: ${e.message}")
278
+ promise.reject("E_MSAL_SIGNOUT", e.message, e)
279
+ } catch (e: InterruptedException) {
280
+ Log.e(TAG, "clearAccounts: interrupted")
281
+ promise.reject("E_MSAL_SIGNOUT", "Interrupted while clearing accounts", e)
282
+ }
283
+ }
284
+
285
+ // -------------------------------------------------------------------------
286
+ // clearAccountCache
287
+ // -------------------------------------------------------------------------
288
+ AsyncFunction("clearAccountCache") { promise: Promise ->
289
+ val appCtx = appContext.reactContext?.applicationContext
290
+ ?: return@AsyncFunction promise.reject("E_NO_CONTEXT", "No application context available", null)
291
+ val authPrefs = appCtx.getSharedPreferences(AUTH_PREFS, android.content.Context.MODE_PRIVATE)
292
+ val configFile = File(appCtx.cacheDir, "msal_config.json")
293
+ val settled = AtomicBoolean(false)
294
+ val mainHandler = Handler(Looper.getMainLooper())
295
+
296
+ fun clearWithClient(client: IMultipleAccountPublicClientApplication) {
297
+ if (!settled.compareAndSet(false, true)) return
298
+ try {
299
+ val accounts = client.accounts
300
+ var removedCount = 0
301
+ var failureCount = 0
302
+ var firstFailure: Exception? = null
303
+ for (account in accounts) {
304
+ try {
305
+ if (client.removeAccount(account)) {
306
+ removedCount += 1
307
+ } else {
308
+ failureCount += 1
309
+ }
310
+ } catch (error: Exception) {
311
+ failureCount += 1
312
+ if (firstFailure == null) {
313
+ firstFailure = error
314
+ }
315
+ }
316
+ }
317
+ if (failureCount > 0) {
318
+ promise.reject(
319
+ "E_MSAL_CLEAR_CACHE",
320
+ "Removed $removedCount account(s), but $failureCount account(s) could not be removed.",
321
+ firstFailure,
322
+ )
323
+ return
324
+ }
325
+ authPrefs.edit().putBoolean(FORCE_ACCOUNT_SELECTION, true).apply()
326
+ promise.resolve(removedCount)
327
+ } catch (error: Exception) {
328
+ promise.reject(
329
+ "E_MSAL_CLEAR_CACHE",
330
+ error.message ?: "Failed to clear the MSAL account cache",
331
+ error,
332
+ )
333
+ }
334
+ }
335
+
336
+ val existingClient = pca
337
+ if (existingClient != null) {
338
+ clearWithClient(existingClient)
339
+ return@AsyncFunction
340
+ }
341
+
342
+ if (!configFile.exists()) {
343
+ settled.set(true)
344
+ promise.reject(
345
+ "E_MSAL_CLEAR_CACHE_CONFIG",
346
+ "Cannot clear cached accounts because the last MSAL configuration is unavailable.",
347
+ null,
348
+ )
349
+ return@AsyncFunction
350
+ }
351
+
352
+ val timeout = Runnable {
353
+ if (settled.compareAndSet(false, true)) {
354
+ promise.reject(
355
+ "E_MSAL_CLEAR_CACHE",
356
+ "Timed out while opening the MSAL account cache.",
357
+ null,
358
+ )
359
+ }
360
+ }
361
+ mainHandler.postDelayed(timeout, 8_000L)
362
+ PublicClientApplication.createMultipleAccountPublicClientApplication(
363
+ appCtx,
364
+ configFile,
365
+ object : IPublicClientApplication.IMultipleAccountApplicationCreatedListener {
366
+ override fun onCreated(application: IMultipleAccountPublicClientApplication) {
367
+ mainHandler.removeCallbacks(timeout)
368
+ pca = application
369
+ clearWithClient(application)
370
+ }
371
+
372
+ override fun onError(exception: MsalException) {
373
+ mainHandler.removeCallbacks(timeout)
374
+ if (settled.compareAndSet(false, true)) {
375
+ promise.reject("E_MSAL_CLEAR_CACHE", exception.message, exception)
376
+ }
377
+ }
378
+ },
379
+ )
380
+ }
381
+
254
382
  // -------------------------------------------------------------------------
255
383
  // signOut
256
384
  // -------------------------------------------------------------------------
@@ -4,9 +4,18 @@ import IntuneMAMSwift
4
4
 
5
5
  // MARK: - Error helpers
6
6
 
7
+ private let expoMsalIntuneErrorDomain = "ExpoMsalIntune"
8
+ private let msalInitErrorCode = 1001
9
+ private let noViewControllerErrorCode = 1002
10
+ private let msalInteractiveErrorCode = 1003
11
+ private let msalSilentInteractionRequiredErrorCode = 1004
12
+ private let msalSilentErrorCode = 1005
13
+ private let msalSignoutErrorCode = 1006
14
+
7
15
  private enum MsalIntuneError: Error {
8
16
  case notInitialized
9
17
  case accountNotFound(String)
18
+ case cacheConfigurationUnavailable
10
19
  case interactionRequired
11
20
  case noResult
12
21
  case intuneError(String)
@@ -19,6 +28,8 @@ extension MsalIntuneError: LocalizedError {
19
28
  return "ExpoMsalIntune: call initializeClient() before acquiring tokens"
20
29
  case .accountNotFound(let id):
21
30
  return "ExpoMsalIntune: account '\(id)' not found in the MSAL cache"
31
+ case .cacheConfigurationUnavailable:
32
+ return "ExpoMsalIntune: cannot clear cached accounts because the last MSAL configuration is unavailable"
22
33
  case .interactionRequired:
23
34
  return "ExpoMsalIntune: silent token acquisition failed — user interaction required"
24
35
  case .noResult:
@@ -32,6 +43,7 @@ extension MsalIntuneError: LocalizedError {
32
43
  // MARK: - Module
33
44
 
34
45
  public class ExpoMsalIntuneModule: Module {
46
+ private static let forceAccountSelectionKey = "powerapps.native.auth.forceAccountSelection"
35
47
  private var pca: MSALPublicClientApplication?
36
48
  /// Stored at initializeClient time; controls which WebView type is used for
37
49
  /// interactive sign-in. true → WKWebView (no Info.plist URL scheme needed).
@@ -54,16 +66,18 @@ public class ExpoMsalIntuneModule: Module {
54
66
  (clientId: String, authority: String, redirectUri: String, useEmbeddedWebView: Bool, useBroker: Bool) in
55
67
 
56
68
  guard let authorityURL = URL(string: authority) else {
57
- throw NSError(
58
- domain: "ExpoMsalIntune",
59
- code: -1,
60
- userInfo: [NSLocalizedDescriptionKey: "Invalid authority URL: \(authority)"]
61
- )
69
+ throw Self.nativeError(code: -1, message: "Invalid authority URL: \(authority)")
62
70
  }
63
71
 
64
- // Store so acquireTokenInteractive can use the correct WebView type.
72
+ // The E2E release artifact must keep authentication inside the app so
73
+ // XCUITest can switch to the inspectable MSAL WKWebView context.
74
+ #if SHRINKWRAP_RELEASE_E2E
75
+ self.useEmbeddedWebView = true
76
+ self.useBroker = false
77
+ #else
65
78
  self.useEmbeddedWebView = useEmbeddedWebView
66
79
  self.useBroker = useBroker
80
+ #endif
67
81
 
68
82
  let msalAuthority = try MSALAuthority(url: authorityURL)
69
83
 
@@ -92,12 +106,15 @@ public class ExpoMsalIntuneModule: Module {
92
106
  // The wrap pipeline adds the required msauth.{bundleId}://auth URL scheme
93
107
  // to Info.plist and CFBundleURLTypes — that's what makes the broker
94
108
  // callback possible at runtime.
95
- MSALGlobalConfig.brokerAvailability = useBroker ? .auto : .none
109
+ MSALGlobalConfig.brokerAvailability = self.useBroker ? .auto : .none
96
110
  do {
97
111
  self.pca = try MSALPublicClientApplication(configuration: config)
98
112
  } catch let err as NSError {
99
- let details = "domain=\(err.domain) code=\(err.code) userInfo=\(err.userInfo)"
100
- throw MsalIntuneError.intuneError("MSAL PCA init failed: \(details)")
113
+ throw Self.nativeMsalError(
114
+ code: msalInitErrorCode,
115
+ operation: "MSAL PCA init",
116
+ error: err
117
+ )
101
118
  }
102
119
 
103
120
  // Persist the resolved MSAL parameters so out-of-process / background
@@ -105,7 +122,13 @@ public class ExpoMsalIntuneModule: Module {
105
122
  // can recreate a PCA that shares this app's Keychain token cache. Mirrors
106
123
  // the Android module, which writes msal_config.json to the cache dir.
107
124
  // The geolocation reader expects flat keys: clientId / redirectUri / authority.
108
- Self.writeMsalConfig(clientId: clientId, redirectUri: iosRedirectUri, authority: authority)
125
+ Self.writeMsalConfig(
126
+ clientId: clientId,
127
+ redirectUri: iosRedirectUri,
128
+ authority: authority,
129
+ useEmbeddedWebView: self.useEmbeddedWebView,
130
+ useBroker: self.useBroker
131
+ )
109
132
  }
110
133
 
111
134
  // -----------------------------------------------------------------------
@@ -123,8 +146,8 @@ public class ExpoMsalIntuneModule: Module {
123
146
  DispatchQueue.main.async {
124
147
  guard let viewController = self.topViewController() else {
125
148
  continuation.resume(throwing: NSError(
126
- domain: "ExpoMsalIntune",
127
- code: -2,
149
+ domain: expoMsalIntuneErrorDomain,
150
+ code: noViewControllerErrorCode,
128
151
  userInfo: [NSLocalizedDescriptionKey: "No view controller available for interactive sign-in"]
129
152
  ))
130
153
  return
@@ -142,20 +165,27 @@ public class ExpoMsalIntuneModule: Module {
142
165
  let params = MSALInteractiveTokenParameters(scopes: scopes, webviewParameters: webviewParameters)
143
166
 
144
167
  if let hint = loginHint { params.loginHint = hint }
145
- if let promptStr = prompt {
168
+ let effectivePrompt = UserDefaults.standard.bool(forKey: Self.forceAccountSelectionKey)
169
+ ? "select_account"
170
+ : prompt
171
+ if let promptStr = effectivePrompt {
146
172
  params.promptType = self.mapPromptType(promptStr)
147
173
  }
148
174
 
149
175
  pca.acquireToken(with: params) { result, error in
150
176
  if let error = error as NSError? {
151
- let details = "domain=\(error.domain) code=\(error.code) userInfo=\(error.userInfo)"
152
- continuation.resume(throwing: MsalIntuneError.intuneError("MSAL acquireToken failed: \(details)"))
177
+ continuation.resume(throwing: Self.nativeMsalError(
178
+ code: msalInteractiveErrorCode,
179
+ operation: "MSAL acquireToken",
180
+ error: error
181
+ ))
153
182
  return
154
183
  }
155
184
  guard let result = result else {
156
185
  continuation.resume(throwing: MsalIntuneError.noResult)
157
186
  return
158
187
  }
188
+ UserDefaults.standard.removeObject(forKey: Self.forceAccountSelectionKey)
159
189
  continuation.resume(returning: self.serializeResult(result))
160
190
  }
161
191
  }
@@ -183,9 +213,17 @@ public class ExpoMsalIntuneModule: Module {
183
213
  // fall back to interactive.
184
214
  if nsError.domain == MSALErrorDomain,
185
215
  nsError.code == MSALError.interactionRequired.rawValue {
186
- continuation.resume(throwing: MsalIntuneError.interactionRequired)
216
+ continuation.resume(throwing: Self.nativeMsalError(
217
+ code: msalSilentInteractionRequiredErrorCode,
218
+ operation: "MSAL acquireTokenSilent interactionRequired",
219
+ error: nsError
220
+ ))
187
221
  } else {
188
- continuation.resume(throwing: error)
222
+ continuation.resume(throwing: Self.nativeMsalError(
223
+ code: msalSilentErrorCode,
224
+ operation: "MSAL acquireTokenSilent",
225
+ error: nsError
226
+ ))
189
227
  }
190
228
  return
191
229
  }
@@ -207,6 +245,43 @@ public class ExpoMsalIntuneModule: Module {
207
245
  return accounts.map { self.serializeAccount($0) }
208
246
  }
209
247
 
248
+ AsyncFunction("clearAccounts") { () throws in
249
+ guard let pca = self.pca else { throw MsalIntuneError.notInitialized }
250
+ for account in try pca.allAccounts() {
251
+ try pca.remove(account)
252
+ }
253
+ }
254
+
255
+ // -----------------------------------------------------------------------
256
+ // clearAccountCache
257
+ // -----------------------------------------------------------------------
258
+ AsyncFunction("clearAccountCache") { () throws -> Int in
259
+ guard let pca = try self.cacheOperationsPca() else {
260
+ throw MsalIntuneError.cacheConfigurationUnavailable
261
+ }
262
+
263
+ let accounts = try pca.allAccounts()
264
+ var removedCount = 0
265
+ var failureCount = 0
266
+ for account in accounts {
267
+ do {
268
+ try pca.remove(account)
269
+ removedCount += 1
270
+ } catch {
271
+ failureCount += 1
272
+ }
273
+ }
274
+
275
+ if failureCount > 0 {
276
+ throw MsalIntuneError.intuneError(
277
+ "Removed \(removedCount) account(s), but \(failureCount) account(s) could not be removed."
278
+ )
279
+ }
280
+
281
+ UserDefaults.standard.set(true, forKey: Self.forceAccountSelectionKey)
282
+ return removedCount
283
+ }
284
+
210
285
  // -----------------------------------------------------------------------
211
286
  // signOut
212
287
  // -----------------------------------------------------------------------
@@ -234,7 +309,11 @@ public class ExpoMsalIntuneModule: Module {
234
309
 
235
310
  pca.signout(with: account, signoutParameters: params) { _, error in
236
311
  if let error = error {
237
- continuation.resume(throwing: error)
312
+ continuation.resume(throwing: Self.nativeMsalError(
313
+ code: msalSignoutErrorCode,
314
+ operation: "MSAL signout",
315
+ error: error as NSError
316
+ ))
238
317
  } else {
239
318
  continuation.resume()
240
319
  }
@@ -299,13 +378,74 @@ public class ExpoMsalIntuneModule: Module {
299
378
 
300
379
  // MARK: - Private helpers
301
380
 
381
+ private static func nativeError(code: Int, message: String) -> NSError {
382
+ NSError(
383
+ domain: expoMsalIntuneErrorDomain,
384
+ code: code,
385
+ userInfo: [NSLocalizedDescriptionKey: message]
386
+ )
387
+ }
388
+
389
+ private static func nativeMsalError(code: Int, operation: String, error: NSError) -> NSError {
390
+ let message = "\(operation) failed: domain=\(error.domain) code=\(error.code) message=\(error.localizedDescription)"
391
+ return NSError(
392
+ domain: expoMsalIntuneErrorDomain,
393
+ code: code,
394
+ userInfo: [
395
+ NSLocalizedDescriptionKey: message,
396
+ NSUnderlyingErrorKey: error,
397
+ ]
398
+ )
399
+ }
400
+
401
+ private func cacheOperationsPca() throws -> MSALPublicClientApplication? {
402
+ if let pca {
403
+ return pca
404
+ }
405
+
406
+ guard let cacheDirectory = FileManager.default.urls(
407
+ for: .cachesDirectory,
408
+ in: .userDomainMask
409
+ ).first else {
410
+ return nil
411
+ }
412
+ let configUrl = cacheDirectory.appendingPathComponent("msal_config.json")
413
+ guard let data = try? Data(contentsOf: configUrl),
414
+ let rawConfig = try? JSONSerialization.jsonObject(with: data),
415
+ let configValue = rawConfig as? [String: Any],
416
+ let clientId = configValue["clientId"] as? String,
417
+ let authority = configValue["authority"] as? String,
418
+ let authorityUrl = URL(string: authority),
419
+ let redirectUri = configValue["redirectUri"] as? String else {
420
+ return nil
421
+ }
422
+
423
+ let config = MSALPublicClientApplicationConfig(
424
+ clientId: clientId,
425
+ redirectUri: redirectUri,
426
+ authority: try MSALAuthority(url: authorityUrl)
427
+ )
428
+ useEmbeddedWebView = configValue["useEmbeddedWebView"] as? Bool ?? true
429
+ useBroker = configValue["useBroker"] as? Bool ?? false
430
+ MSALGlobalConfig.brokerAvailability = useBroker ? .auto : .none
431
+ let restoredPca = try MSALPublicClientApplication(configuration: config)
432
+ pca = restoredPca
433
+ return restoredPca
434
+ }
435
+
302
436
  /// Writes the resolved MSAL parameters to <Caches>/msal_config.json so that
303
437
  /// out-of-process consumers (the powerapps-geolocation-control native sync
304
438
  /// engine) can recreate a PCA sharing this app's Keychain token cache.
305
439
  /// Uses the flat key shape (clientId / redirectUri / authority) that the
306
440
  /// geolocation MsalAuthService reader expects. Static + best-effort: any
307
441
  /// failure is logged and ignored so it never blocks sign-in.
308
- private static func writeMsalConfig(clientId: String, redirectUri: String, authority: String) {
442
+ private static func writeMsalConfig(
443
+ clientId: String,
444
+ redirectUri: String,
445
+ authority: String,
446
+ useEmbeddedWebView: Bool,
447
+ useBroker: Bool
448
+ ) {
309
449
  guard let cacheDir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
310
450
  NSLog("[ExpoMsalIntune] writeMsalConfig: no caches directory")
311
451
  return
@@ -315,6 +455,8 @@ public class ExpoMsalIntuneModule: Module {
315
455
  "clientId": clientId,
316
456
  "redirectUri": redirectUri,
317
457
  "authority": authority,
458
+ "useEmbeddedWebView": useEmbeddedWebView,
459
+ "useBroker": useBroker,
318
460
  ]
319
461
  do {
320
462
  let data = try JSONSerialization.data(withJSONObject: config, options: [])
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.5 has no production third-party dependencies.
5
+ @microsoft/power-apps-native-auth@0.3.8 has no production third-party dependencies.
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.PublicClientApplication = void 0;
7
7
  exports.buildMsalConfig = buildMsalConfig;
8
+ exports.clearAccountCache = clearAccountCache;
8
9
  exports.computeMsalRedirectUri = computeMsalRedirectUri;
9
10
  exports.deRegisterAndUnenrollAccount = deRegisterAndUnenrollAccount;
10
11
  exports.default = void 0;
@@ -78,7 +79,7 @@ class PublicClientApplication {
78
79
  if (!this._initialized) {
79
80
  throw new Error('ExpoMsalIntune: call init() before acquiring tokens');
80
81
  }
81
- const native = await _ExpoMsalIntuneModule.default.acquireTokenInteractive(params.scopes, params.loginHint ?? null, params.prompt ?? (this._forceAccountSelection ? 'select_account' : null));
82
+ const native = await _ExpoMsalIntuneModule.default.acquireTokenInteractive(params.scopes, params.loginHint ?? null, this._forceAccountSelection ? 'select_account' : params.prompt ?? null);
82
83
  const result = (0, _ExpoMsalIntuneModule.mapNativeResult)(native);
83
84
  this._forceAccountSelection = false;
84
85
  this._unvalidatedCachedAccountIds.clear();
@@ -125,23 +126,34 @@ class PublicClientApplication {
125
126
  * SSO session.
126
127
  */
127
128
  async signOut(params) {
128
- await _ExpoMsalIntuneModule.default.signOut(params.account.identifier, params.signoutFromBrowser ?? false);
129
+ try {
130
+ await _ExpoMsalIntuneModule.default.signOut(params.account.identifier, params.signoutFromBrowser ?? false);
131
+ } catch (error) {
132
+ if (!isAccountNotFoundError(error)) throw error;
133
+ await _ExpoMsalIntuneModule.default.clearAccounts();
134
+ this._unvalidatedCachedAccountIds.clear();
135
+ this._forceAccountSelection = true;
136
+ return true;
137
+ }
129
138
  this._unvalidatedCachedAccountIds.delete(params.account.identifier);
139
+ this._forceAccountSelection = true;
130
140
  return true;
131
141
  }
132
142
  async clearCachedAccounts() {
133
- const nativeAccounts = await _ExpoMsalIntuneModule.default.getAccounts();
134
- await Promise.all(nativeAccounts.map(async account => {
135
- try {
136
- await _ExpoMsalIntuneModule.default.signOut(account.identifier, false);
137
- } catch {
138
- // Continue clearing the remaining cached accounts.
139
- }
140
- }));
143
+ await _ExpoMsalIntuneModule.default.clearAccountCache();
141
144
  this._unvalidatedCachedAccountIds.clear();
142
145
  }
143
146
  }
144
147
 
148
+ /**
149
+ * Clear the account cache for the most recently initialized native PCA.
150
+ * Native code restores that PCA after a JS bundle reload when needed.
151
+ */
152
+ exports.PublicClientApplication = PublicClientApplication;
153
+ async function clearAccountCache() {
154
+ return _ExpoMsalIntuneModule.default.clearAccountCache();
155
+ }
156
+
145
157
  // ---------------------------------------------------------------------------
146
158
  // Intune MAM helpers
147
159
  // ---------------------------------------------------------------------------
@@ -154,7 +166,6 @@ class PublicClientApplication {
154
166
  * On iOS: calls `IntuneMAMEnrollmentManager.registerAndEnrollAccount`.
155
167
  * On Android: calls `MAMEnrollmentManager.registerAndEnrollAccount`.
156
168
  */
157
- exports.PublicClientApplication = PublicClientApplication;
158
169
  async function registerAndEnrollAccount(params) {
159
170
  await _ExpoMsalIntuneModule.default.registerAndEnrollAccount(params.upn, params.aadId ?? '', params.tenantId ?? '');
160
171
  }
@@ -66,7 +66,7 @@ export class PublicClientApplication {
66
66
  if (!this._initialized) {
67
67
  throw new Error('ExpoMsalIntune: call init() before acquiring tokens');
68
68
  }
69
- const native = await ExpoMsalIntuneModule.acquireTokenInteractive(params.scopes, params.loginHint ?? null, params.prompt ?? (this._forceAccountSelection ? 'select_account' : null));
69
+ const native = await ExpoMsalIntuneModule.acquireTokenInteractive(params.scopes, params.loginHint ?? null, this._forceAccountSelection ? 'select_account' : params.prompt ?? null);
70
70
  const result = mapNativeResult(native);
71
71
  this._forceAccountSelection = false;
72
72
  this._unvalidatedCachedAccountIds.clear();
@@ -113,23 +113,33 @@ export class PublicClientApplication {
113
113
  * SSO session.
114
114
  */
115
115
  async signOut(params) {
116
- await ExpoMsalIntuneModule.signOut(params.account.identifier, params.signoutFromBrowser ?? false);
116
+ try {
117
+ await ExpoMsalIntuneModule.signOut(params.account.identifier, params.signoutFromBrowser ?? false);
118
+ } catch (error) {
119
+ if (!isAccountNotFoundError(error)) throw error;
120
+ await ExpoMsalIntuneModule.clearAccounts();
121
+ this._unvalidatedCachedAccountIds.clear();
122
+ this._forceAccountSelection = true;
123
+ return true;
124
+ }
117
125
  this._unvalidatedCachedAccountIds.delete(params.account.identifier);
126
+ this._forceAccountSelection = true;
118
127
  return true;
119
128
  }
120
129
  async clearCachedAccounts() {
121
- const nativeAccounts = await ExpoMsalIntuneModule.getAccounts();
122
- await Promise.all(nativeAccounts.map(async account => {
123
- try {
124
- await ExpoMsalIntuneModule.signOut(account.identifier, false);
125
- } catch {
126
- // Continue clearing the remaining cached accounts.
127
- }
128
- }));
130
+ await ExpoMsalIntuneModule.clearAccountCache();
129
131
  this._unvalidatedCachedAccountIds.clear();
130
132
  }
131
133
  }
132
134
 
135
+ /**
136
+ * Clear the account cache for the most recently initialized native PCA.
137
+ * Native code restores that PCA after a JS bundle reload when needed.
138
+ */
139
+ export async function clearAccountCache() {
140
+ return ExpoMsalIntuneModule.clearAccountCache();
141
+ }
142
+
133
143
  // ---------------------------------------------------------------------------
134
144
  // Intune MAM helpers
135
145
  // ---------------------------------------------------------------------------
@@ -39,6 +39,10 @@ export interface NativeExpoMsalIntuneModule {
39
39
  acquireTokenSilent(scopes: string[], accountIdentifier: string, forceRefresh: boolean): Promise<NativeTokenResult>;
40
40
  /** Return all accounts cached in the MSAL token cache. */
41
41
  getAccounts(): Promise<NativeAccount[]>;
42
+ /** Remove every account from the local MSAL token cache. */
43
+ clearAccounts(): Promise<void>;
44
+ /** Remove every account cached for the last initialized PCA. */
45
+ clearAccountCache(): Promise<number>;
42
46
  /**
43
47
  * Remove the account from the MSAL cache and, optionally, the browser
44
48
  * SSO session.
@@ -57,6 +57,11 @@ export declare class PublicClientApplication {
57
57
  signOut(params: MSALSignoutParams): Promise<boolean>;
58
58
  private clearCachedAccounts;
59
59
  }
60
+ /**
61
+ * Clear the account cache for the most recently initialized native PCA.
62
+ * Native code restores that PCA after a JS bundle reload when needed.
63
+ */
64
+ export declare function clearAccountCache(): Promise<number>;
60
65
  /**
61
66
  * Register a signed-in account with Intune MAM and initiate device/app
62
67
  * enrollment. Call this immediately after a successful `acquireToken` to
@@ -39,6 +39,10 @@ export interface NativeExpoMsalIntuneModule {
39
39
  acquireTokenSilent(scopes: string[], accountIdentifier: string, forceRefresh: boolean): Promise<NativeTokenResult>;
40
40
  /** Return all accounts cached in the MSAL token cache. */
41
41
  getAccounts(): Promise<NativeAccount[]>;
42
+ /** Remove every account from the local MSAL token cache. */
43
+ clearAccounts(): Promise<void>;
44
+ /** Remove every account cached for the last initialized PCA. */
45
+ clearAccountCache(): Promise<number>;
42
46
  /**
43
47
  * Remove the account from the MSAL cache and, optionally, the browser
44
48
  * SSO session.
@@ -57,6 +57,11 @@ export declare class PublicClientApplication {
57
57
  signOut(params: MSALSignoutParams): Promise<boolean>;
58
58
  private clearCachedAccounts;
59
59
  }
60
+ /**
61
+ * Clear the account cache for the most recently initialized native PCA.
62
+ * Native code restores that PCA after a JS bundle reload when needed.
63
+ */
64
+ export declare function clearAccountCache(): Promise<number>;
60
65
  /**
61
66
  * Register a signed-in account with Intune MAM and initiate device/app
62
67
  * enrollment. Call this immediately after a successful `acquireToken` to
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/power-apps-native-auth",
3
- "version": "0.3.5",
3
+ "version": "0.3.8",
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",
@@ -37,8 +37,8 @@
37
37
  "expo-module.config.json"
38
38
  ],
39
39
  "scripts": {
40
- "prepack": "bob build && node ../../scripts/notices.js",
41
- "build": "bob build && node ../../scripts/notices.js",
40
+ "prepack": "bob build && node ../../scripts/package-build/notices.js",
41
+ "build": "bob build && node ../../scripts/package-build/notices.js",
42
42
  "type-check": "tsc --noEmit",
43
43
  "setup:ios": "node scripts/setup-ios-frameworks.js",
44
44
  "setup:android": "node scripts/setup-android-sdk.js",
@@ -51,6 +51,7 @@
51
51
  "react-native": ">=0.83.4"
52
52
  },
53
53
  "devDependencies": {
54
+ "@microsoft/power-apps-cli": "0.15.3",
54
55
  "expo-modules-core": "55.0.25",
55
56
  "typescript": "5.9.3"
56
57
  },
package/plugin/index.js CHANGED
@@ -36,7 +36,7 @@
36
36
  * (downloads SDK AARs + plugin jar from GitHub into android/libs/)
37
37
  */
38
38
 
39
- const { withProjectBuildGradle, withAppBuildGradle, withDangerousMod, withStringsXml, withAndroidManifest, withInfoPlist, withEntitlementsPlist } = require('@expo/config-plugins');
39
+ const { withProjectBuildGradle, withAppBuildGradle, withDangerousMod, withStringsXml, withAndroidManifest, withInfoPlist, withEntitlementsPlist, withMainApplication } = require('@expo/config-plugins');
40
40
  const fs = require('fs');
41
41
  const path = require('path');
42
42
 
@@ -269,6 +269,101 @@ function withShrinkWrapFlavor(config) {
269
269
  });
270
270
  }
271
271
 
272
+ // ---------------------------------------------------------------------------
273
+ // Android Release E2E — release build with inspectable WebViews
274
+ // ---------------------------------------------------------------------------
275
+
276
+ const RELEASE_E2E_BUILD_TYPE_SENTINEL = 'releaseE2E {';
277
+ const RELEASE_E2E_BUILD_CONFIG_SENTINEL = 'WEBVIEW_DEBUGGABLE';
278
+
279
+ function withAndroidReleaseE2EBuildType(config) {
280
+ return withAppBuildGradle(config, (mod) => {
281
+ let contents = mod.modResults.contents;
282
+
283
+ if (!contents.includes(RELEASE_E2E_BUILD_CONFIG_SENTINEL)) {
284
+ const anchor = ' buildConfigField "String", "REACT_NATIVE_RELEASE_LEVEL", "\\"${findProperty(\'reactNativeReleaseLevel\') ?: \'stable\'}\\""';
285
+ contents = insertAfter(
286
+ contents,
287
+ anchor,
288
+ '\n buildConfigField "boolean", "WEBVIEW_DEBUGGABLE", "false"',
289
+ RELEASE_E2E_BUILD_CONFIG_SENTINEL
290
+ );
291
+ }
292
+
293
+ if (!contents.includes(RELEASE_E2E_BUILD_TYPE_SENTINEL)) {
294
+ const buildTypesStart = contents.indexOf(' buildTypes {');
295
+ const buildTypesOpeningBrace = contents.indexOf('{', buildTypesStart);
296
+ let braceDepth = 0;
297
+ let buildTypesClosingIndex = -1;
298
+
299
+ if (buildTypesStart !== -1 && buildTypesOpeningBrace !== -1) {
300
+ for (let index = buildTypesOpeningBrace; index < contents.length; index += 1) {
301
+ if (contents[index] === '{') braceDepth += 1;
302
+ if (contents[index] === '}') braceDepth -= 1;
303
+ if (braceDepth === 0) {
304
+ buildTypesClosingIndex = index;
305
+ break;
306
+ }
307
+ }
308
+ }
309
+
310
+ if (buildTypesClosingIndex === -1) {
311
+ throw new Error(
312
+ 'power-apps-native-auth plugin: could not find the buildTypes closing anchor in app/build.gradle.\n' +
313
+ 'The file format may have changed — please file a bug.'
314
+ );
315
+ }
316
+ const buildType =
317
+ ' releaseE2E {\n' +
318
+ ' initWith release\n' +
319
+ " matchingFallbacks = ['release']\n" +
320
+ ' buildConfigField "boolean", "WEBVIEW_DEBUGGABLE", "true"\n' +
321
+ ' }\n';
322
+ contents = contents.slice(0, buildTypesClosingIndex) + buildType + contents.slice(buildTypesClosingIndex);
323
+ }
324
+
325
+ mod.modResults.contents = contents;
326
+ return mod;
327
+ });
328
+ }
329
+
330
+ const WEBVIEW_DEBUG_IMPORT = 'import android.webkit.WebView';
331
+ const WEBVIEW_DEBUG_ON_CREATE_SENTINEL = 'BuildConfig.WEBVIEW_DEBUGGABLE';
332
+
333
+ function withAndroidReleaseE2EWebViewDebugging(config) {
334
+ return withMainApplication(config, (mod) => {
335
+ let contents = mod.modResults.contents;
336
+
337
+ if (!contents.includes(WEBVIEW_DEBUG_IMPORT)) {
338
+ const importAnchor = 'import android.content.res.Configuration';
339
+ if (!contents.includes(importAnchor)) {
340
+ throw new Error(
341
+ 'power-apps-native-auth plugin: could not find the Configuration import in MainApplication.\n' +
342
+ 'The file format may have changed — please file a bug.'
343
+ );
344
+ }
345
+ contents = contents.replace(importAnchor, `${importAnchor}\n${WEBVIEW_DEBUG_IMPORT}`);
346
+ }
347
+
348
+ if (!contents.includes(WEBVIEW_DEBUG_ON_CREATE_SENTINEL)) {
349
+ const onCreateAnchor = ' super.onCreate()';
350
+ if (!contents.includes(onCreateAnchor)) {
351
+ throw new Error(
352
+ 'power-apps-native-auth plugin: could not find super.onCreate() in MainApplication.\n' +
353
+ 'The file format may have changed — please file a bug.'
354
+ );
355
+ }
356
+ contents = contents.replace(
357
+ onCreateAnchor,
358
+ `${onCreateAnchor}\n if (BuildConfig.WEBVIEW_DEBUGGABLE) {\n WebView.setWebContentsDebuggingEnabled(true)\n }`
359
+ );
360
+ }
361
+
362
+ mod.modResults.contents = contents;
363
+ return mod;
364
+ });
365
+ }
366
+
272
367
  // ---------------------------------------------------------------------------
273
368
  // android/app/src/main/AndroidManifest.xml — MSAL BrowserTabActivity
274
369
  // ---------------------------------------------------------------------------
@@ -452,6 +547,61 @@ function withMsalIOSEntitlement(config) {
452
547
  });
453
548
  }
454
549
 
550
+ // ---------------------------------------------------------------------------
551
+ // iOS Podfile — opt-in Release E2E compilation flags
552
+ // ---------------------------------------------------------------------------
553
+
554
+ const RELEASE_E2E_PODFILE_SENTINEL = 'ShrinkWrapReleaseE2E pod flags';
555
+ const RELEASE_E2E_PODFILE_BLOCK = `
556
+
557
+ # ShrinkWrapReleaseE2E pod flags — inert unless the xcodebuild invocation
558
+ # supplies the corresponding user-defined build settings.
559
+ installer.pods_project.targets.each do |target|
560
+ target.build_configurations.each do |build_config|
561
+ if target.name == 'ExpoMsalIntune'
562
+ build_config.build_settings['SWIFT_ACTIVE_COMPILATION_CONDITIONS'] ||= ['$(inherited)']
563
+ build_config.build_settings['SWIFT_ACTIVE_COMPILATION_CONDITIONS'] << '$(SHRINKWRAP_RELEASE_E2E_SWIFT_FLAG)'
564
+ elsif target.name == 'MSAL'
565
+ build_config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)']
566
+ build_config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << '$(SHRINKWRAP_RELEASE_E2E_MSAL_DEBUG)'
567
+ end
568
+ end
569
+ end`;
570
+
571
+ function withReleaseE2EPodFlags(config) {
572
+ return withDangerousMod(config, [
573
+ 'ios',
574
+ async (cfg) => {
575
+ const podfilePath = path.join(cfg.modRequest.platformProjectRoot, 'Podfile');
576
+ let contents = fs.readFileSync(podfilePath, 'utf8');
577
+ if (contents.includes(RELEASE_E2E_PODFILE_SENTINEL)) return cfg;
578
+
579
+ const anchor = ' react_native_post_install(';
580
+ const start = contents.indexOf(anchor);
581
+ if (start < 0) {
582
+ throw new Error(
583
+ 'power-apps-native-auth plugin: could not find react_native_post_install in the iOS Podfile.'
584
+ );
585
+ }
586
+
587
+ const closingLine = '\n )';
588
+ const end = contents.indexOf(closingLine, start);
589
+ if (end < 0) {
590
+ throw new Error(
591
+ 'power-apps-native-auth plugin: could not find the end of react_native_post_install in the iOS Podfile.'
592
+ );
593
+ }
594
+
595
+ const insertionPoint = end + closingLine.length;
596
+ contents = contents.slice(0, insertionPoint)
597
+ + RELEASE_E2E_PODFILE_BLOCK
598
+ + contents.slice(insertionPoint);
599
+ fs.writeFileSync(podfilePath, contents, 'utf8');
600
+ return cfg;
601
+ },
602
+ ]);
603
+ }
604
+
455
605
  // ---------------------------------------------------------------------------
456
606
  // android/app/proguard-rules.pro — suppress R8 warnings for optional deps
457
607
  // ---------------------------------------------------------------------------
@@ -519,12 +669,17 @@ function withExpoMsalIntune(config) {
519
669
  // The ShrinkWrap flavor is required in both dev-client and release builds
520
670
  // because `npm run android` always passes --variant ShrinkWrapDebug.
521
671
  config = withShrinkWrapFlavor(config);
672
+ config = withAndroidReleaseE2EBuildType(config);
673
+ config = withAndroidReleaseE2EWebViewDebugging(config);
522
674
 
523
675
  // iOS: register msauth.<bundleId> URL scheme in CFBundleURLTypes, and add
524
676
  // the com.microsoft.adalcache keychain-access-groups entitlement.
525
677
  // Both are required by MSAL iOS SDK (v1.1.0+) at PCA init time.
526
678
  config = withMsalIOSURLScheme(config);
527
679
  config = withMsalIOSEntitlement(config);
680
+ if (process.env.SHRINKWRAP_RELEASE_E2E === 'true') {
681
+ config = withReleaseE2EPodFlags(config);
682
+ }
528
683
 
529
684
  // iOS: inject real IntuneMAMSettings and the full broker URL scheme list when
530
685
  // ADAL env vars are set (standalone build-from-source via `npm run build:ios`).
@@ -26,11 +26,16 @@ const DOWNLOAD_URL = `https://github.com/${REPO}/archive/refs/tags/${version}.zi
26
26
  const FRAMEWORKS = ['IntuneMAMSwift.xcframework', 'IntuneMAMSwiftStub.xcframework'];
27
27
 
28
28
  const frameworksDir = path.join(__dirname, '..', 'ios', 'Frameworks');
29
+ const sentinelPath = path.join(frameworksDir, '.sdk-version');
29
30
  const tmpZip = path.join(os.tmpdir(), `intune-ios-sdk-${version}.zip`);
30
31
  const tmpExtract = path.join(os.tmpdir(), `intune-ios-sdk-${version}`);
31
32
 
32
33
  // Check if already present
33
- const allPresent = FRAMEWORKS.every(f => fs.existsSync(path.join(frameworksDir, f)));
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)));
34
39
  if (allPresent) {
35
40
  console.log(`✅ IntuneMAMSwift ${version} xcframeworks already present in ios/Frameworks/`);
36
41
  process.exit(0);
@@ -87,6 +92,8 @@ function download(url, dest, redirects = 0) {
87
92
  console.log(`✅ Copied ${framework}`);
88
93
  }
89
94
 
95
+ fs.writeFileSync(sentinelPath, version + '\n', 'utf8');
96
+
90
97
  // Cleanup
91
98
  fs.unlinkSync(tmpZip);
92
99
  execSync(`rm -rf "${tmpExtract}"`);