@open-mercato/enterprise 0.10.1-develop.7727.1.0b89c4f800 → 0.10.1-develop.7736.1.88e07906bf
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modules/security/components/PasskeyProviderDetails.js +11 -10
- package/dist/modules/security/components/PasskeyProviderDetails.js.map +2 -2
- package/dist/modules/security/lib/providers/PasskeyProvider.js +24 -47
- package/dist/modules/security/lib/providers/PasskeyProvider.js.map +2 -2
- package/dist/modules/security/services/MfaService.js +10 -1
- package/dist/modules/security/services/MfaService.js.map +2 -2
- package/package.json +9 -9
- package/src/modules/security/components/PasskeyProviderDetails.tsx +11 -10
- package/src/modules/security/lib/providers/PasskeyProvider.ts +34 -59
- package/src/modules/security/services/MfaService.ts +11 -2
|
@@ -91,15 +91,15 @@ function PasskeyProviderDetails({
|
|
|
91
91
|
}, [label, onMethodAdded, t]);
|
|
92
92
|
const configuredCount = methods.length;
|
|
93
93
|
const keysLabel = configuredCount === 1 ? t("security.profile.mfa.providers.passkey.keySingle", "1 key") : t("security.profile.mfa.providers.passkey.keyMany", "{count} keys", { count: String(configuredCount) });
|
|
94
|
-
return /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-lg border border-
|
|
94
|
+
return /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-lg border border-border bg-card p-4 text-foreground", children: [
|
|
95
95
|
/* @__PURE__ */ jsx("div", { className: "flex items-start justify-between gap-3", children: /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
|
|
96
96
|
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
|
|
97
|
-
/* @__PURE__ */ jsx(Shield, { className: "size-4 text-
|
|
97
|
+
/* @__PURE__ */ jsx(Shield, { className: "size-4 text-foreground", "aria-hidden": "true" }),
|
|
98
98
|
/* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("security.profile.mfa.passkey.title", "Security keys") }),
|
|
99
99
|
configuredCount > 0 ? /* @__PURE__ */ jsx(MfaConfiguredBadge, { label: t("security.profile.mfa.providers.totp.configured", "Configured") }) : null,
|
|
100
|
-
/* @__PURE__ */ jsx(Badge, { variant: "outline",
|
|
100
|
+
/* @__PURE__ */ jsx(Badge, { variant: "outline", children: keysLabel })
|
|
101
101
|
] }),
|
|
102
|
-
/* @__PURE__ */ jsx("p", { className: "text-sm text-
|
|
102
|
+
/* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
|
|
103
103
|
"security.profile.mfa.passkey.description",
|
|
104
104
|
"Security keys are WebAuthn credentials that can only be used as a second factor of authentication."
|
|
105
105
|
) })
|
|
@@ -107,11 +107,11 @@ function PasskeyProviderDetails({
|
|
|
107
107
|
configuredCount > 0 ? /* @__PURE__ */ jsx("div", { className: "space-y-2", children: methods.map((method) => /* @__PURE__ */ jsxs(
|
|
108
108
|
"article",
|
|
109
109
|
{
|
|
110
|
-
className: "flex items-start justify-between gap-3 border-b border-
|
|
110
|
+
className: "flex items-start justify-between gap-3 border-b border-border pb-3 last:border-none last:pb-0",
|
|
111
111
|
children: [
|
|
112
112
|
/* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
|
|
113
|
-
/* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium text-
|
|
114
|
-
/* @__PURE__ */ jsxs("p", { className: "truncate text-xs text-
|
|
113
|
+
/* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium text-foreground", children: method.label ?? t("security.profile.mfa.providers.passkey.title", "Security key") }),
|
|
114
|
+
/* @__PURE__ */ jsxs("p", { className: "truncate text-xs text-muted-foreground", children: [
|
|
115
115
|
t("ui.table.registeredAt", "Registered"),
|
|
116
116
|
": ",
|
|
117
117
|
formatRelative(method.createdAt, t("security.profile.mfa.method.unknownTime", "Unknown")),
|
|
@@ -129,13 +129,14 @@ function PasskeyProviderDetails({
|
|
|
129
129
|
type: "button",
|
|
130
130
|
variant: "outline",
|
|
131
131
|
size: "sm",
|
|
132
|
+
className: "shrink-0",
|
|
132
133
|
disabled: saving || loading,
|
|
133
134
|
"aria-label": t("ui.actions.delete", "Delete"),
|
|
134
135
|
title: t("ui.actions.delete", "Delete"),
|
|
135
136
|
onClick: () => {
|
|
136
137
|
void onRemoveMethod(method);
|
|
137
138
|
},
|
|
138
|
-
children: /* @__PURE__ */ jsx(Trash2, { className: "size-4 text-
|
|
139
|
+
children: /* @__PURE__ */ jsx(Trash2, { className: "size-4 text-destructive" })
|
|
139
140
|
}
|
|
140
141
|
) : null
|
|
141
142
|
]
|
|
@@ -158,7 +159,7 @@ function PasskeyProviderDetails({
|
|
|
158
159
|
value: label,
|
|
159
160
|
onChange: (event) => setLabel(event.target.value),
|
|
160
161
|
placeholder: t("security.profile.mfa.passkey.nicknamePlaceholder", "Enter a nickname for this security key"),
|
|
161
|
-
|
|
162
|
+
size: "lg"
|
|
162
163
|
}
|
|
163
164
|
),
|
|
164
165
|
/* @__PURE__ */ jsxs(
|
|
@@ -167,7 +168,7 @@ function PasskeyProviderDetails({
|
|
|
167
168
|
type: "submit",
|
|
168
169
|
disabled: loading || saving,
|
|
169
170
|
variant: "outline",
|
|
170
|
-
|
|
171
|
+
size: "lg",
|
|
171
172
|
children: [
|
|
172
173
|
loading ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 size-4 animate-spin" }) : null,
|
|
173
174
|
t("ui.actions.add", "Add")
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/components/PasskeyProviderDetails.tsx"],
|
|
4
|
-
"sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { browserSupportsWebAuthn, startRegistration } from '@simplewebauthn/browser'\nimport { formatDistanceToNow } from 'date-fns'\nimport { Eye, EyeOff, Loader2, Shield, Trash2 } from 'lucide-react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport type { MfaMethod } from '../types'\nimport MfaConfiguredBadge from './mfa-provider-list-items/MfaConfiguredBadge'\n\ntype RegisterOptionsResponse = {\n setupId: string\n clientData?: Record<string, unknown>\n}\n\ntype RegisterResponse = {\n ok?: boolean\n recoveryCodes?: string[]\n}\n\nfunction readErrorMessage(error: unknown): string {\n if (error && typeof error === 'object' && 'message' in error && typeof error.message === 'string') {\n return error.message\n }\n return 'Passkey registration failed.'\n}\n\nfunction isAbortError(error: unknown): boolean {\n const name = error && typeof error === 'object' && 'name' in error ? String(error.name) : ''\n if (name === 'AbortError' || name === 'NotAllowedError') {\n return true\n }\n\n const message = readErrorMessage(error).toLowerCase()\n return message.includes('cancel') || message.includes('aborted') || message.includes('not allowed')\n}\n\ntype PasskeyProviderDetailsProps = {\n methods?: MfaMethod[]\n saving?: boolean\n onRemoveMethod?: (method: MfaMethod) => Promise<void> | void\n onMethodAdded?: () => Promise<void> | void\n}\n\nfunction formatRelative(value: string | null, fallback: string): string {\n if (!value) return fallback\n const parsed = new Date(value)\n if (Number.isNaN(parsed.getTime())) return fallback\n return formatDistanceToNow(parsed, { addSuffix: true })\n}\n\nexport default function PasskeyProviderDetails({\n methods = [],\n saving = false,\n onRemoveMethod,\n onMethodAdded,\n}: PasskeyProviderDetailsProps) {\n const t = useT()\n const [label, setLabel] = React.useState('')\n const [loading, setLoading] = React.useState(false)\n\n const handleAddPasskey = React.useCallback(async () => {\n if (!browserSupportsWebAuthn()) {\n flash(\n t('security.profile.mfa.passkey.unsupported', 'Passkeys are not supported by this browser.'),\n 'error',\n )\n return\n }\n\n setLoading(true)\n try {\n const optionsResult = await readApiResultOrThrow<RegisterOptionsResponse>(\n '/api/security/mfa/provider/passkey',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n label: label.trim() || undefined,\n }),\n },\n )\n\n const registrationResponse = await startRegistration({\n optionsJSON: (optionsResult.clientData ?? {}) as never,\n })\n\n await readApiResultOrThrow<RegisterResponse>(\n '/api/security/mfa/provider/passkey',\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n setupId: optionsResult.setupId,\n payload: {\n response: registrationResponse,\n label: label.trim() || undefined,\n },\n }),\n },\n )\n\n setLabel('')\n await onMethodAdded?.()\n flash(t('security.profile.mfa.passkey.success', 'Passkey enabled.'), 'success')\n } catch (error) {\n if (!isAbortError(error)) {\n flash(readErrorMessage(error), 'error')\n }\n } finally {\n setLoading(false)\n }\n }, [label, onMethodAdded, t])\n\n const configuredCount = methods.length\n const keysLabel = configuredCount === 1\n ? t('security.profile.mfa.providers.passkey.keySingle', '1 key')\n : t('security.profile.mfa.providers.passkey.keyMany', '{count} keys', { count: String(configuredCount) })\n\n return (\n <section className=\"space-y-4 rounded-lg border border-
|
|
5
|
-
"mappings": ";AAiIU,SACE,KADF;AA/HV,YAAY,WAAW;AACvB,SAAS,yBAAyB,yBAAyB;AAC3D,SAAS,2BAA2B;AACpC,SAAsB,SAAS,QAAQ,cAAc;AACrD,SAAS,YAAY;AACrB,SAAS,aAAa;AACtB,SAAS,4BAA4B;AACrC,SAAS,aAAa;AACtB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AAEtB,OAAO,wBAAwB;AAY/B,SAAS,iBAAiB,OAAwB;AAChD,MAAI,SAAS,OAAO,UAAU,YAAY,aAAa,SAAS,OAAO,MAAM,YAAY,UAAU;AACjG,WAAO,MAAM;AAAA,EACf;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAyB;AAC7C,QAAM,OAAO,SAAS,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,MAAM,IAAI,IAAI;AAC1F,MAAI,SAAS,gBAAgB,SAAS,mBAAmB;A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AAA,YACvB,SAAS;AAAA,cACP,UAAU;AAAA,cACV,OAAO,MAAM,KAAK,KAAK;AAAA,YACzB;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AAEA,eAAS,EAAE;AACX,YAAM,gBAAgB;AACtB,YAAM,EAAE,wCAAwC,kBAAkB,GAAG,SAAS;AAAA,IAChF,SAAS,OAAO;AACd,UAAI,CAAC,aAAa,KAAK,GAAG;AACxB,cAAM,iBAAiB,KAAK,GAAG,OAAO;AAAA,MACxC;AAAA,IACF,UAAE;AACA,iBAAW,KAAK;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC;AAE5B,QAAM,kBAAkB,QAAQ;AAChC,QAAM,YAAY,oBAAoB,IAClC,EAAE,oDAAoD,OAAO,IAC7D,EAAE,kDAAkD,gBAAgB,EAAE,OAAO,OAAO,eAAe,EAAE,CAAC;AAE1G,SACE,qBAAC,aAAQ,WAAU,
|
|
4
|
+
"sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { browserSupportsWebAuthn, startRegistration } from '@simplewebauthn/browser'\nimport { formatDistanceToNow } from 'date-fns'\nimport { Eye, EyeOff, Loader2, Shield, Trash2 } from 'lucide-react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport type { MfaMethod } from '../types'\nimport MfaConfiguredBadge from './mfa-provider-list-items/MfaConfiguredBadge'\n\ntype RegisterOptionsResponse = {\n setupId: string\n clientData?: Record<string, unknown>\n}\n\ntype RegisterResponse = {\n ok?: boolean\n recoveryCodes?: string[]\n}\n\nfunction readErrorMessage(error: unknown): string {\n if (error && typeof error === 'object' && 'message' in error && typeof error.message === 'string') {\n return error.message\n }\n return 'Passkey registration failed.'\n}\n\nfunction isAbortError(error: unknown): boolean {\n const name = error && typeof error === 'object' && 'name' in error ? String(error.name) : ''\n if (name === 'AbortError' || name === 'NotAllowedError') {\n return true\n }\n\n const message = readErrorMessage(error).toLowerCase()\n return message.includes('cancel') || message.includes('aborted') || message.includes('not allowed')\n}\n\ntype PasskeyProviderDetailsProps = {\n methods?: MfaMethod[]\n saving?: boolean\n onRemoveMethod?: (method: MfaMethod) => Promise<void> | void\n onMethodAdded?: () => Promise<void> | void\n}\n\nfunction formatRelative(value: string | null, fallback: string): string {\n if (!value) return fallback\n const parsed = new Date(value)\n if (Number.isNaN(parsed.getTime())) return fallback\n return formatDistanceToNow(parsed, { addSuffix: true })\n}\n\nexport default function PasskeyProviderDetails({\n methods = [],\n saving = false,\n onRemoveMethod,\n onMethodAdded,\n}: PasskeyProviderDetailsProps) {\n const t = useT()\n const [label, setLabel] = React.useState('')\n const [loading, setLoading] = React.useState(false)\n\n const handleAddPasskey = React.useCallback(async () => {\n if (!browserSupportsWebAuthn()) {\n flash(\n t('security.profile.mfa.passkey.unsupported', 'Passkeys are not supported by this browser.'),\n 'error',\n )\n return\n }\n\n setLoading(true)\n try {\n const optionsResult = await readApiResultOrThrow<RegisterOptionsResponse>(\n '/api/security/mfa/provider/passkey',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n label: label.trim() || undefined,\n }),\n },\n )\n\n const registrationResponse = await startRegistration({\n optionsJSON: (optionsResult.clientData ?? {}) as never,\n })\n\n await readApiResultOrThrow<RegisterResponse>(\n '/api/security/mfa/provider/passkey',\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n setupId: optionsResult.setupId,\n payload: {\n response: registrationResponse,\n label: label.trim() || undefined,\n },\n }),\n },\n )\n\n setLabel('')\n await onMethodAdded?.()\n flash(t('security.profile.mfa.passkey.success', 'Passkey enabled.'), 'success')\n } catch (error) {\n if (!isAbortError(error)) {\n flash(readErrorMessage(error), 'error')\n }\n } finally {\n setLoading(false)\n }\n }, [label, onMethodAdded, t])\n\n const configuredCount = methods.length\n const keysLabel = configuredCount === 1\n ? t('security.profile.mfa.providers.passkey.keySingle', '1 key')\n : t('security.profile.mfa.providers.passkey.keyMany', '{count} keys', { count: String(configuredCount) })\n\n return (\n <section className=\"space-y-4 rounded-lg border border-border bg-card p-4 text-foreground\">\n <div className=\"flex items-start justify-between gap-3\">\n <div className=\"space-y-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <Shield className=\"size-4 text-foreground\" aria-hidden=\"true\" />\n <h2 className=\"text-lg font-semibold\">\n {t('security.profile.mfa.passkey.title', 'Security keys')}\n </h2>\n {configuredCount > 0 ? (\n <MfaConfiguredBadge label={t('security.profile.mfa.providers.totp.configured', 'Configured')} />\n ) : null}\n <Badge variant=\"outline\">\n {keysLabel}\n </Badge>\n </div>\n <p className=\"text-sm text-muted-foreground\">\n {t(\n 'security.profile.mfa.passkey.description',\n 'Security keys are WebAuthn credentials that can only be used as a second factor of authentication.',\n )}\n </p>\n </div>\n </div>\n\n {configuredCount > 0 ? (\n <div className=\"space-y-2\">\n {methods.map((method) => (\n <article\n key={method.id}\n className=\"flex items-start justify-between gap-3 border-b border-border pb-3 last:border-none last:pb-0\"\n >\n <div className=\"min-w-0\">\n <p className=\"truncate text-sm font-medium text-foreground\">\n {method.label ?? t('security.profile.mfa.providers.passkey.title', 'Security key')}\n </p>\n <p className=\"truncate text-xs text-muted-foreground\">\n {t('ui.table.registeredAt', 'Registered')}: {formatRelative(method.createdAt, t('security.profile.mfa.method.unknownTime', 'Unknown'))}\n {' '}|{' '}\n {t('security.profile.mfa.method.lastUsed', 'Last used')}: {formatRelative(method.lastUsedAt, t('security.profile.mfa.method.neverUsed', 'Never used'))}\n </p>\n </div>\n {onRemoveMethod ? (\n <IconButton\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"shrink-0\"\n disabled={saving || loading}\n aria-label={t('ui.actions.delete', 'Delete')}\n title={t('ui.actions.delete', 'Delete')}\n onClick={() => {\n void onRemoveMethod(method)\n }}\n >\n <Trash2 className=\"size-4 text-destructive\" />\n </IconButton>\n ) : null}\n </article>\n ))}\n </div>\n ) : null}\n\n <form\n className=\"flex items-center gap-0 space-x-2\"\n onSubmit={(event) => {\n event.preventDefault()\n if (loading) return\n void handleAddPasskey()\n }}\n >\n <Input\n value={label}\n onChange={(event) => setLabel(event.target.value)}\n placeholder={t('security.profile.mfa.passkey.nicknamePlaceholder', 'Enter a nickname for this security key')}\n size=\"lg\"\n />\n <Button\n type=\"submit\"\n disabled={loading || saving}\n variant=\"outline\"\n size=\"lg\"\n >\n {loading ? <Loader2 className=\"mr-2 size-4 animate-spin\" /> : null}\n {t('ui.actions.add', 'Add')}\n </Button>\n </form>\n </section>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AAiIU,SACE,KADF;AA/HV,YAAY,WAAW;AACvB,SAAS,yBAAyB,yBAAyB;AAC3D,SAAS,2BAA2B;AACpC,SAAsB,SAAS,QAAQ,cAAc;AACrD,SAAS,YAAY;AACrB,SAAS,aAAa;AACtB,SAAS,4BAA4B;AACrC,SAAS,aAAa;AACtB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AAEtB,OAAO,wBAAwB;AAY/B,SAAS,iBAAiB,OAAwB;AAChD,MAAI,SAAS,OAAO,UAAU,YAAY,aAAa,SAAS,OAAO,MAAM,YAAY,UAAU;AACjG,WAAO,MAAM;AAAA,EACf;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAyB;AAC7C,QAAM,OAAO,SAAS,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,MAAM,IAAI,IAAI;AAC1F,MAAI,SAAS,gBAAgB,SAAS,mBAAmB;AACvD,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,iBAAiB,KAAK,EAAE,YAAY;AACpD,SAAO,QAAQ,SAAS,QAAQ,KAA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@ -19,19 +19,10 @@ const setupPayloadSchema = z.object({
|
|
|
19
19
|
userName: z.string().min(1).max(255).optional(),
|
|
20
20
|
authenticatorAttachment: z.enum(["platform", "cross-platform"]).optional()
|
|
21
21
|
});
|
|
22
|
-
const setupConfirmationPayloadSchema = z.
|
|
23
|
-
z.
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
}),
|
|
27
|
-
z.object({
|
|
28
|
-
credentialId: z.string().min(1),
|
|
29
|
-
publicKey: z.string().min(1),
|
|
30
|
-
challenge: z.string().min(1),
|
|
31
|
-
transports: z.array(z.string().min(1)).optional(),
|
|
32
|
-
label: z.string().min(1).max(100).optional()
|
|
33
|
-
})
|
|
34
|
-
]);
|
|
22
|
+
const setupConfirmationPayloadSchema = z.object({
|
|
23
|
+
response: z.record(z.string(), z.unknown()),
|
|
24
|
+
label: z.string().min(1).max(100).optional()
|
|
25
|
+
});
|
|
35
26
|
const verifyPayloadSchema = z.object({
|
|
36
27
|
response: z.record(z.string(), z.unknown())
|
|
37
28
|
});
|
|
@@ -121,44 +112,30 @@ class PasskeyProvider {
|
|
|
121
112
|
if (Date.now() - pending.createdAt > securityConfig.webauthn.setupTtlMs) {
|
|
122
113
|
throw new Error("Passkey setup session expired");
|
|
123
114
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
throw new Error("Passkey registration verification failed");
|
|
134
|
-
}
|
|
135
|
-
const registrationInfo = verification.registrationInfo;
|
|
136
|
-
const credentialId = registrationInfo.credential?.id ?? registrationInfo.credentialID;
|
|
137
|
-
const publicKeyBytes = registrationInfo.credential?.publicKey ?? registrationInfo.credentialPublicKey;
|
|
138
|
-
const counter = registrationInfo.credential?.counter ?? registrationInfo.counter ?? 0;
|
|
139
|
-
const transports = this.normalizeTransports(registrationInfo.credential?.transports);
|
|
140
|
-
if (!credentialId || !publicKeyBytes) {
|
|
141
|
-
throw new Error("Passkey registration did not return credential data");
|
|
142
|
-
}
|
|
143
|
-
return {
|
|
144
|
-
metadata: {
|
|
145
|
-
credentialId,
|
|
146
|
-
credentialPublicKey: this.bytesToBase64Url(publicKeyBytes),
|
|
147
|
-
counter,
|
|
148
|
-
transports,
|
|
149
|
-
label: parsed.label ?? pending.label ?? "Passkey"
|
|
150
|
-
}
|
|
151
|
-
};
|
|
115
|
+
const verification = await verifyRegistrationResponse({
|
|
116
|
+
response: parsed.response,
|
|
117
|
+
expectedChallenge: pending.challenge,
|
|
118
|
+
expectedOrigin: this.getExpectedOrigins(securityConfig),
|
|
119
|
+
expectedRPID: this.getRpId(securityConfig),
|
|
120
|
+
requireUserVerification: false
|
|
121
|
+
});
|
|
122
|
+
if (!verification.verified || !verification.registrationInfo) {
|
|
123
|
+
throw new Error("Passkey registration verification failed");
|
|
152
124
|
}
|
|
153
|
-
|
|
154
|
-
|
|
125
|
+
const registrationInfo = verification.registrationInfo;
|
|
126
|
+
const credentialId = registrationInfo.credential?.id ?? registrationInfo.credentialID;
|
|
127
|
+
const publicKeyBytes = registrationInfo.credential?.publicKey ?? registrationInfo.credentialPublicKey;
|
|
128
|
+
const counter = registrationInfo.credential?.counter ?? registrationInfo.counter ?? 0;
|
|
129
|
+
const transports = this.normalizeTransports(registrationInfo.credential?.transports);
|
|
130
|
+
if (!credentialId || !publicKeyBytes) {
|
|
131
|
+
throw new Error("Passkey registration did not return credential data");
|
|
155
132
|
}
|
|
156
133
|
return {
|
|
157
134
|
metadata: {
|
|
158
|
-
credentialId
|
|
159
|
-
credentialPublicKey:
|
|
160
|
-
counter
|
|
161
|
-
transports
|
|
135
|
+
credentialId,
|
|
136
|
+
credentialPublicKey: this.bytesToBase64Url(publicKeyBytes),
|
|
137
|
+
counter,
|
|
138
|
+
transports,
|
|
162
139
|
label: parsed.label ?? pending.label ?? "Passkey"
|
|
163
140
|
}
|
|
164
141
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/security/lib/providers/PasskeyProvider.ts"],
|
|
4
|
-
"sourcesContent": ["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport {\n generateAuthenticationOptions,\n generateRegistrationOptions,\n verifyAuthenticationResponse,\n verifyRegistrationResponse,\n} from '@simplewebauthn/server'\nimport type { AuthenticatorTransportFuture } from '@simplewebauthn/types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { z } from 'zod'\nimport type {\n MfaMethodRecord,\n MfaProviderConfirmResult,\n MfaProviderInterface,\n MfaProviderRuntimeContext,\n MfaProviderUser,\n MfaVerifyContext,\n} from '../mfa-provider-interface'\nimport type { SecurityModuleConfig } from '../security-config'\nimport {\n readSecurityModuleConfig,\n readSecuritySetupTokenSecret,\n resolveSecurityModuleConfigForRequest,\n} from '../security-config'\n\nconst SETUP_TOKEN_VERSION = 'v1'\n\nconst logger = createLogger('security').child({ component: 'passkey-provider' })\n\nconst setupPayloadSchema = z.object({\n label: z.string().min(1).max(100).optional(),\n userName: z.string().min(1).max(255).optional(),\n authenticatorAttachment: z.enum(['platform', 'cross-platform']).optional(),\n})\n\nconst setupConfirmationPayloadSchema = z.union([\n z.object({\n response: z.record(z.string(), z.unknown()),\n label: z.string().min(1).max(100).optional(),\n }),\n z.object({\n credentialId: z.string().min(1),\n publicKey: z.string().min(1),\n challenge: z.string().min(1),\n transports: z.array(z.string().min(1)).optional(),\n label: z.string().min(1).max(100).optional(),\n }),\n])\n\nconst verifyPayloadSchema = z.object({\n response: z.record(z.string(), z.unknown()),\n})\n\nconst setupTokenSchema = z.object({\n version: z.string().min(1),\n userId: z.string().min(1),\n challenge: z.string().min(1),\n label: z.string().min(1).max(100).optional(),\n createdAt: z.number().int().nonnegative(),\n nonce: z.string().min(1),\n})\n\ntype PendingSetup = {\n version: string\n userId: string\n challenge: string\n label?: string\n createdAt: number\n nonce: string\n}\n\nconst verifyContextSchema = z.object({\n challenge: z.object({\n challenge: z.string().min(1),\n createdAt: z.number().int().nonnegative(),\n }),\n})\n\nconst AUTHENTICATOR_TRANSPORTS: AuthenticatorTransportFuture[] = [\n 'ble',\n 'cable',\n 'hybrid',\n 'internal',\n 'nfc',\n 'smart-card',\n 'usb',\n]\n\nexport class PasskeyProvider implements MfaProviderInterface {\n readonly type = 'passkey'\n readonly label = 'Passkey'\n readonly icon = 'Key'\n readonly allowMultiple = true\n readonly setupSchema = setupPayloadSchema\n readonly verifySchema = verifyPayloadSchema\n\n constructor(\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n private readonly setupTokenSecret: string = readSecuritySetupTokenSecret(),\n ) {}\n\n resolveSetupPayload(user: MfaProviderUser, payload: unknown): unknown {\n const parsed = setupPayloadSchema.parse(payload ?? {})\n const email = typeof user.email === 'string' ? user.email.trim() : ''\n\n return {\n ...parsed,\n ...(parsed.label || email.length === 0 ? {} : { label: email }),\n ...(parsed.userName || email.length === 0 ? {} : { userName: email }),\n }\n }\n\n async setup(\n userId: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ setupId: string; clientData: Record<string, unknown> }> {\n const parsed = setupPayloadSchema.parse(payload ?? {})\n const userName = parsed.userName ?? parsed.label ?? userId\n const userDisplayName = parsed.label ?? parsed.userName ?? userId\n const securityConfig = this.resolveSecurityConfig(context)\n const options = await generateRegistrationOptions({\n rpName: this.getRpName(securityConfig),\n rpID: this.getRpId(securityConfig),\n userID: this.toWebAuthnUserId(userId),\n userName,\n userDisplayName,\n timeout: securityConfig.webauthn.setupTtlMs,\n attestationType: 'none',\n authenticatorSelection: {\n residentKey: 'required',\n userVerification: 'preferred',\n ...(parsed.authenticatorAttachment ? { authenticatorAttachment: parsed.authenticatorAttachment } : {}),\n },\n })\n\n const now = Date.now()\n const setupId = this.createSetupToken({\n version: SETUP_TOKEN_VERSION,\n userId,\n challenge: options.challenge,\n label: parsed.label,\n createdAt: now,\n nonce: randomBytes(16).toString('hex'),\n })\n\n return {\n setupId,\n clientData: options as unknown as Record<string, unknown>,\n }\n }\n\n async confirmSetup(\n userId: string,\n setupId: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<MfaProviderConfirmResult> {\n const parsed = setupConfirmationPayloadSchema.parse(payload)\n const pending = this.readSetupToken(setupId)\n const securityConfig = this.resolveSecurityConfig(context)\n if (!pending || pending.version !== SETUP_TOKEN_VERSION || pending.userId !== userId) {\n throw new Error('Passkey setup session not found')\n }\n if (Date.now() - pending.createdAt > securityConfig.webauthn.setupTtlMs) {\n throw new Error('Passkey setup session expired')\n }\n\n if ('response' in parsed) {\n const verification = await verifyRegistrationResponse({\n response: parsed.response as never,\n expectedChallenge: pending.challenge,\n expectedOrigin: this.getExpectedOrigins(securityConfig),\n expectedRPID: this.getRpId(securityConfig),\n requireUserVerification: false,\n })\n\n if (!verification.verified || !verification.registrationInfo) {\n throw new Error('Passkey registration verification failed')\n }\n\n const registrationInfo = verification.registrationInfo as {\n credential?: {\n id: string\n publicKey: Uint8Array\n counter: number\n transports?: string[]\n }\n credentialID?: string\n credentialPublicKey?: Uint8Array\n counter?: number\n }\n\n const credentialId = registrationInfo.credential?.id ?? registrationInfo.credentialID\n const publicKeyBytes = registrationInfo.credential?.publicKey ?? registrationInfo.credentialPublicKey\n const counter = registrationInfo.credential?.counter ?? registrationInfo.counter ?? 0\n const transports = this.normalizeTransports(registrationInfo.credential?.transports)\n\n if (!credentialId || !publicKeyBytes) {\n throw new Error('Passkey registration did not return credential data')\n }\n\n return {\n metadata: {\n credentialId,\n credentialPublicKey: this.bytesToBase64Url(publicKeyBytes),\n counter,\n transports,\n label: parsed.label ?? pending.label ?? 'Passkey',\n },\n }\n }\n\n if (parsed.challenge !== pending.challenge) {\n throw new Error('Invalid passkey setup challenge')\n }\n\n return {\n metadata: {\n credentialId: parsed.credentialId,\n credentialPublicKey: parsed.publicKey,\n counter: 0,\n transports: parsed.transports ?? [],\n label: parsed.label ?? pending.label ?? 'Passkey',\n },\n }\n }\n\n async prepareChallenge(\n userId: string,\n method: MfaMethodRecord,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ clientData?: Record<string, unknown>; verifyContext?: MfaVerifyContext }> {\n if (method.userId !== userId) {\n throw new Error('MFA method does not belong to user')\n }\n\n const metadata = method.providerMetadata ?? {}\n const credentialId = typeof metadata.credentialId === 'string' ? metadata.credentialId : null\n if (!credentialId) {\n throw new Error('Passkey credential is not configured')\n }\n\n const securityConfig = this.resolveSecurityConfig(context)\n const options = await generateAuthenticationOptions({\n rpID: this.getRpId(securityConfig),\n userVerification: 'preferred',\n timeout: securityConfig.webauthn.challengeTtlMs,\n allowCredentials: [{\n id: credentialId,\n transports: this.normalizeTransports(metadata.transports),\n }],\n })\n\n const now = Date.now()\n\n return {\n clientData: options as unknown as Record<string, unknown>,\n verifyContext: {\n challenge: {\n challenge: options.challenge,\n createdAt: now,\n },\n },\n }\n }\n\n async verify(\n userId: string,\n method: MfaMethodRecord,\n payload: unknown,\n context?: MfaVerifyContext,\n runtimeContext?: MfaProviderRuntimeContext,\n ): Promise<boolean> {\n const parsed = verifyPayloadSchema.safeParse(payload)\n if (!parsed.success) return false\n if (method.userId !== userId) return false\n\n const parsedContext = verifyContextSchema.safeParse(context)\n if (!parsedContext.success) return false\n\n const securityConfig = this.resolveSecurityConfig(runtimeContext)\n const pending = parsedContext.data.challenge\n if (Date.now() - pending.createdAt > securityConfig.webauthn.challengeTtlMs) {\n return false\n }\n\n const metadata = method.providerMetadata ?? {}\n const credentialId = typeof metadata.credentialId === 'string' ? metadata.credentialId : null\n const credentialPublicKey = typeof metadata.credentialPublicKey === 'string'\n ? metadata.credentialPublicKey\n : typeof metadata.publicKey === 'string'\n ? metadata.publicKey\n : null\n const counter = typeof metadata.counter === 'number' && Number.isFinite(metadata.counter)\n ? metadata.counter\n : 0\n\n if (!credentialId || !credentialPublicKey) {\n return false\n }\n\n const verification = await verifyAuthenticationResponse({\n response: parsed.data.response as never,\n expectedChallenge: pending.challenge,\n expectedOrigin: this.getExpectedOrigins(securityConfig),\n expectedRPID: this.getRpId(securityConfig),\n requireUserVerification: false,\n credential: {\n id: credentialId,\n publicKey: this.base64UrlToBytes(credentialPublicKey),\n counter,\n transports: this.normalizeTransports(metadata.transports),\n },\n }).catch((error: unknown) => {\n logger.warn('Passkey assertion could not be verified', {\n methodId: method.id,\n rpId: this.getRpId(securityConfig),\n err: error,\n })\n return null\n })\n\n if (!verification?.verified) {\n return false\n }\n\n const nextCounter = verification.authenticationInfo?.newCounter\n if (typeof nextCounter === 'number' && Number.isFinite(nextCounter)) {\n const providerMetadata = method.providerMetadata ?? {}\n providerMetadata.counter = nextCounter\n method.providerMetadata = providerMetadata\n }\n\n return true\n }\n\n private normalizeTransports(raw: unknown): AuthenticatorTransportFuture[] {\n if (!Array.isArray(raw)) return []\n return raw.filter((value: unknown): value is AuthenticatorTransportFuture =>\n typeof value === 'string' && AUTHENTICATOR_TRANSPORTS.includes(value as AuthenticatorTransportFuture),\n )\n }\n\n private bytesToBase64Url(value: Uint8Array): string {\n return Buffer.from(value).toString('base64url')\n }\n\n private base64UrlToBytes(value: string) {\n return new Uint8Array(Buffer.from(value, 'base64url')).slice()\n }\n\n private createSetupToken(setup: PendingSetup): string {\n const encodedPayload = Buffer.from(JSON.stringify(setup), 'utf8').toString('base64url')\n const signature = this.signSetupPayload(encodedPayload)\n return `${encodedPayload}.${signature}`\n }\n\n private readSetupToken(token: string): PendingSetup | null {\n const [encodedPayload, signature, ...extra] = token.split('.')\n if (!encodedPayload || !signature || extra.length > 0) {\n return null\n }\n\n const expectedSignature = this.signSetupPayload(encodedPayload)\n const providedBuffer = Buffer.from(signature, 'base64url')\n const expectedBuffer = Buffer.from(expectedSignature, 'base64url')\n if (providedBuffer.length !== expectedBuffer.length || !timingSafeEqual(providedBuffer, expectedBuffer)) {\n return null\n }\n\n try {\n const raw = Buffer.from(encodedPayload, 'base64url').toString('utf8')\n const parsed = JSON.parse(raw)\n const result = setupTokenSchema.safeParse(parsed)\n return result.success ? result.data : null\n } catch {\n return null\n }\n }\n\n private signSetupPayload(encodedPayload: string): string {\n return createHmac('sha256', this.getSetupTokenSecret()).update(encodedPayload).digest('base64url')\n }\n\n private getSetupTokenSecret(): string {\n return this.setupTokenSecret\n }\n\n private getRpName(securityConfig: SecurityModuleConfig): string {\n return securityConfig.webauthn.rpName\n }\n\n private getRpId(securityConfig: SecurityModuleConfig): string {\n return securityConfig.webauthn.rpId\n }\n\n private getExpectedOrigins(securityConfig: SecurityModuleConfig): string[] {\n return [...securityConfig.webauthn.expectedOrigins]\n }\n\n private resolveSecurityConfig(context?: MfaProviderRuntimeContext): SecurityModuleConfig {\n return resolveSecurityModuleConfigForRequest(this.securityConfig, context?.request)\n }\n\n private toWebAuthnUserId(userId: string) {\n return new TextEncoder().encode(userId).slice()\n }\n}\n\nexport default PasskeyProvider\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,YAAY,aAAa,uBAAuB;AACzD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAUlB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,sBAAsB;AAE5B,MAAM,SAAS,aAAa,UAAU,EAAE,MAAM,EAAE,WAAW,mBAAmB,CAAC;AAE/E,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AAAA,EAC3C,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AAAA,EAC9C,yBAAyB,EAAE,KAAK,CAAC,YAAY,gBAAgB,CAAC,EAAE,SAAS;AAC3E,CAAC;AAED,MAAM,iCAAiC,EAAE,
|
|
4
|
+
"sourcesContent": ["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport {\n generateAuthenticationOptions,\n generateRegistrationOptions,\n verifyAuthenticationResponse,\n verifyRegistrationResponse,\n} from '@simplewebauthn/server'\nimport type { AuthenticatorTransportFuture } from '@simplewebauthn/types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { z } from 'zod'\nimport type {\n MfaMethodRecord,\n MfaProviderConfirmResult,\n MfaProviderInterface,\n MfaProviderRuntimeContext,\n MfaProviderUser,\n MfaVerifyContext,\n} from '../mfa-provider-interface'\nimport type { SecurityModuleConfig } from '../security-config'\nimport {\n readSecurityModuleConfig,\n readSecuritySetupTokenSecret,\n resolveSecurityModuleConfigForRequest,\n} from '../security-config'\n\nconst SETUP_TOKEN_VERSION = 'v1'\n\nconst logger = createLogger('security').child({ component: 'passkey-provider' })\n\nconst setupPayloadSchema = z.object({\n label: z.string().min(1).max(100).optional(),\n userName: z.string().min(1).max(255).optional(),\n authenticatorAttachment: z.enum(['platform', 'cross-platform']).optional(),\n})\n\nconst setupConfirmationPayloadSchema = z.object({\n response: z.record(z.string(), z.unknown()),\n label: z.string().min(1).max(100).optional(),\n})\n\nconst verifyPayloadSchema = z.object({\n response: z.record(z.string(), z.unknown()),\n})\n\nconst setupTokenSchema = z.object({\n version: z.string().min(1),\n userId: z.string().min(1),\n challenge: z.string().min(1),\n label: z.string().min(1).max(100).optional(),\n createdAt: z.number().int().nonnegative(),\n nonce: z.string().min(1),\n})\n\ntype PendingSetup = {\n version: string\n userId: string\n challenge: string\n label?: string\n createdAt: number\n nonce: string\n}\n\nconst verifyContextSchema = z.object({\n challenge: z.object({\n challenge: z.string().min(1),\n createdAt: z.number().int().nonnegative(),\n }),\n})\n\nconst AUTHENTICATOR_TRANSPORTS: AuthenticatorTransportFuture[] = [\n 'ble',\n 'cable',\n 'hybrid',\n 'internal',\n 'nfc',\n 'smart-card',\n 'usb',\n]\n\nexport class PasskeyProvider implements MfaProviderInterface {\n readonly type = 'passkey'\n readonly label = 'Passkey'\n readonly icon = 'Key'\n readonly allowMultiple = true\n readonly setupSchema = setupPayloadSchema\n readonly verifySchema = verifyPayloadSchema\n\n constructor(\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n private readonly setupTokenSecret: string = readSecuritySetupTokenSecret(),\n ) {}\n\n resolveSetupPayload(user: MfaProviderUser, payload: unknown): unknown {\n const parsed = setupPayloadSchema.parse(payload ?? {})\n const email = typeof user.email === 'string' ? user.email.trim() : ''\n\n return {\n ...parsed,\n ...(parsed.label || email.length === 0 ? {} : { label: email }),\n ...(parsed.userName || email.length === 0 ? {} : { userName: email }),\n }\n }\n\n async setup(\n userId: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ setupId: string; clientData: Record<string, unknown> }> {\n const parsed = setupPayloadSchema.parse(payload ?? {})\n const userName = parsed.userName ?? parsed.label ?? userId\n const userDisplayName = parsed.label ?? parsed.userName ?? userId\n const securityConfig = this.resolveSecurityConfig(context)\n const options = await generateRegistrationOptions({\n rpName: this.getRpName(securityConfig),\n rpID: this.getRpId(securityConfig),\n userID: this.toWebAuthnUserId(userId),\n userName,\n userDisplayName,\n timeout: securityConfig.webauthn.setupTtlMs,\n attestationType: 'none',\n authenticatorSelection: {\n residentKey: 'required',\n userVerification: 'preferred',\n ...(parsed.authenticatorAttachment ? { authenticatorAttachment: parsed.authenticatorAttachment } : {}),\n },\n })\n\n const now = Date.now()\n const setupId = this.createSetupToken({\n version: SETUP_TOKEN_VERSION,\n userId,\n challenge: options.challenge,\n label: parsed.label,\n createdAt: now,\n nonce: randomBytes(16).toString('hex'),\n })\n\n return {\n setupId,\n clientData: options as unknown as Record<string, unknown>,\n }\n }\n\n async confirmSetup(\n userId: string,\n setupId: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<MfaProviderConfirmResult> {\n const parsed = setupConfirmationPayloadSchema.parse(payload)\n const pending = this.readSetupToken(setupId)\n const securityConfig = this.resolveSecurityConfig(context)\n if (!pending || pending.version !== SETUP_TOKEN_VERSION || pending.userId !== userId) {\n throw new Error('Passkey setup session not found')\n }\n if (Date.now() - pending.createdAt > securityConfig.webauthn.setupTtlMs) {\n throw new Error('Passkey setup session expired')\n }\n\n const verification = await verifyRegistrationResponse({\n response: parsed.response as never,\n expectedChallenge: pending.challenge,\n expectedOrigin: this.getExpectedOrigins(securityConfig),\n expectedRPID: this.getRpId(securityConfig),\n requireUserVerification: false,\n })\n\n if (!verification.verified || !verification.registrationInfo) {\n throw new Error('Passkey registration verification failed')\n }\n\n const registrationInfo = verification.registrationInfo as {\n credential?: {\n id: string\n publicKey: Uint8Array\n counter: number\n transports?: string[]\n }\n credentialID?: string\n credentialPublicKey?: Uint8Array\n counter?: number\n }\n\n const credentialId = registrationInfo.credential?.id ?? registrationInfo.credentialID\n const publicKeyBytes = registrationInfo.credential?.publicKey ?? registrationInfo.credentialPublicKey\n const counter = registrationInfo.credential?.counter ?? registrationInfo.counter ?? 0\n const transports = this.normalizeTransports(registrationInfo.credential?.transports)\n\n if (!credentialId || !publicKeyBytes) {\n throw new Error('Passkey registration did not return credential data')\n }\n\n return {\n metadata: {\n credentialId,\n credentialPublicKey: this.bytesToBase64Url(publicKeyBytes),\n counter,\n transports,\n label: parsed.label ?? pending.label ?? 'Passkey',\n },\n }\n }\n\n async prepareChallenge(\n userId: string,\n method: MfaMethodRecord,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ clientData?: Record<string, unknown>; verifyContext?: MfaVerifyContext }> {\n if (method.userId !== userId) {\n throw new Error('MFA method does not belong to user')\n }\n\n const metadata = method.providerMetadata ?? {}\n const credentialId = typeof metadata.credentialId === 'string' ? metadata.credentialId : null\n if (!credentialId) {\n throw new Error('Passkey credential is not configured')\n }\n\n const securityConfig = this.resolveSecurityConfig(context)\n const options = await generateAuthenticationOptions({\n rpID: this.getRpId(securityConfig),\n userVerification: 'preferred',\n timeout: securityConfig.webauthn.challengeTtlMs,\n allowCredentials: [{\n id: credentialId,\n transports: this.normalizeTransports(metadata.transports),\n }],\n })\n\n const now = Date.now()\n\n return {\n clientData: options as unknown as Record<string, unknown>,\n verifyContext: {\n challenge: {\n challenge: options.challenge,\n createdAt: now,\n },\n },\n }\n }\n\n async verify(\n userId: string,\n method: MfaMethodRecord,\n payload: unknown,\n context?: MfaVerifyContext,\n runtimeContext?: MfaProviderRuntimeContext,\n ): Promise<boolean> {\n const parsed = verifyPayloadSchema.safeParse(payload)\n if (!parsed.success) return false\n if (method.userId !== userId) return false\n\n const parsedContext = verifyContextSchema.safeParse(context)\n if (!parsedContext.success) return false\n\n const securityConfig = this.resolveSecurityConfig(runtimeContext)\n const pending = parsedContext.data.challenge\n if (Date.now() - pending.createdAt > securityConfig.webauthn.challengeTtlMs) {\n return false\n }\n\n const metadata = method.providerMetadata ?? {}\n const credentialId = typeof metadata.credentialId === 'string' ? metadata.credentialId : null\n const credentialPublicKey = typeof metadata.credentialPublicKey === 'string'\n ? metadata.credentialPublicKey\n : typeof metadata.publicKey === 'string'\n ? metadata.publicKey\n : null\n const counter = typeof metadata.counter === 'number' && Number.isFinite(metadata.counter)\n ? metadata.counter\n : 0\n\n if (!credentialId || !credentialPublicKey) {\n return false\n }\n\n const verification = await verifyAuthenticationResponse({\n response: parsed.data.response as never,\n expectedChallenge: pending.challenge,\n expectedOrigin: this.getExpectedOrigins(securityConfig),\n expectedRPID: this.getRpId(securityConfig),\n requireUserVerification: false,\n credential: {\n id: credentialId,\n publicKey: this.base64UrlToBytes(credentialPublicKey),\n counter,\n transports: this.normalizeTransports(metadata.transports),\n },\n }).catch((error: unknown) => {\n logger.warn('Passkey assertion could not be verified', {\n methodId: method.id,\n rpId: this.getRpId(securityConfig),\n err: error,\n })\n return null\n })\n\n if (!verification?.verified) {\n return false\n }\n\n const nextCounter = verification.authenticationInfo?.newCounter\n if (typeof nextCounter === 'number' && Number.isFinite(nextCounter)) {\n const providerMetadata = method.providerMetadata ?? {}\n providerMetadata.counter = nextCounter\n method.providerMetadata = providerMetadata\n }\n\n return true\n }\n\n private normalizeTransports(raw: unknown): AuthenticatorTransportFuture[] {\n if (!Array.isArray(raw)) return []\n return raw.filter((value: unknown): value is AuthenticatorTransportFuture =>\n typeof value === 'string' && AUTHENTICATOR_TRANSPORTS.includes(value as AuthenticatorTransportFuture),\n )\n }\n\n private bytesToBase64Url(value: Uint8Array): string {\n return Buffer.from(value).toString('base64url')\n }\n\n private base64UrlToBytes(value: string) {\n return new Uint8Array(Buffer.from(value, 'base64url')).slice()\n }\n\n private createSetupToken(setup: PendingSetup): string {\n const encodedPayload = Buffer.from(JSON.stringify(setup), 'utf8').toString('base64url')\n const signature = this.signSetupPayload(encodedPayload)\n return `${encodedPayload}.${signature}`\n }\n\n private readSetupToken(token: string): PendingSetup | null {\n const [encodedPayload, signature, ...extra] = token.split('.')\n if (!encodedPayload || !signature || extra.length > 0) {\n return null\n }\n\n const expectedSignature = this.signSetupPayload(encodedPayload)\n const providedBuffer = Buffer.from(signature, 'base64url')\n const expectedBuffer = Buffer.from(expectedSignature, 'base64url')\n if (providedBuffer.length !== expectedBuffer.length || !timingSafeEqual(providedBuffer, expectedBuffer)) {\n return null\n }\n\n try {\n const raw = Buffer.from(encodedPayload, 'base64url').toString('utf8')\n const parsed = JSON.parse(raw)\n const result = setupTokenSchema.safeParse(parsed)\n return result.success ? result.data : null\n } catch {\n return null\n }\n }\n\n private signSetupPayload(encodedPayload: string): string {\n return createHmac('sha256', this.getSetupTokenSecret()).update(encodedPayload).digest('base64url')\n }\n\n private getSetupTokenSecret(): string {\n return this.setupTokenSecret\n }\n\n private getRpName(securityConfig: SecurityModuleConfig): string {\n return securityConfig.webauthn.rpName\n }\n\n private getRpId(securityConfig: SecurityModuleConfig): string {\n return securityConfig.webauthn.rpId\n }\n\n private getExpectedOrigins(securityConfig: SecurityModuleConfig): string[] {\n return [...securityConfig.webauthn.expectedOrigins]\n }\n\n private resolveSecurityConfig(context?: MfaProviderRuntimeContext): SecurityModuleConfig {\n return resolveSecurityModuleConfigForRequest(this.securityConfig, context?.request)\n }\n\n private toWebAuthnUserId(userId: string) {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AmB,WAAW;AACjE,QAAI,eAAe,WAAW,eAAe,UAAU,CAAC,gBAAgB,gBAAgB,cAAc,GAAG;AACvG,aAAO;AAAA,IACT;AAEA,QAAI;AACF,YAAM,MAAM,OAAO,KAAK,gBAAgB,WAAW,EAAE,SAAS,MAAM;AACpE,YAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,YAAM,SAAS,iBAAiB,UAAU,MAAM;AAChD,aAAO,OAAO,UAAU,OAAO,OAAO;AAAA,IACxC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEQ,iBAAiB,gBAAgC;AACvD,WAAO,WAAW,UAAU,KAAK,oBAAoB,CAAC,EAAE,OAAO,cAAc,EAAE,OAAO,WAAW;AAAA,EACnG;AAAA,EAEQ,sBAA8B;AACpC,WAAO,KAAK;AAAA,EACd;AAAA,EAEQ,UAAU,gBAA8C;AAC9D,WAAO,eAAe,SAAS;AAAA,EACjC;AAAA,EAEQ,QAAQ,gBAA8C;AAC5D,WAAO,eAAe,SAAS;AAAA,EACjC;AAAA,EAEQ,mBAAmB,gBAAgD;AACzE,WAAO,CAAC,GAAG,eAAe,SAAS,eAAe;AAAA,EACpD;AAAA,EAEQ,sBAAsB,SAA2D;AACvF,WAAO,sCAAsC,KAAK,gBAAgB,SAAS,OAAO;AAAA,EACpF;AAAA,EAEQ,iBAAiB,QAAgB;AACvC,WAAO,IAAI,YAAY,EAAE,OAAO,MAAM,EAAE,MAAM;AAAA,EAChD;AACF;AAEA,IAAO,0BAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { compare, hash } from "bcryptjs";
|
|
3
|
+
import { ZodError } from "zod";
|
|
3
4
|
import { User } from "@open-mercato/core/modules/auth/data/entities";
|
|
4
5
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
5
6
|
import { EnforcementScope, MfaEnforcementPolicy, MfaRecoveryCode, UserMfaMethod } from "../data/entities.js";
|
|
@@ -69,7 +70,15 @@ class MfaService {
|
|
|
69
70
|
throw new MfaServiceError(`MFA provider '${method.type}' is not registered`, 400);
|
|
70
71
|
}
|
|
71
72
|
await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple);
|
|
72
|
-
|
|
73
|
+
let confirmation;
|
|
74
|
+
try {
|
|
75
|
+
confirmation = await provider.confirmSetup(userId, setupId, payload, context);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (error instanceof ZodError) {
|
|
78
|
+
throw new MfaServiceError("Invalid payload", 400);
|
|
79
|
+
}
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
73
82
|
const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null;
|
|
74
83
|
if (resolvedLabel && provider.allowMultiple) {
|
|
75
84
|
const duplicate = await this.em.findOne(UserMfaMethod, {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/services/MfaService.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { compare, hash } from 'bcryptjs'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { EnforcementScope, MfaEnforcementPolicy, MfaRecoveryCode, UserMfaMethod } from '../data/entities'\nimport { emitSecurityEvent } from '../events'\nimport type { MfaProviderRegistry } from '../lib/mfa-provider-registry'\nimport type { MfaProviderRuntimeContext } from '../lib/mfa-provider-interface'\nimport type { SecurityModuleConfig } from '../lib/security-config'\nimport { readSecurityModuleConfig } from '../lib/security-config'\n\ntype SetupResult = {\n setupId: string\n clientData: Record<string, unknown>\n}\n\ntype ProviderDisplay = {\n type: string\n label: string\n icon: string\n allowMultiple: boolean\n components?: {\n setup?: string\n list?: string\n details?: string\n challenge?: string\n }\n}\n\nexport class MfaServiceError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n ) {\n super(message)\n this.name = 'MfaServiceError'\n }\n}\n\nexport class MfaService {\n constructor(\n private readonly em: EntityManager,\n private readonly mfaProviderRegistry: MfaProviderRegistry,\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n ) {}\n\n async setupMethod(\n userId: string,\n providerType: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<SetupResult> {\n const provider = this.mfaProviderRegistry.get(providerType)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${providerType}' is not registered`, 400)\n }\n\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n await this.ensureProviderCanBeConfigured(userId, providerType, provider.allowMultiple)\n\n const resolvedPayload = provider.resolveSetupPayload\n ? await provider.resolveSetupPayload({\n id: user.id,\n email: user.email ?? null,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n }, payload)\n : payload\n\n const result = context\n ? await provider.setup(userId, resolvedPayload, context)\n : await provider.setup(userId, resolvedPayload)\n const now = new Date()\n const method = this.em.create(UserMfaMethod, {\n userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n type: providerType,\n isActive: false,\n secret: result.setupId,\n providerMetadata: null,\n createdAt: now,\n updatedAt: now,\n })\n this.em.persist(method)\n await this.em.flush()\n\n return result\n }\n\n async confirmMethod(\n userId: string,\n setupId: string,\n payload: unknown,\n providerType?: string,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ recoveryCodes?: string[] }> {\n const method = await this.em.findOne(UserMfaMethod, {\n userId,\n isActive: false,\n deletedAt: null,\n secret: setupId,\n })\n if (!method) {\n throw new MfaServiceError('MFA setup session not found', 404)\n }\n if (providerType && method.type !== providerType) {\n throw new MfaServiceError('MFA setup session does not match the requested provider', 400)\n }\n\n const provider = this.mfaProviderRegistry.get(method.type)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${method.type}' is not registered`, 400)\n }\n\n await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple)\n\n const confirmation = await provider.confirmSetup(userId, setupId, payload, context)\n const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null\n\n if (resolvedLabel && provider.allowMultiple) {\n const duplicate = await this.em.findOne(UserMfaMethod, {\n userId,\n type: method.type,\n label: resolvedLabel,\n isActive: true,\n deletedAt: null,\n })\n if (duplicate) {\n throw new MfaServiceError(`An MFA method with this name already exists`, 409)\n }\n }\n\n method.providerMetadata = confirmation.metadata\n method.secret = confirmation.secret ?? null\n method.label = resolvedLabel\n method.isActive = true\n method.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.mfa.enrolled', {\n userId,\n tenantId: method.tenantId,\n organizationId: method.organizationId ?? null,\n methodType: method.type,\n methodId: method.id,\n enrolledAt: new Date().toISOString(),\n })\n\n return {}\n }\n\n async getUserMethods(userId: string): Promise<UserMfaMethod[]> {\n return this.em.find(\n UserMfaMethod,\n {\n userId,\n isActive: true,\n deletedAt: null,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n }\n\n async getAvailableProviders(tenantId: string, orgId?: string): Promise<ProviderDisplay[]> {\n const activePolicy = await this.resolveActiveEnforcementPolicy(tenantId, orgId)\n const providers = this.mfaProviderRegistry.listAvailable(activePolicy?.allowedMethods ?? null)\n return providers.map((provider) => ({\n type: provider.type,\n label: provider.label,\n icon: provider.icon,\n allowMultiple: provider.allowMultiple,\n ...(provider.components ? { components: provider.components } : {}),\n }))\n }\n\n async removeMethod(userId: string, methodId: string): Promise<void> {\n const method = await this.em.findOne(UserMfaMethod, {\n id: methodId,\n userId,\n isActive: true,\n deletedAt: null,\n })\n if (!method) {\n throw new MfaServiceError('MFA method not found', 404)\n }\n\n method.isActive = false\n method.deletedAt = new Date()\n method.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.mfa.removed', {\n userId,\n methodId: method.id,\n methodType: method.type,\n })\n }\n\n async generateRecoveryCodes(userId: string): Promise<string[]> {\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n const existingCodes = await this.em.find(MfaRecoveryCode, {\n userId,\n isUsed: false,\n })\n const now = new Date()\n for (const code of existingCodes) {\n code.isUsed = true\n code.usedAt = now\n }\n\n const plaintextCodes: string[] = []\n for (let index = 0; index < this.securityConfig.recoveryCodes.count; index += 1) {\n const code = this.createRecoveryCode()\n const codeHash = await hash(code, this.securityConfig.recoveryCodes.bcryptCost)\n const recoveryCode = this.em.create(MfaRecoveryCode, {\n userId,\n tenantId: user.tenantId,\n codeHash,\n isUsed: false,\n createdAt: new Date(),\n })\n this.em.persist(recoveryCode)\n plaintextCodes.push(code)\n }\n\n await this.em.flush()\n await emitSecurityEvent('security.recovery.regenerated', {\n userId,\n total: plaintextCodes.length,\n })\n return plaintextCodes\n }\n\n async verifyRecoveryCode(userId: string, code: string): Promise<boolean> {\n const candidates = this.buildRecoveryCodeCandidates(code)\n if (candidates.length === 0) {\n return false\n }\n\n const recoveryCodes = await this.em.find(\n MfaRecoveryCode,\n {\n userId,\n isUsed: false,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n\n for (const recoveryCode of recoveryCodes) {\n let valid = false\n for (const candidate of candidates) {\n if (await compare(candidate, recoveryCode.codeHash)) {\n valid = true\n break\n }\n }\n if (!valid) continue\n recoveryCode.isUsed = true\n recoveryCode.usedAt = new Date()\n await this.em.flush()\n const remaining = await this.em.count(MfaRecoveryCode, { userId, isUsed: false })\n await emitSecurityEvent('security.recovery.used', { userId, remaining })\n return true\n }\n\n return false\n }\n\n private createRecoveryCode(): string {\n return randomBytes(5).toString('hex').toUpperCase()\n }\n\n private buildRecoveryCodeCandidates(input: string): string[] {\n const trimmed = input.trim()\n const compact = trimmed.replace(/[\\s-]/g, '')\n const normalized = compact.toUpperCase()\n const candidates = [trimmed, trimmed.toUpperCase(), compact, normalized]\n .filter((value) => value.length > 0)\n return [...new Set(candidates)]\n }\n\n private getLabelFromMetadata(metadata: Record<string, unknown>): string | null {\n const value = metadata.label\n return typeof value === 'string' && value.length > 0 ? value : null\n }\n\n private async ensureProviderCanBeConfigured(\n userId: string,\n providerType: string,\n allowMultiple: boolean,\n ): Promise<void> {\n if (allowMultiple) return\n\n const existingMethod = await this.em.findOne(UserMfaMethod, {\n userId,\n type: providerType,\n isActive: true,\n deletedAt: null,\n })\n if (existingMethod) {\n throw new MfaServiceError(`MFA provider '${providerType}' is already configured`, 409)\n }\n }\n\n private async findUserById(userId: string): Promise<User | null> {\n return findOneWithDecryption(this.em, User, { id: userId, deletedAt: null }, undefined, {})\n }\n\n private async resolveActiveEnforcementPolicy(\n tenantId: string,\n orgId?: string,\n ): Promise<MfaEnforcementPolicy | null> {\n if (orgId) {\n const organizationPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.ORGANISATION,\n tenantId,\n organizationId: orgId,\n isEnforced: true,\n deletedAt: null,\n })\n if (organizationPolicy) return organizationPolicy\n }\n\n const tenantPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.TENANT,\n tenantId,\n isEnforced: true,\n deletedAt: null,\n })\n if (tenantPolicy) return tenantPolicy\n\n return this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.PLATFORM,\n isEnforced: true,\n deletedAt: null,\n })\n }\n}\n\nexport default MfaService\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,SAAS,YAAY;AAC9B,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,sBAAsB,iBAAiB,qBAAqB;AACvF,SAAS,yBAAyB;AAIlC,SAAS,gCAAgC;AAoBlC,MAAM,wBAAwB,MAAM;AAAA,EACzC,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,WAAW;AAAA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AAAA,MACX,QAAQ;AAAA,IACV,CAAC;AACD,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,gBAAgB,+BAA+B,GAAG;AAAA,IAC9D;AACA,QAAI,gBAAgB,OAAO,SAAS,cAAc;AAChD,YAAM,IAAI,gBAAgB,2DAA2D,GAAG;AAAA,IAC1F;AAEA,UAAM,WAAW,KAAK,oBAAoB,IAAI,OAAO,IAAI;AACzD,QAAI,CAAC,UAAU;AACb,YAAM,IAAI,gBAAgB,iBAAiB,OAAO,IAAI,uBAAuB,GAAG;AAAA,IAClF;AAEA,UAAM,KAAK,8BAA8B,QAAQ,OAAO,MAAM,SAAS,aAAa;AAEpF,
|
|
4
|
+
"sourcesContent": ["import { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { compare, hash } from 'bcryptjs'\nimport { ZodError } from 'zod'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { EnforcementScope, MfaEnforcementPolicy, MfaRecoveryCode, UserMfaMethod } from '../data/entities'\nimport { emitSecurityEvent } from '../events'\nimport type { MfaProviderRegistry } from '../lib/mfa-provider-registry'\nimport type { MfaProviderConfirmResult, MfaProviderRuntimeContext } from '../lib/mfa-provider-interface'\nimport type { SecurityModuleConfig } from '../lib/security-config'\nimport { readSecurityModuleConfig } from '../lib/security-config'\n\ntype SetupResult = {\n setupId: string\n clientData: Record<string, unknown>\n}\n\ntype ProviderDisplay = {\n type: string\n label: string\n icon: string\n allowMultiple: boolean\n components?: {\n setup?: string\n list?: string\n details?: string\n challenge?: string\n }\n}\n\nexport class MfaServiceError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n ) {\n super(message)\n this.name = 'MfaServiceError'\n }\n}\n\nexport class MfaService {\n constructor(\n private readonly em: EntityManager,\n private readonly mfaProviderRegistry: MfaProviderRegistry,\n private readonly securityConfig: SecurityModuleConfig = readSecurityModuleConfig(),\n ) {}\n\n async setupMethod(\n userId: string,\n providerType: string,\n payload: unknown,\n context?: MfaProviderRuntimeContext,\n ): Promise<SetupResult> {\n const provider = this.mfaProviderRegistry.get(providerType)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${providerType}' is not registered`, 400)\n }\n\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n await this.ensureProviderCanBeConfigured(userId, providerType, provider.allowMultiple)\n\n const resolvedPayload = provider.resolveSetupPayload\n ? await provider.resolveSetupPayload({\n id: user.id,\n email: user.email ?? null,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n }, payload)\n : payload\n\n const result = context\n ? await provider.setup(userId, resolvedPayload, context)\n : await provider.setup(userId, resolvedPayload)\n const now = new Date()\n const method = this.em.create(UserMfaMethod, {\n userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n type: providerType,\n isActive: false,\n secret: result.setupId,\n providerMetadata: null,\n createdAt: now,\n updatedAt: now,\n })\n this.em.persist(method)\n await this.em.flush()\n\n return result\n }\n\n async confirmMethod(\n userId: string,\n setupId: string,\n payload: unknown,\n providerType?: string,\n context?: MfaProviderRuntimeContext,\n ): Promise<{ recoveryCodes?: string[] }> {\n const method = await this.em.findOne(UserMfaMethod, {\n userId,\n isActive: false,\n deletedAt: null,\n secret: setupId,\n })\n if (!method) {\n throw new MfaServiceError('MFA setup session not found', 404)\n }\n if (providerType && method.type !== providerType) {\n throw new MfaServiceError('MFA setup session does not match the requested provider', 400)\n }\n\n const provider = this.mfaProviderRegistry.get(method.type)\n if (!provider) {\n throw new MfaServiceError(`MFA provider '${method.type}' is not registered`, 400)\n }\n\n await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple)\n\n let confirmation: MfaProviderConfirmResult\n try {\n confirmation = await provider.confirmSetup(userId, setupId, payload, context)\n } catch (error) {\n if (error instanceof ZodError) {\n throw new MfaServiceError('Invalid payload', 400)\n }\n throw error\n }\n const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null\n\n if (resolvedLabel && provider.allowMultiple) {\n const duplicate = await this.em.findOne(UserMfaMethod, {\n userId,\n type: method.type,\n label: resolvedLabel,\n isActive: true,\n deletedAt: null,\n })\n if (duplicate) {\n throw new MfaServiceError(`An MFA method with this name already exists`, 409)\n }\n }\n\n method.providerMetadata = confirmation.metadata\n method.secret = confirmation.secret ?? null\n method.label = resolvedLabel\n method.isActive = true\n method.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.mfa.enrolled', {\n userId,\n tenantId: method.tenantId,\n organizationId: method.organizationId ?? null,\n methodType: method.type,\n methodId: method.id,\n enrolledAt: new Date().toISOString(),\n })\n\n return {}\n }\n\n async getUserMethods(userId: string): Promise<UserMfaMethod[]> {\n return this.em.find(\n UserMfaMethod,\n {\n userId,\n isActive: true,\n deletedAt: null,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n }\n\n async getAvailableProviders(tenantId: string, orgId?: string): Promise<ProviderDisplay[]> {\n const activePolicy = await this.resolveActiveEnforcementPolicy(tenantId, orgId)\n const providers = this.mfaProviderRegistry.listAvailable(activePolicy?.allowedMethods ?? null)\n return providers.map((provider) => ({\n type: provider.type,\n label: provider.label,\n icon: provider.icon,\n allowMultiple: provider.allowMultiple,\n ...(provider.components ? { components: provider.components } : {}),\n }))\n }\n\n async removeMethod(userId: string, methodId: string): Promise<void> {\n const method = await this.em.findOne(UserMfaMethod, {\n id: methodId,\n userId,\n isActive: true,\n deletedAt: null,\n })\n if (!method) {\n throw new MfaServiceError('MFA method not found', 404)\n }\n\n method.isActive = false\n method.deletedAt = new Date()\n method.updatedAt = new Date()\n await this.em.flush()\n\n await emitSecurityEvent('security.mfa.removed', {\n userId,\n methodId: method.id,\n methodType: method.type,\n })\n }\n\n async generateRecoveryCodes(userId: string): Promise<string[]> {\n const user = await this.findUserById(userId)\n if (!user?.tenantId) {\n throw new MfaServiceError('User not found', 404)\n }\n\n const existingCodes = await this.em.find(MfaRecoveryCode, {\n userId,\n isUsed: false,\n })\n const now = new Date()\n for (const code of existingCodes) {\n code.isUsed = true\n code.usedAt = now\n }\n\n const plaintextCodes: string[] = []\n for (let index = 0; index < this.securityConfig.recoveryCodes.count; index += 1) {\n const code = this.createRecoveryCode()\n const codeHash = await hash(code, this.securityConfig.recoveryCodes.bcryptCost)\n const recoveryCode = this.em.create(MfaRecoveryCode, {\n userId,\n tenantId: user.tenantId,\n codeHash,\n isUsed: false,\n createdAt: new Date(),\n })\n this.em.persist(recoveryCode)\n plaintextCodes.push(code)\n }\n\n await this.em.flush()\n await emitSecurityEvent('security.recovery.regenerated', {\n userId,\n total: plaintextCodes.length,\n })\n return plaintextCodes\n }\n\n async verifyRecoveryCode(userId: string, code: string): Promise<boolean> {\n const candidates = this.buildRecoveryCodeCandidates(code)\n if (candidates.length === 0) {\n return false\n }\n\n const recoveryCodes = await this.em.find(\n MfaRecoveryCode,\n {\n userId,\n isUsed: false,\n },\n {\n orderBy: { createdAt: 'asc' },\n },\n )\n\n for (const recoveryCode of recoveryCodes) {\n let valid = false\n for (const candidate of candidates) {\n if (await compare(candidate, recoveryCode.codeHash)) {\n valid = true\n break\n }\n }\n if (!valid) continue\n recoveryCode.isUsed = true\n recoveryCode.usedAt = new Date()\n await this.em.flush()\n const remaining = await this.em.count(MfaRecoveryCode, { userId, isUsed: false })\n await emitSecurityEvent('security.recovery.used', { userId, remaining })\n return true\n }\n\n return false\n }\n\n private createRecoveryCode(): string {\n return randomBytes(5).toString('hex').toUpperCase()\n }\n\n private buildRecoveryCodeCandidates(input: string): string[] {\n const trimmed = input.trim()\n const compact = trimmed.replace(/[\\s-]/g, '')\n const normalized = compact.toUpperCase()\n const candidates = [trimmed, trimmed.toUpperCase(), compact, normalized]\n .filter((value) => value.length > 0)\n return [...new Set(candidates)]\n }\n\n private getLabelFromMetadata(metadata: Record<string, unknown>): string | null {\n const value = metadata.label\n return typeof value === 'string' && value.length > 0 ? value : null\n }\n\n private async ensureProviderCanBeConfigured(\n userId: string,\n providerType: string,\n allowMultiple: boolean,\n ): Promise<void> {\n if (allowMultiple) return\n\n const existingMethod = await this.em.findOne(UserMfaMethod, {\n userId,\n type: providerType,\n isActive: true,\n deletedAt: null,\n })\n if (existingMethod) {\n throw new MfaServiceError(`MFA provider '${providerType}' is already configured`, 409)\n }\n }\n\n private async findUserById(userId: string): Promise<User | null> {\n return findOneWithDecryption(this.em, User, { id: userId, deletedAt: null }, undefined, {})\n }\n\n private async resolveActiveEnforcementPolicy(\n tenantId: string,\n orgId?: string,\n ): Promise<MfaEnforcementPolicy | null> {\n if (orgId) {\n const organizationPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.ORGANISATION,\n tenantId,\n organizationId: orgId,\n isEnforced: true,\n deletedAt: null,\n })\n if (organizationPolicy) return organizationPolicy\n }\n\n const tenantPolicy = await this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.TENANT,\n tenantId,\n isEnforced: true,\n deletedAt: null,\n })\n if (tenantPolicy) return tenantPolicy\n\n return this.em.findOne(MfaEnforcementPolicy, {\n scope: EnforcementScope.PLATFORM,\n isEnforced: true,\n deletedAt: null,\n })\n }\n}\n\nexport default MfaService\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,SAAS,YAAY;AAC9B,SAAS,gBAAgB;AACzB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC,SAAS,kBAAkB,sBAAsB,iBAAiB,qBAAqB;AACvF,SAAS,yBAAyB;AAIlC,SAAS,gCAAgC;AAoBlC,MAAM,wBAAwB,MAAM;AAAA,EACzC,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,WAAW;AAAA,EACtB,YACmB,IACA,qBACA,iBAAuC,yBAAyB,GACjF;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAEH,MAAM,YACJ,QACA,cACA,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BACZ,UACA,OACsC;AACtC,QAAI,OAAO;AACT,YAAM,qBAAqB,MAAM,KAAK,GAAG,QAAQ,sBAAsB;AAAA,QACrE,OAAO,iBAAiB;AAAA,QACxB;AAAA,QACA,gBAAgB;AAAA,QAChB,YAAY;AAAA,QACZ,WAAW;AAAA,MACb,CAAC;AACD,UAAI,mBAAoB,QAAO;AAAA,IACjC;AAEA,UAAM,eAAe,MAAM,KAAK,GAAG,QAAQ,sBAAsB;AAAA,MAC/D,OAAO,iBAAiB;AAAA,MACxB;AAAA,MACA,YAAY;AAAA,MACZ,WAAW;AAAA,IACb,CAAC;AACD,QAAI,aAAc,QAAO;AAEzB,WAAO,KAAK,GAAG,QAAQ,sBAAsB;AAAA,MAC3C,OAAO,iBAAiB;AAAA,MACxB,YAAY;AAAA,MACZ,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AACF;AAEA,IAAO,qBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/enterprise",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.7736.1.88e07906bf",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -70,12 +70,12 @@
|
|
|
70
70
|
"@dnd-kit/core": "^6.3.1",
|
|
71
71
|
"@dnd-kit/sortable": "^10.0.0",
|
|
72
72
|
"@dnd-kit/utilities": "^3.2.2",
|
|
73
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
74
|
-
"@open-mercato/core": "0.10.1-develop.
|
|
75
|
-
"@open-mercato/queue": "0.10.1-develop.
|
|
76
|
-
"@open-mercato/scheduler": "0.10.1-develop.
|
|
77
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
78
|
-
"@open-mercato/web-research": "0.10.1-develop.
|
|
73
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.7736.1.88e07906bf",
|
|
74
|
+
"@open-mercato/core": "0.10.1-develop.7736.1.88e07906bf",
|
|
75
|
+
"@open-mercato/queue": "0.10.1-develop.7736.1.88e07906bf",
|
|
76
|
+
"@open-mercato/scheduler": "0.10.1-develop.7736.1.88e07906bf",
|
|
77
|
+
"@open-mercato/ui": "0.10.1-develop.7736.1.88e07906bf",
|
|
78
|
+
"@open-mercato/web-research": "0.10.1-develop.7736.1.88e07906bf",
|
|
79
79
|
"@simplewebauthn/browser": "^13.3.0",
|
|
80
80
|
"@simplewebauthn/server": "^13.3.2",
|
|
81
81
|
"@simplewebauthn/types": "^12.0.0",
|
|
@@ -87,13 +87,13 @@
|
|
|
87
87
|
},
|
|
88
88
|
"peerDependencies": {
|
|
89
89
|
"@mikro-orm/core": "^7.0.14",
|
|
90
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
90
|
+
"@open-mercato/shared": "0.10.1-develop.7736.1.88e07906bf",
|
|
91
91
|
"react": "^19.0.0",
|
|
92
92
|
"react-dom": "^19.0.0",
|
|
93
93
|
"zod": ">=3.23.0"
|
|
94
94
|
},
|
|
95
95
|
"devDependencies": {
|
|
96
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
96
|
+
"@open-mercato/shared": "0.10.1-develop.7736.1.88e07906bf",
|
|
97
97
|
"@types/jest": "^30.0.0",
|
|
98
98
|
"@types/react": "^19.2.18",
|
|
99
99
|
"@types/react-dom": "^19.2.5",
|
|
@@ -124,22 +124,22 @@ export default function PasskeyProviderDetails({
|
|
|
124
124
|
: t('security.profile.mfa.providers.passkey.keyMany', '{count} keys', { count: String(configuredCount) })
|
|
125
125
|
|
|
126
126
|
return (
|
|
127
|
-
<section className="space-y-4 rounded-lg border border-
|
|
127
|
+
<section className="space-y-4 rounded-lg border border-border bg-card p-4 text-foreground">
|
|
128
128
|
<div className="flex items-start justify-between gap-3">
|
|
129
129
|
<div className="space-y-1">
|
|
130
130
|
<div className="flex flex-wrap items-center gap-2">
|
|
131
|
-
<Shield className="size-4 text-
|
|
131
|
+
<Shield className="size-4 text-foreground" aria-hidden="true" />
|
|
132
132
|
<h2 className="text-lg font-semibold">
|
|
133
133
|
{t('security.profile.mfa.passkey.title', 'Security keys')}
|
|
134
134
|
</h2>
|
|
135
135
|
{configuredCount > 0 ? (
|
|
136
136
|
<MfaConfiguredBadge label={t('security.profile.mfa.providers.totp.configured', 'Configured')} />
|
|
137
137
|
) : null}
|
|
138
|
-
<Badge variant="outline"
|
|
138
|
+
<Badge variant="outline">
|
|
139
139
|
{keysLabel}
|
|
140
140
|
</Badge>
|
|
141
141
|
</div>
|
|
142
|
-
<p className="text-sm text-
|
|
142
|
+
<p className="text-sm text-muted-foreground">
|
|
143
143
|
{t(
|
|
144
144
|
'security.profile.mfa.passkey.description',
|
|
145
145
|
'Security keys are WebAuthn credentials that can only be used as a second factor of authentication.',
|
|
@@ -153,13 +153,13 @@ export default function PasskeyProviderDetails({
|
|
|
153
153
|
{methods.map((method) => (
|
|
154
154
|
<article
|
|
155
155
|
key={method.id}
|
|
156
|
-
className="flex items-start justify-between gap-3 border-b border-
|
|
156
|
+
className="flex items-start justify-between gap-3 border-b border-border pb-3 last:border-none last:pb-0"
|
|
157
157
|
>
|
|
158
158
|
<div className="min-w-0">
|
|
159
|
-
<p className="truncate text-sm font-medium text-
|
|
159
|
+
<p className="truncate text-sm font-medium text-foreground">
|
|
160
160
|
{method.label ?? t('security.profile.mfa.providers.passkey.title', 'Security key')}
|
|
161
161
|
</p>
|
|
162
|
-
<p className="truncate text-xs text-
|
|
162
|
+
<p className="truncate text-xs text-muted-foreground">
|
|
163
163
|
{t('ui.table.registeredAt', 'Registered')}: {formatRelative(method.createdAt, t('security.profile.mfa.method.unknownTime', 'Unknown'))}
|
|
164
164
|
{' '}|{' '}
|
|
165
165
|
{t('security.profile.mfa.method.lastUsed', 'Last used')}: {formatRelative(method.lastUsedAt, t('security.profile.mfa.method.neverUsed', 'Never used'))}
|
|
@@ -170,6 +170,7 @@ export default function PasskeyProviderDetails({
|
|
|
170
170
|
type="button"
|
|
171
171
|
variant="outline"
|
|
172
172
|
size="sm"
|
|
173
|
+
className="shrink-0"
|
|
173
174
|
disabled={saving || loading}
|
|
174
175
|
aria-label={t('ui.actions.delete', 'Delete')}
|
|
175
176
|
title={t('ui.actions.delete', 'Delete')}
|
|
@@ -177,7 +178,7 @@ export default function PasskeyProviderDetails({
|
|
|
177
178
|
void onRemoveMethod(method)
|
|
178
179
|
}}
|
|
179
180
|
>
|
|
180
|
-
<Trash2 className="size-4 text-
|
|
181
|
+
<Trash2 className="size-4 text-destructive" />
|
|
181
182
|
</IconButton>
|
|
182
183
|
) : null}
|
|
183
184
|
</article>
|
|
@@ -197,13 +198,13 @@ export default function PasskeyProviderDetails({
|
|
|
197
198
|
value={label}
|
|
198
199
|
onChange={(event) => setLabel(event.target.value)}
|
|
199
200
|
placeholder={t('security.profile.mfa.passkey.nicknamePlaceholder', 'Enter a nickname for this security key')}
|
|
200
|
-
|
|
201
|
+
size="lg"
|
|
201
202
|
/>
|
|
202
203
|
<Button
|
|
203
204
|
type="submit"
|
|
204
205
|
disabled={loading || saving}
|
|
205
206
|
variant="outline"
|
|
206
|
-
|
|
207
|
+
size="lg"
|
|
207
208
|
>
|
|
208
209
|
{loading ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
|
|
209
210
|
{t('ui.actions.add', 'Add')}
|
|
@@ -33,19 +33,10 @@ const setupPayloadSchema = z.object({
|
|
|
33
33
|
authenticatorAttachment: z.enum(['platform', 'cross-platform']).optional(),
|
|
34
34
|
})
|
|
35
35
|
|
|
36
|
-
const setupConfirmationPayloadSchema = z.
|
|
37
|
-
z.
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
}),
|
|
41
|
-
z.object({
|
|
42
|
-
credentialId: z.string().min(1),
|
|
43
|
-
publicKey: z.string().min(1),
|
|
44
|
-
challenge: z.string().min(1),
|
|
45
|
-
transports: z.array(z.string().min(1)).optional(),
|
|
46
|
-
label: z.string().min(1).max(100).optional(),
|
|
47
|
-
}),
|
|
48
|
-
])
|
|
36
|
+
const setupConfirmationPayloadSchema = z.object({
|
|
37
|
+
response: z.record(z.string(), z.unknown()),
|
|
38
|
+
label: z.string().min(1).max(100).optional(),
|
|
39
|
+
})
|
|
49
40
|
|
|
50
41
|
const verifyPayloadSchema = z.object({
|
|
51
42
|
response: z.record(z.string(), z.unknown()),
|
|
@@ -166,61 +157,45 @@ export class PasskeyProvider implements MfaProviderInterface {
|
|
|
166
157
|
throw new Error('Passkey setup session expired')
|
|
167
158
|
}
|
|
168
159
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
})
|
|
177
|
-
|
|
178
|
-
if (!verification.verified || !verification.registrationInfo) {
|
|
179
|
-
throw new Error('Passkey registration verification failed')
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
const registrationInfo = verification.registrationInfo as {
|
|
183
|
-
credential?: {
|
|
184
|
-
id: string
|
|
185
|
-
publicKey: Uint8Array
|
|
186
|
-
counter: number
|
|
187
|
-
transports?: string[]
|
|
188
|
-
}
|
|
189
|
-
credentialID?: string
|
|
190
|
-
credentialPublicKey?: Uint8Array
|
|
191
|
-
counter?: number
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
const credentialId = registrationInfo.credential?.id ?? registrationInfo.credentialID
|
|
195
|
-
const publicKeyBytes = registrationInfo.credential?.publicKey ?? registrationInfo.credentialPublicKey
|
|
196
|
-
const counter = registrationInfo.credential?.counter ?? registrationInfo.counter ?? 0
|
|
197
|
-
const transports = this.normalizeTransports(registrationInfo.credential?.transports)
|
|
160
|
+
const verification = await verifyRegistrationResponse({
|
|
161
|
+
response: parsed.response as never,
|
|
162
|
+
expectedChallenge: pending.challenge,
|
|
163
|
+
expectedOrigin: this.getExpectedOrigins(securityConfig),
|
|
164
|
+
expectedRPID: this.getRpId(securityConfig),
|
|
165
|
+
requireUserVerification: false,
|
|
166
|
+
})
|
|
198
167
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
168
|
+
if (!verification.verified || !verification.registrationInfo) {
|
|
169
|
+
throw new Error('Passkey registration verification failed')
|
|
170
|
+
}
|
|
202
171
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
label: parsed.label ?? pending.label ?? 'Passkey',
|
|
210
|
-
},
|
|
172
|
+
const registrationInfo = verification.registrationInfo as {
|
|
173
|
+
credential?: {
|
|
174
|
+
id: string
|
|
175
|
+
publicKey: Uint8Array
|
|
176
|
+
counter: number
|
|
177
|
+
transports?: string[]
|
|
211
178
|
}
|
|
179
|
+
credentialID?: string
|
|
180
|
+
credentialPublicKey?: Uint8Array
|
|
181
|
+
counter?: number
|
|
212
182
|
}
|
|
213
183
|
|
|
214
|
-
|
|
215
|
-
|
|
184
|
+
const credentialId = registrationInfo.credential?.id ?? registrationInfo.credentialID
|
|
185
|
+
const publicKeyBytes = registrationInfo.credential?.publicKey ?? registrationInfo.credentialPublicKey
|
|
186
|
+
const counter = registrationInfo.credential?.counter ?? registrationInfo.counter ?? 0
|
|
187
|
+
const transports = this.normalizeTransports(registrationInfo.credential?.transports)
|
|
188
|
+
|
|
189
|
+
if (!credentialId || !publicKeyBytes) {
|
|
190
|
+
throw new Error('Passkey registration did not return credential data')
|
|
216
191
|
}
|
|
217
192
|
|
|
218
193
|
return {
|
|
219
194
|
metadata: {
|
|
220
|
-
credentialId
|
|
221
|
-
credentialPublicKey:
|
|
222
|
-
counter
|
|
223
|
-
transports
|
|
195
|
+
credentialId,
|
|
196
|
+
credentialPublicKey: this.bytesToBase64Url(publicKeyBytes),
|
|
197
|
+
counter,
|
|
198
|
+
transports,
|
|
224
199
|
label: parsed.label ?? pending.label ?? 'Passkey',
|
|
225
200
|
},
|
|
226
201
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto'
|
|
2
2
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
3
|
import { compare, hash } from 'bcryptjs'
|
|
4
|
+
import { ZodError } from 'zod'
|
|
4
5
|
import { User } from '@open-mercato/core/modules/auth/data/entities'
|
|
5
6
|
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
6
7
|
import { EnforcementScope, MfaEnforcementPolicy, MfaRecoveryCode, UserMfaMethod } from '../data/entities'
|
|
7
8
|
import { emitSecurityEvent } from '../events'
|
|
8
9
|
import type { MfaProviderRegistry } from '../lib/mfa-provider-registry'
|
|
9
|
-
import type { MfaProviderRuntimeContext } from '../lib/mfa-provider-interface'
|
|
10
|
+
import type { MfaProviderConfirmResult, MfaProviderRuntimeContext } from '../lib/mfa-provider-interface'
|
|
10
11
|
import type { SecurityModuleConfig } from '../lib/security-config'
|
|
11
12
|
import { readSecurityModuleConfig } from '../lib/security-config'
|
|
12
13
|
|
|
@@ -120,7 +121,15 @@ export class MfaService {
|
|
|
120
121
|
|
|
121
122
|
await this.ensureProviderCanBeConfigured(userId, method.type, provider.allowMultiple)
|
|
122
123
|
|
|
123
|
-
|
|
124
|
+
let confirmation: MfaProviderConfirmResult
|
|
125
|
+
try {
|
|
126
|
+
confirmation = await provider.confirmSetup(userId, setupId, payload, context)
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof ZodError) {
|
|
129
|
+
throw new MfaServiceError('Invalid payload', 400)
|
|
130
|
+
}
|
|
131
|
+
throw error
|
|
132
|
+
}
|
|
124
133
|
const resolvedLabel = this.getLabelFromMetadata(confirmation.metadata) ?? method.label ?? null
|
|
125
134
|
|
|
126
135
|
if (resolvedLabel && provider.allowMultiple) {
|