diff --git a/.github/integ-config/detox-integ-all.yml b/.github/integ-config/detox-integ-all.yml index 32dc42c76be..9e5115e3558 100644 --- a/.github/integ-config/detox-integ-all.yml +++ b/.github/integ-config/detox-integ-all.yml @@ -4,9 +4,9 @@ - test_name: 'integ_rn_ios_storage_multipart_progress' working_directory: amplify-js-samples-staging/samples/react-native/storage/MultiPartUploadWithProgress timeout_minutes: 120 -- test_name: 'integ_rn_ios_device_tracking' - working_directory: amplify-js-samples-staging/samples/react-native/auth/deviceTracking - timeout_minutes: 120 +#- test_name: 'integ_rn_ios_device_tracking' +# working_directory: amplify-js-samples-staging/samples/react-native/auth/deviceTracking +# timeout_minutes: 120 - test_name: 'integ_rn_ios_datastore_sqlite_adapter' working_directory: amplify-js-samples-staging/samples/react-native/datastore/SQLiteAdapter timeout_minutes: 120 diff --git a/.github/integ-config/integ-all.yml b/.github/integ-config/integ-all.yml index c43ea465c4a..8b99e9b4bea 100644 --- a/.github/integ-config/integ-all.yml +++ b/.github/integ-config/integ-all.yml @@ -892,15 +892,15 @@ tests: yarn_script: ci:next-use-cases-test yarn_script_args: '14' browser: [chrome] - - test_name: integ_next-use-cases-15 - desc: 'Next.js use cases tests with v15' - framework: next - category: ssr-adapter - sample_name: next-use-cases-15 - spec: next-use-cases - yarn_script: ci:next-use-cases-test - yarn_script_args: '15' - browser: [chrome] +# - test_name: integ_next-use-cases-15 +# desc: 'Next.js use cases tests with v15' +# framework: next +# category: ssr-adapter +# sample_name: next-use-cases-15 +# spec: next-use-cases +# yarn_script: ci:next-use-cases-test +# yarn_script_args: '15' +# browser: [chrome] - test_name: integ_next-use-cases-server-auth-14 desc: 'Next.js server-side auth use cases tests with v14' framework: next diff --git a/.github/workflows/push-preid-release.yml b/.github/workflows/push-preid-release.yml index 9837290ed14..4476e51e367 100644 --- a/.github/workflows/push-preid-release.yml +++ b/.github/workflows/push-preid-release.yml @@ -9,7 +9,7 @@ on: push: branches: # Change this to your branch name where "example-preid" corresponds to the preid you want your changes released on - - feat/example-preid-branch/main + - feat/context-cogs jobs: e2e: diff --git a/.gitignore b/.gitignore index 33a707d8cc6..e6295562ff7 100644 --- a/.gitignore +++ b/.gitignore @@ -72,6 +72,9 @@ coverage-ts/ **/.rollup.cache **/buildMeta +# TypeScript build cache +*.tsbuildinfo + # ruby vendor/ Gemfile.lock diff --git a/package.json b/package.json index f8970fb261f..526b7ceacb3 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,8 @@ "packages/react-native/example", "packages/rtn-passkeys", "packages/rtn-passkeys/example", + "packages/rtn-asf", + "packages/rtn-asf/example", "scripts/tsc-compliance-test" ], "nohoist": [ diff --git a/packages/auth/__tests__/providers/cognito/authFlowsWithUserContextData.native.test.ts b/packages/auth/__tests__/providers/cognito/authFlowsWithUserContextData.native.test.ts new file mode 100644 index 00000000000..db89b0deb99 --- /dev/null +++ b/packages/auth/__tests__/providers/cognito/authFlowsWithUserContextData.native.test.ts @@ -0,0 +1,275 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Amplify } from '@aws-amplify/core'; + +import { resetPassword, signIn, signUp } from '../../../src/providers/cognito'; +import { cognitoUserPoolsTokenProvider } from '../../../src/providers/cognito/tokenProvider'; +import { + createForgotPasswordClient, + createInitiateAuthClient, + createRespondToAuthChallengeClient, + createSignUpClient, +} from '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider'; +import * as userContextDataModule from '../../../src/providers/cognito/utils/userContextData'; + +import { authAPITestParams } from './testUtils/authApiTestParams'; + +// Mock service clients +jest.mock( + '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', +); + +// Mock SRP utilities +jest.mock('../../../src/providers/cognito/utils/srp', () => ({ + ...jest.requireActual('../../../src/providers/cognito/utils/srp'), + getAuthenticationHelper: jest.fn(() => ({ + A: { toString: jest.fn() }, + getPasswordAuthenticationKey: jest.fn(), + })), + getSignatureString: jest.fn(), +})); + +// Mock browser detection to simulate React Native environment +jest.mock('@aws-amplify/core/internals/utils', () => ({ + ...jest.requireActual('@aws-amplify/core/internals/utils'), + isBrowser: jest.fn(() => false), +})); + +jest.mock('../../../src/providers/cognito/utils/dispatchSignedInHubEvent'); + +const authConfig = { + Cognito: { + userPoolClientId: '111111-aaaaa-42d8-891d-ee81a1549398', + userPoolId: 'us-west-2_zzzzz', + }, +}; + +describe('Auth flows with UserContextData (React Native)', () => { + const mockEncodedData = 'nativeEncodedContextData123'; + let getUserContextDataSpy: jest.SpyInstance; + + beforeAll(() => { + cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); + Amplify.configure({ Auth: authConfig }); + }); + + beforeEach(() => { + jest.clearAllMocks(); + // Spy on getUserContextData to control its return value + getUserContextDataSpy = jest.spyOn( + userContextDataModule, + 'getUserContextData', + ); + }); + + afterEach(() => { + getUserContextDataSpy.mockRestore(); + }); + + describe('signIn with UserContextData', () => { + const mockInitiateAuth = jest.fn(); + const mockCreateInitiateAuthClient = jest.mocked(createInitiateAuthClient); + const mockRespondToAuthChallenge = jest.fn(); + const mockCreateRespondToAuthChallengeClient = jest.mocked( + createRespondToAuthChallengeClient, + ); + + beforeEach(() => { + mockInitiateAuth.mockResolvedValue({ + ChallengeName: 'PASSWORD_VERIFIER', + Session: '1234234232', + $metadata: {}, + ChallengeParameters: { + USER_ID_FOR_SRP: authAPITestParams.user1.username, + }, + }); + mockCreateInitiateAuthClient.mockReturnValue(mockInitiateAuth); + mockRespondToAuthChallenge.mockResolvedValue( + authAPITestParams.RespondToAuthChallengeCommandOutput, + ); + mockCreateRespondToAuthChallengeClient.mockReturnValue( + mockRespondToAuthChallenge, + ); + }); + + afterEach(() => { + mockInitiateAuth.mockClear(); + mockCreateInitiateAuthClient.mockClear(); + mockRespondToAuthChallenge.mockClear(); + mockCreateRespondToAuthChallengeClient.mockClear(); + }); + + it('should include UserContextData when native module returns data', async () => { + getUserContextDataSpy.mockReturnValue({ EncodedData: mockEncodedData }); + + try { + await signIn({ + username: authAPITestParams.user1.username, + password: authAPITestParams.user1.password, + }); + } catch { + // We only care about the request contents + } + + expect(mockInitiateAuth).toHaveBeenCalledWith( + expect.objectContaining({ + region: 'us-west-2', + }), + expect.objectContaining({ + UserContextData: { + EncodedData: mockEncodedData, + }, + }), + ); + }); + + it('should proceed without UserContextData when native module is unavailable', async () => { + getUserContextDataSpy.mockReturnValue(undefined); + + const result = await signIn({ + username: authAPITestParams.user1.username, + password: authAPITestParams.user1.password, + }); + + expect(result).toEqual(authAPITestParams.signInResult()); + }); + + it('should proceed without UserContextData when native module returns null', async () => { + getUserContextDataSpy.mockReturnValue(undefined); + + const result = await signIn({ + username: authAPITestParams.user1.username, + password: authAPITestParams.user1.password, + }); + + expect(result).toEqual(authAPITestParams.signInResult()); + }); + }); + + describe('signUp with UserContextData', () => { + const mockSignUp = jest.fn(); + const mockCreateSignUpClient = jest.mocked(createSignUpClient); + + beforeEach(() => { + mockSignUp.mockResolvedValue(authAPITestParams.signUpHttpCallResult); + mockCreateSignUpClient.mockReturnValue(mockSignUp); + }); + + afterEach(() => { + mockSignUp.mockClear(); + mockCreateSignUpClient.mockClear(); + }); + + it('should include UserContextData when native module returns data', async () => { + getUserContextDataSpy.mockReturnValue({ EncodedData: mockEncodedData }); + + await signUp({ + username: authAPITestParams.user1.username, + password: authAPITestParams.user1.password, + options: { + userAttributes: { email: authAPITestParams.user1.email }, + }, + }); + + expect(mockSignUp).toHaveBeenCalledWith( + expect.objectContaining({ + region: 'us-west-2', + }), + expect.objectContaining({ + UserContextData: { + EncodedData: mockEncodedData, + }, + }), + ); + }); + + it('should proceed without UserContextData when native module is unavailable', async () => { + getUserContextDataSpy.mockReturnValue(undefined); + + const result = await signUp({ + username: authAPITestParams.user1.username, + password: authAPITestParams.user1.password, + options: { + userAttributes: { email: authAPITestParams.user1.email }, + }, + }); + + expect(result.isSignUpComplete).toBe(false); + expect(result.nextStep.signUpStep).toBe('CONFIRM_SIGN_UP'); + }); + + it('should proceed without UserContextData when native module returns null', async () => { + getUserContextDataSpy.mockReturnValue(undefined); + + const result = await signUp({ + username: authAPITestParams.user1.username, + password: authAPITestParams.user1.password, + options: { + userAttributes: { email: authAPITestParams.user1.email }, + }, + }); + + expect(result.isSignUpComplete).toBe(false); + expect(result.nextStep.signUpStep).toBe('CONFIRM_SIGN_UP'); + }); + }); + + describe('forgotPassword (resetPassword) with UserContextData', () => { + const mockForgotPassword = jest.fn(); + const mockCreateForgotPasswordClient = jest.mocked( + createForgotPasswordClient, + ); + + beforeEach(() => { + mockForgotPassword.mockResolvedValue( + authAPITestParams.resetPasswordHttpCallResult, + ); + mockCreateForgotPasswordClient.mockReturnValue(mockForgotPassword); + }); + + afterEach(() => { + mockForgotPassword.mockClear(); + mockCreateForgotPasswordClient.mockClear(); + }); + + it('should include UserContextData when native module returns data', async () => { + getUserContextDataSpy.mockReturnValue({ EncodedData: mockEncodedData }); + + await resetPassword({ + username: authAPITestParams.user1.username, + }); + + expect(mockForgotPassword).toHaveBeenCalledWith( + expect.objectContaining({ + region: 'us-west-2', + }), + expect.objectContaining({ + UserContextData: { + EncodedData: mockEncodedData, + }, + }), + ); + }); + + it('should proceed without UserContextData when native module is unavailable', async () => { + getUserContextDataSpy.mockReturnValue(undefined); + + const result = await resetPassword({ + username: authAPITestParams.user1.username, + }); + + expect(result).toEqual(authAPITestParams.resetPasswordResult); + }); + + it('should proceed without UserContextData when native module returns null', async () => { + getUserContextDataSpy.mockReturnValue(undefined); + + const result = await resetPassword({ + username: authAPITestParams.user1.username, + }); + + expect(result).toEqual(authAPITestParams.resetPasswordResult); + }); + }); +}); diff --git a/packages/auth/__tests__/providers/cognito/utils/userContextData.native.property.test.ts b/packages/auth/__tests__/providers/cognito/utils/userContextData.native.property.test.ts new file mode 100644 index 00000000000..d9e74bec04d --- /dev/null +++ b/packages/auth/__tests__/providers/cognito/utils/userContextData.native.property.test.ts @@ -0,0 +1,98 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import * as fc from 'fast-check'; +import { loadAmplifyRtnAsf } from '@aws-amplify/react-native'; + +import { getUserContextData } from '../../../../src/providers/cognito/utils/userContextData.native'; + +// Mock the @aws-amplify/react-native module +jest.mock('@aws-amplify/react-native', () => ({ + loadAmplifyRtnAsf: jest.fn(), +})); + +const mockLoadAmplifyRtnAsf = loadAmplifyRtnAsf as jest.Mock; + +/** + * **Feature: native-asf-context-data, Property 3: Output Format Transformation** + * **Validates: Requirements 3.2** + */ +describe('getUserContextData Property Tests', () => { + const mockGetContextData = jest.fn(); + + beforeEach(() => { + jest.clearAllMocks(); + // Reset default mock setup + mockLoadAmplifyRtnAsf.mockReturnValue({ + getContextData: mockGetContextData, + }); + }); + + it('Property 3: Output Format Transformation - returns object with EncodedData property', () => { + fc.assert( + fc.property(fc.string({ minLength: 1 }), encodedData => { + mockGetContextData.mockReturnValue(encodedData); + + const result = getUserContextData({ + username: 'testuser', + userPoolId: 'us-east-1_testpool', + userPoolClientId: 'testclientid', + }); + + expect(result).toBeDefined(); + expect(result).toEqual({ EncodedData: encodedData }); + expect(Object.keys(result!).length).toBe(1); + expect(result!.EncodedData).toBe(encodedData); + }), + { numRuns: 100 }, + ); + }); + + /** + * **Feature: native-asf-context-data, Property 4: Null to Undefined Mapping** + * **Validates: Requirements 3.3, 3.4** + */ + it('Property 4: Null to Undefined Mapping - returns undefined when native module returns null', () => { + fc.assert( + fc.property( + fc.record({ + username: fc.string({ minLength: 1 }), + userPoolId: fc.string({ minLength: 1 }), + userPoolClientId: fc.string({ minLength: 1 }), + }), + params => { + mockGetContextData.mockReturnValue(null); + + const result = getUserContextData(params); + + expect(result).toBeUndefined(); + }, + ), + { numRuns: 100 }, + ); + }); + + /** + * **Feature: native-asf-context-data, Property 4: Null to Undefined Mapping** + * **Validates: Requirements 3.3, 3.4** + */ + it('Property 4: Null to Undefined Mapping - returns undefined when native module is unavailable', () => { + fc.assert( + fc.property( + fc.record({ + username: fc.string({ minLength: 1 }), + userPoolId: fc.string({ minLength: 1 }), + userPoolClientId: fc.string({ minLength: 1 }), + }), + params => { + mockLoadAmplifyRtnAsf.mockReturnValue(undefined); + + const result = getUserContextData(params); + + expect(result).toBeUndefined(); + }, + ), + { numRuns: 100 }, + ); + }); +}); diff --git a/packages/auth/__tests__/providers/cognito/utils/userContextData.native.test.ts b/packages/auth/__tests__/providers/cognito/utils/userContextData.native.test.ts new file mode 100644 index 00000000000..294dc18fd28 --- /dev/null +++ b/packages/auth/__tests__/providers/cognito/utils/userContextData.native.test.ts @@ -0,0 +1,140 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { loadAmplifyRtnAsf } from '@aws-amplify/react-native'; + +import { getUserContextData } from '../../../../src/providers/cognito/utils/userContextData.native'; + +// Mock the @aws-amplify/react-native module +jest.mock('@aws-amplify/react-native', () => ({ + loadAmplifyRtnAsf: jest.fn(), +})); + +const mockLoadAmplifyRtnAsf = loadAmplifyRtnAsf as jest.Mock; + +describe('getUserContextData.native', () => { + const mockGetContextData = jest.fn(); + const defaultParams = { + username: 'testuser', + userPoolId: 'us-east-1_testpool', + userPoolClientId: 'testclientid', + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('when native module returns data', () => { + it('returns { EncodedData } with the encoded string', () => { + const encodedData = 'base64EncodedContextData'; + mockLoadAmplifyRtnAsf.mockReturnValue({ + getContextData: mockGetContextData, + }); + mockGetContextData.mockReturnValue(encodedData); + + const result = getUserContextData(defaultParams); + + expect(result).toEqual({ EncodedData: encodedData }); + }); + + it('calls getContextData with userPoolId and userPoolClientId', () => { + mockLoadAmplifyRtnAsf.mockReturnValue({ + getContextData: mockGetContextData, + }); + mockGetContextData.mockReturnValue('encodedData'); + + getUserContextData(defaultParams); + + expect(mockGetContextData).toHaveBeenCalledWith( + defaultParams.userPoolId, + defaultParams.userPoolClientId, + ); + }); + }); + + describe('when native module is unavailable', () => { + it('returns undefined when loadAmplifyRtnAsf returns undefined', () => { + mockLoadAmplifyRtnAsf.mockReturnValue(undefined); + + const result = getUserContextData(defaultParams); + + expect(result).toBeUndefined(); + }); + + it('returns undefined when loadAmplifyRtnAsf returns null', () => { + mockLoadAmplifyRtnAsf.mockReturnValue(null); + + const result = getUserContextData(defaultParams); + + expect(result).toBeUndefined(); + }); + }); + + describe('when native module returns null', () => { + it('returns undefined when getContextData returns null', () => { + mockLoadAmplifyRtnAsf.mockReturnValue({ + getContextData: mockGetContextData, + }); + mockGetContextData.mockReturnValue(null); + + const result = getUserContextData(defaultParams); + + expect(result).toBeUndefined(); + }); + + it('returns undefined when getContextData returns empty string', () => { + mockLoadAmplifyRtnAsf.mockReturnValue({ + getContextData: mockGetContextData, + }); + mockGetContextData.mockReturnValue(''); + + const result = getUserContextData(defaultParams); + + expect(result).toBeUndefined(); + }); + }); + + describe('when module loader fails', () => { + it('does not throw when loadAmplifyRtnAsf throws an error', () => { + mockLoadAmplifyRtnAsf.mockImplementation(() => { + throw new Error('Module not found'); + }); + + expect(() => getUserContextData(defaultParams)).not.toThrow(); + }); + + it('returns undefined when loadAmplifyRtnAsf throws an error', () => { + mockLoadAmplifyRtnAsf.mockImplementation(() => { + throw new Error('Module not found'); + }); + + const result = getUserContextData(defaultParams); + + expect(result).toBeUndefined(); + }); + + it('returns undefined when getContextData throws an error', () => { + mockLoadAmplifyRtnAsf.mockReturnValue({ + getContextData: mockGetContextData, + }); + mockGetContextData.mockImplementation(() => { + throw new Error('Native module error'); + }); + + const result = getUserContextData(defaultParams); + + expect(result).toBeUndefined(); + }); + + it('does not throw when getContextData throws an error', () => { + mockLoadAmplifyRtnAsf.mockReturnValue({ + getContextData: mockGetContextData, + }); + mockGetContextData.mockImplementation(() => { + throw new Error('Native module error'); + }); + + expect(() => getUserContextData(defaultParams)).not.toThrow(); + }); + }); +}); diff --git a/packages/auth/package.json b/packages/auth/package.json index 568291e37ef..9aab7970adc 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -107,6 +107,7 @@ "devDependencies": { "@aws-amplify/core": "6.15.0", "@aws-amplify/react-native": "1.3.1", - "@jest/test-sequencer": "^29.7.0" + "@jest/test-sequencer": "^29.7.0", + "fast-check": "^3.15.0" } } diff --git a/packages/auth/src/providers/cognito/utils/userContextData.native.ts b/packages/auth/src/providers/cognito/utils/userContextData.native.ts index 9268cba0d02..d46ec289a8c 100644 --- a/packages/auth/src/providers/cognito/utils/userContextData.native.ts +++ b/packages/auth/src/providers/cognito/utils/userContextData.native.ts @@ -1,12 +1,29 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -// TODO: add support after https://amazon-cognito-assets.us-east-1.amazoncognito.com/amazon-cognito-advanced-security-data.min.js can be imported +import { loadAmplifyRtnAsf } from '@aws-amplify/react-native'; -export function getUserContextData(_: { +export function getUserContextData({ + userPoolId, + userPoolClientId, +}: { username: string; userPoolId: string; userPoolClientId: string; -}) { - return undefined; +}): { EncodedData: string } | undefined { + try { + const asfModule = loadAmplifyRtnAsf(); + if (!asfModule) { + return undefined; + } + + const encodedData = asfModule.getContextData(userPoolId, userPoolClientId); + if (!encodedData) { + return undefined; + } + + return { EncodedData: encodedData }; + } catch { + return undefined; + } } diff --git a/packages/react-native/__tests__/loadAmplifyRtnAsf.property.test.ts b/packages/react-native/__tests__/loadAmplifyRtnAsf.property.test.ts new file mode 100644 index 00000000000..16f2ccd78c6 --- /dev/null +++ b/packages/react-native/__tests__/loadAmplifyRtnAsf.property.test.ts @@ -0,0 +1,46 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import * as fc from 'fast-check'; + +/** + * **Feature: native-asf-context-data, Property 5: Module Loader Graceful Degradation** + * **Validates: Requirements 7.1** + */ +describe('loadAmplifyRtnAsf Property Tests', () => { + beforeEach(() => { + jest.resetModules(); + jest.clearAllMocks(); + }); + + it('Property 5: Module Loader Graceful Degradation - returns undefined when package not installed', () => { + fc.assert( + fc.property( + fc.oneof( + fc.constant(new Error('Cannot find module')), + fc.constant(new Error('Module not found')), + fc.constant(new Error('Cannot resolve module')), + fc.constant(new TypeError('Cannot read property')), + fc.constant(new ReferenceError('module is not defined')), + fc.constant(new Error("Cannot find module '@aws-amplify/rtn-asf'")), + fc.constant(new Error('Unable to resolve module')), + ), + error => { + jest.doMock('@aws-amplify/rtn-asf', () => { + throw error; + }); + + const { + loadAmplifyRtnAsf, + } = require('../src/moduleLoaders/loadAmplifyRtnAsf'); + const result = loadAmplifyRtnAsf(); + + expect(result).toBeUndefined(); + + jest.resetModules(); + }, + ), + { numRuns: 100 }, + ); + }); +}); diff --git a/packages/react-native/__tests__/moduleLoaders.test.ts b/packages/react-native/__tests__/moduleLoaders.test.ts index 5baa1effae1..38936fa7538 100644 --- a/packages/react-native/__tests__/moduleLoaders.test.ts +++ b/packages/react-native/__tests__/moduleLoaders.test.ts @@ -237,4 +237,40 @@ describe('Module Loaders', () => { ); }); }); + + describe('loadAmplifyRtnAsf', () => { + it('should return module when package is installed', () => { + const mockModule = { getContextData: jest.fn() }; + jest.doMock('@aws-amplify/rtn-asf', () => ({ + module: mockModule, + })); + + const { + loadAmplifyRtnAsf, + } = require('../src/moduleLoaders/loadAmplifyRtnAsf'); + expect(loadAmplifyRtnAsf()).toBe(mockModule); + }); + + it('should return undefined when package is not installed', () => { + jest.doMock('@aws-amplify/rtn-asf', () => { + throw new Error('Cannot find module'); + }); + + const { + loadAmplifyRtnAsf, + } = require('../src/moduleLoaders/loadAmplifyRtnAsf'); + expect(loadAmplifyRtnAsf()).toBeUndefined(); + }); + + it('should return undefined when require throws', () => { + jest.doMock('@aws-amplify/rtn-asf', () => { + throw new Error('Cannot resolve module undefined'); + }); + + const { + loadAmplifyRtnAsf, + } = require('../src/moduleLoaders/loadAmplifyRtnAsf'); + expect(loadAmplifyRtnAsf()).toBeUndefined(); + }); + }); }); diff --git a/packages/react-native/package.json b/packages/react-native/package.json index d0c02e460c2..93e9d5cf443 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -32,22 +32,28 @@ "react-native-url-polyfill": "^3.0.0" }, "peerDependencies": { + "@aws-amplify/rtn-asf": "^1.0.0", "@aws-amplify/rtn-passkeys": "^1.0.0", "react-native": ">=0.70", "react-native-get-random-values": ">=1.8.0" }, "peerDependenciesMeta": { + "@aws-amplify/rtn-asf": { + "optional": true + }, "@aws-amplify/rtn-passkeys": { "optional": true } }, "devDependencies": { + "@aws-amplify/rtn-asf": "1.0.0", "@aws-amplify/rtn-passkeys": "1.1.1", "@aws-amplify/rtn-push-notification": "1.3.0", "@aws-amplify/rtn-web-browser": "1.3.0", "@react-native-async-storage/async-storage": "^1.17.12", "@react-native-community/netinfo": "4.7.0", "@types/base-64": "1.0.0", + "fast-check": "^3.15.0", "react-native": "0.72.17", "react-native-get-random-values": "1.9.0" }, diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index 8e6efdcde04..08e13af0f05 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -9,6 +9,7 @@ export { getIsNativeError, } from './apis'; export { + loadAmplifyRtnAsf, loadAmplifyRtnPasskeys, loadAmplifyPushNotification, loadAmplifyWebBrowser, diff --git a/packages/react-native/src/moduleLoaders/index.ts b/packages/react-native/src/moduleLoaders/index.ts index 7896de5c53f..0bfe6dec6eb 100644 --- a/packages/react-native/src/moduleLoaders/index.ts +++ b/packages/react-native/src/moduleLoaders/index.ts @@ -1,6 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +export { loadAmplifyRtnAsf } from './loadAmplifyRtnAsf'; export { loadAmplifyRtnPasskeys } from './loadAmplifyRtnPasskeys'; export { loadAmplifyPushNotification } from './loadAmplifyPushNotification'; export { loadAmplifyWebBrowser } from './loadAmplifyWebBrowser'; diff --git a/packages/react-native/src/moduleLoaders/loadAmplifyRtnAsf.ts b/packages/react-native/src/moduleLoaders/loadAmplifyRtnAsf.ts new file mode 100644 index 00000000000..e97979e5905 --- /dev/null +++ b/packages/react-native/src/moduleLoaders/loadAmplifyRtnAsf.ts @@ -0,0 +1,18 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { AmplifyRtnAsfModule } from '@aws-amplify/rtn-asf'; + +export const loadAmplifyRtnAsf = (): AmplifyRtnAsfModule | undefined => { + try { + // metro bundler requires static string for loading module. + // See: https://facebook.github.io/metro/docs/configuration/#dynamicdepsinpackages + const module = require('@aws-amplify/rtn-asf')?.module; + + return module as AmplifyRtnAsfModule | undefined; + } catch { + // Module not installed or linking failed - return undefined for graceful degradation. + // If @aws-amplify/rtn-asf is expected, ensure it is installed and linked. + return undefined; + } +}; diff --git a/packages/rtn-asf/AmplifyRtnAsf.podspec b/packages/rtn-asf/AmplifyRtnAsf.podspec new file mode 100644 index 00000000000..b6bdb56355c --- /dev/null +++ b/packages/rtn-asf/AmplifyRtnAsf.podspec @@ -0,0 +1,39 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +require "json" + +package = JSON.parse(File.read(File.join(__dir__, "package.json"))) +folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32' + +Pod::Spec.new do |s| + s.name = "AmplifyRtnAsf" + s.version = package["version"] + s.summary = package["description"] + s.homepage = package["homepage"] + s.license = package["license"] + s.authors = package["author"] + + s.platforms = { :ios => '15.1' } + s.source = { :git => "https://github.com/aws-amplify/amplify-js.git", :tag => "#{s.version}" } + + s.source_files = "ios/**/*.{h,m,mm,cpp,swift}" + s.exclude_files = [ 'ios/tests' ] + s.private_header_files = "ios/generated/**/*.h" + + # ASF SDK dependency for device context data collection + # Note: AWSCognitoIdentityProviderASF is an Objective-C pod without module maps, + # so we need to enable modular headers for Swift interop + s.dependency 'AWSCognitoIdentityProviderASF', '~> 2.0' + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES' + } + + install_modules_dependencies(s) + + s.test_spec 'tests' do |test_spec| + test_spec.source_files = 'ios/tests/*.swift' + test_spec.frameworks = 'XCTest' + end +end diff --git a/packages/rtn-asf/README.md b/packages/rtn-asf/README.md new file mode 100644 index 00000000000..e9cddd68c43 --- /dev/null +++ b/packages/rtn-asf/README.md @@ -0,0 +1,101 @@ +# @aws-amplify/rtn-asf + +React Native module for AWS Cognito Advanced Security Features (ASF) context data collection. + +This package provides native modules for iOS and Android that collect device fingerprinting data for Cognito's risk-based authentication. The data is automatically included in authentication flows (sign-in, sign-up, password reset) when this package is installed. + +## Installation + +```bash +npm install @aws-amplify/rtn-asf +# or +yarn add @aws-amplify/rtn-asf +``` + +### iOS Setup + +After installing the package, install the CocoaPods dependencies: + +```bash +cd ios && pod install +``` + +### Android Setup + +No additional setup required. The package uses autolinking. + +## Expo Setup + +This package requires native code and is not compatible with Expo Go. You must use one of the following approaches: + +### Development Build (Recommended) + +Use [Expo Development Client](https://docs.expo.dev/develop/development-builds/introduction/) to create a custom development build that includes native modules: + +```bash +npx expo install @aws-amplify/rtn-asf +npx expo prebuild +npx expo run:ios +# or +npx expo run:android +``` + +### Ejected/Bare Workflow + +If you've ejected from Expo or are using the bare workflow, follow the standard React Native installation steps above. + +## Bare React Native + +This package supports React Native's autolinking. After installation: + +1. **iOS**: Run `pod install` in your `ios` directory +2. **Android**: No additional steps required + +Verify the module is linked by checking: +- **iOS**: `Podfile.lock` contains `AmplifyRtnAsf` +- **Android**: The package appears in your app's dependencies + +## Requirements + +- React Native >= 0.76 (New Architecture / TurboModules) +- iOS 13.0+ +- Android API 24+ + +## Usage + +This package is used internally by `@aws-amplify/auth`. When installed, the auth library automatically detects and uses it to collect device context data for Cognito Advanced Security Features. + +No direct usage is required. Simply install the package and the auth flows will include device fingerprinting data automatically. + +## How It Works + +When you call authentication methods like `signIn`, `signUp`, or `resetPassword`, the Amplify Auth library: + +1. Checks if `@aws-amplify/rtn-asf` is installed +2. If available, calls the native module to collect device context data +3. Includes the encoded data in the Cognito API request +4. Cognito uses this data for risk-based authentication decisions + +If the package is not installed, authentication flows continue normally without the device context data. + +## Troubleshooting + +### Module not found + +If you see errors about the module not being found: + +1. Ensure the package is installed: `npm ls @aws-amplify/rtn-asf` +2. For iOS, run `pod install` in the `ios` directory +3. Rebuild your app completely (not just a hot reload) + +### Expo Go + +This package is not compatible with Expo Go. Use a development build or eject to bare workflow. + +### React Native < 0.76 + +This package requires React Native 0.76 or later for TurboModule support. For older versions, device context data collection is not available. + +## License + +Apache-2.0 diff --git a/packages/rtn-asf/android/build.gradle b/packages/rtn-asf/android/build.gradle new file mode 100644 index 00000000000..bdbd9d7691d --- /dev/null +++ b/packages/rtn-asf/android/build.gradle @@ -0,0 +1,90 @@ +buildscript { + ext.getExtOrDefault = { name -> + return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['AmplifyRtnAsf_' + name] + } + + repositories { + google() + mavenCentral() + } + + dependencies { + classpath "com.android.tools.build:gradle:8.7.3" + // noinspection DifferentKotlinGradleVersion + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}" + } +} + + +apply plugin: "com.android.library" +apply plugin: "kotlin-android" +apply plugin: "com.facebook.react" + +def getExtOrIntegerDefault(name) { + return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["AmplifyRtnAsf_" + name]).toInteger() +} + + +android { + namespace "com.amazonaws.amplify.rtnasf" + + compileSdkVersion getExtOrIntegerDefault("compileSdkVersion") + + defaultConfig { + minSdkVersion getExtOrIntegerDefault("minSdkVersion") + targetSdkVersion getExtOrIntegerDefault("targetSdkVersion") + } + + buildFeatures { + buildConfig true + } + + buildTypes { + release { + minifyEnabled false + } + } + + lintOptions { + disable "GradleCompatible" + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + sourceSets { + main { + java.srcDirs += [ + "generated/java", + "generated/jni" + ] + } + } +} + +repositories { + mavenCentral() + google() +} + +def kotlin_version = getExtOrDefault("kotlinVersion") + +dependencies { + implementation "com.facebook.react:react-android" + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + + // AWS Cognito ASF SDK for device context data collection + implementation "com.amazonaws:aws-android-sdk-cognitoidentityprovider-asf:2.77.0" + + testImplementation "junit:junit:4.13.2" + testImplementation "org.robolectric:robolectric:4.14.1" + testImplementation "io.mockk:mockk:1.14.2" +} + +react { + jsRootDir = file("../src/") + libraryName = "AmplifyRtnAsf" + codegenJavaPackageName = "com.amazonaws.amplify.rtnasf" +} diff --git a/packages/rtn-asf/android/generated/java/com/facebook/fbreact/specs/NativeAmplifyRtnAsfSpec.java b/packages/rtn-asf/android/generated/java/com/facebook/fbreact/specs/NativeAmplifyRtnAsfSpec.java new file mode 100644 index 00000000000..68e61acb22d --- /dev/null +++ b/packages/rtn-asf/android/generated/java/com/facebook/fbreact/specs/NativeAmplifyRtnAsfSpec.java @@ -0,0 +1,38 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateModuleJavaSpec.js + * + * @nolint + */ + +package com.facebook.fbreact.specs; + +import com.facebook.proguard.annotations.DoNotStrip; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.ReactContextBaseJavaModule; +import com.facebook.react.bridge.ReactMethod; +import com.facebook.react.turbomodule.core.interfaces.TurboModule; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public abstract class NativeAmplifyRtnAsfSpec extends ReactContextBaseJavaModule implements TurboModule { + public static final String NAME = "AmplifyRtnAsf"; + + public NativeAmplifyRtnAsfSpec(ReactApplicationContext reactContext) { + super(reactContext); + } + + @Override + public @Nonnull String getName() { + return NAME; + } + + @ReactMethod(isBlockingSynchronousMethod = true) + @DoNotStrip + public abstract @Nullable String getContextData(String userPoolId, String clientId); +} diff --git a/packages/rtn-asf/android/generated/jni/AmplifyRtnAsfSpec-generated.cpp b/packages/rtn-asf/android/generated/jni/AmplifyRtnAsfSpec-generated.cpp new file mode 100644 index 00000000000..96a9cdb0444 --- /dev/null +++ b/packages/rtn-asf/android/generated/jni/AmplifyRtnAsfSpec-generated.cpp @@ -0,0 +1,32 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateModuleJniCpp.js + */ + +#include "AmplifyRtnAsfSpec.h" + +namespace facebook::react { + +static facebook::jsi::Value __hostFunction_NativeAmplifyRtnAsfSpecJSI_getContextData(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + static jmethodID cachedMethodId = nullptr; + return static_cast(turboModule).invokeJavaMethod(rt, StringKind, "getContextData", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", args, count, cachedMethodId); +} + +NativeAmplifyRtnAsfSpecJSI::NativeAmplifyRtnAsfSpecJSI(const JavaTurboModule::InitParams ¶ms) + : JavaTurboModule(params) { + methodMap_["getContextData"] = MethodMetadata {2, __hostFunction_NativeAmplifyRtnAsfSpecJSI_getContextData}; +} + +std::shared_ptr AmplifyRtnAsfSpec_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { + if (moduleName == "AmplifyRtnAsf") { + return std::make_shared(params); + } + return nullptr; +} + +} // namespace facebook::react diff --git a/packages/rtn-asf/android/generated/jni/AmplifyRtnAsfSpec.h b/packages/rtn-asf/android/generated/jni/AmplifyRtnAsfSpec.h new file mode 100644 index 00000000000..5836a598936 --- /dev/null +++ b/packages/rtn-asf/android/generated/jni/AmplifyRtnAsfSpec.h @@ -0,0 +1,31 @@ + +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateModuleJniH.js + */ + +#pragma once + +#include +#include +#include + +namespace facebook::react { + +/** + * JNI C++ class for module 'NativeAmplifyRtnAsf' + */ +class JSI_EXPORT NativeAmplifyRtnAsfSpecJSI : public JavaTurboModule { +public: + NativeAmplifyRtnAsfSpecJSI(const JavaTurboModule::InitParams ¶ms); +}; + + +JSI_EXPORT +std::shared_ptr AmplifyRtnAsfSpec_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); + +} // namespace facebook::react diff --git a/packages/rtn-asf/android/generated/jni/CMakeLists.txt b/packages/rtn-asf/android/generated/jni/CMakeLists.txt new file mode 100644 index 00000000000..c93a9ebf66f --- /dev/null +++ b/packages/rtn-asf/android/generated/jni/CMakeLists.txt @@ -0,0 +1,36 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +cmake_minimum_required(VERSION 3.13) +set(CMAKE_VERBOSE_MAKEFILE on) + +file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/AmplifyRtnAsfSpec/*.cpp) + +add_library( + react_codegen_AmplifyRtnAsfSpec + OBJECT + ${react_codegen_SRCS} +) + +target_include_directories(react_codegen_AmplifyRtnAsfSpec PUBLIC . react/renderer/components/AmplifyRtnAsfSpec) + +target_link_libraries( + react_codegen_AmplifyRtnAsfSpec + fbjni + jsi + # We need to link different libraries based on whether we are building rncore or not, that's necessary + # because we want to break a circular dependency between react_codegen_rncore and reactnative + reactnative +) + +target_compile_options( + react_codegen_AmplifyRtnAsfSpec + PRIVATE + -DLOG_TAG=\"ReactNative\" + -fexceptions + -frtti + -std=c++20 + -Wall +) diff --git a/packages/rtn-asf/android/generated/jni/react/renderer/components/AmplifyRtnAsfSpec/AmplifyRtnAsfSpecJSI-generated.cpp b/packages/rtn-asf/android/generated/jni/react/renderer/components/AmplifyRtnAsfSpec/AmplifyRtnAsfSpecJSI-generated.cpp new file mode 100644 index 00000000000..5773300b82c --- /dev/null +++ b/packages/rtn-asf/android/generated/jni/react/renderer/components/AmplifyRtnAsfSpec/AmplifyRtnAsfSpecJSI-generated.cpp @@ -0,0 +1,29 @@ +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateModuleCpp.js + */ + +#include "AmplifyRtnAsfSpecJSI.h" + +namespace facebook::react { + +static jsi::Value __hostFunction_NativeAmplifyRtnAsfCxxSpecJSI_getContextData(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { + auto result = static_cast(&turboModule)->getContextData( + rt, + count <= 0 ? throw jsi::JSError(rt, "Expected argument in position 0 to be passed") : args[0].asString(rt), + count <= 1 ? throw jsi::JSError(rt, "Expected argument in position 1 to be passed") : args[1].asString(rt) + ); + return result ? jsi::Value(std::move(*result)) : jsi::Value::null(); +} + +NativeAmplifyRtnAsfCxxSpecJSI::NativeAmplifyRtnAsfCxxSpecJSI(std::shared_ptr jsInvoker) + : TurboModule("AmplifyRtnAsf", jsInvoker) { + methodMap_["getContextData"] = MethodMetadata {2, __hostFunction_NativeAmplifyRtnAsfCxxSpecJSI_getContextData}; +} + + +} // namespace facebook::react diff --git a/packages/rtn-asf/android/generated/jni/react/renderer/components/AmplifyRtnAsfSpec/AmplifyRtnAsfSpecJSI.h b/packages/rtn-asf/android/generated/jni/react/renderer/components/AmplifyRtnAsfSpec/AmplifyRtnAsfSpecJSI.h new file mode 100644 index 00000000000..a93d72b3958 --- /dev/null +++ b/packages/rtn-asf/android/generated/jni/react/renderer/components/AmplifyRtnAsfSpec/AmplifyRtnAsfSpecJSI.h @@ -0,0 +1,71 @@ +/** + * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * + * Do not edit this file as changes may cause incorrect behavior and will be lost + * once the code is regenerated. + * + * @generated by codegen project: GenerateModuleH.js + */ + +#pragma once + +#include +#include + +namespace facebook::react { + + + class JSI_EXPORT NativeAmplifyRtnAsfCxxSpecJSI : public TurboModule { +protected: + NativeAmplifyRtnAsfCxxSpecJSI(std::shared_ptr jsInvoker); + +public: + virtual std::optional getContextData(jsi::Runtime &rt, jsi::String userPoolId, jsi::String clientId) = 0; + +}; + +template +class JSI_EXPORT NativeAmplifyRtnAsfCxxSpec : public TurboModule { +public: + jsi::Value create(jsi::Runtime &rt, const jsi::PropNameID &propName) override { + return delegate_.create(rt, propName); + } + + std::vector getPropertyNames(jsi::Runtime& runtime) override { + return delegate_.getPropertyNames(runtime); + } + + static constexpr std::string_view kModuleName = "AmplifyRtnAsf"; + +protected: + NativeAmplifyRtnAsfCxxSpec(std::shared_ptr jsInvoker) + : TurboModule(std::string{NativeAmplifyRtnAsfCxxSpec::kModuleName}, jsInvoker), + delegate_(reinterpret_cast(this), jsInvoker) {} + + +private: + class Delegate : public NativeAmplifyRtnAsfCxxSpecJSI { + public: + Delegate(T *instance, std::shared_ptr jsInvoker) : + NativeAmplifyRtnAsfCxxSpecJSI(std::move(jsInvoker)), instance_(instance) { + + } + + std::optional getContextData(jsi::Runtime &rt, jsi::String userPoolId, jsi::String clientId) override { + static_assert( + bridging::getParameterCount(&T::getContextData) == 3, + "Expected getContextData(...) to have 3 parameters"); + + return bridging::callFromJs>( + rt, &T::getContextData, jsInvoker_, instance_, std::move(userPoolId), std::move(clientId)); + } + + private: + friend class NativeAmplifyRtnAsfCxxSpec; + T *instance_; + }; + + Delegate delegate_; +}; + +} // namespace facebook::react diff --git a/packages/rtn-asf/android/gradle.properties b/packages/rtn-asf/android/gradle.properties new file mode 100644 index 00000000000..e03045b2f73 --- /dev/null +++ b/packages/rtn-asf/android/gradle.properties @@ -0,0 +1,6 @@ +AmplifyRtnAsf_kotlinVersion=2.1.20 +AmplifyRtnAsf_minSdkVersion=24 +AmplifyRtnAsf_targetSdkVersion=34 +AmplifyRtnAsf_compileSdkVersion=35 +AmplifyRtnAsf_ndkVersion=27.1.12297006 +android.useAndroidX=true diff --git a/packages/rtn-asf/android/gradle/wrapper/gradle-wrapper.jar b/packages/rtn-asf/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..41d9927a4d4 Binary files /dev/null and b/packages/rtn-asf/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/rtn-asf/android/gradle/wrapper/gradle-wrapper.properties b/packages/rtn-asf/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..1e2fbf0d458 --- /dev/null +++ b/packages/rtn-asf/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/rtn-asf/android/gradlew b/packages/rtn-asf/android/gradlew new file mode 100755 index 00000000000..1b6c787337f --- /dev/null +++ b/packages/rtn-asf/android/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/rtn-asf/android/gradlew.bat b/packages/rtn-asf/android/gradlew.bat new file mode 100644 index 00000000000..ac1b06f9382 --- /dev/null +++ b/packages/rtn-asf/android/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/rtn-asf/android/src/main/AndroidManifest.xml b/packages/rtn-asf/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..a2f47b6057d --- /dev/null +++ b/packages/rtn-asf/android/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + + diff --git a/packages/rtn-asf/android/src/main/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfModule.kt b/packages/rtn-asf/android/src/main/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfModule.kt new file mode 100644 index 00000000000..132941e9041 --- /dev/null +++ b/packages/rtn-asf/android/src/main/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfModule.kt @@ -0,0 +1,44 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.amplify.rtnasf + +import com.amazonaws.cognito.clientcontext.data.UserContextDataProvider +import com.facebook.fbreact.specs.NativeAmplifyRtnAsfSpec +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.module.annotations.ReactModule + +@ReactModule(name = AmplifyRtnAsfModule.NAME) +class AmplifyRtnAsfModule(reactContext: ReactApplicationContext) : + NativeAmplifyRtnAsfSpec(reactContext) { + + override fun getName(): String = NAME + + companion object { + const val NAME = "AmplifyRtnAsf" + } + + override fun getContextData(userPoolId: String, clientId: String): String? { + // Return null for empty or whitespace-only parameters + // Property 2: Invalid Input Returns Null - validates Requirements 2.4 + if (userPoolId.isBlank() || clientId.isBlank()) { + return null + } + + return try { + // The ASF SDK requires username for the signature, but for device fingerprinting + // purposes we use an empty string as the username is not critical for the + // context data collection - the important data is device fingerprint, not user identity. + // The clientId is used as the signature secret. + UserContextDataProvider.getInstance().getEncodedContextData( + reactApplicationContext, + "", // username - not needed for device fingerprinting + userPoolId, + clientId // signatureSecret + ) + } catch (e: Exception) { + // Return null on any exception to ensure graceful degradation + null + } + } +} diff --git a/packages/rtn-asf/android/src/main/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfPackage.kt b/packages/rtn-asf/android/src/main/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfPackage.kt new file mode 100644 index 00000000000..c499760ba5e --- /dev/null +++ b/packages/rtn-asf/android/src/main/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfPackage.kt @@ -0,0 +1,35 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.amplify.rtnasf + +import com.facebook.react.BaseReactPackage +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.module.model.ReactModuleInfo +import com.facebook.react.module.model.ReactModuleInfoProvider + +class AmplifyRtnAsfPackage : BaseReactPackage() { + override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? { + return if (name == AmplifyRtnAsfModule.NAME) { + AmplifyRtnAsfModule(reactContext) + } else { + null + } + } + + override fun getReactModuleInfoProvider(): ReactModuleInfoProvider { + return ReactModuleInfoProvider { + val moduleInfos: MutableMap = HashMap() + moduleInfos[AmplifyRtnAsfModule.NAME] = ReactModuleInfo( + AmplifyRtnAsfModule.NAME, + AmplifyRtnAsfModule.NAME, + false, // canOverrideExistingModule + false, // needsEagerInit + false, // isCxxModule + true // isTurboModule + ) + moduleInfos + } + } +} diff --git a/packages/rtn-asf/android/src/test/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfModuleTest.kt b/packages/rtn-asf/android/src/test/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfModuleTest.kt new file mode 100644 index 00000000000..3b8fb2526d6 --- /dev/null +++ b/packages/rtn-asf/android/src/test/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfModuleTest.kt @@ -0,0 +1,190 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.amplify.rtnasf + +import com.amazonaws.cognito.clientcontext.data.UserContextDataProvider +import com.facebook.react.bridge.ReactApplicationContext +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkStatic +import io.mockk.unmockkStatic +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class AmplifyRtnAsfModuleTest { + + private lateinit var mockContext: ReactApplicationContext + private lateinit var module: AmplifyRtnAsfModule + + private lateinit var mockProvider: UserContextDataProvider + + @Before + fun setUp() { + mockContext = mockk(relaxed = true) + every { mockContext.applicationContext } returns mockk(relaxed = true) + module = AmplifyRtnAsfModule(mockContext) + + // Mock the UserContextDataProvider singleton + mockProvider = mockk(relaxed = true) + mockkStatic(UserContextDataProvider::class) + every { UserContextDataProvider.getInstance() } returns mockProvider + } + + @After + fun tearDown() { + unmockkStatic(UserContextDataProvider::class) + } + + @Test + fun getName_returnsCorrectName() { + assert(module.name == "AmplifyRtnAsf") { + "Expected module name to be 'AmplifyRtnAsf', but got '${module.name}'" + } + } + + @Test + fun getContextData_withValidInputs_returnsEncodedData() { + val userPoolId = "us-east-1_testPool123" + val clientId = "testClientId456" + val expectedEncodedData = "encodedContextDataString" + + every { + mockProvider.getEncodedContextData(any(), any(), userPoolId, clientId) + } returns expectedEncodedData + + val result = module.getContextData(userPoolId, clientId) + + assert(result == expectedEncodedData) { + "Expected '$expectedEncodedData', but got '$result'" + } + } + + @Test + fun getContextData_withEmptyUserPoolId_returnsNull() { + val result = module.getContextData("", "validClientId") + + assert(result == null) { + "Expected null for empty userPoolId, but got '$result'" + } + } + + @Test + fun getContextData_withWhitespaceUserPoolId_returnsNull() { + val result = module.getContextData(" ", "validClientId") + + assert(result == null) { + "Expected null for whitespace-only userPoolId, but got '$result'" + } + } + + @Test + fun getContextData_withEmptyClientId_returnsNull() { + val result = module.getContextData("us-east-1_validPool", "") + + assert(result == null) { + "Expected null for empty clientId, but got '$result'" + } + } + + @Test + fun getContextData_withWhitespaceClientId_returnsNull() { + val result = module.getContextData("us-east-1_validPool", "\t\n") + + assert(result == null) { + "Expected null for whitespace-only clientId, but got '$result'" + } + } + + @Test + fun getContextData_whenSdkThrowsException_returnsNull() { + val userPoolId = "us-east-1_testPool" + val clientId = "testClientId" + + every { + mockProvider.getEncodedContextData(any(), any(), userPoolId, clientId) + } throws RuntimeException("SDK initialization failed") + + val result = module.getContextData(userPoolId, clientId) + + assert(result == null) { + "Expected null when SDK throws exception, but got '$result'" + } + } + + @Test + fun getContextData_whenSdkThrowsIllegalStateException_returnsNull() { + val userPoolId = "us-east-1_testPool" + val clientId = "testClientId" + + every { + mockProvider.getEncodedContextData(any(), any(), userPoolId, clientId) + } throws IllegalStateException("Context not available") + + val result = module.getContextData(userPoolId, clientId) + + assert(result == null) { + "Expected null when SDK throws IllegalStateException, but got '$result'" + } + } + + @Test + fun getContextData_whenSdkThrowsNullPointerException_returnsNull() { + val userPoolId = "us-east-1_testPool" + val clientId = "testClientId" + + every { + mockProvider.getEncodedContextData(any(), any(), userPoolId, clientId) + } throws NullPointerException("Null context") + + val result = module.getContextData(userPoolId, clientId) + + assert(result == null) { + "Expected null when SDK throws NullPointerException, but got '$result'" + } + } + + @Test + fun getContextData_whenSdkReturnsNull_returnsNull() { + val userPoolId = "us-east-1_testPool" + val clientId = "testClientId" + + every { + mockProvider.getEncodedContextData(any(), any(), userPoolId, clientId) + } returns null + + val result = module.getContextData(userPoolId, clientId) + + assert(result == null) { + "Expected null when SDK returns null, but got '$result'" + } + } + + @Test + fun getContextData_withDifferentRegionFormats_returnsEncodedData() { + val testCases = listOf( + "us-east-1_abc123" to "encodedData1", + "eu-west-1_xyz789" to "encodedData2", + "ap-southeast-1_test" to "encodedData3", + "us-west-2_pool" to "encodedData4" + ) + + for ((userPoolId, expectedData) in testCases) { + every { + mockProvider.getEncodedContextData(any(), any(), userPoolId, "clientId") + } returns expectedData + + val result = module.getContextData(userPoolId, "clientId") + + assert(result == expectedData) { + "Expected '$expectedData' for userPoolId '$userPoolId', but got '$result'" + } + } + } +} diff --git a/packages/rtn-asf/android/src/test/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfPropertyTests.kt b/packages/rtn-asf/android/src/test/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfPropertyTests.kt new file mode 100644 index 00000000000..ee998ac4c1b --- /dev/null +++ b/packages/rtn-asf/android/src/test/kotlin/com/amazonaws/amplify/rtnasf/AmplifyRtnAsfPropertyTests.kt @@ -0,0 +1,186 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.amplify.rtnasf + +import com.amazonaws.cognito.clientcontext.data.UserContextDataProvider +import com.facebook.react.bridge.ReactApplicationContext +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkStatic +import io.mockk.unmockkStatic +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import kotlin.random.Random + +/** + * **Feature: native-asf-context-data, Property 2: Invalid Input Returns Null** + * **Validates: Requirements 2.4** + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class AmplifyRtnAsfPropertyTests { + + private lateinit var mockContext: ReactApplicationContext + private lateinit var module: AmplifyRtnAsfModule + + private lateinit var mockProvider: UserContextDataProvider + + @Before + fun setUp() { + mockContext = mockk(relaxed = true) + every { mockContext.applicationContext } returns mockk(relaxed = true) + module = AmplifyRtnAsfModule(mockContext) + + // Mock the UserContextDataProvider singleton + mockProvider = mockk(relaxed = true) + mockkStatic(UserContextDataProvider::class) + every { UserContextDataProvider.getInstance() } returns mockProvider + } + + @After + fun tearDown() { + unmockkStatic(UserContextDataProvider::class) + } + + private fun generateInvalidInputs(): List { + val inputs = mutableListOf() + + // Empty string + inputs.add("") + + // Single whitespace characters + inputs.add(" ") + inputs.add("\t") + inputs.add("\n") + inputs.add("\r") + inputs.add("\r\n") + + // Multiple whitespace characters + for (count in 2..10) { + inputs.add(" ".repeat(count)) + inputs.add("\t".repeat(count)) + } + + // Mixed whitespace + inputs.add(" \t") + inputs.add("\t ") + inputs.add(" \n ") + inputs.add("\t\n\r") + inputs.add(" \t\t ") + inputs.add("\n\n\n") + inputs.add(" \t \n \r ") + + // Random length whitespace strings (property-based approach) + val whitespaceChars = listOf(" ", "\t", "\n", "\r") + for (i in 0 until 50) { + val length = Random.nextInt(1, 21) + val randomWhitespace = StringBuilder() + for (j in 0 until length) { + randomWhitespace.append(whitespaceChars.random()) + } + inputs.add(randomWhitespace.toString()) + } + + return inputs + } + + private fun generateValidInputs(): List { + return listOf( + "us-east-1_abc123", + "eu-west-1_xyz789", + "ap-southeast-1_test", + "validClientId", + "abc123def456", + "a", + "1", + "test-pool-id", + "client_id_with_underscore" + ) + } + + @Test + fun testGetContextDataWithEmptyUserPoolIdReturnsNull() { + val validClientIds = generateValidInputs() + val invalidUserPoolIds = generateInvalidInputs() + + var testCount = 0 + + // For any empty or whitespace-only userPoolId with any valid clientId + for (invalidUserPoolId in invalidUserPoolIds) { + for (validClientId in validClientIds) { + val result = module.getContextData(invalidUserPoolId, validClientId) + + assert(result == null) { + "Expected null for invalid userPoolId '${invalidUserPoolId.escape()}' " + + "with clientId '$validClientId', but got '$result'" + } + testCount++ + } + } + + // Ensure we ran at least 100 iterations as per design doc requirements + assert(testCount >= 100) { "Property test should run at least 100 iterations, ran $testCount" } + println("Property 2 (empty userPoolId): Ran $testCount test iterations") + } + + @Test + fun testGetContextDataWithEmptyClientIdReturnsNull() { + val validUserPoolIds = generateValidInputs() + val invalidClientIds = generateInvalidInputs() + + var testCount = 0 + + // For any valid userPoolId with any empty or whitespace-only clientId + for (validUserPoolId in validUserPoolIds) { + for (invalidClientId in invalidClientIds) { + val result = module.getContextData(validUserPoolId, invalidClientId) + + assert(result == null) { + "Expected null for userPoolId '$validUserPoolId' " + + "with invalid clientId '${invalidClientId.escape()}', but got '$result'" + } + testCount++ + } + } + + // Ensure we ran at least 100 iterations as per design doc requirements + assert(testCount >= 100) { "Property test should run at least 100 iterations, ran $testCount" } + println("Property 2 (empty clientId): Ran $testCount test iterations") + } + + @Test + fun testGetContextDataWithBothParametersEmptyReturnsNull() { + val invalidInputs = generateInvalidInputs() + + var testCount = 0 + + // For any combination of empty/whitespace-only inputs for both parameters + for (invalidUserPoolId in invalidInputs) { + for (invalidClientId in invalidInputs) { + val result = module.getContextData(invalidUserPoolId, invalidClientId) + + assert(result == null) { + "Expected null for invalid userPoolId '${invalidUserPoolId.escape()}' " + + "with invalid clientId '${invalidClientId.escape()}', but got '$result'" + } + testCount++ + } + } + + // Ensure we ran at least 100 iterations as per design doc requirements + assert(testCount >= 100) { "Property test should run at least 100 iterations, ran $testCount" } + println("Property 2 (both empty): Ran $testCount test iterations") + } + + private fun String.escape(): String { + return this + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + } +} diff --git a/packages/rtn-asf/example/.watchmanconfig b/packages/rtn-asf/example/.watchmanconfig new file mode 100644 index 00000000000..0967ef424bc --- /dev/null +++ b/packages/rtn-asf/example/.watchmanconfig @@ -0,0 +1 @@ +{} diff --git a/packages/rtn-asf/example/Gemfile b/packages/rtn-asf/example/Gemfile new file mode 100644 index 00000000000..6a4c5f17185 --- /dev/null +++ b/packages/rtn-asf/example/Gemfile @@ -0,0 +1,16 @@ +source 'https://rubygems.org' + +# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version +ruby ">= 2.6.10" + +# Exclude problematic versions of cocoapods and activesupport that causes build failures. +gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1' +gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0' +gem 'xcodeproj', '< 1.26.0' +gem 'concurrent-ruby', '< 1.3.4' + +# Ruby 3.4.0 has removed some libraries from the standard library. +gem 'bigdecimal' +gem 'logger' +gem 'benchmark' +gem 'mutex_m' diff --git a/packages/rtn-asf/example/README.md b/packages/rtn-asf/example/README.md new file mode 100644 index 00000000000..ee062d36ea6 --- /dev/null +++ b/packages/rtn-asf/example/README.md @@ -0,0 +1,71 @@ +# @aws-amplify/rtn-asf Example + +This is a React Native example app for testing the `@aws-amplify/rtn-asf` native module. + +## Setup + +1. Install dependencies: +```bash +cd packages/rtn-asf/example +yarn install +``` + +2. For iOS, install pods: +```bash +cd ios +pod install +``` + +## Running the App + +### Android +```bash +yarn android +``` + +### iOS +```bash +yarn ios +``` + +## Running Tests + +### Android Unit Tests +From the `packages/rtn-asf` directory: +```bash +yarn test:android +``` + +Or directly: +```bash +cd example/android +./gradlew test -i +``` + +### iOS Unit Tests +From the `packages/rtn-asf` directory: +```bash +yarn test:ios +``` + +Or directly using xcodebuild: +```bash +xcodebuild test -quiet -workspace example/ios/AmplifyRtnAsfExample.xcworkspace -destination 'platform=iOS Simulator,name=iPhone 16' -scheme AmplifyRtnAsf-Unit-tests +``` + +Note: iOS tests require: +1. Running `pod install` in the `example/ios` directory first +2. An iOS Simulator with iPhone 16 available + +## What This Example Tests + +The example app provides a simple UI to test the ASF context data collection: + +1. **Get Context Data** - Tests calling `getContextData` with valid userPoolId and clientId +2. **Test Empty UserPoolId** - Verifies that empty userPoolId returns null +3. **Test Empty ClientId** - Verifies that empty clientId returns null + +The app displays: +- Whether the native module is available +- The result of each test (context data string or null) +- Any errors that occur diff --git a/packages/rtn-asf/example/android/app/build.gradle b/packages/rtn-asf/example/android/app/build.gradle new file mode 100644 index 00000000000..fe4bead54ec --- /dev/null +++ b/packages/rtn-asf/example/android/app/build.gradle @@ -0,0 +1,132 @@ +apply plugin: "com.android.application" +apply plugin: "org.jetbrains.kotlin.android" +apply plugin: "com.facebook.react" + +/** + * This is the configuration block to customize your React Native Android app. + * By default you don't need to apply any configuration, just uncomment the lines you need. + */ +react { + /* Folders */ + // The root of your project, i.e. where "package.json" lives. Default is '../..' + // root = file("../../") + // The folder where the react-native NPM package is. Default is ../../node_modules/react-native + // reactNativeDir = file("../../node_modules/react-native") + // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen + // codegenDir = file("../../node_modules/@react-native/codegen") + // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js + // cliFile = file("../../node_modules/react-native/cli.js") + + /* Variants */ + // The list of variants to that are debuggable. For those we're going to + // skip the bundling of the JS bundle and the assets. By default is just 'debug'. + // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. + // debuggableVariants = ["liteDebug", "prodDebug"] + + /* Bundling */ + // A list containing the node command and its flags. Default is just 'node'. + // nodeExecutableAndArgs = ["node"] + // + // The command to run when bundling. By default is 'bundle' + // bundleCommand = "ram-bundle" + // + // The path to the CLI configuration file. Default is empty. + // bundleConfig = file(../rn-cli.config.js) + // + // The name of the generated asset file containing your JS bundle + // bundleAssetName = "MyApplication.android.bundle" + // + // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' + // entryFile = file("../js/MyApplication.android.js") + // + // A list of extra flags to pass to the 'bundle' commands. + // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle + // extraPackagerArgs = [] + + /* Hermes Commands */ + // The hermes compiler command to run. By default it is 'hermesc' + // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" + // + // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" + // hermesFlags = ["-O", "-output-source-map"] + + /* Autolinking */ + autolinkLibrariesWithApp() +} + +/** + * Set this to true to Run Proguard on Release builds to minify the Java bytecode. + */ +def enableProguardInReleaseBuilds = false + +/** + * The preferred build flavor of JavaScriptCore (JSC) + * + * For example, to use the international variant, you can use: + * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` + * + * The international variant includes ICU i18n library and necessary data + * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that + * give correct results when using with locales other than en-US. Note that + * this variant is about 6MiB larger per architecture than default. + */ +def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' + +android { + ndkVersion rootProject.ext.ndkVersion + buildToolsVersion rootProject.ext.buildToolsVersion + compileSdk rootProject.ext.compileSdkVersion + + namespace "com.amazonaws.amplify.rtnasf.example" + defaultConfig { + applicationId "com.amazonaws.amplify.rtnasf.example" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0" + } + signingConfigs { + debug { + storeFile file('debug.keystore') + storePassword 'android' + keyAlias 'androiddebugkey' + keyPassword 'android' + } + } + buildTypes { + debug { + signingConfig signingConfigs.debug + } + release { + // Caution! In production, you need to generate your own keystore file. + // see https://reactnative.dev/docs/signed-apk-android. + signingConfig signingConfigs.debug + minifyEnabled enableProguardInReleaseBuilds + proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" + } + } +} + +dependencies { + // The version of react-native is set by the React Native Gradle Plugin + implementation("com.facebook.react:react-android") + + if (hermesEnabled.toBoolean()) { + implementation("com.facebook.react:hermes-android") + } else { + implementation jscFlavor + } +} + +def isNewArchitectureEnabled() { + return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true" +} + +if (isNewArchitectureEnabled()) { + // Since our library doesn't invoke codegen automatically we need to do it here. + tasks.register('invokeLibraryCodegen', Exec) { + workingDir "$rootDir/../../" + commandLine 'sh', '-c', 'yarn codegen:android' + } + preBuild.dependsOn invokeLibraryCodegen +} diff --git a/packages/rtn-asf/example/android/app/debug.keystore b/packages/rtn-asf/example/android/app/debug.keystore new file mode 100644 index 00000000000..364e105ed39 Binary files /dev/null and b/packages/rtn-asf/example/android/app/debug.keystore differ diff --git a/packages/rtn-asf/example/android/app/proguard-rules.pro b/packages/rtn-asf/example/android/app/proguard-rules.pro new file mode 100644 index 00000000000..11b025724a3 --- /dev/null +++ b/packages/rtn-asf/example/android/app/proguard-rules.pro @@ -0,0 +1,10 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: diff --git a/packages/rtn-asf/example/android/app/src/debug/AndroidManifest.xml b/packages/rtn-asf/example/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000000..eb98c01afd7 --- /dev/null +++ b/packages/rtn-asf/example/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/packages/rtn-asf/example/android/app/src/main/AndroidManifest.xml b/packages/rtn-asf/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..f936ac79828 --- /dev/null +++ b/packages/rtn-asf/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + diff --git a/packages/rtn-asf/example/android/app/src/main/java/com/amazonaws/amplify/rtnasf/example/MainActivity.kt b/packages/rtn-asf/example/android/app/src/main/java/com/amazonaws/amplify/rtnasf/example/MainActivity.kt new file mode 100644 index 00000000000..7ba6978ff2b --- /dev/null +++ b/packages/rtn-asf/example/android/app/src/main/java/com/amazonaws/amplify/rtnasf/example/MainActivity.kt @@ -0,0 +1,25 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.amplify.rtnasf.example + +import com.facebook.react.ReactActivity +import com.facebook.react.ReactActivityDelegate +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled +import com.facebook.react.defaults.DefaultReactActivityDelegate + +class MainActivity : ReactActivity() { + + /** + * Returns the name of the main component registered from JavaScript. This is used to schedule + * rendering of the component. + */ + override fun getMainComponentName(): String = "AmplifyRtnAsfExample" + + /** + * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] + * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] + */ + override fun createReactActivityDelegate(): ReactActivityDelegate = + DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) +} diff --git a/packages/rtn-asf/example/android/app/src/main/java/com/amazonaws/amplify/rtnasf/example/MainApplication.kt b/packages/rtn-asf/example/android/app/src/main/java/com/amazonaws/amplify/rtnasf/example/MainApplication.kt new file mode 100644 index 00000000000..e5cebe082d6 --- /dev/null +++ b/packages/rtn-asf/example/android/app/src/main/java/com/amazonaws/amplify/rtnasf/example/MainApplication.kt @@ -0,0 +1,47 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.amazonaws.amplify.rtnasf.example + +import android.app.Application +import com.facebook.react.PackageList +import com.facebook.react.ReactApplication +import com.facebook.react.ReactHost +import com.facebook.react.ReactNativeHost +import com.facebook.react.ReactPackage +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load +import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost +import com.facebook.react.defaults.DefaultReactNativeHost +import com.facebook.react.soloader.OpenSourceMergedSoMapping +import com.facebook.soloader.SoLoader + +class MainApplication : Application(), ReactApplication { + + override val reactNativeHost: ReactNativeHost = + object : DefaultReactNativeHost(this) { + override fun getPackages(): List = + PackageList(this).packages.apply { + // Packages that cannot be autolinked yet can be added manually here, for example: + // add(MyReactNativePackage()) + } + + override fun getJSMainModuleName(): String = "index" + + override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG + + override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED + override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED + } + + override val reactHost: ReactHost + get() = getDefaultReactHost(applicationContext, reactNativeHost) + + override fun onCreate() { + super.onCreate() + SoLoader.init(this, OpenSourceMergedSoMapping) + if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { + // If you opted-in for the New Architecture, we load the native entry point for this app. + load() + } + } +} diff --git a/packages/rtn-asf/example/android/app/src/main/res/drawable/rn_edit_text_material.xml b/packages/rtn-asf/example/android/app/src/main/res/drawable/rn_edit_text_material.xml new file mode 100644 index 00000000000..5c25e728ea2 --- /dev/null +++ b/packages/rtn-asf/example/android/app/src/main/res/drawable/rn_edit_text_material.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + diff --git a/packages/rtn-asf/example/android/app/src/main/res/values/strings.xml b/packages/rtn-asf/example/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000000..bad7d38902d --- /dev/null +++ b/packages/rtn-asf/example/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + AmplifyRtnAsfExample + diff --git a/packages/rtn-asf/example/android/app/src/main/res/values/styles.xml b/packages/rtn-asf/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000000..7ba83a2ad5a --- /dev/null +++ b/packages/rtn-asf/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/packages/rtn-asf/example/android/build.gradle b/packages/rtn-asf/example/android/build.gradle new file mode 100644 index 00000000000..a14f7994911 --- /dev/null +++ b/packages/rtn-asf/example/android/build.gradle @@ -0,0 +1,19 @@ +buildscript { + ext { + buildToolsVersion = "35.0.0" + minSdkVersion = 24 + compileSdkVersion = 35 + targetSdkVersion = 35 + ndkVersion = "27.1.12297006" + kotlinVersion = "2.0.21" + } + repositories { + google() + mavenCentral() + } + dependencies { + classpath("com.android.tools.build:gradle") + classpath("com.facebook.react:react-native-gradle-plugin") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") + } +} diff --git a/packages/rtn-asf/example/android/gradle.properties b/packages/rtn-asf/example/android/gradle.properties new file mode 100644 index 00000000000..5e24e3aa8db --- /dev/null +++ b/packages/rtn-asf/example/android/gradle.properties @@ -0,0 +1,39 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m +org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true + +# Use this property to specify which architecture you want to build. +# You can also override it from the CLI using +# ./gradlew -PreactNativeArchitectures=x86_64 +reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 + +# Use this property to enable support to the new architecture. +# This will allow you to use TurboModules and the Fabric render in +# your application. You should enable this flag either if you want +# to write custom TurboModules/Fabric components OR use libraries that +# are providing them. +newArchEnabled=true + +# Use this property to enable or disable the Hermes JS engine. +# If set to false, you will be using JSC instead. +hermesEnabled=true diff --git a/packages/rtn-asf/example/android/gradle/wrapper/gradle-wrapper.jar b/packages/rtn-asf/example/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..a4b76b9530d Binary files /dev/null and b/packages/rtn-asf/example/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/rtn-asf/example/android/gradle/wrapper/gradle-wrapper.properties b/packages/rtn-asf/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..37f853b1c84 --- /dev/null +++ b/packages/rtn-asf/example/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/rtn-asf/example/android/gradlew b/packages/rtn-asf/example/android/gradlew new file mode 100755 index 00000000000..f3b75f3b0d4 --- /dev/null +++ b/packages/rtn-asf/example/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/rtn-asf/example/android/gradlew.bat b/packages/rtn-asf/example/android/gradlew.bat new file mode 100644 index 00000000000..9b42019c791 --- /dev/null +++ b/packages/rtn-asf/example/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/rtn-asf/example/android/settings.gradle b/packages/rtn-asf/example/android/settings.gradle new file mode 100644 index 00000000000..a381836b7a3 --- /dev/null +++ b/packages/rtn-asf/example/android/settings.gradle @@ -0,0 +1,6 @@ +pluginManagement { includeBuild("../../node_modules/@react-native/gradle-plugin") } +plugins { id("com.facebook.react.settings") } +extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } +rootProject.name = 'com.amazonaws.amplify.rtnasf.example' +include ':app' +includeBuild('../../node_modules/@react-native/gradle-plugin') diff --git a/packages/rtn-asf/example/app.json b/packages/rtn-asf/example/app.json new file mode 100644 index 00000000000..28cb39bea39 --- /dev/null +++ b/packages/rtn-asf/example/app.json @@ -0,0 +1,4 @@ +{ + "name": "AmplifyRtnAsfExample", + "displayName": "AmplifyRtnAsfExample" +} diff --git a/packages/rtn-asf/example/babel.config.js b/packages/rtn-asf/example/babel.config.js new file mode 100644 index 00000000000..903ccef0608 --- /dev/null +++ b/packages/rtn-asf/example/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: ['module:@react-native/babel-preset'], +}; diff --git a/packages/rtn-asf/example/index.js b/packages/rtn-asf/example/index.js new file mode 100644 index 00000000000..733692d9506 --- /dev/null +++ b/packages/rtn-asf/example/index.js @@ -0,0 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { AppRegistry } from 'react-native'; + +import App from './src/App'; +import { name as appName } from './app.json'; + +AppRegistry.registerComponent(appName, () => App); diff --git a/packages/rtn-asf/example/ios/.xcode.env b/packages/rtn-asf/example/ios/.xcode.env new file mode 100644 index 00000000000..3d5782c7156 --- /dev/null +++ b/packages/rtn-asf/example/ios/.xcode.env @@ -0,0 +1,11 @@ +# This `.xcode.env` file is versioned and is used to source the environment +# used when running script phases inside Xcode. +# To customize your local environment, you can create an `.xcode.env.local` +# file that is not versioned. + +# NODE_BINARY variable contains the PATH to the node executable. +# +# Customize the NODE_BINARY variable here. +# For example, to use nvm with brew, add the following line +# . "$(brew --prefix nvm)/nvm.sh" --no-use +export NODE_BINARY=$(command -v node) diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample.xcodeproj/project.pbxproj b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..ad9131b7a59 --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample.xcodeproj/project.pbxproj @@ -0,0 +1,625 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 0C80B921A6F3F58F76C31292 /* libPods-AmplifyRtnAsfExample.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-AmplifyRtnAsfExample.a */; }; + 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; + 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; }; + 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; }; + C6C4B65C3851578AB80D5744 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 1D7533FB2DD2898F00B464C4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 13B07F861A680F5B00A75B9A; + remoteInfo = AmplifyRtnAsfExample; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 13B07F961A680F5B00A75B9A /* AmplifyRtnAsfExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AmplifyRtnAsfExample.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = AmplifyRtnAsfExample/Images.xcassets; sourceTree = ""; }; + 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = AmplifyRtnAsfExample/Info.plist; sourceTree = ""; }; + 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = AmplifyRtnAsfExample/PrivacyInfo.xcprivacy; sourceTree = ""; }; + 1D7533F72DD2898F00B464C4 /* AmplifyRtnAsfExampleTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = AmplifyRtnAsfExampleTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 28B60A264610278F0F5A136A /* Pods-AmplifyRtnAsfExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AmplifyRtnAsfExample.release.xcconfig"; path = "Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample.release.xcconfig"; sourceTree = ""; }; + 35DEFAAFB11EC5A06275E6CA /* Pods-AmplifyRtnAsfExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AmplifyRtnAsfExample.debug.xcconfig"; path = "Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample.debug.xcconfig"; sourceTree = ""; }; + 5DCACB8F33CDC322A6C60F78 /* libPods-AmplifyRtnAsfExample.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-AmplifyRtnAsfExample.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 761780EC2CA45674006654EE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = AmplifyRtnAsfExample/AppDelegate.swift; sourceTree = ""; }; + 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = AmplifyRtnAsfExample/LaunchScreen.storyboard; sourceTree = ""; }; + ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0C80B921A6F3F58F76C31292 /* libPods-AmplifyRtnAsfExample.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1D7533F42DD2898F00B464C4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 13B07FAE1A68108700A75B9A /* AmplifyRtnAsfExample */ = { + isa = PBXGroup; + children = ( + 13B07FB51A68108700A75B9A /* Images.xcassets */, + 761780EC2CA45674006654EE /* AppDelegate.swift */, + 13B07FB61A68108700A75B9A /* Info.plist */, + 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */, + 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */, + ); + name = AmplifyRtnAsfExample; + sourceTree = ""; + }; + 2D16E6871FA4F8E400B85C8A /* Frameworks */ = { + isa = PBXGroup; + children = ( + ED297162215061F000B7C4FE /* JavaScriptCore.framework */, + 5DCACB8F33CDC322A6C60F78 /* libPods-AmplifyRtnAsfExample.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 56E5D2791365D644F24728F6 /* Pods */ = { + isa = PBXGroup; + children = ( + 35DEFAAFB11EC5A06275E6CA /* Pods-AmplifyRtnAsfExample.debug.xcconfig */, + 28B60A264610278F0F5A136A /* Pods-AmplifyRtnAsfExample.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 832341AE1AAA6A7D00B99B32 /* Libraries */ = { + isa = PBXGroup; + children = ( + ); + name = Libraries; + sourceTree = ""; + }; + 83CBB9F61A601CBA00E9B192 = { + isa = PBXGroup; + children = ( + 13B07FAE1A68108700A75B9A /* AmplifyRtnAsfExample */, + 832341AE1AAA6A7D00B99B32 /* Libraries */, + 83CBBA001A601CBA00E9B192 /* Products */, + 2D16E6871FA4F8E400B85C8A /* Frameworks */, + 56E5D2791365D644F24728F6 /* Pods */, + ); + indentWidth = 2; + sourceTree = ""; + tabWidth = 2; + usesTabs = 0; + }; + 83CBBA001A601CBA00E9B192 /* Products */ = { + isa = PBXGroup; + children = ( + 13B07F961A680F5B00A75B9A /* AmplifyRtnAsfExample.app */, + 1D7533F72DD2898F00B464C4 /* AmplifyRtnAsfExampleTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 13B07F861A680F5B00A75B9A /* AmplifyRtnAsfExample */ = { + isa = PBXNativeTarget; + buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "AmplifyRtnAsfExample" */; + buildPhases = ( + C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */, + 13B07F871A680F5B00A75B9A /* Sources */, + 13B07F8C1A680F5B00A75B9A /* Frameworks */, + 13B07F8E1A680F5B00A75B9A /* Resources */, + 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, + 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */, + E235C05ADACE081382539298 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = AmplifyRtnAsfExample; + productName = AmplifyRtnAsfExample; + productReference = 13B07F961A680F5B00A75B9A /* AmplifyRtnAsfExample.app */; + productType = "com.apple.product-type.application"; + }; + 1D7533F62DD2898F00B464C4 /* AmplifyRtnAsfExampleTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1D7533FF2DD2898F00B464C4 /* Build configuration list for PBXNativeTarget "AmplifyRtnAsfExampleTests" */; + buildPhases = ( + 1D7533F32DD2898F00B464C4 /* Sources */, + 1D7533F42DD2898F00B464C4 /* Frameworks */, + 1D7533F52DD2898F00B464C4 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 1D7533FC2DD2898F00B464C4 /* PBXTargetDependency */, + ); + name = AmplifyRtnAsfExampleTests; + productName = AmplifyRtnAsfExampleTests; + productReference = 1D7533F72DD2898F00B464C4 /* AmplifyRtnAsfExampleTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 83CBB9F71A601CBA00E9B192 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1610; + LastUpgradeCheck = 1210; + TargetAttributes = { + 13B07F861A680F5B00A75B9A = { + LastSwiftMigration = 1120; + }; + 1D7533F62DD2898F00B464C4 = { + CreatedOnToolsVersion = 16.1; + TestTargetID = 13B07F861A680F5B00A75B9A; + }; + }; + }; + buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "AmplifyRtnAsfExample" */; + compatibilityVersion = "Xcode 12.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 83CBB9F61A601CBA00E9B192; + productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 13B07F861A680F5B00A75B9A /* AmplifyRtnAsfExample */, + 1D7533F62DD2898F00B464C4 /* AmplifyRtnAsfExampleTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 13B07F8E1A680F5B00A75B9A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */, + 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */, + C6C4B65C3851578AB80D5744 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1D7533F52DD2898F00B464C4 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "$(SRCROOT)/.xcode.env.local", + "$(SRCROOT)/.xcode.env", + ); + name = "Bundle React Native code and images"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\"\n"; + }; + 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-AmplifyRtnAsfExample-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample-resources-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Copy Pods Resources"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample-resources-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-AmplifyRtnAsfExample/Pods-AmplifyRtnAsfExample-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 13B07F871A680F5B00A75B9A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1D7533F32DD2898F00B464C4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 1D7533FC2DD2898F00B464C4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 13B07F861A680F5B00A75B9A /* AmplifyRtnAsfExample */; + targetProxy = 1D7533FB2DD2898F00B464C4 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 13B07F941A680F5B00A75B9A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 35DEFAAFB11EC5A06275E6CA /* Pods-AmplifyRtnAsfExample.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = 1; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = AmplifyRtnAsfExample/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.amazonaws.amplify.rtnasf.example; + PRODUCT_NAME = AmplifyRtnAsfExample; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 13B07F951A680F5B00A75B9A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 28B60A264610278F0F5A136A /* Pods-AmplifyRtnAsfExample.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = 1; + INFOPLIST_FILE = AmplifyRtnAsfExample/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.amazonaws.amplify.rtnasf.example; + PRODUCT_NAME = AmplifyRtnAsfExample; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; + 1D7533FD2DD2898F00B464C4 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = com.amazonaws.amplify.AmplifyRtnAsfExampleTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AmplifyRtnAsfExample.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/AmplifyRtnAsfExample"; + }; + name = Debug; + }; + 1D7533FE2DD2898F00B464C4 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_STYLE = Automatic; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = com.amazonaws.amplify.AmplifyRtnAsfExampleTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AmplifyRtnAsfExample.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/AmplifyRtnAsfExample"; + }; + name = Release; + }; + 83CBBA201A601CBA00E9B192 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_CXX_LANGUAGE_STANDARD = "c++20"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + /usr/lib/swift, + "$(inherited)", + ); + LIBRARY_SEARCH_PATHS = ( + "\"$(SDKROOT)/usr/lib/swift\"", + "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", + "\"$(inherited)\"", + ); + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_CPLUSPLUSFLAGS = ( + "$(OTHER_CFLAGS)", + "-DFOLLY_NO_CONFIG", + "-DFOLLY_MOBILE=1", + "-DFOLLY_USE_LIBCPP=1", + "-DFOLLY_CFG_NO_COROUTINES=1", + "-DFOLLY_HAVE_CLOCK_GETTIME=1", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + " ", + ); + REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native"; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG"; + USE_HERMES = true; + }; + name = Debug; + }; + 83CBBA211A601CBA00E9B192 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_CXX_LANGUAGE_STANDARD = "c++20"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + /usr/lib/swift, + "$(inherited)", + ); + LIBRARY_SEARCH_PATHS = ( + "\"$(SDKROOT)/usr/lib/swift\"", + "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", + "\"$(inherited)\"", + ); + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_CPLUSPLUSFLAGS = ( + "$(OTHER_CFLAGS)", + "-DFOLLY_NO_CONFIG", + "-DFOLLY_MOBILE=1", + "-DFOLLY_USE_LIBCPP=1", + "-DFOLLY_CFG_NO_COROUTINES=1", + "-DFOLLY_HAVE_CLOCK_GETTIME=1", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + " ", + ); + REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native"; + SDKROOT = iphoneos; + USE_HERMES = true; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "AmplifyRtnAsfExample" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 13B07F941A680F5B00A75B9A /* Debug */, + 13B07F951A680F5B00A75B9A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1D7533FF2DD2898F00B464C4 /* Build configuration list for PBXNativeTarget "AmplifyRtnAsfExampleTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1D7533FD2DD2898F00B464C4 /* Debug */, + 1D7533FE2DD2898F00B464C4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "AmplifyRtnAsfExample" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 83CBBA201A601CBA00E9B192 /* Debug */, + 83CBBA211A601CBA00E9B192 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */; +} diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample.xcworkspace/contents.xcworkspacedata b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..223f6ac1a4d --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/AppDelegate.swift b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/AppDelegate.swift new file mode 100644 index 00000000000..0e0e5fabc73 --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/AppDelegate.swift @@ -0,0 +1,51 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import React +import ReactAppDependencyProvider +import React_RCTAppDelegate +import UIKit + +@main +class AppDelegate: UIResponder, UIApplicationDelegate { + var window: UIWindow? + + var reactNativeDelegate: ReactNativeDelegate? + var reactNativeFactory: RCTReactNativeFactory? + + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil + ) -> Bool { + let delegate: ReactNativeDelegate = ReactNativeDelegate() + let factory = RCTReactNativeFactory(delegate: delegate) + delegate.dependencyProvider = RCTAppDependencyProvider() + + reactNativeDelegate = delegate + reactNativeFactory = factory + + window = UIWindow(frame: UIScreen.main.bounds) + + factory.startReactNative( + withModuleName: "AmplifyRtnAsfExample", + in: window, + launchOptions: launchOptions + ) + + return true + } +} + +class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { + override func sourceURL(for bridge: RCTBridge) -> URL? { + self.bundleURL() + } + + override func bundleURL() -> URL? { + #if DEBUG + RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") + #else + Bundle.main.url(forResource: "main", withExtension: "jsbundle") + #endif + } +} diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Images.xcassets/AppIcon.appiconset/Contents.json b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Images.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000000..81213230deb --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Images.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,53 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Images.xcassets/Contents.json b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Images.xcassets/Contents.json new file mode 100644 index 00000000000..2d92bd53fdb --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Images.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Info.plist b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Info.plist new file mode 100644 index 00000000000..1082c30fa2c --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/Info.plist @@ -0,0 +1,51 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + AmplifyRtnAsfExample + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + LSRequiresIPhoneOS + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + NSAllowsLocalNetworking + + + NSLocationWhenInUseUsageDescription + + UILaunchStoryboardName + LaunchScreen + UIRequiredDeviceCapabilities + + arm64 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/LaunchScreen.storyboard b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/LaunchScreen.storyboard new file mode 100644 index 00000000000..a018fd36616 --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/LaunchScreen.storyboard @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/PrivacyInfo.xcprivacy b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/PrivacyInfo.xcprivacy new file mode 100644 index 00000000000..41b8317f065 --- /dev/null +++ b/packages/rtn-asf/example/ios/AmplifyRtnAsfExample/PrivacyInfo.xcprivacy @@ -0,0 +1,37 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategorySystemBootTime + NSPrivacyAccessedAPITypeReasons + + 35F9.1 + + + + NSPrivacyCollectedDataTypes + + NSPrivacyTracking + + + diff --git a/packages/rtn-asf/example/ios/Podfile b/packages/rtn-asf/example/ios/Podfile new file mode 100644 index 00000000000..3a84adddf0c --- /dev/null +++ b/packages/rtn-asf/example/ios/Podfile @@ -0,0 +1,41 @@ +ENV['RCT_NEW_ARCH_ENABLED'] = '1' + +# Resolve react_native_pods.rb with node to allow for hoisting +require Pod::Executable.execute_command('node', ['-p', + 'require.resolve( + "react-native/scripts/react_native_pods.rb", + {paths: [process.argv[1]]}, + )', __dir__]).strip + +platform :ios, '17.4' +prepare_react_native_project! + +linkage = ENV['USE_FRAMEWORKS'] +if linkage != nil + Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green + use_frameworks! :linkage => linkage.to_sym +end + +target 'AmplifyRtnAsfExample' do + # Enable modular headers for AWSCognitoIdentityProviderASF (required for Swift integration) + pod 'AWSCognitoIdentityProviderASF', :modular_headers => true + pod 'AmplifyRtnAsf', :path => '../..', :testspecs => ['tests'] + + config = use_native_modules! + + use_react_native!( + :path => config[:reactNativePath], + # An absolute path to your application root. + :app_path => "#{Pod::Config.instance.installation_root}/.." + ) + + post_install do |installer| + # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 + react_native_post_install( + installer, + config[:reactNativePath], + :mac_catalyst_enabled => false, + # :ccache_enabled => true + ) + end +end diff --git a/packages/rtn-asf/example/jest.config.js b/packages/rtn-asf/example/jest.config.js new file mode 100644 index 00000000000..8eb675e9bc6 --- /dev/null +++ b/packages/rtn-asf/example/jest.config.js @@ -0,0 +1,3 @@ +module.exports = { + preset: 'react-native', +}; diff --git a/packages/rtn-asf/example/metro.config.js b/packages/rtn-asf/example/metro.config.js new file mode 100644 index 00000000000..53a999a7edf --- /dev/null +++ b/packages/rtn-asf/example/metro.config.js @@ -0,0 +1,51 @@ +const path = require('path'); + +const { getDefaultConfig } = require('@react-native/metro-config'); + +const projectRoot = __dirname; +const monorepoRoot = path.resolve(projectRoot, '../../../'); + +const config = getDefaultConfig(projectRoot); + +// only look for internal deps from monorepo root +const monorepoPackages = { + '@aws-amplify/rtn-asf': path.resolve( + monorepoRoot, + 'packages/rtn-asf', + ), +}; + +config.watchFolders = [ + projectRoot, + monorepoRoot, + ...Object.values(monorepoPackages), +]; + +config.transformer = { + ...config.transformer, + getTransformOptions: () => ({ + transform: { + experimentalImportSupport: false, + inlineRequires: true, + }, + }), +}; + +// add internal deps as extra node modules +config.resolver.extraNodeModules = monorepoPackages; + +// disable default node dependency resolution functionality +config.resolver.disableHierarchicalLookup = true; + +// only look for node modules here +config.resolver.nodeModulesPaths = [ + path.resolve(projectRoot, 'node_modules'), + path.resolve(monorepoRoot, 'node_modules'), +]; + +config.projectRoot = projectRoot; + +// can be disabled +config.resetCache = true; + +module.exports = config; diff --git a/packages/rtn-asf/example/package.json b/packages/rtn-asf/example/package.json new file mode 100644 index 00000000000..520f3de7f12 --- /dev/null +++ b/packages/rtn-asf/example/package.json @@ -0,0 +1,39 @@ +{ + "name": "@aws-amplify/rtn-asf-example", + "version": "0.1.0", + "private": true, + "scripts": { + "android": "react-native run-android", + "ios": "react-native run-ios", + "start": "react-native start", + "build:android": "react-native build-android --extra-params \"--no-daemon --console=plain -PreactNativeArchitectures=arm64-v8a\"", + "build:ios": "react-native build-ios --scheme AmplifyRtnAsfExample --mode Debug --extra-params \"-sdk iphonesimulator CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ GCC_OPTIMIZATION_LEVEL=0 GCC_PRECOMPILE_PREFIX_HEADER=YES ASSETCATALOG_COMPILER_OPTIMIZATION=time DEBUG_INFORMATION_FORMAT=dwarf COMPILER_INDEX_STORE_ENABLE=NO\"" + }, + "dependencies": { + "@aws-amplify/rtn-asf": "1.0.0", + "react": "19.2.1", + "react-native": "0.79.2" + }, + "devDependencies": { + "@babel/core": "^7.25.2", + "@babel/preset-env": "^7.25.3", + "@babel/runtime": "^7.25.0", + "@react-native-community/cli": "18.0.1", + "@react-native-community/cli-platform-android": "18.0.0", + "@react-native-community/cli-platform-ios": "18.0.0", + "@react-native/babel-preset": "0.79.2", + "@react-native/codegen": "0.79.2", + "@react-native/eslint-config": "0.79.2", + "@react-native/metro-config": "0.79.2", + "@react-native/typescript-config": "0.79.2" + }, + "engines": { + "node": ">=18" + }, + "workspaces": { + "nohoist": [ + "**/@react-native/codegen", + "**/@react-native/codegen/**" + ] + } +} diff --git a/packages/rtn-asf/example/react-native.config.js b/packages/rtn-asf/example/react-native.config.js new file mode 100644 index 00000000000..046e095d41f --- /dev/null +++ b/packages/rtn-asf/example/react-native.config.js @@ -0,0 +1,22 @@ +const path = require('path'); + +const pkg = require('../package.json'); + +module.exports = { + project: { + ios: { + automaticPodsInstallation: true, + }, + }, + dependencies: { + [pkg.name]: { + root: path.join(__dirname, '..'), + platforms: { + // Codegen script incorrectly fails without this + // So we explicitly specify the platforms with empty object + ios: {}, + android: {}, + }, + }, + }, +}; diff --git a/packages/rtn-asf/example/src/App.tsx b/packages/rtn-asf/example/src/App.tsx new file mode 100644 index 00000000000..83c2747fad7 --- /dev/null +++ b/packages/rtn-asf/example/src/App.tsx @@ -0,0 +1,206 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* eslint-disable no-console */ +import React, { useState } from 'react'; +import { + Button, + SafeAreaView, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native'; +import NativeAmplifyRtnAsf from '@aws-amplify/rtn-asf'; + +function App(): React.JSX.Element { + const [userPoolId, setUserPoolId] = useState('us-east-1_testPool'); + const [clientId, setClientId] = useState('testClientId'); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + + const handleGetContextData = () => { + try { + setError(null); + const contextData = NativeAmplifyRtnAsf?.getContextData( + userPoolId, + clientId, + ); + setResult(contextData ?? 'null (no data returned)'); + console.log('Context data:', contextData); + } catch (e) { + const errorMessage = e instanceof Error ? e.message : String(e); + setError(errorMessage); + console.error('Error getting context data:', e); + } + }; + + const handleTestEmptyUserPoolId = () => { + try { + setError(null); + const contextData = NativeAmplifyRtnAsf?.getContextData('', clientId); + setResult(contextData ?? 'null (expected for empty userPoolId)'); + } catch (e) { + const errorMessage = e instanceof Error ? e.message : String(e); + setError(errorMessage); + } + }; + + const handleTestEmptyClientId = () => { + try { + setError(null); + const contextData = NativeAmplifyRtnAsf?.getContextData(userPoolId, ''); + setResult(contextData ?? 'null (expected for empty clientId)'); + } catch (e) { + const errorMessage = e instanceof Error ? e.message : String(e); + setError(errorMessage); + } + }; + + return ( + + + ASF Context Data Test + + + User Pool ID: + + + + + Client ID: + + + + +