@expo/cli 57.0.14 → 57.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +1 -1
- package/build/src/api/graphql/queries/UserQuery.js +3 -0
- package/build/src/api/graphql/queries/UserQuery.js.map +1 -1
- package/build/src/api/user/user.js +2 -0
- package/build/src/api/user/user.js.map +1 -1
- package/build/src/events/index.js +1 -1
- package/build/src/run/ios/appleDevice/AppleDevice.js +4 -1
- package/build/src/run/ios/appleDevice/AppleDevice.js.map +1 -1
- package/build/src/utils/codesigning.js +3 -0
- package/build/src/utils/codesigning.js.map +1 -1
- package/build/src/utils/npm.js +16 -3
- package/build/src/utils/npm.js.map +1 -1
- package/build/src/utils/telemetry/Telemetry.js +5 -0
- package/build/src/utils/telemetry/Telemetry.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/build/src/utils/telemetry/utils/sandbox.js +39 -0
- package/build/src/utils/telemetry/utils/sandbox.js.map +1 -0
- package/package.json +11 -10
package/build/bin/cli
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/api/graphql/queries/UserQuery.ts"],"sourcesContent":["import { graphql, query } from '../client';\n\nexport type Permission = 'ADMIN' | 'OWN' | 'PUBLISH' | 'VIEW';\n\ntype CurrentUserDataUser = {\n permissions: Permission[];\n actor: {\n __typename: 'Robot' | 'SSOUser' | 'User';\n id: string;\n };\n};\n\ntype CurrentUserDataAccount = {\n __typename?: 'Account';\n id: string;\n users: CurrentUserDataUser[];\n};\n\nexport type Actor =\n | {\n __typename: 'Robot';\n firstName?: string | null;\n id: string;\n accounts: CurrentUserDataAccount[];\n }\n | {\n __typename: 'SSOUser' | 'User';\n id: string;\n username: string;\n primaryAccount: {\n id: string;\n };\n accounts: CurrentUserDataAccount[];\n };\n\ntype CurrentUserData = {\n meActor: Actor | null;\n};\n\nconst CurrentUserDocument = graphql<CurrentUserData>(`\n query CurrentUser {\n meActor {\n __typename\n id\n ... on UserActor {\n primaryAccount {\n id\n }\n username\n }\n ... on Robot {\n firstName\n }\n accounts {\n id\n users {\n actor {\n __typename\n id\n }\n permissions\n }\n }\n }\n }\n`);\n\ntype UserQueryData = {\n meUserActor: {\n id: string;\n username: string;\n };\n};\n\nconst UserQueryDocument = graphql<UserQueryData>(`\n query UserQuery {\n meUserActor {\n id\n username\n }\n }\n`);\n\nexport const UserQuery = {\n async currentUserAsync() {\n const data = await query(CurrentUserDocument, {});\n return data.meActor;\n },\n async meUserActorAsync(headers: Record<string, string>) {\n const data = await query(UserQueryDocument, {}, { headers });\n return {\n id: data.meUserActor.id,\n username: data.meUserActor.username,\n };\n },\n};\n"],"names":["UserQuery","CurrentUserDocument","graphql","UserQueryDocument","currentUserAsync","data","query","meActor","meUserActorAsync","headers","id","meUserActor","username"],"mappings":";;;;+
|
|
1
|
+
{"version":3,"sources":["../../../../../src/api/graphql/queries/UserQuery.ts"],"sourcesContent":["import { graphql, query } from '../client';\n\nexport type Permission = 'ADMIN' | 'OWN' | 'PUBLISH' | 'VIEW';\n\ntype CurrentUserDataUser = {\n permissions: Permission[];\n actor: {\n __typename: 'PartnerActor' | 'Robot' | 'SSOUser' | 'User';\n id: string;\n };\n};\n\ntype CurrentUserDataAccount = {\n __typename?: 'Account';\n id: string;\n users: CurrentUserDataUser[];\n};\n\nexport type Actor =\n | {\n __typename: 'Robot';\n firstName?: string | null;\n id: string;\n accounts: CurrentUserDataAccount[];\n }\n | {\n __typename: 'SSOUser' | 'User';\n id: string;\n username: string;\n primaryAccount: {\n id: string;\n };\n accounts: CurrentUserDataAccount[];\n }\n | {\n __typename: 'PartnerActor';\n id: string;\n username: string;\n accounts: CurrentUserDataAccount[];\n };\n\ntype CurrentUserData = {\n meActor: Actor | null;\n};\n\nconst CurrentUserDocument = graphql<CurrentUserData>(`\n query CurrentUser {\n meActor {\n __typename\n id\n ... on UserActor {\n primaryAccount {\n id\n }\n username\n }\n ... on Robot {\n firstName\n }\n ... on PartnerActor {\n username\n }\n accounts {\n id\n users {\n actor {\n __typename\n id\n }\n permissions\n }\n }\n }\n }\n`);\n\ntype UserQueryData = {\n meUserActor: {\n id: string;\n username: string;\n };\n};\n\nconst UserQueryDocument = graphql<UserQueryData>(`\n query UserQuery {\n meUserActor {\n id\n username\n }\n }\n`);\n\nexport const UserQuery = {\n async currentUserAsync() {\n const data = await query(CurrentUserDocument, {});\n return data.meActor;\n },\n async meUserActorAsync(headers: Record<string, string>) {\n const data = await query(UserQueryDocument, {}, { headers });\n return {\n id: data.meUserActor.id,\n username: data.meUserActor.username,\n };\n },\n};\n"],"names":["UserQuery","CurrentUserDocument","graphql","UserQueryDocument","currentUserAsync","data","query","meActor","meUserActorAsync","headers","id","meUserActor","username"],"mappings":";;;;+BA4FaA;;;eAAAA;;;wBA5FkB;AA6C/B,MAAMC,sBAAsBC,IAAAA,eAAO,EAAkB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BtD,CAAC;AASD,MAAMC,oBAAoBD,IAAAA,eAAO,EAAgB,CAAC;;;;;;;AAOlD,CAAC;AAEM,MAAMF,YAAY;IACvB,MAAMI;QACJ,MAAMC,OAAO,MAAMC,IAAAA,aAAK,EAACL,qBAAqB,CAAC;QAC/C,OAAOI,KAAKE,OAAO;IACrB;IACA,MAAMC,kBAAiBC,OAA+B;QACpD,MAAMJ,OAAO,MAAMC,IAAAA,aAAK,EAACH,mBAAmB,CAAC,GAAG;YAAEM;QAAQ;QAC1D,OAAO;YACLC,IAAIL,KAAKM,WAAW,CAACD,EAAE;YACvBE,UAAUP,KAAKM,WAAW,CAACC,QAAQ;QACrC;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/api/user/user.ts"],"sourcesContent":["import { promises as fs } from 'fs';\n\nimport { getAccessToken, getSession, setSessionAsync } from './UserSettings';\nimport { getSessionUsingBrowserAuthFlowAsync } from './expoSsoLauncher';\nimport * as Log from '../../log';\nimport { getDevelopmentCodeSigningDirectory } from '../../utils/codesigning';\nimport { env } from '../../utils/env';\nimport { getExpoWebsiteBaseUrl } from '../endpoint';\nimport { UserQuery, type Actor } from '../graphql/queries/UserQuery';\nimport { fetchAsync } from '../rest/client';\n\nconst debug = require('debug')('expo:api:user') as typeof console.log;\n\nlet currentUser: Actor | undefined;\n\nexport const ANONYMOUS_USERNAME = 'anonymous';\n\n/**\n * Resolve the name of the actor, either normal user or robot user.\n * This should be used whenever the \"current user\" needs to be displayed.\n * The display name CANNOT be used as project owner.\n */\nexport function getActorDisplayName(user?: Actor): string {\n switch (user?.__typename) {\n case 'User':\n return user.username;\n case 'SSOUser':\n return user.username;\n case 'Robot':\n return user.firstName ? `${user.firstName} (robot)` : 'robot';\n default:\n return ANONYMOUS_USERNAME;\n }\n}\n\nexport type { Actor };\n\nexport async function getUserAsync(): Promise<Actor | undefined> {\n const hasCredentials = getAccessToken() || getSession()?.sessionSecret;\n if (!env.EXPO_OFFLINE && !currentUser && hasCredentials) {\n const user = await UserQuery.currentUserAsync();\n currentUser = user ?? undefined;\n }\n return currentUser;\n}\n\nexport async function loginAsync(credentials: {\n username: string;\n password: string;\n otp?: string;\n}): Promise<void> {\n const res = await fetchAsync('auth/loginAsync', {\n method: 'POST',\n body: JSON.stringify(credentials),\n });\n const json: any = await res.json();\n const sessionSecret = json.data.sessionSecret;\n\n const userData = await UserQuery.meUserActorAsync({\n 'expo-session': sessionSecret,\n });\n\n await setSessionAsync({\n sessionSecret,\n userId: userData.id,\n username: userData.username,\n currentConnection: 'Username-Password-Authentication',\n });\n}\n\nexport async function browserLoginAsync({ sso = false }): Promise<void> {\n const sessionSecret = await getSessionUsingBrowserAuthFlowAsync({\n expoWebsiteUrl: getExpoWebsiteBaseUrl(),\n sso,\n });\n const userData = await UserQuery.meUserActorAsync({\n 'expo-session': sessionSecret,\n });\n await setSessionAsync({\n sessionSecret,\n userId: userData.id,\n username: userData.username,\n currentConnection: 'Browser-Flow-Authentication',\n });\n}\n\nexport async function logoutAsync(): Promise<void> {\n const sessionSecret = getSession()?.sessionSecret;\n if (sessionSecret) {\n try {\n await fetchAsync('auth/logout', { method: 'POST' });\n } catch (error) {\n debug('Failed to invalidate session secret on server:', error);\n }\n }\n currentUser = undefined;\n await Promise.all([\n fs.rm(getDevelopmentCodeSigningDirectory(), { recursive: true, force: true }),\n setSessionAsync(undefined),\n ]);\n Log.log('Logged out');\n}\n"],"names":["ANONYMOUS_USERNAME","browserLoginAsync","getActorDisplayName","getUserAsync","loginAsync","logoutAsync","debug","require","currentUser","user","__typename","username","firstName","getSession","hasCredentials","getAccessToken","sessionSecret","env","EXPO_OFFLINE","UserQuery","currentUserAsync","undefined","credentials","res","fetchAsync","method","body","JSON","stringify","json","data","userData","meUserActorAsync","setSessionAsync","userId","id","currentConnection","sso","getSessionUsingBrowserAuthFlowAsync","expoWebsiteUrl","getExpoWebsiteBaseUrl","error","Promise","all","fs","rm","getDevelopmentCodeSigningDirectory","recursive","force","Log","log"],"mappings":";;;;;;;;;;;QAeaA;eAAAA;;
|
|
1
|
+
{"version":3,"sources":["../../../../src/api/user/user.ts"],"sourcesContent":["import { promises as fs } from 'fs';\n\nimport { getAccessToken, getSession, setSessionAsync } from './UserSettings';\nimport { getSessionUsingBrowserAuthFlowAsync } from './expoSsoLauncher';\nimport * as Log from '../../log';\nimport { getDevelopmentCodeSigningDirectory } from '../../utils/codesigning';\nimport { env } from '../../utils/env';\nimport { getExpoWebsiteBaseUrl } from '../endpoint';\nimport { UserQuery, type Actor } from '../graphql/queries/UserQuery';\nimport { fetchAsync } from '../rest/client';\n\nconst debug = require('debug')('expo:api:user') as typeof console.log;\n\nlet currentUser: Actor | undefined;\n\nexport const ANONYMOUS_USERNAME = 'anonymous';\n\n/**\n * Resolve the name of the actor, either normal user or robot user.\n * This should be used whenever the \"current user\" needs to be displayed.\n * The display name CANNOT be used as project owner.\n */\nexport function getActorDisplayName(user?: Actor): string {\n switch (user?.__typename) {\n case 'User':\n return user.username;\n case 'SSOUser':\n return user.username;\n case 'Robot':\n return user.firstName ? `${user.firstName} (robot)` : 'robot';\n case 'PartnerActor':\n return user.username;\n default:\n return ANONYMOUS_USERNAME;\n }\n}\n\nexport type { Actor };\n\nexport async function getUserAsync(): Promise<Actor | undefined> {\n const hasCredentials = getAccessToken() || getSession()?.sessionSecret;\n if (!env.EXPO_OFFLINE && !currentUser && hasCredentials) {\n const user = await UserQuery.currentUserAsync();\n currentUser = user ?? undefined;\n }\n return currentUser;\n}\n\nexport async function loginAsync(credentials: {\n username: string;\n password: string;\n otp?: string;\n}): Promise<void> {\n const res = await fetchAsync('auth/loginAsync', {\n method: 'POST',\n body: JSON.stringify(credentials),\n });\n const json: any = await res.json();\n const sessionSecret = json.data.sessionSecret;\n\n const userData = await UserQuery.meUserActorAsync({\n 'expo-session': sessionSecret,\n });\n\n await setSessionAsync({\n sessionSecret,\n userId: userData.id,\n username: userData.username,\n currentConnection: 'Username-Password-Authentication',\n });\n}\n\nexport async function browserLoginAsync({ sso = false }): Promise<void> {\n const sessionSecret = await getSessionUsingBrowserAuthFlowAsync({\n expoWebsiteUrl: getExpoWebsiteBaseUrl(),\n sso,\n });\n const userData = await UserQuery.meUserActorAsync({\n 'expo-session': sessionSecret,\n });\n await setSessionAsync({\n sessionSecret,\n userId: userData.id,\n username: userData.username,\n currentConnection: 'Browser-Flow-Authentication',\n });\n}\n\nexport async function logoutAsync(): Promise<void> {\n const sessionSecret = getSession()?.sessionSecret;\n if (sessionSecret) {\n try {\n await fetchAsync('auth/logout', { method: 'POST' });\n } catch (error) {\n debug('Failed to invalidate session secret on server:', error);\n }\n }\n currentUser = undefined;\n await Promise.all([\n fs.rm(getDevelopmentCodeSigningDirectory(), { recursive: true, force: true }),\n setSessionAsync(undefined),\n ]);\n Log.log('Logged out');\n}\n"],"names":["ANONYMOUS_USERNAME","browserLoginAsync","getActorDisplayName","getUserAsync","loginAsync","logoutAsync","debug","require","currentUser","user","__typename","username","firstName","getSession","hasCredentials","getAccessToken","sessionSecret","env","EXPO_OFFLINE","UserQuery","currentUserAsync","undefined","credentials","res","fetchAsync","method","body","JSON","stringify","json","data","userData","meUserActorAsync","setSessionAsync","userId","id","currentConnection","sso","getSessionUsingBrowserAuthFlowAsync","expoWebsiteUrl","getExpoWebsiteBaseUrl","error","Promise","all","fs","rm","getDevelopmentCodeSigningDirectory","recursive","force","Log","log"],"mappings":";;;;;;;;;;;QAeaA;eAAAA;;QAyDSC;eAAAA;;QAlDNC;eAAAA;;QAiBMC;eAAAA;;QASAC;eAAAA;;QAwCAC;eAAAA;;;;yBAxFS;;;;;;8BAE6B;iCACR;6DAC/B;6BAC8B;qBAC/B;0BACkB;2BACA;wBACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3B,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,IAAIC;AAEG,MAAMR,qBAAqB;AAO3B,SAASE,oBAAoBO,IAAY;IAC9C,OAAQA,wBAAAA,KAAMC,UAAU;QACtB,KAAK;YACH,OAAOD,KAAKE,QAAQ;QACtB,KAAK;YACH,OAAOF,KAAKE,QAAQ;QACtB,KAAK;YACH,OAAOF,KAAKG,SAAS,GAAG,GAAGH,KAAKG,SAAS,CAAC,QAAQ,CAAC,GAAG;QACxD,KAAK;YACH,OAAOH,KAAKE,QAAQ;QACtB;YACE,OAAOX;IACX;AACF;AAIO,eAAeG;QACuBU;IAA3C,MAAMC,iBAAiBC,IAAAA,4BAAc,SAAMF,cAAAA,IAAAA,wBAAU,wBAAVA,YAAcG,aAAa;IACtE,IAAI,CAACC,QAAG,CAACC,YAAY,IAAI,CAACV,eAAeM,gBAAgB;QACvD,MAAML,OAAO,MAAMU,oBAAS,CAACC,gBAAgB;QAC7CZ,cAAcC,QAAQY;IACxB;IACA,OAAOb;AACT;AAEO,eAAeJ,WAAWkB,WAIhC;IACC,MAAMC,MAAM,MAAMC,IAAAA,kBAAU,EA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'v0-jsonl',
|
|
78
78
|
// Version is added in the build script.
|
|
79
|
-
version: "57.0.
|
|
79
|
+
version: "57.0.15" ?? 'UNVERSIONED'
|
|
80
80
|
};
|
|
81
81
|
}
|
|
82
82
|
function getWellKnownTemporaryLogFile(projectRoot, command) {
|
|
@@ -165,7 +165,10 @@ async function getConnectedDevicesAsync() {
|
|
|
165
165
|
deviceType: 'device',
|
|
166
166
|
connectionType: device.Properties.ConnectionType,
|
|
167
167
|
udid: device.Properties.SerialNumber,
|
|
168
|
-
|
|
168
|
+
// Lockdownd returns a reduced property set (without `DeviceClass`) for devices
|
|
169
|
+
// connected over the network ("Connect via network" on iOS <= 16), so fall back
|
|
170
|
+
// to `ProductName` ("iPhone OS") to avoid dropping wireless devices from the list.
|
|
171
|
+
osType: coerceUsbmuxdPlatformToOsType(deviceValues.DeviceClass ?? deviceValues.ProductName)
|
|
169
172
|
};
|
|
170
173
|
}));
|
|
171
174
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/run/ios/appleDevice/AppleDevice.ts"],"sourcesContent":["import Debug from 'debug';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { ClientManager } from './ClientManager';\nimport type { IPLookupResult, OnInstallProgressCallback } from './client/InstallationProxyClient';\nimport { LockdowndClient } from './client/LockdowndClient';\nimport { UsbmuxdClient } from './client/UsbmuxdClient';\nimport { AFC_STATUS, AFCError } from './protocol/AFCProtocol';\nimport { Log } from '../../../log';\nimport { XcodeDeveloperDiskImagePrerequisite } from '../../../start/doctor/apple/XcodeDeveloperDiskImagePrerequisite';\nimport * as devicectl from '../../../start/platforms/ios/devicectl';\nimport { launchAppWithDeviceCtl } from '../../../start/platforms/ios/devicectl';\nimport type { OSType } from '../../../start/platforms/ios/simctl';\nimport { uniqBy } from '../../../utils/array';\nimport { delayAsync } from '../../../utils/delay';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { profile } from '../../../utils/profile';\n\nconst debug = Debug('expo:apple-device');\n\n// NOTE(EvanBacon): I have a feeling this shape will change with new iOS versions (tested against iOS 15).\nexport interface ConnectedDevice {\n /** @example `00008101-001964A22629003A` */\n udid: string;\n /** @example `Evan's phone` */\n name: string;\n /** @example `iPhone13,4` */\n model: string;\n /** @example `device` */\n deviceType: 'device' | 'catalyst';\n /** @example `USB` */\n connectionType: 'USB' | 'Network';\n /** @example `15.4.1` */\n osVersion: string;\n\n osType: OSType;\n}\n\nasync function getConnectedDevicesUsingNativeToolsAsync(): Promise<ConnectedDevice[]> {\n return (\n (await devicectl.getConnectedAppleDevicesAsync())\n // Filter out unpaired and unavailable devices.\n // TODO: We could improve this logic in the future to attempt pairing if specified.\n .filter(\n (device) =>\n device.connectionProperties.pairingState === 'paired' &&\n device.connectionProperties.tunnelState !== 'unavailable'\n )\n .map((device) => {\n return {\n name: device.deviceProperties.name,\n model: device.hardwareProperties.productType,\n osVersion: device.deviceProperties.osVersionNumber,\n udid: device.hardwareProperties.udid,\n deviceType: 'device',\n connectionType:\n device.connectionProperties.transportType === 'localNetwork' ? 'Network' : 'USB',\n osType: coercePlatformToOsType(device.hardwareProperties.platform),\n };\n })\n );\n}\n\nfunction coercePlatformToOsType(platform: string): OSType {\n // The only two devices I have to test against...\n switch (platform) {\n case 'iOS':\n return 'iOS';\n case 'xrOS':\n return 'xrOS';\n default:\n debug('Unknown devicectl platform (needs to be added to Expo CLI):', platform);\n return platform as OSType;\n }\n}\nfunction coerceUsbmuxdPlatformToOsType(platform: string): OSType {\n // The only connectable device I have to test against...\n switch (platform) {\n case 'iPhone':\n case 'iPad':\n case 'iPhone OS':\n return 'iOS';\n default:\n debug('Unknown usbmuxd platform (needs to be added to Expo CLI):', platform);\n return platform as OSType;\n }\n}\n\n/** @returns a list of connected Apple devices. */\nexport async function getConnectedDevicesAsync(): Promise<ConnectedDevice[]> {\n const devices = await Promise.all([\n // Prioritize native tools since they can provide more accurate information.\n // NOTE: xcrun is substantially slower than custom tooling. +1.5s vs 9ms.\n profile(getConnectedDevicesUsingNativeToolsAsync)(),\n profile(getConnectedDevicesUsingCustomToolingAsync)(),\n ]);\n\n return uniqBy(devices.flat(), (device) => device.udid);\n}\n\n/**\n * This supports devices that are running OS versions older than iOS 17.\n *\n * @returns a list of connected Apple devices.\n */\nasync function getConnectedDevicesUsingCustomToolingAsync(): Promise<ConnectedDevice[]> {\n const client = new UsbmuxdClient(UsbmuxdClient.connectUsbmuxdSocket());\n const devices = await client.getDevices();\n client.socket.end();\n\n return Promise.all(\n devices.map(async (device): Promise<ConnectedDevice> => {\n const socket = await new UsbmuxdClient(UsbmuxdClient.connectUsbmuxdSocket()).connect(\n device,\n 62078\n );\n const deviceValues = await new LockdowndClient(socket).getAllValues();\n socket.end();\n // TODO(EvanBacon): Add support for osType (ipad, watchos, etc)\n return {\n // TODO(EvanBacon): Better name\n name: deviceValues.DeviceName ?? deviceValues.ProductType ?? 'unknown iOS device',\n model: deviceValues.ProductType,\n osVersion: deviceValues.ProductVersion,\n deviceType: 'device',\n connectionType: device.Properties.ConnectionType,\n udid: device.Properties.SerialNumber,\n osType: coerceUsbmuxdPlatformToOsType(deviceValues.DeviceClass),\n };\n })\n );\n}\n\n/** Install and run an Apple app binary on a connected Apple device. */\nexport async function runOnDevice({\n udid,\n appPath,\n bundleId,\n waitForApp,\n deltaPath,\n onProgress,\n}: {\n /** Apple device UDID */\n udid: string;\n /** File path to the app binary (ipa) */\n appPath: string;\n /** Bundle identifier for the app at `appPath` */\n bundleId: string;\n /** Wait for the app to launch before returning */\n waitForApp: boolean;\n /** File path to the app deltas folder to use for faster subsequent installs */\n deltaPath: string;\n /** Callback to be called with progress updates */\n onProgress: OnInstallProgressCallback;\n}) {\n debug('Running on device:', { udid, appPath, bundleId, waitForApp, deltaPath });\n\n const clientManager = await ClientManager.create(udid);\n\n try {\n await mountDeveloperDiskImage(clientManager);\n\n const packageName = path.basename(appPath);\n const destPackagePath = path.join('PublicStaging', packageName);\n\n await uploadApp(clientManager, { appBinaryPath: appPath, destinationPath: destPackagePath });\n\n const installer = await clientManager.getInstallationProxyClient();\n await installer.installApp(\n destPackagePath,\n bundleId,\n {\n // https://github.com/ios-control/ios-deploy/blob/0f2ffb1e564aa67a2dfca7cdf13de47ce489d835/src/ios-deploy/ios-deploy.m#L2491-L2508\n ApplicationsType: 'Any',\n\n CFBundleIdentifier: bundleId,\n CloseOnInvalidate: '1',\n InvalidateOnDetach: '1',\n IsUserInitiated: '1',\n // Disable checking for wifi devices, this is nominally faster.\n PreferWifi: '0',\n // Only info I could find on these:\n // https://github.com/wwxxyx/Quectel_BG96/blob/310876f90fc1093a59e45e381160eddcc31697d0/Apple_Homekit/homekit_certification_tools/ATS%206/ATS%206/ATS.app/Contents/Frameworks/CaptureKit.framework/Versions/A/Resources/MobileDevice/MobileInstallation.h#L112-L121\n PackageType: 'Developer',\n ShadowParentKey: deltaPath,\n // SkipUninstall: '1'\n },\n onProgress\n );\n\n // NOTE(EvanBacon): This can be undefined when querying App Clips.\n const lookupResult = await installer.lookupApp([bundleId]);\n const appInfo = lookupResult?.[bundleId];\n\n if (appInfo) {\n // launch fails with EBusy or ENotFound if you try to launch immediately after install\n await delayAsync(200);\n const debugServerClient = await launchApp(clientManager, {\n bundleId,\n appInfo,\n detach: !waitForApp,\n });\n\n if (waitForApp && debugServerClient) {\n installExitHooks(async () => {\n // causes continue() to return\n debugServerClient.halt();\n // give continue() time to return response\n await delayAsync(64);\n });\n\n debug(`Waiting for app to close...\\n`);\n const result = await debugServerClient.continue();\n // TODO: I have no idea what this packet means yet (successful close?)\n // if not a close (ie, most likely due to halt from onBeforeExit), then kill the app\n if (result !== 'W00') {\n await debugServerClient.kill();\n }\n }\n } else {\n Log.warn(`App \"${bundleId}\" installed but couldn't be launched. Open on device manually.`);\n }\n } finally {\n clientManager.end();\n }\n}\n\n/** Mount the developer disk image for Xcode. */\nasync function mountDeveloperDiskImage(clientManager: ClientManager) {\n const imageMounter = await clientManager.getMobileImageMounterClient();\n // Check if already mounted. If not, mount.\n if (!(await imageMounter.lookupImage()).ImageSignature) {\n // verify DeveloperDiskImage exists (TODO: how does this work on Windows/Linux?)\n // TODO: if windows/linux, download?\n const version = await (await clientManager.getLockdowndClient()).getValue('ProductVersion');\n const developerDiskImagePath = await XcodeDeveloperDiskImagePrerequisite.instance.assertAsync({\n version,\n });\n const developerDiskImageSig = fs.readFileSync(`${developerDiskImagePath}.signature`);\n await imageMounter.uploadImage(developerDiskImagePath, developerDiskImageSig);\n await imageMounter.mountImage(developerDiskImagePath, developerDiskImageSig);\n }\n}\n\nasync function uploadApp(\n clientManager: ClientManager,\n { appBinaryPath, destinationPath }: { appBinaryPath: string; destinationPath: string }\n) {\n const afcClient = await clientManager.getAFCClient();\n try {\n await afcClient.getFileInfo('PublicStaging');\n } catch (err: any) {\n if (err instanceof AFCError && err.status === AFC_STATUS.OBJECT_NOT_FOUND) {\n await afcClient.makeDirectory('PublicStaging');\n } else {\n throw err;\n }\n }\n await afcClient.uploadDirectory(appBinaryPath, destinationPath);\n}\n\nasync function launchAppWithUsbmux(\n clientManager: ClientManager,\n { appInfo, detach }: { appInfo: IPLookupResult[string]; detach?: boolean }\n) {\n let tries = 0;\n while (tries < 3) {\n const debugServerClient = await clientManager.getDebugserverClient();\n await debugServerClient.setMaxPacketSize(1024);\n await debugServerClient.setWorkingDir(appInfo.Container);\n await debugServerClient.launchApp(appInfo.Path, appInfo.CFBundleExecutable);\n\n const result = await debugServerClient.checkLaunchSuccess();\n if (result === 'OK') {\n if (detach) {\n // https://github.com/libimobiledevice/libimobiledevice/blob/25059d4c7d75e03aab516af2929d7c6e6d4c17de/tools/idevicedebug.c#L455-L464\n const res = await debugServerClient.sendCommand('D', []);\n debug('Disconnect from debug server request:', res);\n if (res !== 'OK') {\n console.warn(\n 'Something went wrong while attempting to disconnect from iOS debug server, you may need to reopen the app manually.'\n );\n }\n }\n\n return debugServerClient;\n } else if (result === 'EBusy' || result === 'ENotFound') {\n debug('Device busy or app not found, trying to launch again in .5s...');\n tries++;\n debugServerClient.socket.end();\n await delayAsync(500);\n } else {\n throw new CommandError(`There was an error launching app: ${result}`);\n }\n }\n throw new CommandError('Unable to launch app, number of tries exceeded');\n}\n\n/**\n * iOS 17 introduces a new protocol called RemoteXPC.\n * This is not yet implemented, so we fallback to devicectl.\n *\n * @see https://github.com/doronz88/pymobiledevice3/blob/master/misc/RemoteXPC.md#process-remoted\n */\nasync function launchApp(\n clientManager: ClientManager,\n {\n bundleId,\n appInfo,\n detach,\n }: { bundleId: string; appInfo: IPLookupResult[string]; detach?: boolean }\n) {\n try {\n return await launchAppWithUsbmux(clientManager, { appInfo, detach });\n } catch (error) {\n debug('Failed to launch app with Usbmuxd, falling back to xcrun...', error);\n\n // Get the device UDID and close the connection, to allow `xcrun devicectl` to connect\n const deviceId = clientManager.device.Properties.SerialNumber;\n clientManager.end();\n\n // Fallback to devicectl for iOS 17 support\n return await launchAppWithDeviceCtl(deviceId, bundleId);\n }\n}\n"],"names":["getConnectedDevicesAsync","runOnDevice","debug","Debug","getConnectedDevicesUsingNativeToolsAsync","devicectl","getConnectedAppleDevicesAsync","filter","device","connectionProperties","pairingState","tunnelState","map","name","deviceProperties","model","hardwareProperties","productType","osVersion","osVersionNumber","udid","deviceType","connectionType","transportType","osType","coercePlatformToOsType","platform","coerceUsbmuxdPlatformToOsType","devices","Promise","all","profile","getConnectedDevicesUsingCustomToolingAsync","uniqBy","flat","client","UsbmuxdClient","connectUsbmuxdSocket","getDevices","socket","end","connect","deviceValues","LockdowndClient","getAllValues","DeviceName","ProductType","ProductVersion","Properties","ConnectionType","SerialNumber","DeviceClass","appPath","bundleId","waitForApp","deltaPath","onProgress","clientManager","ClientManager","create","mountDeveloperDiskImage","packageName","path","basename","destPackagePath","join","uploadApp","appBinaryPath","destinationPath","installer","getInstallationProxyClient","installApp","ApplicationsType","CFBundleIdentifier","CloseOnInvalidate","InvalidateOnDetach","IsUserInitiated","PreferWifi","PackageType","ShadowParentKey","lookupResult","lookupApp","appInfo","delayAsync","debugServerClient","launchApp","detach","installExitHooks","halt","result","continue","kill","Log","warn","imageMounter","getMobileImageMounterClient","lookupImage","ImageSignature","version","getLockdowndClient","getValue","developerDiskImagePath","XcodeDeveloperDiskImagePrerequisite","instance","assertAsync","developerDiskImageSig","fs","readFileSync","uploadImage","mountImage","afcClient","getAFCClient","getFileInfo","err","AFCError","status","AFC_STATUS","OBJECT_NOT_FOUND","makeDirectory","uploadDirectory","launchAppWithUsbmux","tries","getDebugserverClient","setMaxPacketSize","setWorkingDir","Container","Path","CFBundleExecutable","checkLaunchSuccess","res","sendCommand","console","CommandError","error","deviceId","launchAppWithDeviceCtl"],"mappings":";;;;;;;;;;;QA2FsBA;eAAAA;;QA6CAC;eAAAA;;;;gEAxIJ;;;;;;;gEACH;;;;;;;gEACE;;;;;;+BAEa;iCAEE;+BACF;6BACO;qBACjB;qDACgC;mEACzB;uBAGJ;uBACI;wBACE;sBACI;yBACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,MAAMC,QAAQC,IAAAA,gBAAK,EAAC;AAoBpB,eAAeC;IACb,OACE,AAAC,CAAA,MAAMC,WAAUC,6BAA6B,EAAC,CAC7C,+CAA+C;IAC/C,mFAAmF;KAClFC,MAAM,CACL,CAACC,SACCA,OAAOC,oBAAoB,CAACC,YAAY,KAAK,YAC7CF,OAAOC,oBAAoB,CAACE,WAAW,KAAK,eAE/CC,GAAG,CAAC,CAACJ;QACJ,OAAO;YACLK,MAAML,OAAOM,gBAAgB,CAACD,IAAI;YAClCE,OAAOP,OAAOQ,kBAAkB,CAACC,WAAW;YAC5CC,WAAWV,OAAOM,gBAAgB,CAACK,eAAe;YAClDC,MAAMZ,OAAOQ,kBAAkB,CAACI,IAAI;YACpCC,YAAY;YACZC,gBACEd,OAAOC,oBAAoB,CAACc,aAAa,KAAK,iBAAiB,YAAY;YAC7EC,QAAQC,uBAAuBjB,OAAOQ,kBAAkB,CAACU,QAAQ;Q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jF;IAChD;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/run/ios/appleDevice/AppleDevice.ts"],"sourcesContent":["import Debug from 'debug';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { ClientManager } from './ClientManager';\nimport type { IPLookupResult, OnInstallProgressCallback } from './client/InstallationProxyClient';\nimport { LockdowndClient } from './client/LockdowndClient';\nimport { UsbmuxdClient } from './client/UsbmuxdClient';\nimport { AFC_STATUS, AFCError } from './protocol/AFCProtocol';\nimport { Log } from '../../../log';\nimport { XcodeDeveloperDiskImagePrerequisite } from '../../../start/doctor/apple/XcodeDeveloperDiskImagePrerequisite';\nimport * as devicectl from '../../../start/platforms/ios/devicectl';\nimport { launchAppWithDeviceCtl } from '../../../start/platforms/ios/devicectl';\nimport type { OSType } from '../../../start/platforms/ios/simctl';\nimport { uniqBy } from '../../../utils/array';\nimport { delayAsync } from '../../../utils/delay';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { profile } from '../../../utils/profile';\n\nconst debug = Debug('expo:apple-device');\n\n// NOTE(EvanBacon): I have a feeling this shape will change with new iOS versions (tested against iOS 15).\nexport interface ConnectedDevice {\n /** @example `00008101-001964A22629003A` */\n udid: string;\n /** @example `Evan's phone` */\n name: string;\n /** @example `iPhone13,4` */\n model: string;\n /** @example `device` */\n deviceType: 'device' | 'catalyst';\n /** @example `USB` */\n connectionType: 'USB' | 'Network';\n /** @example `15.4.1` */\n osVersion: string;\n\n osType: OSType;\n}\n\nasync function getConnectedDevicesUsingNativeToolsAsync(): Promise<ConnectedDevice[]> {\n return (\n (await devicectl.getConnectedAppleDevicesAsync())\n // Filter out unpaired and unavailable devices.\n // TODO: We could improve this logic in the future to attempt pairing if specified.\n .filter(\n (device) =>\n device.connectionProperties.pairingState === 'paired' &&\n device.connectionProperties.tunnelState !== 'unavailable'\n )\n .map((device) => {\n return {\n name: device.deviceProperties.name,\n model: device.hardwareProperties.productType,\n osVersion: device.deviceProperties.osVersionNumber,\n udid: device.hardwareProperties.udid,\n deviceType: 'device',\n connectionType:\n device.connectionProperties.transportType === 'localNetwork' ? 'Network' : 'USB',\n osType: coercePlatformToOsType(device.hardwareProperties.platform),\n };\n })\n );\n}\n\nfunction coercePlatformToOsType(platform: string): OSType {\n // The only two devices I have to test against...\n switch (platform) {\n case 'iOS':\n return 'iOS';\n case 'xrOS':\n return 'xrOS';\n default:\n debug('Unknown devicectl platform (needs to be added to Expo CLI):', platform);\n return platform as OSType;\n }\n}\nfunction coerceUsbmuxdPlatformToOsType(platform: string): OSType {\n // The only connectable device I have to test against...\n switch (platform) {\n case 'iPhone':\n case 'iPad':\n case 'iPhone OS':\n return 'iOS';\n default:\n debug('Unknown usbmuxd platform (needs to be added to Expo CLI):', platform);\n return platform as OSType;\n }\n}\n\n/** @returns a list of connected Apple devices. */\nexport async function getConnectedDevicesAsync(): Promise<ConnectedDevice[]> {\n const devices = await Promise.all([\n // Prioritize native tools since they can provide more accurate information.\n // NOTE: xcrun is substantially slower than custom tooling. +1.5s vs 9ms.\n profile(getConnectedDevicesUsingNativeToolsAsync)(),\n profile(getConnectedDevicesUsingCustomToolingAsync)(),\n ]);\n\n return uniqBy(devices.flat(), (device) => device.udid);\n}\n\n/**\n * This supports devices that are running OS versions older than iOS 17.\n *\n * @returns a list of connected Apple devices.\n */\nasync function getConnectedDevicesUsingCustomToolingAsync(): Promise<ConnectedDevice[]> {\n const client = new UsbmuxdClient(UsbmuxdClient.connectUsbmuxdSocket());\n const devices = await client.getDevices();\n client.socket.end();\n\n return Promise.all(\n devices.map(async (device): Promise<ConnectedDevice> => {\n const socket = await new UsbmuxdClient(UsbmuxdClient.connectUsbmuxdSocket()).connect(\n device,\n 62078\n );\n const deviceValues = await new LockdowndClient(socket).getAllValues();\n socket.end();\n // TODO(EvanBacon): Add support for osType (ipad, watchos, etc)\n return {\n // TODO(EvanBacon): Better name\n name: deviceValues.DeviceName ?? deviceValues.ProductType ?? 'unknown iOS device',\n model: deviceValues.ProductType,\n osVersion: deviceValues.ProductVersion,\n deviceType: 'device',\n connectionType: device.Properties.ConnectionType,\n udid: device.Properties.SerialNumber,\n // Lockdownd returns a reduced property set (without `DeviceClass`) for devices\n // connected over the network (\"Connect via network\" on iOS <= 16), so fall back\n // to `ProductName` (\"iPhone OS\") to avoid dropping wireless devices from the list.\n osType: coerceUsbmuxdPlatformToOsType(deviceValues.DeviceClass ?? deviceValues.ProductName),\n };\n })\n );\n}\n\n/** Install and run an Apple app binary on a connected Apple device. */\nexport async function runOnDevice({\n udid,\n appPath,\n bundleId,\n waitForApp,\n deltaPath,\n onProgress,\n}: {\n /** Apple device UDID */\n udid: string;\n /** File path to the app binary (ipa) */\n appPath: string;\n /** Bundle identifier for the app at `appPath` */\n bundleId: string;\n /** Wait for the app to launch before returning */\n waitForApp: boolean;\n /** File path to the app deltas folder to use for faster subsequent installs */\n deltaPath: string;\n /** Callback to be called with progress updates */\n onProgress: OnInstallProgressCallback;\n}) {\n debug('Running on device:', { udid, appPath, bundleId, waitForApp, deltaPath });\n\n const clientManager = await ClientManager.create(udid);\n\n try {\n await mountDeveloperDiskImage(clientManager);\n\n const packageName = path.basename(appPath);\n const destPackagePath = path.join('PublicStaging', packageName);\n\n await uploadApp(clientManager, { appBinaryPath: appPath, destinationPath: destPackagePath });\n\n const installer = await clientManager.getInstallationProxyClient();\n await installer.installApp(\n destPackagePath,\n bundleId,\n {\n // https://github.com/ios-control/ios-deploy/blob/0f2ffb1e564aa67a2dfca7cdf13de47ce489d835/src/ios-deploy/ios-deploy.m#L2491-L2508\n ApplicationsType: 'Any',\n\n CFBundleIdentifier: bundleId,\n CloseOnInvalidate: '1',\n InvalidateOnDetach: '1',\n IsUserInitiated: '1',\n // Disable checking for wifi devices, this is nominally faster.\n PreferWifi: '0',\n // Only info I could find on these:\n // https://github.com/wwxxyx/Quectel_BG96/blob/310876f90fc1093a59e45e381160eddcc31697d0/Apple_Homekit/homekit_certification_tools/ATS%206/ATS%206/ATS.app/Contents/Frameworks/CaptureKit.framework/Versions/A/Resources/MobileDevice/MobileInstallation.h#L112-L121\n PackageType: 'Developer',\n ShadowParentKey: deltaPath,\n // SkipUninstall: '1'\n },\n onProgress\n );\n\n // NOTE(EvanBacon): This can be undefined when querying App Clips.\n const lookupResult = await installer.lookupApp([bundleId]);\n const appInfo = lookupResult?.[bundleId];\n\n if (appInfo) {\n // launch fails with EBusy or ENotFound if you try to launch immediately after install\n await delayAsync(200);\n const debugServerClient = await launchApp(clientManager, {\n bundleId,\n appInfo,\n detach: !waitForApp,\n });\n\n if (waitForApp && debugServerClient) {\n installExitHooks(async () => {\n // causes continue() to return\n debugServerClient.halt();\n // give continue() time to return response\n await delayAsync(64);\n });\n\n debug(`Waiting for app to close...\\n`);\n const result = await debugServerClient.continue();\n // TODO: I have no idea what this packet means yet (successful close?)\n // if not a close (ie, most likely due to halt from onBeforeExit), then kill the app\n if (result !== 'W00') {\n await debugServerClient.kill();\n }\n }\n } else {\n Log.warn(`App \"${bundleId}\" installed but couldn't be launched. Open on device manually.`);\n }\n } finally {\n clientManager.end();\n }\n}\n\n/** Mount the developer disk image for Xcode. */\nasync function mountDeveloperDiskImage(clientManager: ClientManager) {\n const imageMounter = await clientManager.getMobileImageMounterClient();\n // Check if already mounted. If not, mount.\n if (!(await imageMounter.lookupImage()).ImageSignature) {\n // verify DeveloperDiskImage exists (TODO: how does this work on Windows/Linux?)\n // TODO: if windows/linux, download?\n const version = await (await clientManager.getLockdowndClient()).getValue('ProductVersion');\n const developerDiskImagePath = await XcodeDeveloperDiskImagePrerequisite.instance.assertAsync({\n version,\n });\n const developerDiskImageSig = fs.readFileSync(`${developerDiskImagePath}.signature`);\n await imageMounter.uploadImage(developerDiskImagePath, developerDiskImageSig);\n await imageMounter.mountImage(developerDiskImagePath, developerDiskImageSig);\n }\n}\n\nasync function uploadApp(\n clientManager: ClientManager,\n { appBinaryPath, destinationPath }: { appBinaryPath: string; destinationPath: string }\n) {\n const afcClient = await clientManager.getAFCClient();\n try {\n await afcClient.getFileInfo('PublicStaging');\n } catch (err: any) {\n if (err instanceof AFCError && err.status === AFC_STATUS.OBJECT_NOT_FOUND) {\n await afcClient.makeDirectory('PublicStaging');\n } else {\n throw err;\n }\n }\n await afcClient.uploadDirectory(appBinaryPath, destinationPath);\n}\n\nasync function launchAppWithUsbmux(\n clientManager: ClientManager,\n { appInfo, detach }: { appInfo: IPLookupResult[string]; detach?: boolean }\n) {\n let tries = 0;\n while (tries < 3) {\n const debugServerClient = await clientManager.getDebugserverClient();\n await debugServerClient.setMaxPacketSize(1024);\n await debugServerClient.setWorkingDir(appInfo.Container);\n await debugServerClient.launchApp(appInfo.Path, appInfo.CFBundleExecutable);\n\n const result = await debugServerClient.checkLaunchSuccess();\n if (result === 'OK') {\n if (detach) {\n // https://github.com/libimobiledevice/libimobiledevice/blob/25059d4c7d75e03aab516af2929d7c6e6d4c17de/tools/idevicedebug.c#L455-L464\n const res = await debugServerClient.sendCommand('D', []);\n debug('Disconnect from debug server request:', res);\n if (res !== 'OK') {\n console.warn(\n 'Something went wrong while attempting to disconnect from iOS debug server, you may need to reopen the app manually.'\n );\n }\n }\n\n return debugServerClient;\n } else if (result === 'EBusy' || result === 'ENotFound') {\n debug('Device busy or app not found, trying to launch again in .5s...');\n tries++;\n debugServerClient.socket.end();\n await delayAsync(500);\n } else {\n throw new CommandError(`There was an error launching app: ${result}`);\n }\n }\n throw new CommandError('Unable to launch app, number of tries exceeded');\n}\n\n/**\n * iOS 17 introduces a new protocol called RemoteXPC.\n * This is not yet implemented, so we fallback to devicectl.\n *\n * @see https://github.com/doronz88/pymobiledevice3/blob/master/misc/RemoteXPC.md#process-remoted\n */\nasync function launchApp(\n clientManager: ClientManager,\n {\n bundleId,\n appInfo,\n detach,\n }: { bundleId: string; appInfo: IPLookupResult[string]; detach?: boolean }\n) {\n try {\n return await launchAppWithUsbmux(clientManager, { appInfo, detach });\n } catch (error) {\n debug('Failed to launch app with Usbmuxd, falling back to xcrun...', error);\n\n // Get the device UDID and close the connection, to allow `xcrun devicectl` to connect\n const deviceId = clientManager.device.Properties.SerialNumber;\n clientManager.end();\n\n // Fallback to devicectl for iOS 17 support\n return await launchAppWithDeviceCtl(deviceId, bundleId);\n }\n}\n"],"names":["getConnectedDevicesAsync","runOnDevice","debug","Debug","getConnectedDevicesUsingNativeToolsAsync","devicectl","getConnectedAppleDevicesAsync","filter","device","connectionProperties","pairingState","tunnelState","map","name","deviceProperties","model","hardwareProperties","productType","osVersion","osVersionNumber","udid","deviceType","connectionType","transportType","osType","coercePlatformToOsType","platform","coerceUsbmuxdPlatformToOsType","devices","Promise","all","profile","getConnectedDevicesUsingCustomToolingAsync","uniqBy","flat","client","UsbmuxdClient","connectUsbmuxdSocket","getDevices","socket","end","connect","deviceValues","LockdowndClient","getAllValues","DeviceName","ProductType","ProductVersion","Properties","ConnectionType","SerialNumber","DeviceClass","ProductName","appPath","bundleId","waitForApp","deltaPath","onProgress","clientManager","ClientManager","create","mountDeveloperDiskImage","packageName","path","basename","destPackagePath","join","uploadApp","appBinaryPath","destinationPath","installer","getInstallationProxyClient","installApp","ApplicationsType","CFBundleIdentifier","CloseOnInvalidate","InvalidateOnDetach","IsUserInitiated","PreferWifi","PackageType","ShadowParentKey","lookupResult","lookupApp","appInfo","delayAsync","debugServerClient","launchApp","detach","installExitHooks","halt","result","continue","kill","Log","warn","imageMounter","getMobileImageMounterClient","lookupImage","ImageSignature","version","getLockdowndClient","getValue","developerDiskImagePath","XcodeDeveloperDiskImagePrerequisite","instance","assertAsync","developerDiskImageSig","fs","readFileSync","uploadImage","mountImage","afcClient","getAFCClient","getFileInfo","err","AFCError","status","AFC_STATUS","OBJECT_NOT_FOUND","makeDirectory","uploadDirectory","launchAppWithUsbmux","tries","getDebugserverClient","setMaxPacketSize","setWorkingDir","Container","Path","CFBundleExecutable","checkLaunchSuccess","res","sendCommand","console","CommandError","error","deviceId","launchAppWithDeviceCtl"],"mappings":";;;;;;;;;;;QA2FsBA;eAAAA;;QA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nB,IAAIH,QAAQ;gBACV,oIAAoI;gBACpI,MAAM2C,MAAM,MAAM7C,kBAAkB8C,WAAW,CAAC,KAAK,EAAE;gBACvDjI,MAAM,yCAAyCgI;gBAC/C,IAAIA,QAAQ,MAAM;oBAChBE,QAAQtC,IAAI,CACV;gBAEJ;YACF;YAEA,OAAOT;QACT,OAAO,IAAIK,WAAW,WAAWA,WAAW,aAAa;YACvDxF,MAAM;YACNwH;YACArC,kBAAkB9C,MAAM,CAACC,GAAG;YAC5B,MAAM4C,IAAAA,iBAAU,EAAC;QACnB,OAAO;YACL,MAAM,IAAIiD,oBAAY,CAAC,CAAC,kCAAkC,EAAE3C,QAAQ;QACtE;IACF;IACA,MAAM,IAAI2C,oBAAY,CAAC;AACzB;AAEA;;;;;CAKC,GACD,eAAe/C,UACb5B,aAA4B,EAC5B,EACEJ,QAAQ,EACR6B,OAAO,EACPI,MAAM,EACkE;IAE1E,IAAI;QACF,OAAO,MAAMkC,oBAAoB/D,eAAe;YAAEyB;YAASI;QAAO;IACpE,EAAE,OAAO+C,OAAO;QACdpI,MAAM,+DAA+DoI;QAErE,sFAAsF;QACtF,MAAMC,WAAW7E,cAAclD,MAAM,CAACwC,UAAU,CAACE,YAAY;QAC7DQ,cAAclB,GAAG;QAEjB,2CAA2C;QAC3C,OAAO,MAAMgG,IAAAA,iCAAsB,EAACD,UAAUjF;IAChD;AACF"}
|
|
@@ -257,6 +257,9 @@ async function getCodeSigningInfoAsync(exp, expectSignatureHeader, privateKeyPat
|
|
|
257
257
|
var _exp_updates, _exp_updates1;
|
|
258
258
|
const codeSigningCertificatePath = (_exp_updates = exp.updates) == null ? void 0 : _exp_updates.codeSigningCertificate;
|
|
259
259
|
if (!codeSigningCertificatePath) {
|
|
260
|
+
if (privateKeyPath) {
|
|
261
|
+
throw new _errors.CommandError('--private-key-path was specified, but updates.codeSigningCertificate is not set in the resolved app config. Code signing requires both the certificate in app config and the private key. Ensure codeSigningCertificate (and codeSigningMetadata) are present, or omit --private-key-path if you do not intend to sign.\nLearn more: https://docs.expo.dev/eas-update/code-signing/');
|
|
262
|
+
}
|
|
260
263
|
return null;
|
|
261
264
|
}
|
|
262
265
|
if (!privateKeyPath) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/codesigning.ts"],"sourcesContent":["import {\n convertCertificatePEMToCertificate,\n convertKeyPairToPEM,\n convertCSRToCSRPEM,\n generateKeyPair,\n generateCSR,\n convertPrivateKeyPEMToPrivateKey,\n validateSelfSignedCertificate,\n signBufferRSASHA256AndVerify,\n} from '@expo/code-signing-certificates';\nimport type { ExpoConfig } from '@expo/config';\nimport type { JSONObject } from '@expo/json-file';\nimport JsonFile from '@expo/json-file';\nimport { promises as fs } from 'fs';\nimport type { pki as PKI } from 'node-forge';\nimport path from 'path';\nimport type { Dictionary } from 'structured-headers';\nimport { parseDictionary } from 'structured-headers';\n\nimport { env } from './env';\nimport { CommandError } from './errors';\nimport { getExpoGoIntermediateCertificateAsync } from '../api/getExpoGoIntermediateCertificate';\nimport { getProjectDevelopmentCertificateAsync } from '../api/getProjectDevelopmentCertificate';\nimport { UnexpectedServerError, UnexpectedServerData } from '../api/graphql/client';\nimport { AppQuery, type App } from '../api/graphql/queries/AppQuery';\nimport { getExpoHomeDirectory } from '../api/user/UserSettings';\nimport { tryGetUserAsync } from '../api/user/actions';\nimport type { Actor } from '../api/user/user';\nimport * as Log from '../log';\nimport { learnMore } from '../utils/link';\n\nconst debug = require('debug')('expo:codesigning') as typeof console.log;\n\nexport type CodeSigningInfo = {\n keyId: string;\n privateKey: string;\n certificateForPrivateKey: string;\n /**\n * Chain of certificates to serve in the manifest multipart body \"certificate_chain\" part.\n * The leaf certificate must be the 0th element of the array, followed by any intermediate certificates\n * necessary to evaluate the chain of trust ending in the implicitly trusted root certificate embedded in\n * the client.\n *\n * An empty array indicates that there is no need to serve the certificate chain in the multipart response.\n */\n certificateChainForResponse: string[];\n /**\n * Scope key cached for the project when certificate is development Expo Go code signing.\n * For project-specific code signing (keyId == the project's generated keyId) this is undefined.\n */\n scopeKey: string | null;\n};\n\ntype StoredDevelopmentExpoRootCodeSigningInfo = {\n easProjectId: string | null;\n scopeKey: string | null;\n privateKey: string | null;\n certificateChain: string[] | null;\n};\nconst DEVELOPMENT_CODE_SIGNING_SETTINGS_FILE_NAME = 'development-code-signing-settings-2.json';\n\nexport function getDevelopmentCodeSigningDirectory(): string {\n return path.join(getExpoHomeDirectory(), 'codesigning');\n}\n\nfunction assertBasenameValue(input: string): void {\n if (!input || input === '.' || input === '..' || input !== path.basename(input)) {\n throw new CommandError('Invalid EAS project ID for development code signing cache');\n }\n}\n\nfunction getProjectDevelopmentCodeSigningInfoFile<T extends JSONObject>(defaults: T) {\n function getFile(easProjectId: string): JsonFile<T> {\n assertBasenameValue(easProjectId);\n const filePath = path.join(\n getDevelopmentCodeSigningDirectory(),\n easProjectId,\n DEVELOPMENT_CODE_SIGNING_SETTINGS_FILE_NAME\n );\n return new JsonFile<T>(filePath);\n }\n\n async function readAsync(easProjectId: string): Promise<T> {\n let projectSettings;\n try {\n projectSettings = await getFile(easProjectId).readAsync();\n } catch {\n projectSettings = await getFile(easProjectId).writeAsync(defaults, { ensureDir: true });\n }\n // Set defaults for any missing fields\n return { ...defaults, ...projectSettings };\n }\n\n async function setAsync(easProjectId: string, json: Partial<T>): Promise<T> {\n try {\n return await getFile(easProjectId).mergeAsync(json, {\n cantReadFileDefault: defaults,\n });\n } catch {\n return await getFile(easProjectId).writeAsync(\n {\n ...defaults,\n ...json,\n },\n { ensureDir: true }\n );\n }\n }\n\n return {\n getFile,\n readAsync,\n setAsync,\n };\n}\n\nexport const DevelopmentCodeSigningInfoFile =\n getProjectDevelopmentCodeSigningInfoFile<StoredDevelopmentExpoRootCodeSigningInfo>({\n easProjectId: null,\n scopeKey: null,\n privateKey: null,\n certificateChain: null,\n });\n\n/**\n * Get info necessary to generate a response `expo-signature` header given a project and incoming request `expo-expect-signature` header.\n * This only knows how to serve two code signing keyids:\n * - `expo-root` indicates that it should use a development certificate in the `expo-root` chain. See {@link getExpoRootDevelopmentCodeSigningInfoAsync}\n * - <developer's expo-updates keyid> indicates that it should sign with the configured certificate. See {@link getProjectCodeSigningCertificateAsync}\n */\nexport async function getCodeSigningInfoAsync(\n exp: ExpoConfig,\n expectSignatureHeader: string | null,\n privateKeyPath: string | undefined\n): Promise<CodeSigningInfo | null> {\n if (!expectSignatureHeader) {\n return null;\n }\n\n let parsedExpectSignature: Dictionary;\n try {\n parsedExpectSignature = parseDictionary(expectSignatureHeader);\n } catch {\n throw new CommandError('Invalid value for expo-expect-signature header');\n }\n\n const expectedKeyIdOuter = parsedExpectSignature.get('keyid');\n if (!expectedKeyIdOuter) {\n throw new CommandError('keyid not present in expo-expect-signature header');\n }\n\n const expectedKeyId = expectedKeyIdOuter[0];\n if (typeof expectedKeyId !== 'string') {\n throw new CommandError(\n `Invalid value for keyid in expo-expect-signature header: ${expectedKeyId}`\n );\n }\n\n let expectedAlg: string | null = null;\n const expectedAlgOuter = parsedExpectSignature.get('alg');\n if (expectedAlgOuter) {\n const expectedAlgTemp = expectedAlgOuter[0];\n if (typeof expectedAlgTemp !== 'string') {\n throw new CommandError('Invalid value for alg in expo-expect-signature header');\n }\n expectedAlg = expectedAlgTemp;\n }\n\n if (expectedKeyId === 'expo-root') {\n return await getExpoRootDevelopmentCodeSigningInfoAsync(exp);\n } else if (expectedKeyId === 'expo-go') {\n throw new CommandError(\n 'Invalid certificate requested: cannot sign with embedded keyid=expo-go key'\n );\n } else {\n return await getProjectCodeSigningCertificateAsync(\n exp,\n privateKeyPath,\n expectedKeyId,\n expectedAlg\n );\n }\n}\n\n/**\n * Get a development code signing certificate for the expo-root -> expo-go -> (development certificate) certificate chain.\n * This requires the user be logged in and online, otherwise try to use the cached development certificate.\n */\nasync function getExpoRootDevelopmentCodeSigningInfoAsync(\n exp: ExpoConfig\n): Promise<CodeSigningInfo | null> {\n const easProjectId = exp.extra?.eas?.projectId;\n // can't check for scope key validity since scope key is derived on the server from projectId and we may be offline.\n // we rely upon the client certificate check to validate the scope key\n if (!easProjectId) {\n debug(\n `WARN: Expo Application Services (EAS) is not configured for your project. Configuring EAS enables a more secure development experience amongst many other benefits. ${learnMore(\n 'https://docs.expo.dev/eas/'\n )}`\n );\n return null;\n }\n\n const developmentCodeSigningInfoFromFile =\n await DevelopmentCodeSigningInfoFile.readAsync(easProjectId);\n const validatedCodeSigningInfo = validateStoredDevelopmentExpoRootCertificateCodeSigningInfo(\n developmentCodeSigningInfoFromFile,\n easProjectId\n );\n\n // 1. If online, ensure logged in, generate key pair and CSR, fetch and cache certificate chain for projectId\n // (overwriting existing dev cert in case projectId changed or it has expired)\n if (!env.EXPO_OFFLINE) {\n try {\n const newCodeSigningInfo =\n await fetchAndCacheNewDevelopmentCodeSigningInfoAsync(easProjectId);\n\n if (newCodeSigningInfo) {\n return newCodeSigningInfo;\n // fall back to cached certificate if we couldn't fetch a new one\n } else if (validatedCodeSigningInfo) {\n Log.warn(\n 'Could not fetch new Expo development certificate, falling back to cached certificate'\n );\n return validatedCodeSigningInfo;\n } else {\n return null;\n }\n } catch (e: any) {\n if (validatedCodeSigningInfo) {\n Log.warn(\n 'There was an error fetching the Expo development certificate, falling back to cached certificate'\n );\n return validatedCodeSigningInfo;\n } else {\n // need to return null here and say a message\n throw e;\n }\n }\n }\n\n // 2. check for cached cert/private key matching projectId and scopeKey of project, if found and valid return private key and cert chain including expo-go cert\n if (validatedCodeSigningInfo) {\n return validatedCodeSigningInfo;\n }\n\n // 3. if offline, return null\n Log.warn('Offline and no cached development certificate found, unable to sign manifest');\n return null;\n}\n\n/**\n * Get the certificate configured for expo-updates for this project.\n */\nasync function getProjectCodeSigningCertificateAsync(\n exp: ExpoConfig,\n privateKeyPath: string | undefined,\n expectedKeyId: string,\n expectedAlg: string | null\n): Promise<CodeSigningInfo | null> {\n const codeSigningCertificatePath = exp.updates?.codeSigningCertificate;\n if (!codeSigningCertificatePath) {\n return null;\n }\n\n if (!privateKeyPath) {\n throw new CommandError(\n 'Must specify --private-key-path argument to sign development manifest for requested code signing key'\n );\n }\n\n const codeSigningMetadata = exp.updates?.codeSigningMetadata;\n if (!codeSigningMetadata) {\n throw new CommandError(\n 'Must specify \"codeSigningMetadata\" under the \"updates\" field of your app config file to use EAS code signing'\n );\n }\n\n const { alg, keyid } = codeSigningMetadata;\n if (!alg || !keyid) {\n throw new CommandError(\n 'Must specify \"keyid\" and \"alg\" in the \"codeSigningMetadata\" field under the \"updates\" field of your app config file to use EAS code signing'\n );\n }\n\n if (expectedKeyId !== keyid) {\n throw new CommandError(`keyid mismatch: client=${expectedKeyId}, project=${keyid}`);\n }\n\n if (expectedAlg && expectedAlg !== alg) {\n throw new CommandError(`\"alg\" field mismatch (client=${expectedAlg}, project=${alg})`);\n }\n\n const { privateKeyPEM, certificatePEM } =\n await getProjectPrivateKeyAndCertificateFromFilePathsAsync({\n codeSigningCertificatePath,\n privateKeyPath,\n });\n\n return {\n keyId: keyid,\n privateKey: privateKeyPEM,\n certificateForPrivateKey: certificatePEM,\n certificateChainForResponse: [],\n scopeKey: null,\n };\n}\n\nasync function readFileWithErrorAsync(path: string, errorMessage: string): Promise<string> {\n try {\n return await fs.readFile(path, 'utf8');\n } catch {\n throw new CommandError(errorMessage);\n }\n}\n\nasync function getProjectPrivateKeyAndCertificateFromFilePathsAsync({\n codeSigningCertificatePath,\n privateKeyPath,\n}: {\n codeSigningCertificatePath: string;\n privateKeyPath: string;\n}): Promise<{ privateKeyPEM: string; certificatePEM: string }> {\n const [codeSigningCertificatePEM, privateKeyPEM] = await Promise.all([\n readFileWithErrorAsync(\n codeSigningCertificatePath,\n `Code signing certificate cannot be read from path: ${codeSigningCertificatePath}`\n ),\n readFileWithErrorAsync(\n privateKeyPath,\n `Code signing private key cannot be read from path: ${privateKeyPath}`\n ),\n ]);\n\n const privateKey = convertPrivateKeyPEMToPrivateKey(privateKeyPEM);\n const certificate = convertCertificatePEMToCertificate(codeSigningCertificatePEM);\n validateSelfSignedCertificate(certificate, {\n publicKey: certificate.publicKey as PKI.rsa.PublicKey,\n privateKey,\n });\n\n return { privateKeyPEM, certificatePEM: codeSigningCertificatePEM };\n}\n\n/**\n * Validate that the cached code signing info is still valid for the current project and\n * that it hasn't expired. If invalid, return null.\n */\nfunction validateStoredDevelopmentExpoRootCertificateCodeSigningInfo(\n codeSigningInfo: StoredDevelopmentExpoRootCodeSigningInfo,\n easProjectId: string\n): CodeSigningInfo | null {\n if (codeSigningInfo.easProjectId !== easProjectId) {\n return null;\n }\n\n const {\n privateKey: privateKeyPEM,\n certificateChain: certificatePEMs,\n scopeKey,\n } = codeSigningInfo;\n if (!privateKeyPEM || !certificatePEMs?.length) {\n return null;\n }\n\n const certificateChain = certificatePEMs.map((certificatePEM) =>\n convertCertificatePEMToCertificate(certificatePEM)\n );\n\n // TODO(wschurman): maybe move to @expo/code-signing-certificates\n\n // ensure all intermediate certificates are valid\n for (const certificate of certificateChain) {\n const now = new Date();\n if (certificate.validity.notBefore > now || certificate.validity.notAfter < now) {\n return null;\n }\n }\n\n // TODO(wschurman): maybe do more validation, like validation of projectID and scopeKey within eas certificate extension\n\n return {\n keyId: 'expo-go',\n certificateChainForResponse: certificatePEMs,\n certificateForPrivateKey: certificatePEMs[0]!,\n privateKey: privateKeyPEM,\n scopeKey,\n };\n}\n\nfunction actorCanGetProjectDevelopmentCertificate(actor: Actor, app: App) {\n const owningAccountId = app.ownerAccount.id;\n\n const owningAccountIsActorPrimaryAccount =\n actor.__typename === 'User' || actor.__typename === 'SSOUser'\n ? actor.primaryAccount.id === owningAccountId\n : false;\n const userHasPublishPermissionForOwningAccount = !!actor.accounts\n .find((account) => account.id === owningAccountId)\n ?.users?.find((userPermission) => userPermission.actor.id === actor.id)\n ?.permissions?.includes('PUBLISH');\n return owningAccountIsActorPrimaryAccount || userHasPublishPermissionForOwningAccount;\n}\n\nasync function fetchAndCacheNewDevelopmentCodeSigningInfoAsync(\n easProjectId: string\n): Promise<CodeSigningInfo | null> {\n const actor = await tryGetUserAsync();\n\n if (!actor) {\n return null;\n }\n\n let app: App;\n try {\n app = await AppQuery.byIdAsync(easProjectId);\n } catch (e) {\n if (e instanceof UnexpectedServerError || e instanceof UnexpectedServerData) {\n return null;\n }\n throw e;\n }\n if (!actorCanGetProjectDevelopmentCertificate(actor, app)) {\n return null;\n }\n\n const keyPair = generateKeyPair();\n const keyPairPEM = convertKeyPairToPEM(keyPair);\n const csr = generateCSR(keyPair, `Development Certificate for ${easProjectId}`);\n const csrPEM = convertCSRToCSRPEM(csr);\n const [developmentSigningCertificate, expoGoIntermediateCertificate] = await Promise.all([\n getProjectDevelopmentCertificateAsync(easProjectId, csrPEM),\n getExpoGoIntermediateCertificateAsync(easProjectId),\n ]);\n\n await DevelopmentCodeSigningInfoFile.setAsync(easProjectId, {\n easProjectId,\n scopeKey: app.scopeKey,\n privateKey: keyPairPEM.privateKeyPEM,\n certificateChain: [developmentSigningCertificate, expoGoIntermediateCertificate],\n });\n\n return {\n keyId: 'expo-go',\n certificateChainForResponse: [developmentSigningCertificate, expoGoIntermediateCertificate],\n certificateForPrivateKey: developmentSigningCertificate,\n privateKey: keyPairPEM.privateKeyPEM,\n scopeKey: app.scopeKey,\n };\n}\n/**\n * Generate the `expo-signature` header for a manifest and code signing info.\n */\nexport function signManifestString(\n stringifiedManifest: string,\n codeSigningInfo: CodeSigningInfo\n): string {\n const privateKey = convertPrivateKeyPEMToPrivateKey(codeSigningInfo.privateKey);\n const certificate = convertCertificatePEMToCertificate(codeSigningInfo.certificateForPrivateKey);\n return signBufferRSASHA256AndVerify(\n privateKey,\n certificate,\n Buffer.from(stringifiedManifest, 'utf8')\n );\n}\n"],"names":["DevelopmentCodeSigningInfoFile","getCodeSigningInfoAsync","getDevelopmentCodeSigningDirectory","signManifestString","debug","require","DEVELOPMENT_CODE_SIGNING_SETTINGS_FILE_NAME","path","join","getExpoHomeDirectory","assertBasenameValue","input","basename","CommandError","getProjectDevelopmentCodeSigningInfoFile","defaults","getFile","easProjectId","filePath","JsonFile","readAsync","projectSettings","writeAsync","ensureDir","setAsync","json","mergeAsync","cantReadFileDefault","scopeKey","privateKey","certificateChain","exp","expectSignatureHeader","privateKeyPath","parsedExpectSignature","parseDictionary","expectedKeyIdOuter","get","expectedKeyId","expectedAlg","expectedAlgOuter","expectedAlgTemp","getExpoRootDevelopmentCodeSigningInfoAsync","getProjectCodeSigningCertificateAsync","extra","eas","projectId","learnMore","developmentCodeSigningInfoFromFile","validatedCodeSigningInfo","validateStoredDevelopmentExpoRootCertificateCodeSigningInfo","env","EXPO_OFFLINE","newCodeSigningInfo","fetchAndCacheNewDevelopmentCodeSigningInfoAsync","Log","warn","e","codeSigningCertificatePath","updates","codeSigningCertificate","codeSigningMetadata","alg","keyid","privateKeyPEM","certificatePEM","getProjectPrivateKeyAndCertificateFromFilePathsAsync","keyId","certificateForPrivateKey","certificateChainForResponse","readFileWithErrorAsync","errorMessage","fs","readFile","codeSigningCertificatePEM","Promise","all","convertPrivateKeyPEMToPrivateKey","certificate","convertCertificatePEMToCertificate","validateSelfSignedCertificate","publicKey","codeSigningInfo","certificatePEMs","length","map","now","Date","validity","notBefore","notAfter","actorCanGetProjectDevelopmentCertificate","actor","app","owningAccountId","ownerAccount","id","owningAccountIsActorPrimaryAccount","__typename","primaryAccount","userHasPublishPermissionForOwningAccount","accounts","find","account","users","userPermission","permissions","includes","tryGetUserAsync","AppQuery","byIdAsync","UnexpectedServerError","UnexpectedServerData","keyPair","generateKeyPair","keyPairPEM","convertKeyPairToPEM","csr","generateCSR","csrPEM","convertCSRToCSRPEM","developmentSigningCertificate","expoGoIntermediateCertificate","getProjectDevelopmentCertificateAsync","getExpoGoIntermediateCertificateAsync","stringifiedManifest","signBufferRSASHA256AndVerify","Buffer","from"],"mappings":";;;;;;;;;;;QAoHaA;eAAAA;;QAcSC;eAAAA;;QArENC;eAAAA;;QAwYAC;eAAAA;;;;yBA5bT;;;;;;;gEAGc;;;;;;;yBACU;;;;;;;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Content":["import {\n convertCertificatePEMToCertificate,\n convertKeyPairToPEM,\n convertCSRToCSRPEM,\n generateKeyPair,\n generateCSR,\n convertPrivateKeyPEMToPrivateKey,\n validateSelfSignedCertificate,\n signBufferRSASHA256AndVerify,\n} from '@expo/code-signing-certificates';\nimport type { ExpoConfig } from '@expo/config';\nimport type { JSONObject } from '@expo/json-file';\nimport JsonFile from '@expo/json-file';\nimport { promises as fs } from 'fs';\nimport type { pki as PKI } from 'node-forge';\nimport path from 'path';\nimport type { Dictionary } from 'structured-headers';\nimport { parseDictionary } from 'structured-headers';\n\nimport { env } from './env';\nimport { CommandError } from './errors';\nimport { getExpoGoIntermediateCertificateAsync } from '../api/getExpoGoIntermediateCertificate';\nimport { getProjectDevelopmentCertificateAsync } from '../api/getProjectDevelopmentCertificate';\nimport { UnexpectedServerError, UnexpectedServerData } from '../api/graphql/client';\nimport { AppQuery, type App } from '../api/graphql/queries/AppQuery';\nimport { getExpoHomeDirectory } from '../api/user/UserSettings';\nimport { tryGetUserAsync } from '../api/user/actions';\nimport type { Actor } from '../api/user/user';\nimport * as Log from '../log';\nimport { learnMore } from '../utils/link';\n\nconst debug = require('debug')('expo:codesigning') as typeof console.log;\n\nexport type CodeSigningInfo = {\n keyId: string;\n privateKey: string;\n certificateForPrivateKey: string;\n /**\n * Chain of certificates to serve in the manifest multipart body \"certificate_chain\" part.\n * The leaf certificate must be the 0th element of the array, followed by any intermediate certificates\n * necessary to evaluate the chain of trust ending in the implicitly trusted root certificate embedded in\n * the client.\n *\n * An empty array indicates that there is no need to serve the certificate chain in the multipart response.\n */\n certificateChainForResponse: string[];\n /**\n * Scope key cached for the project when certificate is development Expo Go code signing.\n * For project-specific code signing (keyId == the project's generated keyId) this is undefined.\n */\n scopeKey: string | null;\n};\n\ntype StoredDevelopmentExpoRootCodeSigningInfo = {\n easProjectId: string | null;\n scopeKey: string | null;\n privateKey: string | null;\n certificateChain: string[] | null;\n};\nconst DEVELOPMENT_CODE_SIGNING_SETTINGS_FILE_NAME = 'development-code-signing-settings-2.json';\n\nexport function getDevelopmentCodeSigningDirectory(): string {\n return path.join(getExpoHomeDirectory(), 'codesigning');\n}\n\nfunction assertBasenameValue(input: string): void {\n if (!input || input === '.' || input === '..' || input !== path.basename(input)) {\n throw new CommandError('Invalid EAS project ID for development code signing cache');\n }\n}\n\nfunction getProjectDevelopmentCodeSigningInfoFile<T extends JSONObject>(defaults: T) {\n function getFile(easProjectId: string): JsonFile<T> {\n assertBasenameValue(easProjectId);\n const filePath = path.join(\n getDevelopmentCodeSigningDirectory(),\n easProjectId,\n DEVELOPMENT_CODE_SIGNING_SETTINGS_FILE_NAME\n );\n return new JsonFile<T>(filePath);\n }\n\n async function readAsync(easProjectId: string): Promise<T> {\n let projectSettings;\n try {\n projectSettings = await getFile(easProjectId).readAsync();\n } catch {\n projectSettings = await getFile(easProjectId).writeAsync(defaults, { ensureDir: true });\n }\n // Set defaults for any missing fields\n return { ...defaults, ...projectSettings };\n }\n\n async function setAsync(easProjectId: string, json: Partial<T>): Promise<T> {\n try {\n return await getFile(easProjectId).mergeAsync(json, {\n cantReadFileDefault: defaults,\n });\n } catch {\n return await getFile(easProjectId).writeAsync(\n {\n ...defaults,\n ...json,\n },\n { ensureDir: true }\n );\n }\n }\n\n return {\n getFile,\n readAsync,\n setAsync,\n };\n}\n\nexport const DevelopmentCodeSigningInfoFile =\n getProjectDevelopmentCodeSigningInfoFile<StoredDevelopmentExpoRootCodeSigningInfo>({\n easProjectId: null,\n scopeKey: null,\n privateKey: null,\n certificateChain: null,\n });\n\n/**\n * Get info necessary to generate a response `expo-signature` header given a project and incoming request `expo-expect-signature` header.\n * This only knows how to serve two code signing keyids:\n * - `expo-root` indicates that it should use a development certificate in the `expo-root` chain. See {@link getExpoRootDevelopmentCodeSigningInfoAsync}\n * - <developer's expo-updates keyid> indicates that it should sign with the configured certificate. See {@link getProjectCodeSigningCertificateAsync}\n */\nexport async function getCodeSigningInfoAsync(\n exp: ExpoConfig,\n expectSignatureHeader: string | null,\n privateKeyPath: string | undefined\n): Promise<CodeSigningInfo | null> {\n if (!expectSignatureHeader) {\n return null;\n }\n\n let parsedExpectSignature: Dictionary;\n try {\n parsedExpectSignature = parseDictionary(expectSignatureHeader);\n } catch {\n throw new CommandError('Invalid value for expo-expect-signature header');\n }\n\n const expectedKeyIdOuter = parsedExpectSignature.get('keyid');\n if (!expectedKeyIdOuter) {\n throw new CommandError('keyid not present in expo-expect-signature header');\n }\n\n const expectedKeyId = expectedKeyIdOuter[0];\n if (typeof expectedKeyId !== 'string') {\n throw new CommandError(\n `Invalid value for keyid in expo-expect-signature header: ${expectedKeyId}`\n );\n }\n\n let expectedAlg: string | null = null;\n const expectedAlgOuter = parsedExpectSignature.get('alg');\n if (expectedAlgOuter) {\n const expectedAlgTemp = expectedAlgOuter[0];\n if (typeof expectedAlgTemp !== 'string') {\n throw new CommandError('Invalid value for alg in expo-expect-signature header');\n }\n expectedAlg = expectedAlgTemp;\n }\n\n if (expectedKeyId === 'expo-root') {\n return await getExpoRootDevelopmentCodeSigningInfoAsync(exp);\n } else if (expectedKeyId === 'expo-go') {\n throw new CommandError(\n 'Invalid certificate requested: cannot sign with embedded keyid=expo-go key'\n );\n } else {\n return await getProjectCodeSigningCertificateAsync(\n exp,\n privateKeyPath,\n expectedKeyId,\n expectedAlg\n );\n }\n}\n\n/**\n * Get a development code signing certificate for the expo-root -> expo-go -> (development certificate) certificate chain.\n * This requires the user be logged in and online, otherwise try to use the cached development certificate.\n */\nasync function getExpoRootDevelopmentCodeSigningInfoAsync(\n exp: ExpoConfig\n): Promise<CodeSigningInfo | null> {\n const easProjectId = exp.extra?.eas?.projectId;\n // can't check for scope key validity since scope key is derived on the server from projectId and we may be offline.\n // we rely upon the client certificate check to validate the scope key\n if (!easProjectId) {\n debug(\n `WARN: Expo Application Services (EAS) is not configured for your project. Configuring EAS enables a more secure development experience amongst many other benefits. ${learnMore(\n 'https://docs.expo.dev/eas/'\n )}`\n );\n return null;\n }\n\n const developmentCodeSigningInfoFromFile =\n await DevelopmentCodeSigningInfoFile.readAsync(easProjectId);\n const validatedCodeSigningInfo = validateStoredDevelopmentExpoRootCertificateCodeSigningInfo(\n developmentCodeSigningInfoFromFile,\n easProjectId\n );\n\n // 1. If online, ensure logged in, generate key pair and CSR, fetch and cache certificate chain for projectId\n // (overwriting existing dev cert in case projectId changed or it has expired)\n if (!env.EXPO_OFFLINE) {\n try {\n const newCodeSigningInfo =\n await fetchAndCacheNewDevelopmentCodeSigningInfoAsync(easProjectId);\n\n if (newCodeSigningInfo) {\n return newCodeSigningInfo;\n // fall back to cached certificate if we couldn't fetch a new one\n } else if (validatedCodeSigningInfo) {\n Log.warn(\n 'Could not fetch new Expo development certificate, falling back to cached certificate'\n );\n return validatedCodeSigningInfo;\n } else {\n return null;\n }\n } catch (e: any) {\n if (validatedCodeSigningInfo) {\n Log.warn(\n 'There was an error fetching the Expo development certificate, falling back to cached certificate'\n );\n return validatedCodeSigningInfo;\n } else {\n // need to return null here and say a message\n throw e;\n }\n }\n }\n\n // 2. check for cached cert/private key matching projectId and scopeKey of project, if found and valid return private key and cert chain including expo-go cert\n if (validatedCodeSigningInfo) {\n return validatedCodeSigningInfo;\n }\n\n // 3. if offline, return null\n Log.warn('Offline and no cached development certificate found, unable to sign manifest');\n return null;\n}\n\n/**\n * Get the certificate configured for expo-updates for this project.\n */\nasync function getProjectCodeSigningCertificateAsync(\n exp: ExpoConfig,\n privateKeyPath: string | undefined,\n expectedKeyId: string,\n expectedAlg: string | null\n): Promise<CodeSigningInfo | null> {\n const codeSigningCertificatePath = exp.updates?.codeSigningCertificate;\n if (!codeSigningCertificatePath) {\n if (privateKeyPath) {\n throw new CommandError(\n '--private-key-path was specified, but updates.codeSigningCertificate is not set in the resolved app config. Code signing requires both the certificate in app config and the private key. Ensure codeSigningCertificate (and codeSigningMetadata) are present, or omit --private-key-path if you do not intend to sign.\\nLearn more: https://docs.expo.dev/eas-update/code-signing/'\n );\n }\n return null;\n }\n\n if (!privateKeyPath) {\n throw new CommandError(\n 'Must specify --private-key-path argument to sign development manifest for requested code signing key'\n );\n }\n\n const codeSigningMetadata = exp.updates?.codeSigningMetadata;\n if (!codeSigningMetadata) {\n throw new CommandError(\n 'Must specify \"codeSigningMetadata\" under the \"updates\" field of your app config file to use EAS code signing'\n );\n }\n\n const { alg, keyid } = codeSigningMetadata;\n if (!alg || !keyid) {\n throw new CommandError(\n 'Must specify \"keyid\" and \"alg\" in the \"codeSigningMetadata\" field under the \"updates\" field of your app config file to use EAS code signing'\n );\n }\n\n if (expectedKeyId !== keyid) {\n throw new CommandError(`keyid mismatch: client=${expectedKeyId}, project=${keyid}`);\n }\n\n if (expectedAlg && expectedAlg !== alg) {\n throw new CommandError(`\"alg\" field mismatch (client=${expectedAlg}, project=${alg})`);\n }\n\n const { privateKeyPEM, certificatePEM } =\n await getProjectPrivateKeyAndCertificateFromFilePathsAsync({\n codeSigningCertificatePath,\n privateKeyPath,\n });\n\n return {\n keyId: keyid,\n privateKey: privateKeyPEM,\n certificateForPrivateKey: certificatePEM,\n certificateChainForResponse: [],\n scopeKey: null,\n };\n}\n\nasync function readFileWithErrorAsync(path: string, errorMessage: string): Promise<string> {\n try {\n return await fs.readFile(path, 'utf8');\n } catch {\n throw new CommandError(errorMessage);\n }\n}\n\nasync function getProjectPrivateKeyAndCertificateFromFilePathsAsync({\n codeSigningCertificatePath,\n privateKeyPath,\n}: {\n codeSigningCertificatePath: string;\n privateKeyPath: string;\n}): Promise<{ privateKeyPEM: string; certificatePEM: string }> {\n const [codeSigningCertificatePEM, privateKeyPEM] = await Promise.all([\n readFileWithErrorAsync(\n codeSigningCertificatePath,\n `Code signing certificate cannot be read from path: ${codeSigningCertificatePath}`\n ),\n readFileWithErrorAsync(\n privateKeyPath,\n `Code signing private key cannot be read from path: ${privateKeyPath}`\n ),\n ]);\n\n const privateKey = convertPrivateKeyPEMToPrivateKey(privateKeyPEM);\n const certificate = convertCertificatePEMToCertificate(codeSigningCertificatePEM);\n validateSelfSignedCertificate(certificate, {\n publicKey: certificate.publicKey as PKI.rsa.PublicKey,\n privateKey,\n });\n\n return { privateKeyPEM, certificatePEM: codeSigningCertificatePEM };\n}\n\n/**\n * Validate that the cached code signing info is still valid for the current project and\n * that it hasn't expired. If invalid, return null.\n */\nfunction validateStoredDevelopmentExpoRootCertificateCodeSigningInfo(\n codeSigningInfo: StoredDevelopmentExpoRootCodeSigningInfo,\n easProjectId: string\n): CodeSigningInfo | null {\n if (codeSigningInfo.easProjectId !== easProjectId) {\n return null;\n }\n\n const {\n privateKey: privateKeyPEM,\n certificateChain: certificatePEMs,\n scopeKey,\n } = codeSigningInfo;\n if (!privateKeyPEM || !certificatePEMs?.length) {\n return null;\n }\n\n const certificateChain = certificatePEMs.map((certificatePEM) =>\n convertCertificatePEMToCertificate(certificatePEM)\n );\n\n // TODO(wschurman): maybe move to @expo/code-signing-certificates\n\n // ensure all intermediate certificates are valid\n for (const certificate of certificateChain) {\n const now = new Date();\n if (certificate.validity.notBefore > now || certificate.validity.notAfter < now) {\n return null;\n }\n }\n\n // TODO(wschurman): maybe do more validation, like validation of projectID and scopeKey within eas certificate extension\n\n return {\n keyId: 'expo-go',\n certificateChainForResponse: certificatePEMs,\n certificateForPrivateKey: certificatePEMs[0]!,\n privateKey: privateKeyPEM,\n scopeKey,\n };\n}\n\nfunction actorCanGetProjectDevelopmentCertificate(actor: Actor, app: App) {\n const owningAccountId = app.ownerAccount.id;\n\n const owningAccountIsActorPrimaryAccount =\n actor.__typename === 'User' || actor.__typename === 'SSOUser'\n ? actor.primaryAccount.id === owningAccountId\n : false;\n const userHasPublishPermissionForOwningAccount = !!actor.accounts\n .find((account) => account.id === owningAccountId)\n ?.users?.find((userPermission) => userPermission.actor.id === actor.id)\n ?.permissions?.includes('PUBLISH');\n return owningAccountIsActorPrimaryAccount || userHasPublishPermissionForOwningAccount;\n}\n\nasync function fetchAndCacheNewDevelopmentCodeSigningInfoAsync(\n easProjectId: string\n): Promise<CodeSigningInfo | null> {\n const actor = await tryGetUserAsync();\n\n if (!actor) {\n return null;\n }\n\n let app: App;\n try {\n app = await AppQuery.byIdAsync(easProjectId);\n } catch (e) {\n if (e instanceof UnexpectedServerError || e instanceof UnexpectedServerData) {\n return null;\n }\n throw e;\n }\n if (!actorCanGetProjectDevelopmentCertificate(actor, app)) {\n return null;\n }\n\n const keyPair = generateKeyPair();\n const keyPairPEM = convertKeyPairToPEM(keyPair);\n const csr = generateCSR(keyPair, `Development Certificate for ${easProjectId}`);\n const csrPEM = convertCSRToCSRPEM(csr);\n const [developmentSigningCertificate, expoGoIntermediateCertificate] = await Promise.all([\n getProjectDevelopmentCertificateAsync(easProjectId, csrPEM),\n getExpoGoIntermediateCertificateAsync(easProjectId),\n ]);\n\n await DevelopmentCodeSigningInfoFile.setAsync(easProjectId, {\n easProjectId,\n scopeKey: app.scopeKey,\n privateKey: keyPairPEM.privateKeyPEM,\n certificateChain: [developmentSigningCertificate, expoGoIntermediateCertificate],\n });\n\n return {\n keyId: 'expo-go',\n certificateChainForResponse: [developmentSigningCertificate, expoGoIntermediateCertificate],\n certificateForPrivateKey: developmentSigningCertificate,\n privateKey: keyPairPEM.privateKeyPEM,\n scopeKey: app.scopeKey,\n };\n}\n/**\n * Generate the `expo-signature` header for a manifest and code signing info.\n */\nexport function signManifestString(\n stringifiedManifest: string,\n codeSigningInfo: CodeSigningInfo\n): string {\n const privateKey = convertPrivateKeyPEMToPrivateKey(codeSigningInfo.privateKey);\n const certificate = convertCertificatePEMToCertificate(codeSigningInfo.certificateForPrivateKey);\n return signBufferRSASHA256AndVerify(\n privateKey,\n certificate,\n Buffer.from(stringifiedManifest, 'utf8')\n );\n}\n"],"names":["DevelopmentCodeSigningInfoFile","getCodeSigningInfoAsync","getDevelopmentCodeSigningDirectory","signManifestString","debug","require","DEVELOPMENT_CODE_SIGNING_SETTINGS_FILE_NAME","path","join","getExpoHomeDirectory","assertBasenameValue","input","basename","CommandError","getProjectDevelopmentCodeSigningInfoFile","defaults","getFile","easProjectId","filePath","JsonFile","readAsync","projectSettings","writeAsync","ensureDir","setAsync","json","mergeAsync","cantReadFileDefault","scopeKey","privateKey","certificateChain","exp","expectSignatureHeader","privateKeyPath","parsedExpectSignature","parseDictionary","expectedKeyIdOuter","get","expectedKeyId","expectedAlg","expectedAlgOuter","expectedAlgTemp","getExpoRootDevelopmentCodeSigningInfoAsync","getProjectCodeSigningCertificateAsync","extra","eas","projectId","learnMore","developmentCodeSigningInfoFromFile","validatedCodeSigningInfo","validateStoredDevelopmentExpoRootCertificateCodeSigningInfo","env","EXPO_OFFLINE","newCodeSigningInfo","fetchAndCacheNewDevelopmentCodeSigningInfoAsync","Log","warn","e","codeSigningCertificatePath","updates","codeSigningCertificate","codeSigningMetadata","alg","keyid","privateKeyPEM","certificatePEM","getProjectPrivateKeyAndCertificateFromFilePathsAsync","keyId","certificateForPrivateKey","certificateChainForResponse","readFileWithErrorAsync","errorMessage","fs","readFile","codeSigningCertificatePEM","Promise","all","convertPrivateKeyPEMToPrivateKey","certificate","convertCertificatePEMToCertificate","validateSelfSignedCertificate","publicKey","codeSigningInfo","certificatePEMs","length","map","now","Date","validity","notBefore","notAfter","actorCanGetProjectDevelopmentCertificate","actor","app","owningAccountId","ownerAccount","id","owningAccountIsActorPrimaryAccount","__typename","primaryAccount","userHasPublishPermissionForOwningAccount","accounts","find","account","users","userPermission","permissions","includes","tryGetUserAsync","AppQuery","byIdAsync","UnexpectedServerError","UnexpectedServerData","keyPair","generateKeyPair","keyPairPEM","convertKeyPairToPEM","csr","generateCSR","csrPEM","convertCSRToCSRPEM","developmentSigningCertificate","expoGoIntermediateCertificate","getProjectDevelopmentCertificateAsync","getExpoGoIntermediateCertificateAsync","stringifiedManifest","signBufferRSASHA256AndVerify","Buffer","from"],"mappings":";;;;;;;;;;;QAoHaA;eAAAA;;QAcSC;eAAAA;;QArENC;eAAAA;;QA6YAC;eAAAA;;;;yBAjcT;;;;;;;gEAGc;;;;;;;yBACU;;;;;;;gEAE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AAErC"}
|
package/build/src/utils/npm.js
CHANGED
|
@@ -24,6 +24,9 @@ _export(exports, {
|
|
|
24
24
|
get getNpmUrlAsync () {
|
|
25
25
|
return getNpmUrlAsync;
|
|
26
26
|
},
|
|
27
|
+
get normalizeNpmPackResult () {
|
|
28
|
+
return normalizeNpmPackResult;
|
|
29
|
+
},
|
|
27
30
|
get npmViewAsync () {
|
|
28
31
|
return npmViewAsync;
|
|
29
32
|
},
|
|
@@ -211,13 +214,23 @@ async function packNpmTarballAsync(packageDir) {
|
|
|
211
214
|
cwd: packageDir
|
|
212
215
|
})).stdout) == null ? void 0 : _stdout.trim();
|
|
213
216
|
try {
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
|
|
217
|
+
const packages = normalizeNpmPackResult(JSON.parse(results));
|
|
218
|
+
const packageInfo = packages == null ? void 0 : packages[0];
|
|
219
|
+
(0, _nodeassert().default)(packageInfo && typeof packageInfo === 'object' && 'filename' in packageInfo && typeof packageInfo.filename === 'string', 'Expected filename property in npm pack JSON output of type "string"');
|
|
220
|
+
return _nodepath().default.resolve(packageDir, packageInfo.filename);
|
|
217
221
|
} catch (error) {
|
|
218
222
|
const cmdString = `npm ${cmdArgs.join(' ')}`;
|
|
219
223
|
throw new Error(`Could not parse JSON returned from "${cmdString}".\n\n${results}\n\nError: ${error.message}`);
|
|
220
224
|
}
|
|
221
225
|
}
|
|
226
|
+
function normalizeNpmPackResult(result) {
|
|
227
|
+
if (Array.isArray(result)) {
|
|
228
|
+
return result;
|
|
229
|
+
} else if (result && typeof result === 'object') {
|
|
230
|
+
return Object.values(result);
|
|
231
|
+
} else {
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
222
235
|
|
|
223
236
|
//# sourceMappingURL=npm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/npm.ts"],"sourcesContent":["import { IOSConfig } from '@expo/config-plugins';\nimport type { JSONValue } from '@expo/json-file';\nimport spawnAsync from '@expo/spawn-async';\nimport { TarTypeFlag } from 'multitars';\nimport assert from 'node:assert';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport slugify from 'slugify';\nimport { Readable } from 'stream';\n\nimport { CommandError } from './errors';\nimport { extractStream } from './tar';\n\nconst debug = require('debug')('expo:utils:npm') as typeof console.log;\n\nexport function sanitizeNpmPackageName(name: string): string {\n // https://github.com/npm/validate-npm-package-name/#naming-rules\n return (\n applyKnownNpmPackageNameRules(name) ||\n applyKnownNpmPackageNameRules(slugify(name)) ||\n // If nothing is left use 'app' like we do in Xcode projects.\n 'app'\n );\n}\n\nfunction applyKnownNpmPackageNameRules(name: string): string | null {\n // https://github.com/npm/validate-npm-package-name/#naming-rules\n\n // package name cannot start with '.' or '_'.\n while (/^(\\.|_)/.test(name)) {\n name = name.substring(1);\n }\n\n name = name.toLowerCase().replace(/[^a-zA-Z._\\-/@]/g, '');\n\n return (\n name\n // .replace(/![a-z0-9-._~]+/g, '')\n // Remove special characters\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '') || null\n );\n}\n\nexport async function npmViewAsync(...props: string[]): Promise<JSONValue> {\n const cmd = ['view', ...props, '--json'];\n const results = (await spawnAsync('npm', cmd)).stdout?.trim();\n const cmdString = `npm ${cmd.join(' ')}`;\n debug('Run:', cmdString);\n if (!results) {\n return null;\n }\n try {\n return JSON.parse(results);\n } catch (error: any) {\n throw new Error(\n `Could not parse JSON returned from \"${cmdString}\".\\n\\n${results}\\n\\nError: ${error.message}`\n );\n }\n}\n\n/** Given a package name like `expo` or `expo@beta`, return the registry URL if it exists. */\nexport async function getNpmUrlAsync(packageName: string): Promise<string> {\n const results = await npmViewAsync(packageName, 'dist');\n\n assert(results, `Could not get npm url for package \"${packageName}\"`);\n\n // Fully qualified url returns an object.\n // Example:\n // 𝝠 npm view expo-template-bare-minimum@sdk-33 dist --json\n if (typeof results === 'object' && !Array.isArray(results)) {\n return results.tarball as string;\n }\n\n // When the tag is arbitrary, the tarball is an array, return the last value as it's the most recent.\n // Example:\n // 𝝠 npm view expo-template-bare-minimum@33 dist --json\n if (Array.isArray(results)) {\n const lastResult = results[results.length - 1];\n\n if (lastResult && typeof lastResult === 'object' && !Array.isArray(lastResult)) {\n return lastResult.tarball as string;\n }\n }\n\n throw new CommandError(\n 'Expected results of `npm view ...` to be an array or string. Instead found: ' + results\n );\n}\n\nexport interface ExtractProps {\n expName?: string;\n filter?(path: string): boolean | undefined | null;\n strip?: number;\n}\n\nfunction renameNpmTarballEntries(expName: string | undefined) {\n const renameConfigs = (input: string, typeflag: TarTypeFlag): string | null => {\n if (typeflag === TarTypeFlag.FILE && path.basename(input) === 'gitignore') {\n // Rename `gitignore` because npm ignores files named `.gitignore` when publishing.\n // See: https://github.com/npm/npm/issues/1862\n return input.replace(/gitignore$/, '.gitignore');\n } else {\n return input;\n }\n };\n if (expName) {\n const androidName = IOSConfig.XcodeUtils.sanitizedName(expName.toLowerCase());\n const iosName = IOSConfig.XcodeUtils.sanitizedName(expName);\n const lowerCaseName = iosName.toLowerCase();\n return (input: string, typeflag: TarTypeFlag) => {\n input = input\n .replace(/HelloWorld/g, input.includes('android') ? androidName : iosName)\n .replace(/helloworld/g, lowerCaseName);\n return renameConfigs(input, typeflag);\n };\n } else {\n return renameConfigs;\n }\n}\n\n/**\n * Extracts a tarball stream to a directory and returns the checksum of the tarball.\n */\nexport async function extractNpmTarballAsync(\n stream: ReadableStream,\n output: string,\n props: ExtractProps\n): Promise<string> {\n return await extractStream(stream, output, {\n filter: props.filter,\n rename: renameNpmTarballEntries(props.expName),\n strip: props.strip ?? 1,\n });\n}\n\nexport async function extractNpmTarballFromUrlAsync(\n url: string,\n output: string,\n props: ExtractProps\n): Promise<string> {\n const response = await fetch(url);\n if (!response.ok || !response.body) {\n throw new Error(`Unexpected response: ${response.statusText}. From url: ${url}`);\n }\n return await extractNpmTarballAsync(response.body, output, props);\n}\n\nexport async function downloadAndExtractNpmModuleAsync(\n npmName: string,\n output: string,\n props: ExtractProps\n): Promise<string> {\n const url = await getNpmUrlAsync(npmName);\n debug('Fetch from URL:', url);\n return await extractNpmTarballFromUrlAsync(url, output, props);\n}\n\nexport async function extractLocalNpmTarballAsync(\n tarFilePath: string,\n output: string,\n props: ExtractProps\n): Promise<string> {\n return await extractNpmTarballAsync(\n Readable.toWeb(fs.createReadStream(tarFilePath)) as ReadableStream,\n output,\n props\n );\n}\n\nexport async function packNpmTarballAsync(packageDir: string): Promise<string> {\n const cmdArgs = ['pack', '--json', '--foreground-scripts=false'];\n const results = (\n await spawnAsync('npm', cmdArgs, {\n env: { ...process.env },\n cwd: packageDir,\n })\n ).stdout?.trim();\n try {\n const [json] = JSON.parse(results) as { filename: string }[];\n assert(\n typeof json?.filename === 'string',\n 'Expected filename property on JSON array of type \"string\"'\n );\n return path.resolve(packageDir, json.filename);\n } catch (error: any) {\n const cmdString = `npm ${cmdArgs.join(' ')}`;\n throw new Error(\n `Could not parse JSON returned from \"${cmdString}\".\\n\\n${results}\\n\\nError: ${error.message}`\n );\n }\n}\n"],"names":["downloadAndExtractNpmModuleAsync","extractLocalNpmTarballAsync","extractNpmTarballAsync","extractNpmTarballFromUrlAsync","getNpmUrlAsync","npmViewAsync","packNpmTarballAsync","sanitizeNpmPackageName","debug","require","name","applyKnownNpmPackageNameRules","slugify","test","substring","toLowerCase","replace","normalize","props","cmd","results","spawnAsync","stdout","trim","cmdString","join","JSON","parse","error","Error","message","packageName","assert","Array","isArray","tarball","lastResult","length","CommandError","renameNpmTarballEntries","expName","renameConfigs","input","typeflag","TarTypeFlag","FILE","path","basename","androidName","IOSConfig","XcodeUtils","sanitizedName","iosName","lowerCaseName","includes","stream","output","extractStream","filter","rename","strip","url","response","fetch","ok","body","statusText","npmName","tarFilePath","Readable","toWeb","fs","createReadStream","packageDir","cmdArgs","env","process","cwd","json","filename","resolve"],"mappings":";;;;;;;;;;;QAoJsBA;eAAAA;;QAUAC;eAAAA;;QAlCAC;eAAAA;;QAYAC;eAAAA;;QA1EAC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jC,mBAAI,CAACkC,OAAO,CAACP,YAAYK,KAAKC,QAAQ;IAC/C,EAAE,OAAOnD,OAAY;QACnB,MAAMJ,YAAY,CAAC,IAAI,EAAEkD,QAAQjD,IAAI,CAAC,MAAM;QAC5C,MAAM,IAAII,MACR,CAAC,oCAAoC,EAAEL,UAAU,MAAM,EAAEJ,QAAQ,WAAW,EAAEQ,MAAME,OAAO,EAAE;IAEjG;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/npm.ts"],"sourcesContent":["import { IOSConfig } from '@expo/config-plugins';\nimport type { JSONValue } from '@expo/json-file';\nimport spawnAsync from '@expo/spawn-async';\nimport { TarTypeFlag } from 'multitars';\nimport assert from 'node:assert';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport slugify from 'slugify';\nimport { Readable } from 'stream';\n\nimport { CommandError } from './errors';\nimport { extractStream } from './tar';\n\nconst debug = require('debug')('expo:utils:npm') as typeof console.log;\n\nexport function sanitizeNpmPackageName(name: string): string {\n // https://github.com/npm/validate-npm-package-name/#naming-rules\n return (\n applyKnownNpmPackageNameRules(name) ||\n applyKnownNpmPackageNameRules(slugify(name)) ||\n // If nothing is left use 'app' like we do in Xcode projects.\n 'app'\n );\n}\n\nfunction applyKnownNpmPackageNameRules(name: string): string | null {\n // https://github.com/npm/validate-npm-package-name/#naming-rules\n\n // package name cannot start with '.' or '_'.\n while (/^(\\.|_)/.test(name)) {\n name = name.substring(1);\n }\n\n name = name.toLowerCase().replace(/[^a-zA-Z._\\-/@]/g, '');\n\n return (\n name\n // .replace(/![a-z0-9-._~]+/g, '')\n // Remove special characters\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '') || null\n );\n}\n\nexport async function npmViewAsync(...props: string[]): Promise<JSONValue> {\n const cmd = ['view', ...props, '--json'];\n const results = (await spawnAsync('npm', cmd)).stdout?.trim();\n const cmdString = `npm ${cmd.join(' ')}`;\n debug('Run:', cmdString);\n if (!results) {\n return null;\n }\n try {\n return JSON.parse(results);\n } catch (error: any) {\n throw new Error(\n `Could not parse JSON returned from \"${cmdString}\".\\n\\n${results}\\n\\nError: ${error.message}`\n );\n }\n}\n\n/** Given a package name like `expo` or `expo@beta`, return the registry URL if it exists. */\nexport async function getNpmUrlAsync(packageName: string): Promise<string> {\n const results = await npmViewAsync(packageName, 'dist');\n\n assert(results, `Could not get npm url for package \"${packageName}\"`);\n\n // Fully qualified url returns an object.\n // Example:\n // 𝝠 npm view expo-template-bare-minimum@sdk-33 dist --json\n if (typeof results === 'object' && !Array.isArray(results)) {\n return results.tarball as string;\n }\n\n // When the tag is arbitrary, the tarball is an array, return the last value as it's the most recent.\n // Example:\n // 𝝠 npm view expo-template-bare-minimum@33 dist --json\n if (Array.isArray(results)) {\n const lastResult = results[results.length - 1];\n\n if (lastResult && typeof lastResult === 'object' && !Array.isArray(lastResult)) {\n return lastResult.tarball as string;\n }\n }\n\n throw new CommandError(\n 'Expected results of `npm view ...` to be an array or string. Instead found: ' + results\n );\n}\n\nexport interface ExtractProps {\n expName?: string;\n filter?(path: string): boolean | undefined | null;\n strip?: number;\n}\n\nfunction renameNpmTarballEntries(expName: string | undefined) {\n const renameConfigs = (input: string, typeflag: TarTypeFlag): string | null => {\n if (typeflag === TarTypeFlag.FILE && path.basename(input) === 'gitignore') {\n // Rename `gitignore` because npm ignores files named `.gitignore` when publishing.\n // See: https://github.com/npm/npm/issues/1862\n return input.replace(/gitignore$/, '.gitignore');\n } else {\n return input;\n }\n };\n if (expName) {\n const androidName = IOSConfig.XcodeUtils.sanitizedName(expName.toLowerCase());\n const iosName = IOSConfig.XcodeUtils.sanitizedName(expName);\n const lowerCaseName = iosName.toLowerCase();\n return (input: string, typeflag: TarTypeFlag) => {\n input = input\n .replace(/HelloWorld/g, input.includes('android') ? androidName : iosName)\n .replace(/helloworld/g, lowerCaseName);\n return renameConfigs(input, typeflag);\n };\n } else {\n return renameConfigs;\n }\n}\n\n/**\n * Extracts a tarball stream to a directory and returns the checksum of the tarball.\n */\nexport async function extractNpmTarballAsync(\n stream: ReadableStream,\n output: string,\n props: ExtractProps\n): Promise<string> {\n return await extractStream(stream, output, {\n filter: props.filter,\n rename: renameNpmTarballEntries(props.expName),\n strip: props.strip ?? 1,\n });\n}\n\nexport async function extractNpmTarballFromUrlAsync(\n url: string,\n output: string,\n props: ExtractProps\n): Promise<string> {\n const response = await fetch(url);\n if (!response.ok || !response.body) {\n throw new Error(`Unexpected response: ${response.statusText}. From url: ${url}`);\n }\n return await extractNpmTarballAsync(response.body, output, props);\n}\n\nexport async function downloadAndExtractNpmModuleAsync(\n npmName: string,\n output: string,\n props: ExtractProps\n): Promise<string> {\n const url = await getNpmUrlAsync(npmName);\n debug('Fetch from URL:', url);\n return await extractNpmTarballFromUrlAsync(url, output, props);\n}\n\nexport async function extractLocalNpmTarballAsync(\n tarFilePath: string,\n output: string,\n props: ExtractProps\n): Promise<string> {\n return await extractNpmTarballAsync(\n Readable.toWeb(fs.createReadStream(tarFilePath)) as ReadableStream,\n output,\n props\n );\n}\n\nexport async function packNpmTarballAsync(packageDir: string): Promise<string> {\n const cmdArgs = ['pack', '--json', '--foreground-scripts=false'];\n const results = (\n await spawnAsync('npm', cmdArgs, {\n env: { ...process.env },\n cwd: packageDir,\n })\n ).stdout?.trim();\n try {\n const packages = normalizeNpmPackResult(JSON.parse(results));\n const packageInfo = packages?.[0];\n assert(\n packageInfo &&\n typeof packageInfo === 'object' &&\n 'filename' in packageInfo &&\n typeof packageInfo.filename === 'string',\n 'Expected filename property in npm pack JSON output of type \"string\"'\n );\n return path.resolve(packageDir, packageInfo.filename);\n } catch (error: any) {\n const cmdString = `npm ${cmdArgs.join(' ')}`;\n throw new Error(\n `Could not parse JSON returned from \"${cmdString}\".\\n\\n${results}\\n\\nError: ${error.message}`\n );\n }\n}\n\n/** Normalize the npm pack JSON formats used before and after npm 12 */\nexport function normalizeNpmPackResult(result: unknown): unknown[] | null {\n if (Array.isArray(result)) {\n return result;\n } else if (result && typeof result === 'object') {\n return Object.values(result);\n } else {\n return null;\n }\n}\n"],"names":["downloadAndExtractNpmModuleAsync","extractLocalNpmTarballAsync","extractNpmTarballAsync","extractNpmTarballFromUrlAsync","getNpmUrlAsync","normalizeNpmPackResult","npmViewAsync","packNpmTarballAsync","sanitizeNpmPackageName","debug","require","name","applyKnownNpmPackageNameRules","slugify","test","substring","toLowerCase","replace","normalize","props","cmd","results","spawnAsync","stdout","trim","cmdString","join","JSON","parse","error","Error","message","packageName","assert","Array","isArray","tarball","lastResult","length","CommandError","renameNpmTarballEntries","expName","renameConfigs","input","typeflag","TarTypeFlag","FILE","path","basename","androidName","IOSConfig","XcodeUtils","sanitizedName","iosName","lowerCaseName","includes","stream","output","extractStream","filter","rename","strip","url","response","fetch","ok","body","statusText","npmName","tarFilePath","Readable","toWeb","fs","createReadStream","packageDir","cmdArgs","env","process","cwd","packages","packageInfo","filename","resolve","result","Object","values"],"mappings":";;;;;;;;;;;QAoJsBA;eAAAA;;QAUAC;eAAAA;;QAlCAC;eAAAA;;QAYAC;eAAAA;;QA1EAC;eAAAA;;QAwINC;eAAAA;;QA1JMC;eAAAA;;QA8HAC;eAAAA;;QA3JNC;eAAAA;;;;yBAfU;;;;;;;gEAEH;;;;;;;yBACK;;;;;;;gEACT;;;;;;;gEACJ;;;;;;;gEACE;;;;;;;gEACG;;;;;;;yBACK;;;;;;wBAEI;qBACC;;;;;;AAE9B,MAAMC,QAAQC,QAAQ,SAAS;AAExB,SAASF,uBAAuBG,IAAY;IACjD,iEAAiE;IACjE,OACEC,8BAA8BD,SAC9BC,8BAA8BC,IAAAA,kBAAO,EAACF,UACtC,6DAA6D;IAC7D;AAEJ;AAEA,SAASC,8BAA8BD,IAAY;IACjD,iEAAiE;IAEjE,6CAA6C;IAC7C,MAAO,UAAUG,IAAI,CAACH,MAAO;QAC3BA,OAAOA,KAAKI,SAAS,CAAC;IACxB;IAEAJ,OAAOA,KAAKK,WAAW,GAAGC,OAAO,CAAC,oBAAoB;IAEtD,OACEN,IACE,k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Client = require("./clients/FetchClient");
|
|
|
19
19
|
const _FetchDetachedClient = require("./clients/FetchDetachedClient");
|
|
20
20
|
const _agent = require("./utils/agent");
|
|
21
21
|
const _context = require("./utils/context");
|
|
22
|
+
const _sandbox = require("./utils/sandbox");
|
|
22
23
|
const _UserSettings = require("../../api/user/UserSettings");
|
|
23
24
|
const _env = require("../env");
|
|
24
25
|
function _interop_require_default(obj) {
|
|
@@ -76,6 +77,7 @@ class Telemetry {
|
|
|
76
77
|
}
|
|
77
78
|
recordInternal(records) {
|
|
78
79
|
const agent = (0, _agent.getAgentTelemetryContext)();
|
|
80
|
+
const sandboxProvider = (0, _sandbox.getSandboxTelemetryContext)();
|
|
79
81
|
return this.client.record(records.map((record)=>({
|
|
80
82
|
...record,
|
|
81
83
|
type: 'track',
|
|
@@ -86,6 +88,9 @@ class Telemetry {
|
|
|
86
88
|
context: {
|
|
87
89
|
...this.context,
|
|
88
90
|
sessionId: this.actor.sessionId,
|
|
91
|
+
...sandboxProvider ? {
|
|
92
|
+
sandbox_provider: sandboxProvider
|
|
93
|
+
} : {},
|
|
89
94
|
...agent ? {
|
|
90
95
|
agent
|
|
91
96
|
} : {},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/utils/telemetry/Telemetry.ts"],"sourcesContent":["import crypto from 'node:crypto';\n\nimport { FetchClient } from './clients/FetchClient';\nimport { FetchDetachedClient } from './clients/FetchDetachedClient';\nimport type { TelemetryClient, TelemetryClientStrategy, TelemetryRecord } from './types';\nimport { getAgentTelemetryContext } from './utils/agent';\nimport { createContext } from './utils/context';\nimport { getAnonymousId } from '../../api/user/UserSettings';\nimport { env } from '../env';\n\nconst debug = require('debug')('expo:telemetry') as typeof console.log;\n\ntype TelemetryOptions = {\n /** A locally generated ID, untracable to an actual user */\n anonymousId?: string;\n /** A locally generated ID, per CLI invocation */\n sessionId?: string;\n /** The authenticated user ID, this is used to generate an untracable hash */\n userId?: string;\n /** The underlying telemetry strategy to use */\n strategy?: TelemetryClientStrategy;\n};\n\ntype TelemetryActor = Required<Pick<TelemetryOptions, 'anonymousId' | 'sessionId'>> & {\n /**\n * Hashed version of the user ID, untracable to an actual user.\n * If this value is set to `undefined`, telemetry is considered uninitialized and will wait until its set.\n * If this value is set to `null`, telemetry is considered initialized without an authenticated user.\n * If this value is set to a string, telemetry is considered initialized with an authenticated user.\n */\n userHash?: string | null;\n};\n\nexport class Telemetry {\n private context = createContext();\n private client: TelemetryClient = new FetchDetachedClient();\n private actor: TelemetryActor;\n\n /** A list of all events, recorded before the telemetry was fully initialized */\n private earlyRecords: TelemetryRecord[] = [];\n\n constructor({\n anonymousId = getAnonymousId(),\n sessionId = crypto.randomUUID(),\n userId,\n strategy = 'detached',\n }: TelemetryOptions = {}) {\n this.actor = { anonymousId, sessionId };\n this.setStrategy(env.EXPO_NO_TELEMETRY_DETACH ? 'debug' : strategy);\n\n if (userId) {\n this.initialize({ userId });\n }\n }\n\n get strategy() {\n return this.client.strategy;\n }\n\n setStrategy(strategy: TelemetryOptions['strategy']) {\n // Abort when client is already using the correct strategy\n if (this.client.strategy === strategy) return;\n // Abort when debugging the telemetry\n if (env.EXPO_NO_TELEMETRY_DETACH && strategy !== 'debug') return;\n\n debug('Switching strategy from %s to %s', this.client.strategy, strategy);\n\n // Load and instantiate the correct client, based on strategy\n const client = createClientFromStrategy(strategy);\n // Replace the client, and re-record any pending records\n this.client.abort().forEach((record) => client.record([record]));\n this.client = client;\n\n return this;\n }\n\n get isInitialized() {\n return this.actor.userHash !== undefined;\n }\n\n initialize({ userId }: { userId: string | null }) {\n this.actor.userHash = userId ? hashUserId(userId) : null;\n this.flushEarlyRecords();\n }\n\n private flushEarlyRecords() {\n if (this.earlyRecords.length) {\n this.recordInternal(this.earlyRecords);\n this.earlyRecords = [];\n }\n }\n\n private recordInternal(records: TelemetryRecord[]) {\n const agent = getAgentTelemetryContext();\n\n return this.client.record(\n records.map((record) => ({\n ...record,\n type: 'track' as const,\n sentAt: new Date(),\n messageId: createMessageId(record),\n anonymousId: this.actor.anonymousId,\n userHash: this.actor.userHash,\n context: {\n ...this.context,\n sessionId: this.actor.sessionId,\n ...(agent ? { agent } : {}),\n client: { mode: this.client.strategy },\n },\n }))\n );\n }\n\n record(record: TelemetryRecord | TelemetryRecord[]) {\n const records = Array.isArray(record) ? record : [record];\n\n debug('Recording %d event(s)', records.length);\n\n if (!this.isInitialized) {\n this.earlyRecords.push(...records);\n return;\n }\n\n return this.recordInternal(records);\n }\n\n flush() {\n debug('Flushing events...');\n this.flushEarlyRecords();\n return this.client.flush();\n }\n\n flushOnExit() {\n this.setStrategy('detached');\n this.flushEarlyRecords();\n return this.client.flush();\n }\n}\n\nfunction createClientFromStrategy(strategy: TelemetryOptions['strategy']) {\n // When debugging, use the actual Rudderstack client, but lazy load it\n if (env.EXPO_NO_TELEMETRY_DETACH || strategy === 'debug' || strategy === 'instant') {\n return new FetchClient();\n }\n\n return new FetchDetachedClient();\n}\n\n/** Generate a unique message ID using a random hash and UUID */\nfunction createMessageId(record: TelemetryRecord) {\n const uuid = crypto.randomUUID();\n const md5 = crypto.createHash('md5').update(JSON.stringify(record)).digest('hex');\n\n return `node-${md5}-${uuid}`;\n}\n\n/** Hash the user identifier to make it untracable */\nfunction hashUserId(userId: string) {\n return crypto.createHash('sha256').update(userId).digest('hex');\n}\n"],"names":["Telemetry","debug","require","anonymousId","getAnonymousId","sessionId","crypto","randomUUID","userId","strategy","context","createContext","client","FetchDetachedClient","earlyRecords","actor","setStrategy","env","EXPO_NO_TELEMETRY_DETACH","initialize","createClientFromStrategy","abort","forEach","record","isInitialized","userHash","undefined","hashUserId","flushEarlyRecords","length","recordInternal","records","agent","getAgentTelemetryContext","map","type","sentAt","Date","messageId","createMessageId","mode","Array","isArray","push","flush","flushOnExit","FetchClient","uuid","md5","createHash","update","JSON","stringify","digest"],"mappings":";;;;+
|
|
1
|
+
{"version":3,"sources":["../../../../src/utils/telemetry/Telemetry.ts"],"sourcesContent":["import crypto from 'node:crypto';\n\nimport { FetchClient } from './clients/FetchClient';\nimport { FetchDetachedClient } from './clients/FetchDetachedClient';\nimport type { TelemetryClient, TelemetryClientStrategy, TelemetryRecord } from './types';\nimport { getAgentTelemetryContext } from './utils/agent';\nimport { createContext } from './utils/context';\nimport { getSandboxTelemetryContext } from './utils/sandbox';\nimport { getAnonymousId } from '../../api/user/UserSettings';\nimport { env } from '../env';\n\nconst debug = require('debug')('expo:telemetry') as typeof console.log;\n\ntype TelemetryOptions = {\n /** A locally generated ID, untracable to an actual user */\n anonymousId?: string;\n /** A locally generated ID, per CLI invocation */\n sessionId?: string;\n /** The authenticated user ID, this is used to generate an untracable hash */\n userId?: string;\n /** The underlying telemetry strategy to use */\n strategy?: TelemetryClientStrategy;\n};\n\ntype TelemetryActor = Required<Pick<TelemetryOptions, 'anonymousId' | 'sessionId'>> & {\n /**\n * Hashed version of the user ID, untracable to an actual user.\n * If this value is set to `undefined`, telemetry is considered uninitialized and will wait until its set.\n * If this value is set to `null`, telemetry is considered initialized without an authenticated user.\n * If this value is set to a string, telemetry is considered initialized with an authenticated user.\n */\n userHash?: string | null;\n};\n\nexport class Telemetry {\n private context = createContext();\n private client: TelemetryClient = new FetchDetachedClient();\n private actor: TelemetryActor;\n\n /** A list of all events, recorded before the telemetry was fully initialized */\n private earlyRecords: TelemetryRecord[] = [];\n\n constructor({\n anonymousId = getAnonymousId(),\n sessionId = crypto.randomUUID(),\n userId,\n strategy = 'detached',\n }: TelemetryOptions = {}) {\n this.actor = { anonymousId, sessionId };\n this.setStrategy(env.EXPO_NO_TELEMETRY_DETACH ? 'debug' : strategy);\n\n if (userId) {\n this.initialize({ userId });\n }\n }\n\n get strategy() {\n return this.client.strategy;\n }\n\n setStrategy(strategy: TelemetryOptions['strategy']) {\n // Abort when client is already using the correct strategy\n if (this.client.strategy === strategy) return;\n // Abort when debugging the telemetry\n if (env.EXPO_NO_TELEMETRY_DETACH && strategy !== 'debug') return;\n\n debug('Switching strategy from %s to %s', this.client.strategy, strategy);\n\n // Load and instantiate the correct client, based on strategy\n const client = createClientFromStrategy(strategy);\n // Replace the client, and re-record any pending records\n this.client.abort().forEach((record) => client.record([record]));\n this.client = client;\n\n return this;\n }\n\n get isInitialized() {\n return this.actor.userHash !== undefined;\n }\n\n initialize({ userId }: { userId: string | null }) {\n this.actor.userHash = userId ? hashUserId(userId) : null;\n this.flushEarlyRecords();\n }\n\n private flushEarlyRecords() {\n if (this.earlyRecords.length) {\n this.recordInternal(this.earlyRecords);\n this.earlyRecords = [];\n }\n }\n\n private recordInternal(records: TelemetryRecord[]) {\n const agent = getAgentTelemetryContext();\n const sandboxProvider = getSandboxTelemetryContext();\n\n return this.client.record(\n records.map((record) => ({\n ...record,\n type: 'track' as const,\n sentAt: new Date(),\n messageId: createMessageId(record),\n anonymousId: this.actor.anonymousId,\n userHash: this.actor.userHash,\n context: {\n ...this.context,\n sessionId: this.actor.sessionId,\n ...(sandboxProvider ? { sandbox_provider: sandboxProvider } : {}),\n ...(agent ? { agent } : {}),\n client: { mode: this.client.strategy },\n },\n }))\n );\n }\n\n record(record: TelemetryRecord | TelemetryRecord[]) {\n const records = Array.isArray(record) ? record : [record];\n\n debug('Recording %d event(s)', records.length);\n\n if (!this.isInitialized) {\n this.earlyRecords.push(...records);\n return;\n }\n\n return this.recordInternal(records);\n }\n\n flush() {\n debug('Flushing events...');\n this.flushEarlyRecords();\n return this.client.flush();\n }\n\n flushOnExit() {\n this.setStrategy('detached');\n this.flushEarlyRecords();\n return this.client.flush();\n }\n}\n\nfunction createClientFromStrategy(strategy: TelemetryOptions['strategy']) {\n // When debugging, use the actual Rudderstack client, but lazy load it\n if (env.EXPO_NO_TELEMETRY_DETACH || strategy === 'debug' || strategy === 'instant') {\n return new FetchClient();\n }\n\n return new FetchDetachedClient();\n}\n\n/** Generate a unique message ID using a random hash and UUID */\nfunction createMessageId(record: TelemetryRecord) {\n const uuid = crypto.randomUUID();\n const md5 = crypto.createHash('md5').update(JSON.stringify(record)).digest('hex');\n\n return `node-${md5}-${uuid}`;\n}\n\n/** Hash the user identifier to make it untracable */\nfunction hashUserId(userId: string) {\n return crypto.createHash('sha256').update(userId).digest('hex');\n}\n"],"names":["Telemetry","debug","require","anonymousId","getAnonymousId","sessionId","crypto","randomUUID","userId","strategy","context","createContext","client","FetchDetachedClient","earlyRecords","actor","setStrategy","env","EXPO_NO_TELEMETRY_DETACH","initialize","createClientFromStrategy","abort","forEach","record","isInitialized","userHash","undefined","hashUserId","flushEarlyRecords","length","recordInternal","records","agent","getAgentTelemetryContext","sandboxProvider","getSandboxTelemetryContext","map","type","sentAt","Date","messageId","createMessageId","sandbox_provider","mode","Array","isArray","push","flush","flushOnExit","FetchClient","uuid","md5","createHash","update","JSON","stringify","digest"],"mappings":";;;;+BAkCaA;;;eAAAA;;;;gEAlCM;;;;;;6BAES;qCACQ;uBAEK;yBACX;yBACa;8BACZ;qBACX;;;;;;AAEpB,MAAMC,QAAQC,QAAQ,SAAS;AAuBxB,MAAMF;IAQX,YAAY,EACVG,cAAcC,IAAAA,4BAAc,GAAE,EAC9BC,YAAYC,qBAAM,CAACC,UAAU,EAAE,EAC/BC,MAAM,EACNC,WAAW,UAAU,EACJ,GAAG,CAAC,CAAC,CAAE;aAZlBC,UAAUC,IAAAA,sBAAa;aACvBC,SAA0B,IAAIC,wCAAmB;QAGzD,8EAA8E,QACtEC,eAAkC,EAAE;QAQ1C,IAAI,CAACC,KAAK,GAAG;YAAEZ;YAAaE;QAAU;QACtC,IAAI,CAACW,WAAW,CAACC,QAAG,CAACC,wBAAwB,GAAG,UAAUT;QAE1D,IAAID,QAAQ;YACV,IAAI,CAACW,UAAU,CAAC;gBAAEX;YAAO;QAC3B;IACF;IAEA,IAAIC,WAAW;QACb,OAAO,IAAI,CAACG,MAAM,CAACH,QAAQ;IAC7B;IAEAO,YAAYP,QAAsC,EAAE;QAClD,0DAA0D;QAC1D,IAAI,IAAI,CAACG,MAAM,CAACH,QAAQ,KAAKA,UAAU;QACvC,qCA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AC7C,QAAQgD,MAAM,CAAC;AAC3D"}
|
|
@@ -26,7 +26,7 @@ class FetchClient {
|
|
|
26
26
|
this.headers = {
|
|
27
27
|
accept: 'application/json',
|
|
28
28
|
'content-type': 'application/json',
|
|
29
|
-
'user-agent': `expo-cli/${"57.0.
|
|
29
|
+
'user-agent': `expo-cli/${"57.0.15"}`,
|
|
30
30
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
31
31
|
};
|
|
32
32
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "getSandboxTelemetryContext", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return getSandboxTelemetryContext;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
function _sandboxclidetector() {
|
|
12
|
+
const data = require("sandbox-cli-detector");
|
|
13
|
+
_sandboxclidetector = function() {
|
|
14
|
+
return data;
|
|
15
|
+
};
|
|
16
|
+
return data;
|
|
17
|
+
}
|
|
18
|
+
const debug = require('debug')('expo:telemetry:sandbox');
|
|
19
|
+
let sandboxTelemetryContext;
|
|
20
|
+
function getSandboxTelemetryContext() {
|
|
21
|
+
if (sandboxTelemetryContext === undefined) {
|
|
22
|
+
sandboxTelemetryContext = resolveSandboxTelemetryContext();
|
|
23
|
+
}
|
|
24
|
+
return sandboxTelemetryContext;
|
|
25
|
+
}
|
|
26
|
+
function resolveSandboxTelemetryContext() {
|
|
27
|
+
try {
|
|
28
|
+
const { detected, sandbox } = (0, _sandboxclidetector().detectSandbox)();
|
|
29
|
+
if (!detected || sandbox == null) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
return sandbox.id;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
debug('Failed to detect sandbox: %s', (error == null ? void 0 : error.message) ?? error);
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=sandbox.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../src/utils/telemetry/utils/sandbox.ts"],"sourcesContent":["import { detectSandbox } from 'sandbox-cli-detector';\n\nconst debug = require('debug')('expo:telemetry:sandbox') as typeof console.log;\n\ntype SandboxTelemetryContext = string | null;\n\nlet sandboxTelemetryContext: SandboxTelemetryContext | undefined;\n\nexport function getSandboxTelemetryContext(): SandboxTelemetryContext {\n if (sandboxTelemetryContext === undefined) {\n sandboxTelemetryContext = resolveSandboxTelemetryContext();\n }\n\n return sandboxTelemetryContext;\n}\n\nfunction resolveSandboxTelemetryContext(): SandboxTelemetryContext {\n try {\n const { detected, sandbox } = detectSandbox();\n if (!detected || sandbox == null) {\n return null;\n }\n return sandbox.id;\n } catch (error: any) {\n debug('Failed to detect sandbox: %s', error?.message ?? error);\n return null;\n }\n}\n"],"names":["getSandboxTelemetryContext","debug","require","sandboxTelemetryContext","undefined","resolveSandboxTelemetryContext","detected","sandbox","detectSandbox","id","error","message"],"mappings":";;;;+BAQgBA;;;eAAAA;;;;yBARc;;;;;;AAE9B,MAAMC,QAAQC,QAAQ,SAAS;AAI/B,IAAIC;AAEG,SAASH;IACd,IAAIG,4BAA4BC,WAAW;QACzCD,0BAA0BE;IAC5B;IAEA,OAAOF;AACT;AAEA,SAASE;IACP,IAAI;QACF,MAAM,EAAEC,QAAQ,EAAEC,OAAO,EAAE,GAAGC,IAAAA,mCAAa;QAC3C,IAAI,CAACF,YAAYC,WAAW,MAAM;YAChC,OAAO;QACT;QACA,OAAOA,QAAQE,EAAE;IACnB,EAAE,OAAOC,OAAY;QACnBT,MAAM,gCAAgCS,CAAAA,yBAAAA,MAAOC,OAAO,KAAID;QACxD,OAAO;IACT;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "57.0.
|
|
3
|
+
"version": "57.0.15",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "main.js",
|
|
6
6
|
"bin": {
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"@expo/code-signing-certificates": "^0.0.6",
|
|
41
41
|
"@expo/config": "~57.0.7",
|
|
42
|
-
"@expo/config-plugins": "~57.0.
|
|
42
|
+
"@expo/config-plugins": "~57.0.8",
|
|
43
43
|
"@expo/devcert": "^1.2.1",
|
|
44
44
|
"@expo/env": "~2.4.2",
|
|
45
45
|
"@expo/image-utils": "^0.11.4",
|
|
@@ -52,9 +52,9 @@
|
|
|
52
52
|
"@expo/osascript": "^2.7.1",
|
|
53
53
|
"@expo/package-manager": "^1.13.1",
|
|
54
54
|
"@expo/plist": "^0.8.1",
|
|
55
|
-
"@expo/prebuild-config": "^57.0.
|
|
55
|
+
"@expo/prebuild-config": "^57.0.12",
|
|
56
56
|
"@expo/require-utils": "^57.0.4",
|
|
57
|
-
"@expo/router-server": "^57.0.
|
|
57
|
+
"@expo/router-server": "^57.0.6",
|
|
58
58
|
"@expo/schema-utils": "^57.0.2",
|
|
59
59
|
"@expo/spawn-async": "^1.8.0",
|
|
60
60
|
"@expo/ws-tunnel": "^2.0.0",
|
|
@@ -71,12 +71,12 @@
|
|
|
71
71
|
"connect": "^3.7.0",
|
|
72
72
|
"debug": "^4.3.4",
|
|
73
73
|
"dnssd-advertise": "^1.1.4",
|
|
74
|
-
"expo-server": "^57.0.
|
|
74
|
+
"expo-server": "^57.0.3",
|
|
75
75
|
"fetch-nodeshim": "^0.4.10",
|
|
76
76
|
"getenv": "^2.0.0",
|
|
77
77
|
"glob": "^13.0.0",
|
|
78
78
|
"lan-network": "^0.2.1",
|
|
79
|
-
"multitars": "^1.0.
|
|
79
|
+
"multitars": "^1.0.2",
|
|
80
80
|
"node-forge": "^1.3.3",
|
|
81
81
|
"npm-package-arg": "^11.0.0",
|
|
82
82
|
"ora": "^3.4.0",
|
|
@@ -85,6 +85,7 @@
|
|
|
85
85
|
"progress": "^2.0.3",
|
|
86
86
|
"prompts": "^2.3.2",
|
|
87
87
|
"resolve-from": "^5.0.0",
|
|
88
|
+
"sandbox-cli-detector": "^0.2.0",
|
|
88
89
|
"semver": "^7.6.0",
|
|
89
90
|
"send": "^0.19.0",
|
|
90
91
|
"slugify": "^1.3.4",
|
|
@@ -156,13 +157,13 @@
|
|
|
156
157
|
"playwright": "^1.59.0",
|
|
157
158
|
"taskr": "^1.1.0",
|
|
158
159
|
"tree-kill": "^1.2.2",
|
|
159
|
-
"expo": "57.0.
|
|
160
|
+
"expo": "57.0.13",
|
|
160
161
|
"@expo/fingerprint": "0.20.7",
|
|
162
|
+
"expo-modules-autolinking": "57.0.10",
|
|
161
163
|
"expo-module-scripts": "56.0.3",
|
|
162
|
-
"expo-
|
|
163
|
-
"expo-router": "57.0.12"
|
|
164
|
+
"expo-router": "57.0.13"
|
|
164
165
|
},
|
|
165
|
-
"gitHead": "
|
|
166
|
+
"gitHead": "125b8d4472432db3dc4ae047730432d7bd5bd30c",
|
|
166
167
|
"scripts": {
|
|
167
168
|
"build": "taskr",
|
|
168
169
|
"clean": "expo-module clean",
|