Skip to content

Commit

Permalink
feat: ai overasking (#233)
Browse files Browse the repository at this point in the history
Signed-off-by: Jan <[email protected]>
  • Loading branch information
janrtvld authored Nov 26, 2024
1 parent 03cecfb commit cd9ea4c
Show file tree
Hide file tree
Showing 9 changed files with 205 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import {
BiometricAuthenticationCancelledError,
type CredentialsForProofRequest,
type FormattedSubmissionEntrySatisfied,
getCredentialsForProofRequest,
getDisclosedAttributeNamesForDisplay,
shareProof,
} from '@package/agent'
import { useToastController } from '@package/ui'
import { useLocalSearchParams } from 'expo-router'
import React, { useEffect, useState, useMemo, useCallback } from 'react'
import React, { useEffect, useState, useCallback } from 'react'

import { useAppAgent } from '@easypid/agent'
import { analyzeVerification } from '@easypid/use-cases/ValidateVerification'
import type { VerificationAnalysisResponse } from '@easypid/use-cases/ValidateVerification'
import { usePushToWallet } from '@package/app/src/hooks/usePushToWallet'
import { setWalletServiceProviderPin } from '../../crypto/WalletServiceProviderClient'
import { useShouldUsePinForSubmission } from '../../hooks/useShouldUsePinForPresentation'
Expand Down Expand Up @@ -53,6 +57,40 @@ export function FunkeOpenIdPresentationNotificationScreen() {
})
}, [credentialsForRequest, params.data, params.uri, toast.show, agent, pushToWallet, toast])

const [verificationAnalysis, setVerificationAnalysis] = useState<{
isLoading: boolean
result: VerificationAnalysisResponse | undefined
}>({
isLoading: false,
result: undefined,
})

useEffect(() => {
if (!credentialsForRequest?.formattedSubmission || !credentialsForRequest?.formattedSubmission.areAllSatisfied) {
return
}
setVerificationAnalysis((prev) => ({ ...prev, isLoading: true }))

const submission = credentialsForRequest.formattedSubmission
const requestedCards = submission.entries
.filter((entry): entry is FormattedSubmissionEntrySatisfied => entry.isSatisfied)
.flatMap((entry) => entry.credentials)

analyzeVerification({
verifier: {
name: credentialsForRequest.verifier.name ?? 'No name provided',
domain: credentialsForRequest.verifier.hostName ?? 'No domain provided',
},
name: submission.name ?? 'No name provided',
purpose: submission.purpose ?? 'No purpose provided',
cards: requestedCards.map((credential) => ({
name: credential.credential.display.name ?? 'Card name',
subtitle: credential.credential.display.description ?? 'Card description',
requestedAttributes: getDisclosedAttributeNamesForDisplay(credential),
})),
}).then((result) => setVerificationAnalysis((prev) => ({ ...prev, isLoading: false, result })))
}, [credentialsForRequest])

const onProofAccept = useCallback(
async (pin?: string): Promise<PresentationRequestResult> => {
if (!credentialsForRequest)
Expand Down Expand Up @@ -149,6 +187,7 @@ export function FunkeOpenIdPresentationNotificationScreen() {
trustedEntities={credentialsForRequest?.verifier.trustedEntities}
lastInteractionDate={lastInteractionDate}
onComplete={() => pushToWallet('replace')}
verificationAnalysis={verificationAnalysis}
/>
)
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { DisplayImage, FormattedSubmission, TrustedEntity } from '@package/agent'

import type { VerificationAnalysisResult } from '@easypid/use-cases/ValidateVerification'
import { type SlideStep, SlideWizard } from '@package/app'
import { LoadingRequestSlide } from '../receive/slides/LoadingRequestSlide'
import { VerifyPartySlide } from '../receive/slides/VerifyPartySlide'
Expand All @@ -13,6 +14,7 @@ interface FunkePresentationNotificationScreenProps {
verifierName?: string
logo?: DisplayImage
lastInteractionDate?: string
verificationAnalysis: VerificationAnalysisResult
trustedEntities?: Array<TrustedEntity>
submission?: FormattedSubmission
usePin: boolean
Expand All @@ -33,6 +35,7 @@ export function FunkePresentationNotificationScreen({
isAccepting,
submission,
onComplete,
verificationAnalysis,
trustedEntities,
}: FunkePresentationNotificationScreenProps) {
return (
Expand Down Expand Up @@ -71,6 +74,7 @@ export function FunkePresentationNotificationScreen({
logo={logo}
submission={submission}
isAccepting={isAccepting}
verificationAnalysis={verificationAnalysis}
/>
),
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,87 @@
import { Circle, Heading, HeroIcons, Image, MessageBox, Stack, YStack } from '@package/ui'
import type { VerificationAnalysisResult } from '@easypid/use-cases/ValidateVerification'
import {
AnimatedStack,
Circle,
Heading,
HeroIcons,
Image,
InfoSheet,
MessageBox,
Stack,
XStack,
YStack,
useScaleAnimation,
} from '@package/ui'
import type { DisplayImage } from 'packages/agent/src'
import { useState } from 'react'
import { ZoomIn } from 'react-native-reanimated'
import { VerificationAnalysisIcon } from './VerificationAnalysisIcon'

interface RequestPurposeSectionProps {
purpose: string
logo?: DisplayImage
verificationAnalysis?: VerificationAnalysisResult
}

export function RequestPurposeSection({ purpose, logo }: RequestPurposeSectionProps) {
export function RequestPurposeSection({ purpose, logo, verificationAnalysis }: RequestPurposeSectionProps) {
const [isAnalysisModalOpen, setIsAnalysisModalOpen] = useState(false)

const { handlePressIn, handlePressOut, pressStyle } = useScaleAnimation()

const toggleAnalysisModal = () => setIsAnalysisModalOpen(!isAnalysisModalOpen)

return (
<YStack gap="$2">
<Heading variant="sub2">PURPOSE</Heading>
<MessageBox
variant="light"
message={purpose}
icon={
<Circle size="$4" overflow="hidden">
{logo?.url ? (
<Image circle src={logo.url} alt={logo.altText} width="100%" height="100%" resizeMode="contain" />
) : (
<Stack bg="$grey-200" width="100%" height="100%" ai="center" jc="center">
<HeroIcons.BuildingOffice color="$grey-800" size={24} />
</Stack>
<>
<YStack gap="$2">
{verificationAnalysis?.result?.validRequest === 'no' && (
<AnimatedStack
style={pressStyle}
onPressIn={handlePressIn}
onPressOut={handlePressOut}
onPress={toggleAnalysisModal}
mb="$4"
>
<MessageBox
icon={<HeroIcons.InformationCircleFilled />}
variant="error"
message="The purpose given does not match the data requested."
/>
</AnimatedStack>
)}
<XStack gap="$2" jc="space-between" ai="center">
<Heading variant="sub2">PURPOSE</Heading>
<Stack h="$2" w="$2" ai="center" jc="center">
{verificationAnalysis && (
<AnimatedStack key={verificationAnalysis.result?.validRequest} entering={ZoomIn}>
<VerificationAnalysisIcon verificationAnalysis={verificationAnalysis} />
</AnimatedStack>
)}
</Circle>
}
</Stack>
</XStack>
<MessageBox
variant="light"
message={purpose}
icon={
<Circle size="$4" overflow="hidden">
{logo?.url ? (
<Image circle src={logo.url} alt={logo.altText} width="100%" height="100%" resizeMode="contain" />
) : (
<Stack bg="$grey-200" width="100%" height="100%" ai="center" jc="center">
<HeroIcons.BuildingOffice color="$grey-800" size={24} />
</Stack>
)}
</Circle>
}
/>
</YStack>
<InfoSheet
variant="danger"
isOpen={isAnalysisModalOpen}
setIsOpen={setIsAnalysisModalOpen}
title="Overasking detected"
description="This organization seems to be asking for different or more data than their purpose suggests. Read the request carefully. You can deny the request if you do not agree with the data asked."
onClose={toggleAnalysisModal}
/>
</YStack>
</>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { VerificationAnalysisResult } from '@easypid/use-cases/ValidateVerification'
import { HeroIcons, Spinner } from 'packages/ui/src'

interface VerificationAnalysisIconProps {
verificationAnalysis: VerificationAnalysisResult
}

export function VerificationAnalysisIcon({ verificationAnalysis }: VerificationAnalysisIconProps) {
if (!verificationAnalysis.result || verificationAnalysis.isLoading) return <Spinner scale={0.8} />

if (verificationAnalysis.result.validRequest === 'could_not_determine') {
// AI doesn't know or an error was thrown
return null
}

if (verificationAnalysis.result.validRequest === 'yes') {
return <HeroIcons.CheckCircleFilled size={26} color="$positive-500" />
}

return <HeroIcons.ExclamationTriangleFilled size={26} color="$danger-500" />
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { VerificationAnalysisResult } from '@easypid/use-cases/ValidateVerification'
import type { DisplayImage, FormattedSubmission } from '@package/agent'
import { DualResponseButtons, usePushToWallet, useScrollViewPosition } from '@package/app'
import { useWizard } from '@package/app'
Expand All @@ -16,6 +17,7 @@ interface ShareCredentialsSlideProps {
isAccepting: boolean

isOffline?: boolean
verificationAnalysis?: VerificationAnalysisResult
}

export const ShareCredentialsSlide = ({
Expand All @@ -25,6 +27,7 @@ export const ShareCredentialsSlide = ({
onDecline,
isAccepting,
isOffline,
verificationAnalysis,
}: ShareCredentialsSlideProps) => {
const { onNext, onCancel } = useWizard()
const [scrollViewHeight, setScrollViewHeight] = useState(0)
Expand Down Expand Up @@ -85,6 +88,7 @@ export const ShareCredentialsSlide = ({
purpose={
submission.purpose ?? 'No information was provided on the purpose of the data request. Be cautious'
}
verificationAnalysis={verificationAnalysis}
logo={logo}
/>
)}
Expand Down
54 changes: 54 additions & 0 deletions apps/easypid/src/use-cases/ValidateVerification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const PLAYGROUND_URL = 'https://funke.animo.id'

export type VerificationAnalysisInput = {
verifier: {
name: string
domain: string
}
name: string
purpose: string
cards: Array<{
name: string
subtitle: string
requestedAttributes: Array<string>
}>
}

export type VerificationAnalysisResponse = {
validRequest: 'yes' | 'no' | 'could_not_determine'
reason: string
}

export type VerificationAnalysisResult = {
isLoading: boolean
result: VerificationAnalysisResponse | undefined
}

export const analyzeVerification = async ({
verifier,
name,
purpose,
cards,
}: VerificationAnalysisInput): Promise<VerificationAnalysisResponse> => {
try {
const response = await fetch(`${PLAYGROUND_URL}/api/validate-verification-request`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ verifier, name, purpose, cards }),
})

if (!response.ok) {
throw new Error(`Request to AI returned ${response.status}`)
}

return await response.json()
} catch (error) {
console.error('AI analysis failed:', error)
return {
validRequest: 'could_not_determine',
reason: 'An error occurred while validating the verification',
}
}
}
1 change: 0 additions & 1 deletion packages/agent/src/format/formatPresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
getCredentialForDisplay,
getDisclosedAttributePathArrays,
} from '../display'
import { applyLimitdisclosureForSdJwtRequestedPayload } from './disclosureFrame'

export interface FormattedSubmission {
name?: string
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/panels/InfoSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const infoSheetVariants = {
background: '$warning-300',
},
danger: {
icon: <HeroIcons.ExclamationCircleFilled />,
icon: <HeroIcons.ExclamationTriangleFilled />,
accent: '$danger-500',
layer: '$danger-400',
background: '$danger-300',
Expand Down
8 changes: 6 additions & 2 deletions packages/ui/src/panels/MessageBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const messageBoxVariants = {
color: '$white',
},
success: {
bg: '$success-500',
bg: '$positive-500',
color: '$white',
},
}
Expand All @@ -40,7 +40,11 @@ export function MessageBox({ message, textVariant = 'normal', variant = 'default
return (
<XStack gap="$2" p="$3.5" bg={messageBoxVariants[variant].bg} borderRadius="$8">
<YStack gap="$2" f={1}>
{title && <Heading variant="sub2">{title}</Heading>}
{title && (
<Heading variant="sub2" color={messageBoxVariants[variant].color}>
{title}
</Heading>
)}
<Paragraph f={1} color={messageBoxVariants[variant].color} variant={textVariant}>
{message}
</Paragraph>
Expand Down

0 comments on commit cd9ea4c

Please sign in to comment.