Skip to content

Commit

Permalink
Fixes for API endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
forgetso committed Jun 5, 2024
1 parent f232cfd commit aeac68e
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 39 deletions.
6 changes: 3 additions & 3 deletions demos/provider-mock/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ export function prosopoRouter(): Router {
* @param {string} userAccount - Dapp User id
* @param {string} commitmentId - The captcha solution to look up
*/
router.post(ApiPaths.VerifyCaptchaSolutionDapp, async (req, res, next) => {
router.post(ApiPaths.VerifyImageCaptchaSolutionDapp, async (req, res, next) => {
let body: VerifySolutionBodyTypeOutput
try {
body = VerifySolutionBody.parse(req.body)
} catch (err) {
return next(
new ProsopoApiError('CAPTCHA.PARSE_ERROR', {
context: { error: err, errorCode: 400 },
context: { error: err, code: 400 },
logLevel: 'info',
})
)
Expand Down Expand Up @@ -69,7 +69,7 @@ export function prosopoRouter(): Router {
verified: false,
})
} catch (err) {
return next(new ProsopoApiError('API.UNKNOWN', { context: { error: err, errorCode: 500 } }))
return next(new ProsopoApiError('API.UNKNOWN', { context: { error: err, code: 500 } }))
}
})

Expand Down
16 changes: 8 additions & 8 deletions packages/api/src/api/ProviderApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ export default class ProviderApi extends HttpClientBase implements ProviderApi {
public getCaptchaChallenge(userAccount: AccountId, randomProvider: RandomProvider): Promise<CaptchaResponseBody> {
const { provider, blockNumber } = randomProvider
const dappAccount = this.account
const url = `${ApiPaths.GetCaptchaChallenge}/${provider.datasetId}/${userAccount}/${dappAccount}/${blockNumber
.toString()
.replace(/,/g, '')}`
const url = `${ApiPaths.GetImageCaptchaChallenge}/${
provider.datasetId
}/${userAccount}/${dappAccount}/${blockNumber.toString().replace(/,/g, '')}`
return this.fetch(url)
}

Expand All @@ -73,7 +73,7 @@ export default class ProviderApi extends HttpClientBase implements ProviderApi {
salt,
signature,
})
return this.post(ApiPaths.SubmitCaptchaSolution, captchaSolutionBody)
return this.post(ApiPaths.SubmitImageCaptchaSolution, captchaSolutionBody)
}

public verifyDappUser(
Expand All @@ -89,7 +89,7 @@ export default class ProviderApi extends HttpClientBase implements ProviderApi {
payload[ApiParams.maxVerifiedTime] = maxVerifiedTime
}

return this.post(ApiPaths.VerifyCaptchaSolutionDapp, payload)
return this.post(ApiPaths.VerifyImageCaptchaSolutionDapp, payload)
}

public verifyUser(
Expand All @@ -103,7 +103,7 @@ export default class ProviderApi extends HttpClientBase implements ProviderApi {
...(maxVerifiedTime && { [ApiParams.maxVerifiedTime]: maxVerifiedTime }),
}

return this.post(ApiPaths.VerifyCaptchaSolutionUser, payload)
return this.post(ApiPaths.VerifyImageCaptchaSolutionUser, payload)
}

public getPowCaptchaChallenge(user: AccountId, dapp: AccountId): Promise<GetPowCaptchaResponse> {
Expand Down Expand Up @@ -156,9 +156,9 @@ export default class ProviderApi extends HttpClientBase implements ProviderApi {
): Promise<VerificationResponse> {
const body: ServerPowCaptchaVerifyRequestBodyType = {
[ApiParams.token]: token,
[ApiParams.dappUserSignature]: signatureHex,
[ApiParams.dappSignature]: signatureHex,
[ApiParams.verifiedTimeout]: recencyLimit,
}
return this.post(ApiPaths.ServerPowCaptchaVerify, body)
return this.post(ApiPaths.VerifyPowCaptchaSolution, body)
}
}
6 changes: 3 additions & 3 deletions packages/common/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,9 @@ export class ProsopoApiError extends ProsopoBaseError<ApiContextParams> {

constructor(error: Error | TranslationKey, options?: BaseErrorOptions<ApiContextParams>) {
const errorName = options?.name || 'ProsopoApiError'
const errorCode = options?.context?.code || 500
options = { ...options, name: errorName, context: { ...options?.context, errorCode } }
const code = options?.context?.code || 500
options = { ...options, name: errorName, context: { ...options?.context, code } }
super(error, options)
this.code = errorCode
this.code = code
}
}
2 changes: 1 addition & 1 deletion packages/contract/src/accounts/mnemonic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export async function generateMnemonic(keyring?: Keyring, pairType?: KeypairType
* @param keyring
* @param pairType
*/
export async function generateSecret(keyring?: Keyring, pairType?: KeypairType): Promise<[Uint8Array, string]> {
export async function generateMiniSecret(keyring?: Keyring, pairType?: KeypairType): Promise<[Uint8Array, string]> {
const [mnemonic, address] = await generateMnemonic(keyring, pairType)
return [mnemonicToMiniSecret(mnemonic), address]
}
4 changes: 2 additions & 2 deletions packages/provider/src/api/captcha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function prosopoRouter(env: ProviderEnvironment): Router {
* @return {Captcha} - The Captcha data
*/
router.get(
`${ApiPaths.GetCaptchaChallenge}/:${ApiParams.datasetId}/:${ApiParams.user}/:${ApiParams.dapp}/:${ApiParams.blockNumber}`,
`${ApiPaths.GetImageCaptchaChallenge}/:${ApiParams.datasetId}/:${ApiParams.user}/:${ApiParams.dapp}/:${ApiParams.blockNumber}`,
async (req, res, next) => {
try {
const { blockNumber, datasetId, user, dapp } = CaptchaRequestBody.parse(req.params)

Check warning on line 59 in packages/provider/src/api/captcha.ts

View workflow job for this annotation

GitHub Actions / check

'dapp' is assigned a value but never used
Expand Down Expand Up @@ -95,7 +95,7 @@ export function prosopoRouter(env: ProviderEnvironment): Router {
* @param {Captcha[]} captchas - The Captcha solutions
* @return {DappUserSolutionResult} - The Captcha solution result and proof
*/
router.post(ApiPaths.SubmitCaptchaSolution, async (req, res, next) => {
router.post(ApiPaths.SubmitImageCaptchaSolution, async (req, res, next) => {
let parsed: CaptchaSolutionBodyType
try {
parsed = CaptchaSolutionBody.parse(req.body)
Expand Down
8 changes: 2 additions & 6 deletions packages/provider/src/api/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@ export const handleErrors = (
while (err instanceof ProsopoBaseError && err.context && err.context.error) {
err = err.context.error
}
let message = err.message
const message = err.message

if (typeof message !== 'string') {
message = JSON.stringify(message)
}

response.writeHead(code, message, { 'content-type': 'application/json' }).end()
response.writeHead(code, JSON.stringify(message), { 'content-type': 'application/json' }).end()
}
25 changes: 15 additions & 10 deletions packages/provider/src/api/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function prosopoVerifyRouter(env: ProviderEnvironment): Router {
* @param {NextFunction} next - Express next function.
* @param {boolean} isDapp - Indicates whether the verification is for a dapp (true) or user (false).
*/
async function verifySolution(res: Response, req: Request, next: NextFunction, isDapp: boolean) {
async function verifyImageSolution(res: Response, req: Request, next: NextFunction, isDapp: boolean) {
const parsed = VerifySolutionBody.parse(req.body)
try {
const { dappUserSignature, token } = parsed
Expand Down Expand Up @@ -120,9 +120,9 @@ export function prosopoVerifyRouter(env: ProviderEnvironment): Router {
* @param {string} commitmentId - The captcha solution to look up
* @param {number} maxVerifiedTime - The maximum time in milliseconds since the blockNumber
*/
router.post(ApiPaths.VerifyCaptchaSolutionDapp, async (req, res, next) => {
router.post(ApiPaths.VerifyImageCaptchaSolutionDapp, async (req, res, next) => {
try {
await verifySolution(res, req, next, true)
await verifyImageSolution(res, req, next, true)
} catch (err) {
return next(new ProsopoApiError('CAPTCHA.PARSE_ERROR', { context: { code: 400, error: err } }))
}
Expand All @@ -138,9 +138,9 @@ export function prosopoVerifyRouter(env: ProviderEnvironment): Router {
* @param {string} commitmentId - The captcha solution to look up
* @param {number} maxVerifiedTime - The maximum time in milliseconds since the blockNumber
*/
router.post(ApiPaths.VerifyCaptchaSolutionUser, async (req, res, next) => {
router.post(ApiPaths.VerifyImageCaptchaSolutionUser, async (req, res, next) => {
try {
await verifySolution(res, req, next, false)
await verifyImageSolution(res, req, next, false)
} catch (err) {
return next(new ProsopoApiError('CAPTCHA.PARSE_ERROR', { context: { code: 400, error: err } }))
}
Expand All @@ -152,9 +152,9 @@ export function prosopoVerifyRouter(env: ProviderEnvironment): Router {
* @param {string} dappAccount - Dapp User id
* @param {string} challenge - The captcha solution to look up
*/
router.post(ApiPaths.ServerPowCaptchaVerify, async (req, res, next) => {
router.post(ApiPaths.VerifyPowCaptchaSolution, async (req, res, next) => {
try {
const { token, dappUserSignature, verifiedTimeout } = ServerPowCaptchaVerifyRequestBody.parse(req.body)
const { token, dappSignature, verifiedTimeout } = ServerPowCaptchaVerifyRequestBody.parse(req.body)

const { dapp, blockNumber, challenge } = decodeProcaptchaOutput(token)

Expand All @@ -170,10 +170,15 @@ export function prosopoVerifyRouter(env: ProviderEnvironment): Router {
const dappPair = env.keyring.addFromAddress(dapp)

// Will throw an error if the signature is invalid
verifySignature(dappUserSignature, blockNumber.toString(), dappPair)

verifySignature(dappSignature, blockNumber.toString(), dappPair)
console.log({
dapp,
blockNumber,
challenge,
verifiedTimeout,
})
const approved = await tasks.serverVerifyPowCaptchaSolution(dapp, challenge, verifiedTimeout)

console.log('approved', approved)
const verificationResponse: VerificationResponse = {
status: req.t(approved ? 'API.USER_VERIFIED' : 'API.USER_NOT_VERIFIED'),
[ApiParams.verified]: approved,
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/api/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export enum ApiParams {
captchas = 'captchas',
commitmentId = 'commitmentId',
proof = 'proof',
dappSignature = 'dappSignature',
dappUserSignature = 'dappUserSignature',
providerUrl = 'providerUrl',
procaptchaResponse = 'procaptcha-response',
Expand Down
12 changes: 6 additions & 6 deletions packages/types/src/provider/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ import { ProcaptchaTokenSpec } from '../procaptcha/index.js'
import { array, input, number, object, output, string, infer as zInfer } from 'zod'

export enum ApiPaths {
GetCaptchaChallenge = '/v1/prosopo/provider/captcha',
GetImageCaptchaChallenge = '/v1/prosopo/provider/captcha/image',
GetPowCaptchaChallenge = '/v1/prosopo/provider/captcha/pow',
SubmitCaptchaSolution = '/v1/prosopo/provider/solution',
SubmitImageCaptchaSolution = '/v1/prosopo/provider/solution',
SubmitPowCaptchaSolution = '/v1/prosopo/provider/pow/solution',
ServerPowCaptchaVerify = '/v1/prosopo/provider/pow/server-verify',
VerifyCaptchaSolutionDapp = '/v1/prosopo/provider/dapp-verify',
VerifyCaptchaSolutionUser = '/v1/prosopo/provider/user-verify',
VerifyPowCaptchaSolution = '/v1/prosopo/provider/pow/verify',
VerifyImageCaptchaSolutionDapp = `/v1/prosopo/provider/image/${ApiParams.dapp}/verify`,
VerifyImageCaptchaSolutionUser = `/v1/prosopo/provider/image/${ApiParams.user}/verify`,
GetProviderStatus = '/v1/prosopo/provider/status',
GetProviderDetails = '/v1/prosopo/provider/details',
SubmitUserEvents = '/v1/prosopo/provider/events',
Expand Down Expand Up @@ -133,7 +133,7 @@ export interface PowCaptchaSolutionResponse {
*/
export const ServerPowCaptchaVerifyRequestBody = object({
[ApiParams.token]: ProcaptchaTokenSpec,
[ApiParams.dappUserSignature]: string(),
[ApiParams.dappSignature]: string(),
[ApiParams.verifiedTimeout]: number().optional().default(DEFAULT_POW_CAPTCHA_VERIFIED_TIMEOUT),
})

Expand Down

0 comments on commit aeac68e

Please sign in to comment.