@microsoft/power-apps-native-auth 0.3.4 → 0.3.6

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
  // -------------------------------------------------------------------------
@@ -7,6 +7,7 @@ import IntuneMAMSwift
7
7
  private enum MsalIntuneError: Error {
8
8
  case notInitialized
9
9
  case accountNotFound(String)
10
+ case cacheConfigurationUnavailable
10
11
  case interactionRequired
11
12
  case noResult
12
13
  case intuneError(String)
@@ -19,6 +20,8 @@ extension MsalIntuneError: LocalizedError {
19
20
  return "ExpoMsalIntune: call initializeClient() before acquiring tokens"
20
21
  case .accountNotFound(let id):
21
22
  return "ExpoMsalIntune: account '\(id)' not found in the MSAL cache"
23
+ case .cacheConfigurationUnavailable:
24
+ return "ExpoMsalIntune: cannot clear cached accounts because the last MSAL configuration is unavailable"
22
25
  case .interactionRequired:
23
26
  return "ExpoMsalIntune: silent token acquisition failed — user interaction required"
24
27
  case .noResult:
@@ -32,6 +35,7 @@ extension MsalIntuneError: LocalizedError {
32
35
  // MARK: - Module
33
36
 
34
37
  public class ExpoMsalIntuneModule: Module {
38
+ private static let forceAccountSelectionKey = "powerapps.native.auth.forceAccountSelection"
35
39
  private var pca: MSALPublicClientApplication?
36
40
  /// Stored at initializeClient time; controls which WebView type is used for
37
41
  /// interactive sign-in. true → WKWebView (no Info.plist URL scheme needed).
@@ -61,9 +65,15 @@ public class ExpoMsalIntuneModule: Module {
61
65
  )
62
66
  }
63
67
 
64
- // Store so acquireTokenInteractive can use the correct WebView type.
68
+ // The E2E release artifact must keep authentication inside the app so
69
+ // XCUITest can switch to the inspectable MSAL WKWebView context.
70
+ #if SHRINKWRAP_RELEASE_E2E
71
+ self.useEmbeddedWebView = true
72
+ self.useBroker = false
73
+ #else
65
74
  self.useEmbeddedWebView = useEmbeddedWebView
66
75
  self.useBroker = useBroker
76
+ #endif
67
77
 
68
78
  let msalAuthority = try MSALAuthority(url: authorityURL)
69
79
 
@@ -105,7 +115,13 @@ public class ExpoMsalIntuneModule: Module {
105
115
  // can recreate a PCA that shares this app's Keychain token cache. Mirrors
106
116
  // the Android module, which writes msal_config.json to the cache dir.
107
117
  // The geolocation reader expects flat keys: clientId / redirectUri / authority.
108
- Self.writeMsalConfig(clientId: clientId, redirectUri: iosRedirectUri, authority: authority)
118
+ Self.writeMsalConfig(
119
+ clientId: clientId,
120
+ redirectUri: iosRedirectUri,
121
+ authority: authority,
122
+ useEmbeddedWebView: useEmbeddedWebView,
123
+ useBroker: useBroker
124
+ )
109
125
  }
110
126
 
111
127
  // -----------------------------------------------------------------------
@@ -142,7 +158,10 @@ public class ExpoMsalIntuneModule: Module {
142
158
  let params = MSALInteractiveTokenParameters(scopes: scopes, webviewParameters: webviewParameters)
143
159
 
144
160
  if let hint = loginHint { params.loginHint = hint }
145
- if let promptStr = prompt {
161
+ let effectivePrompt = UserDefaults.standard.bool(forKey: Self.forceAccountSelectionKey)
162
+ ? "select_account"
163
+ : prompt
164
+ if let promptStr = effectivePrompt {
146
165
  params.promptType = self.mapPromptType(promptStr)
147
166
  }
148
167
 
@@ -156,6 +175,7 @@ public class ExpoMsalIntuneModule: Module {
156
175
  continuation.resume(throwing: MsalIntuneError.noResult)
157
176
  return
158
177
  }
178
+ UserDefaults.standard.removeObject(forKey: Self.forceAccountSelectionKey)
159
179
  continuation.resume(returning: self.serializeResult(result))
160
180
  }
161
181
  }
@@ -207,6 +227,43 @@ public class ExpoMsalIntuneModule: Module {
207
227
  return accounts.map { self.serializeAccount($0) }
208
228
  }
209
229
 
230
+ AsyncFunction("clearAccounts") { () throws in
231
+ guard let pca = self.pca else { throw MsalIntuneError.notInitialized }
232
+ for account in try pca.allAccounts() {
233
+ try pca.remove(account)
234
+ }
235
+ }
236
+
237
+ // -----------------------------------------------------------------------
238
+ // clearAccountCache
239
+ // -----------------------------------------------------------------------
240
+ AsyncFunction("clearAccountCache") { () throws -> Int in
241
+ guard let pca = try self.cacheOperationsPca() else {
242
+ throw MsalIntuneError.cacheConfigurationUnavailable
243
+ }
244
+
245
+ let accounts = try pca.allAccounts()
246
+ var removedCount = 0
247
+ var failureCount = 0
248
+ for account in accounts {
249
+ do {
250
+ try pca.remove(account)
251
+ removedCount += 1
252
+ } catch {
253
+ failureCount += 1
254
+ }
255
+ }
256
+
257
+ if failureCount > 0 {
258
+ throw MsalIntuneError.intuneError(
259
+ "Removed \(removedCount) account(s), but \(failureCount) account(s) could not be removed."
260
+ )
261
+ }
262
+
263
+ UserDefaults.standard.set(true, forKey: Self.forceAccountSelectionKey)
264
+ return removedCount
265
+ }
266
+
210
267
  // -----------------------------------------------------------------------
211
268
  // signOut
212
269
  // -----------------------------------------------------------------------
@@ -216,10 +273,13 @@ public class ExpoMsalIntuneModule: Module {
216
273
  guard let pca = self.pca else { throw MsalIntuneError.notInitialized }
217
274
  let account = try self.findAccount(pca: pca, identifier: accountIdentifier)
218
275
 
276
+ if !signoutFromBrowser {
277
+ try pca.remove(account)
278
+ return
279
+ }
280
+
219
281
  return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
220
- // pca.signout(with:) must run on the main thread. When signoutFromBrowser
221
- // is true MSAL needs a view controller to present the browser; we obtain
222
- // one from topViewController() which is also a UIKit operation.
282
+ // Browser sign-out must run on the main thread and needs a view controller.
223
283
  DispatchQueue.main.async {
224
284
  guard let viewController = self.topViewController() else {
225
285
  continuation.resume(throwing: MsalIntuneError.intuneError("No top view controller for signout"))
@@ -296,13 +356,54 @@ public class ExpoMsalIntuneModule: Module {
296
356
 
297
357
  // MARK: - Private helpers
298
358
 
359
+ private func cacheOperationsPca() throws -> MSALPublicClientApplication? {
360
+ if let pca {
361
+ return pca
362
+ }
363
+
364
+ guard let cacheDirectory = FileManager.default.urls(
365
+ for: .cachesDirectory,
366
+ in: .userDomainMask
367
+ ).first else {
368
+ return nil
369
+ }
370
+ let configUrl = cacheDirectory.appendingPathComponent("msal_config.json")
371
+ guard let data = try? Data(contentsOf: configUrl),
372
+ let rawConfig = try? JSONSerialization.jsonObject(with: data),
373
+ let configValue = rawConfig as? [String: Any],
374
+ let clientId = configValue["clientId"] as? String,
375
+ let authority = configValue["authority"] as? String,
376
+ let authorityUrl = URL(string: authority),
377
+ let redirectUri = configValue["redirectUri"] as? String else {
378
+ return nil
379
+ }
380
+
381
+ let config = MSALPublicClientApplicationConfig(
382
+ clientId: clientId,
383
+ redirectUri: redirectUri,
384
+ authority: try MSALAuthority(url: authorityUrl)
385
+ )
386
+ useEmbeddedWebView = configValue["useEmbeddedWebView"] as? Bool ?? true
387
+ useBroker = configValue["useBroker"] as? Bool ?? false
388
+ MSALGlobalConfig.brokerAvailability = useBroker ? .auto : .none
389
+ let restoredPca = try MSALPublicClientApplication(configuration: config)
390
+ pca = restoredPca
391
+ return restoredPca
392
+ }
393
+
299
394
  /// Writes the resolved MSAL parameters to <Caches>/msal_config.json so that
300
395
  /// out-of-process consumers (the powerapps-geolocation-control native sync
301
396
  /// engine) can recreate a PCA sharing this app's Keychain token cache.
302
397
  /// Uses the flat key shape (clientId / redirectUri / authority) that the
303
398
  /// geolocation MsalAuthService reader expects. Static + best-effort: any
304
399
  /// failure is logged and ignored so it never blocks sign-in.
305
- private static func writeMsalConfig(clientId: String, redirectUri: String, authority: String) {
400
+ private static func writeMsalConfig(
401
+ clientId: String,
402
+ redirectUri: String,
403
+ authority: String,
404
+ useEmbeddedWebView: Bool,
405
+ useBroker: Bool
406
+ ) {
306
407
  guard let cacheDir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
307
408
  NSLog("[ExpoMsalIntune] writeMsalConfig: no caches directory")
308
409
  return
@@ -312,6 +413,8 @@ public class ExpoMsalIntuneModule: Module {
312
413
  "clientId": clientId,
313
414
  "redirectUri": redirectUri,
314
415
  "authority": authority,
416
+ "useEmbeddedWebView": useEmbeddedWebView,
417
+ "useBroker": useBroker,
315
418
  ]
316
419
  do {
317
420
  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.4 has no production third-party dependencies.
5
+ @microsoft/power-apps-native-auth@0.3.6 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;
@@ -29,6 +30,14 @@ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r
29
30
  *
30
31
  */
31
32
 
33
+ function isAccountNotFoundError(error) {
34
+ if (!(error instanceof Error)) {
35
+ return false;
36
+ }
37
+ const code = error.code;
38
+ return code === 'E_ACCOUNT_NOT_FOUND' || /not found in (?:the )?MSAL cache/i.test(error.message);
39
+ }
40
+
32
41
  // ---------------------------------------------------------------------------
33
42
  // PublicClientApplication
34
43
  // ---------------------------------------------------------------------------
@@ -42,6 +51,8 @@ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r
42
51
  */
43
52
  class PublicClientApplication {
44
53
  _initialized = false;
54
+ _unvalidatedCachedAccountIds = new Set();
55
+ _forceAccountSelection = false;
45
56
  constructor(config) {
46
57
  this._config = config;
47
58
  }
@@ -68,8 +79,11 @@ class PublicClientApplication {
68
79
  if (!this._initialized) {
69
80
  throw new Error('ExpoMsalIntune: call init() before acquiring tokens');
70
81
  }
71
- const native = await _ExpoMsalIntuneModule.default.acquireTokenInteractive(params.scopes, params.loginHint ?? null, params.prompt ?? null);
72
- return (0, _ExpoMsalIntuneModule.mapNativeResult)(native);
82
+ const native = await _ExpoMsalIntuneModule.default.acquireTokenInteractive(params.scopes, params.loginHint ?? null, this._forceAccountSelection ? 'select_account' : params.prompt ?? null);
83
+ const result = (0, _ExpoMsalIntuneModule.mapNativeResult)(native);
84
+ this._forceAccountSelection = false;
85
+ this._unvalidatedCachedAccountIds.clear();
86
+ return result;
73
87
  }
74
88
 
75
89
  /**
@@ -82,14 +96,29 @@ class PublicClientApplication {
82
96
  if (!this._initialized) {
83
97
  throw new Error('ExpoMsalIntune: call init() before acquiring tokens');
84
98
  }
85
- const native = await _ExpoMsalIntuneModule.default.acquireTokenSilent(params.scopes, params.account.identifier, params.forceRefresh ?? false);
86
- return (0, _ExpoMsalIntuneModule.mapNativeResult)(native);
99
+ try {
100
+ const native = await _ExpoMsalIntuneModule.default.acquireTokenSilent(params.scopes, params.account.identifier, params.forceRefresh ?? false);
101
+ this._unvalidatedCachedAccountIds.delete(params.account.identifier);
102
+ return (0, _ExpoMsalIntuneModule.mapNativeResult)(native);
103
+ } catch (error) {
104
+ if (this._unvalidatedCachedAccountIds.has(params.account.identifier) && isAccountNotFoundError(error)) {
105
+ this._forceAccountSelection = true;
106
+ try {
107
+ await this.clearCachedAccounts();
108
+ } catch {
109
+ this._unvalidatedCachedAccountIds.clear();
110
+ }
111
+ }
112
+ throw error;
113
+ }
87
114
  }
88
115
 
89
116
  /** Return all accounts from the MSAL token cache. */
90
117
  async getAccounts() {
91
118
  const nativeAccounts = await _ExpoMsalIntuneModule.default.getAccounts();
92
- return nativeAccounts.map(_ExpoMsalIntuneModule.mapNativeAccount);
119
+ const accounts = nativeAccounts.map(_ExpoMsalIntuneModule.mapNativeAccount);
120
+ this._unvalidatedCachedAccountIds = new Set(accounts.map(account => account.identifier));
121
+ return accounts;
93
122
  }
94
123
 
95
124
  /**
@@ -97,9 +126,32 @@ class PublicClientApplication {
97
126
  * SSO session.
98
127
  */
99
128
  async signOut(params) {
100
- 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
+ }
138
+ this._unvalidatedCachedAccountIds.delete(params.account.identifier);
139
+ this._forceAccountSelection = true;
101
140
  return true;
102
141
  }
142
+ async clearCachedAccounts() {
143
+ await _ExpoMsalIntuneModule.default.clearAccountCache();
144
+ this._unvalidatedCachedAccountIds.clear();
145
+ }
146
+ }
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();
103
155
  }
104
156
 
105
157
  // ---------------------------------------------------------------------------
@@ -114,7 +166,6 @@ class PublicClientApplication {
114
166
  * On iOS: calls `IntuneMAMEnrollmentManager.registerAndEnrollAccount`.
115
167
  * On Android: calls `MAMEnrollmentManager.registerAndEnrollAccount`.
116
168
  */
117
- exports.PublicClientApplication = PublicClientApplication;
118
169
  async function registerAndEnrollAccount(params) {
119
170
  await _ExpoMsalIntuneModule.default.registerAndEnrollAccount(params.upn, params.aadId ?? '', params.tenantId ?? '');
120
171
  }
@@ -17,6 +17,14 @@
17
17
  */
18
18
 
19
19
  import ExpoMsalIntuneModule, { mapNativeAccount, mapNativeResult } from "./ExpoMsalIntuneModule.js";
20
+ function isAccountNotFoundError(error) {
21
+ if (!(error instanceof Error)) {
22
+ return false;
23
+ }
24
+ const code = error.code;
25
+ return code === 'E_ACCOUNT_NOT_FOUND' || /not found in (?:the )?MSAL cache/i.test(error.message);
26
+ }
27
+
20
28
  // ---------------------------------------------------------------------------
21
29
  // PublicClientApplication
22
30
  // ---------------------------------------------------------------------------
@@ -30,6 +38,8 @@ import ExpoMsalIntuneModule, { mapNativeAccount, mapNativeResult } from "./ExpoM
30
38
  */
31
39
  export class PublicClientApplication {
32
40
  _initialized = false;
41
+ _unvalidatedCachedAccountIds = new Set();
42
+ _forceAccountSelection = false;
33
43
  constructor(config) {
34
44
  this._config = config;
35
45
  }
@@ -56,8 +66,11 @@ export class PublicClientApplication {
56
66
  if (!this._initialized) {
57
67
  throw new Error('ExpoMsalIntune: call init() before acquiring tokens');
58
68
  }
59
- const native = await ExpoMsalIntuneModule.acquireTokenInteractive(params.scopes, params.loginHint ?? null, params.prompt ?? null);
60
- return mapNativeResult(native);
69
+ const native = await ExpoMsalIntuneModule.acquireTokenInteractive(params.scopes, params.loginHint ?? null, this._forceAccountSelection ? 'select_account' : params.prompt ?? null);
70
+ const result = mapNativeResult(native);
71
+ this._forceAccountSelection = false;
72
+ this._unvalidatedCachedAccountIds.clear();
73
+ return result;
61
74
  }
62
75
 
63
76
  /**
@@ -70,14 +83,29 @@ export class PublicClientApplication {
70
83
  if (!this._initialized) {
71
84
  throw new Error('ExpoMsalIntune: call init() before acquiring tokens');
72
85
  }
73
- const native = await ExpoMsalIntuneModule.acquireTokenSilent(params.scopes, params.account.identifier, params.forceRefresh ?? false);
74
- return mapNativeResult(native);
86
+ try {
87
+ const native = await ExpoMsalIntuneModule.acquireTokenSilent(params.scopes, params.account.identifier, params.forceRefresh ?? false);
88
+ this._unvalidatedCachedAccountIds.delete(params.account.identifier);
89
+ return mapNativeResult(native);
90
+ } catch (error) {
91
+ if (this._unvalidatedCachedAccountIds.has(params.account.identifier) && isAccountNotFoundError(error)) {
92
+ this._forceAccountSelection = true;
93
+ try {
94
+ await this.clearCachedAccounts();
95
+ } catch {
96
+ this._unvalidatedCachedAccountIds.clear();
97
+ }
98
+ }
99
+ throw error;
100
+ }
75
101
  }
76
102
 
77
103
  /** Return all accounts from the MSAL token cache. */
78
104
  async getAccounts() {
79
105
  const nativeAccounts = await ExpoMsalIntuneModule.getAccounts();
80
- return nativeAccounts.map(mapNativeAccount);
106
+ const accounts = nativeAccounts.map(mapNativeAccount);
107
+ this._unvalidatedCachedAccountIds = new Set(accounts.map(account => account.identifier));
108
+ return accounts;
81
109
  }
82
110
 
83
111
  /**
@@ -85,9 +113,31 @@ export class PublicClientApplication {
85
113
  * SSO session.
86
114
  */
87
115
  async signOut(params) {
88
- 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
+ }
125
+ this._unvalidatedCachedAccountIds.delete(params.account.identifier);
126
+ this._forceAccountSelection = true;
89
127
  return true;
90
128
  }
129
+ async clearCachedAccounts() {
130
+ await ExpoMsalIntuneModule.clearAccountCache();
131
+ this._unvalidatedCachedAccountIds.clear();
132
+ }
133
+ }
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();
91
141
  }
92
142
 
93
143
  // ---------------------------------------------------------------------------
@@ -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.
@@ -27,6 +27,8 @@ export type { AuthConfig, MsalAuthConfig, IntuneConfig } from './AuthConfig.type
27
27
  export declare class PublicClientApplication {
28
28
  private readonly _config;
29
29
  private _initialized;
30
+ private _unvalidatedCachedAccountIds;
31
+ private _forceAccountSelection;
30
32
  constructor(config: MSALPublicClientApplicationConfig);
31
33
  /** True after `init()` has completed successfully. */
32
34
  get isInitialized(): boolean;
@@ -53,7 +55,13 @@ export declare class PublicClientApplication {
53
55
  * SSO session.
54
56
  */
55
57
  signOut(params: MSALSignoutParams): Promise<boolean>;
58
+ private clearCachedAccounts;
56
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>;
57
65
  /**
58
66
  * Register a signed-in account with Intune MAM and initiate device/app
59
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.
@@ -27,6 +27,8 @@ export type { AuthConfig, MsalAuthConfig, IntuneConfig } from './AuthConfig.type
27
27
  export declare class PublicClientApplication {
28
28
  private readonly _config;
29
29
  private _initialized;
30
+ private _unvalidatedCachedAccountIds;
31
+ private _forceAccountSelection;
30
32
  constructor(config: MSALPublicClientApplicationConfig);
31
33
  /** True after `init()` has completed successfully. */
32
34
  get isInitialized(): boolean;
@@ -53,7 +55,13 @@ export declare class PublicClientApplication {
53
55
  * SSO session.
54
56
  */
55
57
  signOut(params: MSALSignoutParams): Promise<boolean>;
58
+ private clearCachedAccounts;
56
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>;
57
65
  /**
58
66
  * Register a signed-in account with Intune MAM and initiate device/app
59
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.4",
3
+ "version": "0.3.6",
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",
@@ -30,6 +30,7 @@
30
30
  "android/src/",
31
31
  "android/build.gradle",
32
32
  "ios/",
33
+ "!ios/Frameworks/",
33
34
  "plugin/",
34
35
  "scripts/",
35
36
  "app.plugin.js",
package/plugin/index.js CHANGED
@@ -36,11 +36,13 @@
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
 
43
- const withMsalRedirectScheme = require('./withMsalRedirectScheme.js');
43
+ const withMsalRedirectScheme = require('./withMsalRedirectScheme.js');
44
+ const withIntuneMAMSettings = require('./withIntuneMAMSettings.js');
45
+ const withMsalBrokerURLSchemes = require('./withMsalBrokerURLSchemes.js');
44
46
 
45
47
  const IS_DEVELOPMENT_PLAYER = process.env.POWER_APPS_DEV_PLAYER === 'true' || process.env.DEV_CLIENT === 'true';
46
48
 
@@ -267,6 +269,101 @@ function withShrinkWrapFlavor(config) {
267
269
  });
268
270
  }
269
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
+
270
367
  // ---------------------------------------------------------------------------
271
368
  // android/app/src/main/AndroidManifest.xml — MSAL BrowserTabActivity
272
369
  // ---------------------------------------------------------------------------
@@ -292,6 +389,17 @@ function withMsalBrowserTabActivity(config) {
292
389
  return mod;
293
390
  }
294
391
 
392
+ // For standalone builds (real ANDROID_PACKAGE set), use the real bundle ID
393
+ // and pathPrefix so any signing certificate's hash is matched by the OS;
394
+ // MSAL validates the hash programmatically at the SDK level.
395
+ // For wrap-pipeline builds (no env var), use placeholder values that the
396
+ // wrap script replaces at post-build patch time.
397
+ const realBundleId = process.env.ANDROID_PACKAGE;
398
+ const isStandalone = realBundleId && realBundleId !== MSAL_PLACEHOLDER_BUNDLE_ID;
399
+ const intentData = isStandalone
400
+ ? [{ $: { 'android:scheme': 'msauth', 'android:host': realBundleId, 'android:pathPrefix': '/' } }]
401
+ : [{ $: { 'android:scheme': 'msauth', 'android:host': MSAL_PLACEHOLDER_BUNDLE_ID, 'android:path': `/${MSAL_PLACEHOLDER_SIG_HASH}` } }];
402
+
295
403
  activities.push({
296
404
  $: {
297
405
  'android:name': BROWSER_TAB_ACTIVITY_NAME,
@@ -303,13 +411,7 @@ function withMsalBrowserTabActivity(config) {
303
411
  { $: { 'android:name': 'android.intent.category.DEFAULT' } },
304
412
  { $: { 'android:name': 'android.intent.category.BROWSABLE' } },
305
413
  ],
306
- data: [{
307
- $: {
308
- 'android:scheme': 'msauth',
309
- 'android:host': MSAL_PLACEHOLDER_BUNDLE_ID,
310
- 'android:path': `/${MSAL_PLACEHOLDER_SIG_HASH}`,
311
- },
312
- }],
414
+ data: intentData,
313
415
  }],
314
416
  });
315
417
 
@@ -348,7 +450,25 @@ function withWrapStringPlaceholders(config) {
348
450
  return withStringsXml(config, (mod) => {
349
451
  const strings = mod.modResults.resources.string ?? [];
350
452
 
351
- for (const { name, value } of WRAP_PLACEHOLDER_STRINGS) {
453
+ // Use real ADAL values when env vars are set (standalone build-from-source
454
+ // flow via `npm run build:android`). Fall back to placeholder tags for the
455
+ // traditional AAB+protoc wrap pipeline which patches them post-build.
456
+ // adal_redirect_uri stays as a placeholder — the value depends on the signing
457
+ // certificate, which is unknown at prebuild time; MSAL computes it at runtime.
458
+ const resolvedStrings = WRAP_PLACEHOLDER_STRINGS.map(({ name, value }) => {
459
+ if (name === 'app_name' && process.env.APP_DISPLAY_NAME) {
460
+ return { name, value: process.env.APP_DISPLAY_NAME };
461
+ }
462
+ if (name === 'adal_client_id' && process.env.ADAL_CLIENT_ID) {
463
+ return { name, value: process.env.ADAL_CLIENT_ID };
464
+ }
465
+ if (name === 'adal_tenant_id' && process.env.ADAL_TENANT_ID) {
466
+ return { name, value: process.env.ADAL_TENANT_ID };
467
+ }
468
+ return { name, value };
469
+ });
470
+
471
+ for (const { name, value } of resolvedStrings) {
352
472
  const existing = strings.find((s) => s.$?.name === name);
353
473
  if (existing) {
354
474
  existing._ = value;
@@ -427,6 +547,61 @@ function withMsalIOSEntitlement(config) {
427
547
  });
428
548
  }
429
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
+
430
605
  // ---------------------------------------------------------------------------
431
606
  // android/app/proguard-rules.pro — suppress R8 warnings for optional deps
432
607
  // ---------------------------------------------------------------------------
@@ -494,12 +669,23 @@ function withExpoMsalIntune(config) {
494
669
  // The ShrinkWrap flavor is required in both dev-client and release builds
495
670
  // because `npm run android` always passes --variant ShrinkWrapDebug.
496
671
  config = withShrinkWrapFlavor(config);
672
+ config = withAndroidReleaseE2EBuildType(config);
673
+ config = withAndroidReleaseE2EWebViewDebugging(config);
497
674
 
498
675
  // iOS: register msauth.<bundleId> URL scheme in CFBundleURLTypes, and add
499
676
  // the com.microsoft.adalcache keychain-access-groups entitlement.
500
677
  // Both are required by MSAL iOS SDK (v1.1.0+) at PCA init time.
501
678
  config = withMsalIOSURLScheme(config);
502
679
  config = withMsalIOSEntitlement(config);
680
+ if (process.env.SHRINKWRAP_RELEASE_E2E === 'true') {
681
+ config = withReleaseE2EPodFlags(config);
682
+ }
683
+
684
+ // iOS: inject real IntuneMAMSettings and the full broker URL scheme list when
685
+ // ADAL env vars are set (standalone build-from-source via `npm run build:ios`).
686
+ // These are no-ops when the env vars are absent (dev builds, wrap pipeline).
687
+ config = withIntuneMAMSettings(config);
688
+ config = withMsalBrokerURLSchemes(config);
503
689
 
504
690
  // In development-player builds, skip the MAM Gradle plugin (no bytecode instrumentation
505
691
  // needed) and the proguard rules (R8 is disabled in debug anyway).
@@ -0,0 +1,58 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * Expo config plugin: inject IntuneMAMSettings into iOS Info.plist.
6
+ *
7
+ * In standalone build-from-source workflows the build script (build android /
8
+ * build ios) sets ADAL_CLIENT_ID, ADAL_TENANT_ID, and IOS_ADAL_REDIRECT_URI
9
+ * before running expo prebuild. This plugin reads those env vars and writes
10
+ * the real values directly into IntuneMAMSettings so no post-build binary
11
+ * patching is needed.
12
+ *
13
+ * When the env vars are absent (dev builds, wrap-pipeline builds) this plugin
14
+ * is a no-op and the placeholder tag values from the app config's ios.infoPlist
15
+ * section are left intact for the downstream wrap pipeline to replace.
16
+ */
17
+
18
+ const { withInfoPlist } = require('@expo/config-plugins');
19
+
20
+ /** @param {import('@expo/config-plugins').ExpoConfig} config */
21
+ function withIntuneMAMSettings(config) {
22
+ return withInfoPlist(config, (mod) => {
23
+ const clientId = process.env.ADAL_CLIENT_ID;
24
+ const tenantId = process.env.ADAL_TENANT_ID;
25
+ const redirectUri = process.env.IOS_ADAL_REDIRECT_URI;
26
+ const bundleId = config.ios?.bundleIdentifier;
27
+ const isDevBuild = process.env.DEV_CLIENT === 'true' ||
28
+ process.env.POWER_APPS_DEV_PLAYER === 'true';
29
+
30
+ // Dev builds never call getWrapConfig() — skip entirely.
31
+ if (isDevBuild) return mod;
32
+
33
+ if (clientId && clientId !== 'ADAL_CLIENT_ID_TAG') {
34
+ // Standalone build-from-source: inject real values so no post-build
35
+ // patching is needed.
36
+ mod.modResults.IntuneMAMSettings = {
37
+ ADALClientId: clientId,
38
+ ADALRedirectUri: redirectUri ?? `msauth.${bundleId}://auth`,
39
+ ADALTenantId: tenantId ?? '',
40
+ ADALAuthority: `https://login.microsoftonline.com/${tenantId ?? ''}`,
41
+ };
42
+ } else {
43
+ // Release build without env vars (wrap pipeline base IPA).
44
+ // Write placeholder tags so the wrap script can locate and replace them
45
+ // with `plutil -replace IntuneMAMSettings.*`, preserving the original
46
+ // template behaviour.
47
+ mod.modResults.IntuneMAMSettings = {
48
+ ADALClientId: 'ADAL_CLIENT_ID_TAG',
49
+ ADALRedirectUri: 'ADAL_REDIRECT_URI_TAG',
50
+ ADALTenantId: 'ADAL_TENANT_ID_TAG',
51
+ };
52
+ }
53
+
54
+ return mod;
55
+ });
56
+ }
57
+
58
+ module.exports = withIntuneMAMSettings;
@@ -0,0 +1,75 @@
1
+ // @ts-check
2
+ 'use strict';
3
+
4
+ /**
5
+ * Expo config plugin: replace the minimal msauth URL scheme with the full set
6
+ * of MSAL auth-broker + Intune MAM URL schemes required for production builds.
7
+ *
8
+ * The minimal entry (msauth.<bundleId>) added by withMsalIOSURLScheme is
9
+ * sufficient for dev builds and satisfies MSAL's init-time check. For
10
+ * distribution (standalone build-from-source or wrap pipeline) the full
11
+ * scheme list mirrors what wrap-local Step 3 injects post-build.
12
+ *
13
+ * This plugin is a no-op when ADAL_CLIENT_ID is absent or a placeholder tag —
14
+ * i.e. in all `npm run dev` / `expo prebuild` calls not driven by build.js.
15
+ */
16
+
17
+ const { withInfoPlist } = require('@expo/config-plugins');
18
+
19
+ /** @param {import('@expo/config-plugins').ExpoConfig} config */
20
+ function withMsalBrokerURLSchemes(config) {
21
+ return withInfoPlist(config, (mod) => {
22
+ const clientId = process.env.ADAL_CLIENT_ID;
23
+ const bundleId = config.ios?.bundleIdentifier;
24
+
25
+ if (!clientId || clientId === 'ADAL_CLIENT_ID_TAG' || !bundleId) {
26
+ return mod; // dev build — keep minimal scheme entry
27
+ }
28
+
29
+ const msauthScheme = `msauth.${bundleId}`;
30
+ const bundleIdDashes = bundleId.replace(/\./g, '-');
31
+ const bundleSpecificScheme = `ms-mobile-apps-${bundleIdDashes}`;
32
+ const xMsauthSchemes = [
33
+ `x-msauth-${bundleIdDashes}`,
34
+ `x-msauth-${bundleIdDashes}-intunemam`,
35
+ ];
36
+
37
+ // Remove any existing minimal msauth.<bundleId> entries that were added by
38
+ // withMsalIOSURLScheme / withMsalRedirectScheme so we don't produce duplicates.
39
+ const remaining = (mod.modResults.CFBundleURLTypes ?? []).filter(
40
+ (t) =>
41
+ !Array.isArray(t.CFBundleURLSchemes) ||
42
+ !t.CFBundleURLSchemes.includes(msauthScheme),
43
+ );
44
+
45
+ mod.modResults.CFBundleURLTypes = [
46
+ ...remaining,
47
+ // Entry 0: all auth-broker + deep-link schemes (mirrors wrap-local Step 3)
48
+ {
49
+ CFBundleURLName: bundleId,
50
+ CFBundleURLSchemes: [
51
+ msauthScheme,
52
+ `${msauthScheme}-intunemam`,
53
+ 'projectsiena',
54
+ 'projectsiena-intunemam',
55
+ 'ms-mobile-apps',
56
+ 'ms-mobile-apps-intunemam',
57
+ bundleSpecificScheme,
58
+ `${bundleSpecificScheme}-intunemam`,
59
+ 'ms-mobile-app',
60
+ 'ms-mobile-app-intunemam',
61
+ 'ms-app',
62
+ 'ms-app-intunemam',
63
+ ],
64
+ },
65
+ // Entries 1-3: x-msauth broker schemes (mirrors wrap-local production structure)
66
+ { CFBundleURLName: bundleId, CFBundleURLSchemes: xMsauthSchemes },
67
+ { CFBundleURLName: bundleId, CFBundleURLSchemes: xMsauthSchemes },
68
+ { CFBundleURLName: bundleId, CFBundleURLSchemes: xMsauthSchemes },
69
+ ];
70
+
71
+ return mod;
72
+ });
73
+ }
74
+
75
+ module.exports = withMsalBrokerURLSchemes;
@@ -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}"`);