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/chilly-suns-dress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@exactly/server": patch
---

✨ add provisioning to card
163 changes: 89 additions & 74 deletions server/api/card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
getCard,
getNonce,
getPIN,
getProcessorDetails,
getSecrets,
getUser,
setPIN,
Expand Down Expand Up @@ -92,6 +93,12 @@ const CardResponse = object({
}),
productId: pipe(string(), metadata({ examples: ["402"] })),
challenge: optional(pipe(string(), metadata({ examples: ["1a2b3c"] }))),
provisioning: optional(
object({
id: pipe(string(), metadata({ examples: ["card_abc123"] })),
secret: pipe(string(), metadata({ examples: ["otp_xyz"] })),
}),
),
});

const CreatedCardResponse = object({
Expand Down Expand Up @@ -145,7 +152,7 @@ const UpdatedCardResponse = union([
object({ verification: literal("OK") }),
]);

const Scopes = picklist(["siwe", "webauthn"]);
const Scopes = picklist(["provisioning", "siwe", "webauthn"]);

export default new Hono()
.get(
Expand Down Expand Up @@ -183,6 +190,8 @@ The \`sessionid\` header and the \`scope\` query parameter are independent and m
- Provide \`sessionid\` to receive \`encryptedPan\`, \`encryptedCvc\`, and \`pin\`. Without it, only the card profile is returned.
- Provide \`scope=siwe\` or \`scope=webauthn\` to receive a \`challenge\` to be signed and submitted via \`PATCH /\`. \`siwe\` and \`webauthn\` are mutually exclusive within a single request.

Successful responses include push-provisioning credentials in the \`provisioning\` field only when the \`scope=provisioning\` query parameter is sent.

**Retrieving encrypted card details**
1. **Generate a session ID**: Encrypt a 32‑character hexadecimal secret (no spaces/dashes) with the provided public RSA key using RSA‑OAEP.
2. **Send the request**: Include the encrypted secret in the header \`sessionid\` when calling this endpoint.
Expand Down Expand Up @@ -273,9 +282,9 @@ function decrypt(base64Secret: string, base64Iv: string, secretKey: string): str
},
}),
async (c) => {
const { scope } = c.req.valid("query");
const query = c.req.valid("query");
function include(type: InferInput<typeof Scopes>) {
return Array.isArray(scope) ? scope.includes(type) : scope === type;
return Array.isArray(query.scope) ? query.scope.includes(type) : query.scope === type;
}
const { credentialId } = c.req.valid("cookie");
const credential = await database.query.credentials.findFirst({
Expand All @@ -293,78 +302,84 @@ function decrypt(base64Secret: string, base64Iv: string, secretKey: string): str
setUser({ id: account });
if (!credential.pandaId) return c.json({ code: "no panda" }, 403);
const sessionid = c.req.valid("header").sessionid;
if (credential.cards.length > 0 && credential.cards[0]) {
const { id, lastFour, status, mode, productId } = credential.cards[0];
if (status === "DELETED") throw new Error("card deleted");
const [{ expirationMonth, expirationYear, limit }, pan, user, pin, challenge] = await Promise.all([
getCard(id),
sessionid && getSecrets(id, sessionid),
getUser(credential.pandaId).catch((error: unknown) => {
const issue = noUser(error);
if (!issue) throw error;
const shouldCapture = issue.error.status === 404 || status === "ACTIVE";
if (shouldCapture) {
withScope((s) => {
s.addEventProcessor((event) => {
if (event.exception?.values?.[0]) event.exception.values[0].type = issue.type;
return event;
});
captureException(issue.error, {
level: "warning",
fingerprint: ["{{ default }}", issue.type],
extra: {
cardId: id,
credentialId,
pandaId: credential.pandaId,
status,
shouldCapture,
userIssue: issue.type,
},
});
if (credential.cards.length === 0 || !credential.cards[0]) return c.json({ code: "no card" }, 404);
const { id, lastFour, status, mode, productId } = credential.cards[0];
if (status === "DELETED") throw new Error("card deleted");
const [{ expirationMonth, expirationYear, limit }, pan, user, pin, challenge, provisioning] = await Promise.all([
getCard(id),
sessionid && getSecrets(id, sessionid),
getUser(credential.pandaId).catch((error: unknown) => {
const issue = noUser(error);
if (!issue) throw error;
const shouldCapture = issue.error.status === 404 || status === "ACTIVE";
if (shouldCapture) {
withScope((scope) => {
scope.addEventProcessor((event) => {
if (event.exception?.values?.[0]) event.exception.values[0].type = issue.type;
return event;
});
}
return null;
}),
sessionid && getPIN(id, sessionid),
(async () => {
if (include("siwe")) {
if (!credential.pandaId) return;
return getNonce(credential.pandaId).then(({ nonce }) =>
createSiweMessage({
domain,
address: parse(Address, credentialId),
statement: `I authorize the account ${account} to be linked with the card ending in ${lastFour} for my user (${credential.pandaId})`,
uri: `https://${domain}`,
version: "1",
chainId: chain.id,
nonce,
}),
);
} else if (include("webauthn")) {
return `I authorize the account ${account} to be linked with the card ending in ${lastFour} for my user (${credential.pandaId})`;
}
})(),
]);
if (!user) return c.json({ code: "no panda" }, 403);

return c.json(
{
...(pan && { ...pan }),
...(pin && { ...pin }),
displayName: `${user.firstName} ${user.lastName}`,
expirationMonth,
expirationYear,
lastFour,
mode,
provider: "panda" as const,
status,
limit,
productId,
...(challenge && { challenge }),
} satisfies InferOutput<typeof CardResponse>,
200,
);
} else return c.json({ code: "no card" }, 404);
captureException(issue.error, {
level: "warning",
fingerprint: ["{{ default }}", issue.type],
extra: {
cardId: id,
credentialId,
pandaId: credential.pandaId,
status,
shouldCapture,
userIssue: issue.type,
},
});
});
}
return null;
}),
sessionid && getPIN(id, sessionid),
(async () => {
if (include("siwe")) {
if (!credential.pandaId) return;
return getNonce(credential.pandaId).then(({ nonce }) =>
createSiweMessage({
domain,
address: parse(Address, credentialId),
statement: `I authorize the account ${account} to be linked with the card ending in ${lastFour} for my user (${credential.pandaId})`,
uri: `https://${domain}`,
version: "1",
chainId: chain.id,
nonce,
}),
);
} else if (include("webauthn")) {
return `I authorize the account ${account} to be linked with the card ending in ${lastFour} for my user (${credential.pandaId})`;
}
})(),
include("provisioning")
? getProcessorDetails(id).then(({ processorCardId, timeBasedSecret }) => ({
id: processorCardId,
secret: timeBasedSecret,
}))
: undefined,
]);
if (!user) return c.json({ code: "no panda" }, 403);
if (include("provisioning")) c.header("Cache-Control", "no-store");
return c.json(
{
...pan,
...pin,
displayName: `${user.firstName} ${user.lastName}`,
expirationMonth,
expirationYear,
lastFour,
mode,
provider: "panda" as const,
status,
limit,
productId,
...(challenge && { challenge }),
...(provisioning && { provisioning }),
} satisfies InferOutput<typeof CardResponse>,
200,
);
},
)
.post(
Expand Down
Loading
Loading