// src/routes/signup/+page.server.ts
import { fail } from '@sveltejs/kit';
import { SHIELDLABS_API_KEY, SHIELDLABS_DOMAIN_ID } from '$env/static/private';
import { ShieldLabs, ShieldLabsError, evaluateIdentification, parseHistoryEntity, type Identification } from '@shieldlabs-ai/node';
import type { Actions } from './$types';
const shieldlabs = new ShieldLabs({ apiKey: SHIELDLABS_API_KEY });
const usedIdentificationIds = new Set<string>(); // in production, your database
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const identificationId = String(data.get('identificationId') ?? '');
let identification: Identification | null = null;
if (identificationId) {
try {
// Polls for a stored result within a bounded budget.
identification = await shieldlabs.identifications.get(identificationId, { domainId: SHIELDLABS_DOMAIN_ID });
if (identification) {
const card = parseHistoryEntity(identification.raw);
if (card.type !== 'identification' || card.id !== identificationId ||
card.domain_id !== SHIELDLABS_DOMAIN_ID || card.risk.state !== 'ok' ||
card.signals.state !== 'ok' || !Number.isFinite(identification.risk_score)) identification = null;
}
} catch (error) {
identification = null;
if (!(error instanceof ShieldLabsError)) throw error; // a malformed ID stays unverified
}
}
const verdict = evaluateIdentification(identification, {
isReplay: (id) => usedIdentificationIds.has(`${SHIELDLABS_DOMAIN_ID}:${id}`), // Identification IDs that already authorized an action
});
if (!verdict.ok) return fail(403, { message: 'We could not verify this signup.' });
usedIdentificationIds.add(`${SHIELDLABS_DOMAIN_ID}:${identificationId}`); // one identification authorizes one signup
// ...create the account
},
} satisfies Actions;