Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/clear-cobras-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@exactly/server": patch
---

✨ add card limit case update
118 changes: 107 additions & 11 deletions server/api/kyc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default new Hono()
"query",
object({
countryCode: optional(literal("true")),
scope: optional(picklist(["basic", "bridge", "manteca"])),
scope: optional(picklist(["basic", "bridge", "cardLimit", "manteca"])),
}),
validatorHook(),
),
Expand All @@ -59,6 +59,40 @@ export default new Hono()
setUser({ id: account });
setContext("exa", { credential });

if (scope === "cardLimit") {
if (!credential.pandaId) return c.json({ code: "bad kyc" }, 400);
if (await getPendingInquiryTemplate(credentialId, "basic")) return c.json({ code: "not started" }, 200);
let templateId: Awaited<ReturnType<typeof getPendingInquiryTemplate>>;
try {
templateId = await getPendingInquiryTemplate(credentialId, "cardLimit");
} catch (error: unknown) {
if (error instanceof Error && error.message === scopeValidationErrors.NOT_SUPPORTED) {
return c.json({ code: "not supported" }, 400);
}
throw error;
}
const template = getCardLimitTemplate(credentialId, templateId);
if (!template) return c.json({ code: "not started" }, 200);
const cardLimitInquiry = await getInquiry(credentialId, template);
if (!cardLimitInquiry) return c.json({ code: "not started" }, 200);
switch (cardLimitInquiry.attributes.status) {
case "approved":
return c.json({ code: "ok" }, 200);
case "completed":
case "needs_review":
return c.json({ code: "processing" }, 400);
case "created":
case "pending":
case "expired":
return c.json({ code: "not started" }, 200);
case "failed":
case "declined":
return c.json({ code: "bad kyc" }, 400);
default:
throw new Error("unknown inquiry status");
}
}

if (scope === "basic" && credential.pandaId) {
if (c.req.valid("query").countryCode) {
const personaAccount = await getAccount(credentialId, scope).catch((error: unknown) => {
Expand Down Expand Up @@ -113,7 +147,7 @@ export default new Hono()
case "declined":
return c.json({ code: "bad kyc", legacy: "kyc not approved" }, 400);
default:
throw new Error("Unknown inquiry status");
throw new Error("unknown inquiry status");
}
},
)
Expand All @@ -124,7 +158,7 @@ export default new Hono()
"json",
object({
redirectURI: optional(string()),
scope: optional(picklist(["basic", "bridge", "manteca"])),
scope: optional(picklist(["basic", "bridge", "cardLimit", "manteca"])),
}),
validatorHook({ debug }),
),
Expand All @@ -141,6 +175,56 @@ export default new Hono()
setUser({ id: parse(Address, credential.account) });
setContext("exa", { credential });

if (scope === "cardLimit") {
if (await getPendingInquiryTemplate(credentialId, "basic")) return c.json({ code: "not started" }, 400);
let templateId: Awaited<ReturnType<typeof getPendingInquiryTemplate>>;
try {
templateId = await getPendingInquiryTemplate(credentialId, "cardLimit");
} catch (error: unknown) {
if (error instanceof Error && error.message === scopeValidationErrors.NOT_SUPPORTED) {
return c.json({ code: "not supported" }, 400);
}
throw error;
}
const template = getCardLimitTemplate(credentialId, templateId);
if (!template) return c.json({ code: "not started" }, 400);
const cardLimitInquiry = await getInquiry(credentialId, template);
if (!cardLimitInquiry) {
const account = await getAccount(credentialId, "basic").catch((error: unknown) => {
captureException(error, { level: "error", contexts: { details: { credentialId, scope: "cardLimit" } } });
});
const { data } = await createInquiry(
credentialId,
template,
redirectURI,
account
? { "name-first": account.attributes["name-first"], "name-last": account.attributes["name-last"] }
: undefined,
);
return c.json(await generateInquiryTokens(data.id), 200);
}
switch (cardLimitInquiry.attributes.status) {
case "approved":
captureException(new Error("inquiry approved but account not updated"), {
level: "error",
contexts: { inquiry: { templateId: template, referenceId: credentialId } },
});
return c.json({ code: "already approved" }, 400);
case "completed":
case "needs_review":
return c.json({ code: "processing" }, 400);
case "pending":
case "created":
case "expired":
return c.json(await generateInquiryTokens(cardLimitInquiry.id), 200);
case "failed":
case "declined":
return c.json({ code: "failed" }, 400);
default:
throw new Error("unknown inquiry status");
}
}

let inquiryTemplateId: Awaited<ReturnType<typeof getPendingInquiryTemplate>>;
try {
inquiryTemplateId = await getPendingInquiryTemplate(credentialId, scope);
Expand All @@ -157,8 +241,7 @@ export default new Hono()
const inquiry = await getInquiry(credentialId, inquiryTemplateId);
if (!inquiry) {
const { data } = await createInquiry(credentialId, inquiryTemplateId, redirectURI);
const { inquiryId, sessionToken } = await generateInquiryTokens(data.id);
return c.json({ inquiryId, sessionToken }, 200);
return c.json(await generateInquiryTokens(data.id), 200);
}

switch (inquiry.attributes.status) {
Expand All @@ -173,15 +256,13 @@ export default new Hono()
return c.json({ code: "failed", legacy: "kyc failed" }, 400);
case "completed":
case "needs_review":
return c.json({ code: "failed", legacy: "kyc failed" }, 400); // TODO send a different response
return c.json({ code: "processing", legacy: "kyc failed" }, 400);
case "pending":
case "created":
case "expired": {
const { inquiryId, sessionToken } = await generateInquiryTokens(inquiry.id);
return c.json({ inquiryId, sessionToken }, 200);
}
case "expired":
return c.json(await generateInquiryTokens(inquiry.id), 200);
default:
throw new Error("Unknown inquiry status");
throw new Error("unknown inquiry status");
}
},
);
Expand Down Expand Up @@ -212,6 +293,21 @@ async function isLegacy(
});
}

function getCardLimitTemplate(
credentialId: string,
inquiryTemplateId: Awaited<ReturnType<typeof getPendingInquiryTemplate>>,
) {
if (inquiryTemplateId === PANDA_TEMPLATE) {
captureException(new Error("cardLimit: basic not found in Persona despite pandaId set"), {
level: "error",
contexts: { credential: { credentialId } },
});
return null;
}
if (!inquiryTemplateId) throw new Error("unexpected: no template for cardLimit");
return inquiryTemplateId;
}

async function generateInquiryTokens(inquiryId: string): Promise<{ inquiryId: string; sessionToken: string }> {
const { meta: sessionTokenMeta } = await resumeInquiry(inquiryId);
return { inquiryId, sessionToken: sessionTokenMeta["session-token"] };
Expand Down
72 changes: 68 additions & 4 deletions server/hooks/persona.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
literal,
looseObject,
minLength,
minValue,
nullable,
number,
object,
optional,
picklist,
Expand All @@ -23,13 +25,16 @@ import {

import { Address } from "@exactly/common/validation";

import database, { credentials } from "../database/index";
import { createUser } from "../utils/panda";
import database, { cards, credentials } from "../database/index";
import { createUser, updateCard } from "../utils/panda";
import { addCapita, deriveAssociateId } from "../utils/pax";
import {
addDocument,
ADDRESS_TEMPLATE,
CARD_LIMIT_CASE_TEMPLATE,
CARD_LIMIT_TEMPLATE,
CRYPTOMATE_TEMPLATE,
getInquiryById,
headerValidator,
MANTECA_TEMPLATE_EXTRA_FIELDS,
MANTECA_TEMPLATE_WITH_ID_CLASS,
Expand Down Expand Up @@ -184,6 +189,29 @@ export default new Hono().post(
}),
transform((payload) => ({ template: "manteca" as const, ...payload })),
),
pipe(
object({
data: object({
type: literal("case"),
id: string(),
attributes: object({
status: picklist(["Approved", "Declined", "Open", "Pending"]),
fields: looseObject({
cardLimitUsd: optional(
object({ type: literal("integer"), value: nullable(pipe(number(), minValue(1))) }),
),
}),
}),
relationships: object({
caseTemplate: object({ data: object({ id: literal(CARD_LIMIT_CASE_TEMPLATE) }) }),
inquiries: object({
data: array(object({ type: literal("inquiry"), id: string() })),
}),
}),
}),
}),
transform((payload) => ({ template: "cardLimit" as const, ...payload })),
),
pipe(
object({
data: object({
Expand All @@ -192,7 +220,12 @@ export default new Hono().post(
relationships: object({
inquiryTemplate: object({
data: object({
id: picklist([ADDRESS_TEMPLATE, CRYPTOMATE_TEMPLATE, MANTECA_TEMPLATE_EXTRA_FIELDS]),
id: picklist([
ADDRESS_TEMPLATE,
CARD_LIMIT_TEMPLATE,
CRYPTOMATE_TEMPLATE,
MANTECA_TEMPLATE_EXTRA_FIELDS,
]),
}),
}),
}),
Expand All @@ -210,7 +243,38 @@ export default new Hono().post(
const payload = c.req.valid("json").data.attributes.payload;

if (payload.template === "ignored") return c.json({ code: "ok" }, 200);

if (payload.template === "cardLimit") {
getActiveSpan()?.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, "persona.case.card-limit");
if (payload.data.attributes.status !== "Approved") return c.json({ code: "ok" }, 200);
const cardLimitUsd = payload.data.attributes.fields.cardLimitUsd?.value;
if (cardLimitUsd == null) return c.json({ code: "no limit" }, 200);
const inquiry = payload.data.relationships.inquiries.data[0];
if (!inquiry?.id) return c.json({ code: "no inquiry" }, 200);
const {
data: {
attributes: { "reference-id": referenceId },
},
} = await getInquiryById(inquiry.id);
const credential = await database.query.credentials.findFirst({
columns: { pandaId: true },
where: eq(credentials.id, referenceId),
with: { cards: { columns: { id: true }, where: eq(cards.status, "ACTIVE"), limit: 1 } },
});
if (!credential) {
captureException(new Error("no credential"), { level: "error", contexts: { credential: { referenceId } } });
return c.json({ code: "no credential" }, 200);
}
if (!credential.pandaId) return c.json({ code: "no panda" }, 200);
if (!credential.cards[0]) {
captureException(new Error("no card"), { level: "error", contexts: { card: { referenceId } } });
return c.json({ code: "no card" }, 200);
}
await updateCard({
id: credential.cards[0].id,
limit: { amount: cardLimitUsd * 100, frequency: "per7DayPeriod" },
});
return c.json({ code: "ok" }, 200);
}
if (payload.template === "manteca") {
getActiveSpan()?.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, "persona.inquiry.manteca");
await addDocument(payload.data.attributes.referenceId, {
Expand Down
Loading
Loading