@soropass/core 0.1.0
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/checkAuth-C2AcXqFe.d.cts +110 -0
- package/dist/checkAuth-C2AcXqFe.d.ts +110 -0
- package/dist/chunk-AHFGTIBY.js +36 -0
- package/dist/chunk-AHFGTIBY.js.map +1 -0
- package/dist/chunk-AMYFJQAC.js +29 -0
- package/dist/chunk-AMYFJQAC.js.map +1 -0
- package/dist/chunk-BIRF5I6I.js +265 -0
- package/dist/chunk-BIRF5I6I.js.map +1 -0
- package/dist/chunk-JNJ2FY45.js +209 -0
- package/dist/chunk-JNJ2FY45.js.map +1 -0
- package/dist/chunk-LB4HOTLV.js +135 -0
- package/dist/chunk-LB4HOTLV.js.map +1 -0
- package/dist/chunk-LM2AZXKZ.js +108 -0
- package/dist/chunk-LM2AZXKZ.js.map +1 -0
- package/dist/chunk-LUDXP56M.js +3 -0
- package/dist/chunk-LUDXP56M.js.map +1 -0
- package/dist/chunk-MMB4ZIW3.js +48 -0
- package/dist/chunk-MMB4ZIW3.js.map +1 -0
- package/dist/chunk-MOLZIRIH.js +22 -0
- package/dist/chunk-MOLZIRIH.js.map +1 -0
- package/dist/chunk-OGSUGATA.js +3 -0
- package/dist/chunk-OGSUGATA.js.map +1 -0
- package/dist/chunk-TPBBZNPP.js +30 -0
- package/dist/chunk-TPBBZNPP.js.map +1 -0
- package/dist/chunk-UQKNPO44.js +32 -0
- package/dist/chunk-UQKNPO44.js.map +1 -0
- package/dist/chunk-UV5HORMF.js +175 -0
- package/dist/chunk-UV5HORMF.js.map +1 -0
- package/dist/chunk-W75OQKHR.js +133 -0
- package/dist/chunk-W75OQKHR.js.map +1 -0
- package/dist/connect.cjs +166 -0
- package/dist/connect.cjs.map +1 -0
- package/dist/connect.d.cts +24 -0
- package/dist/connect.d.ts +24 -0
- package/dist/connect.js +6 -0
- package/dist/connect.js.map +1 -0
- package/dist/create.cjs +483 -0
- package/dist/create.cjs.map +1 -0
- package/dist/create.d.cts +106 -0
- package/dist/create.d.ts +106 -0
- package/dist/create.js +8 -0
- package/dist/create.js.map +1 -0
- package/dist/index.cjs +1542 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +197 -0
- package/dist/index.d.ts +197 -0
- package/dist/index.js +354 -0
- package/dist/index.js.map +1 -0
- package/dist/recover-0wbOXDjR.d.cts +23 -0
- package/dist/recover-COnsxhYk.d.ts +23 -0
- package/dist/recover.cjs +802 -0
- package/dist/recover.cjs.map +1 -0
- package/dist/recover.d.cts +49 -0
- package/dist/recover.d.ts +49 -0
- package/dist/recover.js +10 -0
- package/dist/recover.js.map +1 -0
- package/dist/sign-Cfg0NM0T.d.cts +73 -0
- package/dist/sign-Cfg0NM0T.d.ts +73 -0
- package/dist/sign.cjs +883 -0
- package/dist/sign.cjs.map +1 -0
- package/dist/sign.d.cts +143 -0
- package/dist/sign.d.ts +143 -0
- package/dist/sign.js +8 -0
- package/dist/sign.js.map +1 -0
- package/dist/submit-BDKADQq0.d.cts +112 -0
- package/dist/submit-BO0Nh49I.d.ts +112 -0
- package/dist/testing.cjs +955 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +86 -0
- package/dist/testing.d.ts +86 -0
- package/dist/testing.js +235 -0
- package/dist/testing.js.map +1 -0
- package/dist/types--WNl-Sda.d.cts +125 -0
- package/dist/types--WNl-Sda.d.ts +125 -0
- package/dist/types-dMRWEEo0.d.cts +73 -0
- package/dist/types-lW2h8Uxn.d.ts +73 -0
- package/dist/types.cjs +44 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +5 -0
- package/dist/types.d.ts +5 -0
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -0
- package/package.json +117 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { xdr } from '@stellar/stellar-sdk';
|
|
2
|
+
|
|
3
|
+
/** The subset of clientDataJSON fields we rely on. */
|
|
4
|
+
interface ClientData {
|
|
5
|
+
type: string;
|
|
6
|
+
/** base64url-encoded challenge as embedded by the client. */
|
|
7
|
+
challenge: string;
|
|
8
|
+
origin: string;
|
|
9
|
+
crossOrigin?: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** Encode a raw challenge as the base64url string embedded in clientDataJSON. */
|
|
12
|
+
declare function encodeChallenge(challenge: Uint8Array): string;
|
|
13
|
+
/** Decode the base64url challenge embedded in clientDataJSON back to bytes. */
|
|
14
|
+
declare function decodeChallenge(challenge: string): Uint8Array;
|
|
15
|
+
/** Parse clientDataJSON bytes into a typed, validated-shape object. */
|
|
16
|
+
declare function parseClientDataJSON(clientDataJSON: Uint8Array): ClientData;
|
|
17
|
+
/**
|
|
18
|
+
* Parse and verify clientDataJSON for an authentication (`webauthn.get`)
|
|
19
|
+
* assertion: the ceremony type, the origin (exact match against one or more
|
|
20
|
+
* allowed origins), and the embedded challenge (base64url string).
|
|
21
|
+
*/
|
|
22
|
+
declare function verifyClientDataJSON(clientDataJSON: Uint8Array, expected: {
|
|
23
|
+
origin: string | string[];
|
|
24
|
+
challenge: string;
|
|
25
|
+
}): ClientData;
|
|
26
|
+
|
|
27
|
+
interface AuthenticatorDataFlags {
|
|
28
|
+
/** User Present */
|
|
29
|
+
up: boolean;
|
|
30
|
+
/** User Verified */
|
|
31
|
+
uv: boolean;
|
|
32
|
+
/** Backup Eligible */
|
|
33
|
+
be: boolean;
|
|
34
|
+
/** Backup State */
|
|
35
|
+
bs: boolean;
|
|
36
|
+
/** Attested credential data present */
|
|
37
|
+
at: boolean;
|
|
38
|
+
/** Extension data present */
|
|
39
|
+
ed: boolean;
|
|
40
|
+
/** Raw flags byte. */
|
|
41
|
+
bits: number;
|
|
42
|
+
}
|
|
43
|
+
interface ParsedAuthenticatorData {
|
|
44
|
+
rpIdHash: Uint8Array;
|
|
45
|
+
flags: AuthenticatorDataFlags;
|
|
46
|
+
signCount: number;
|
|
47
|
+
aaguid?: Uint8Array;
|
|
48
|
+
credentialId?: Uint8Array;
|
|
49
|
+
/** Raw CBOR-encoded COSE public key (exact bytes), if attested data present. */
|
|
50
|
+
credentialPublicKey?: Uint8Array;
|
|
51
|
+
}
|
|
52
|
+
/** Parse the authenticatorData byte structure (WebAuthn §6.1). */
|
|
53
|
+
declare function parseAuthenticatorData(authData: Uint8Array): ParsedAuthenticatorData;
|
|
54
|
+
/** Verify that authenticatorData's rpIdHash equals SHA-256(rpId). */
|
|
55
|
+
declare function verifyRpIdHash(authData: Uint8Array, rpId: string): void;
|
|
56
|
+
|
|
57
|
+
interface VerifyAssertionInput {
|
|
58
|
+
/** SEC-1 uncompressed public key (65 bytes, `0x04 ‖ X ‖ Y`). */
|
|
59
|
+
publicKey: Uint8Array;
|
|
60
|
+
authenticatorData: Uint8Array;
|
|
61
|
+
clientDataJSON: Uint8Array;
|
|
62
|
+
/** DER-encoded (≤72 B) or already-compact (64 B) signature. */
|
|
63
|
+
signature: Uint8Array;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Verify a WebAuthn assertion the way the on-chain `secp256r1_verify` does:
|
|
67
|
+
* reconstruct `SHA256(authData ‖ SHA256(cdj))` and check ECDSA. `lowS: false`
|
|
68
|
+
* mirrors the host function, which does NOT enforce low-S (we normalize
|
|
69
|
+
* separately before submitting — see S04/YK-430).
|
|
70
|
+
*/
|
|
71
|
+
declare function verifyAssertionSignature(input: VerifyAssertionInput): boolean;
|
|
72
|
+
|
|
73
|
+
interface CheckAuthResult {
|
|
74
|
+
success: boolean;
|
|
75
|
+
/** clientDataJSON.challenge === base64url(preimage hash). */
|
|
76
|
+
challengeBound: boolean;
|
|
77
|
+
/** secp256r1_verify over SHA256(authData ‖ SHA256(cdj)) passed. */
|
|
78
|
+
signatureValid: boolean;
|
|
79
|
+
reason?: string;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A faithful JavaScript model of the on-chain `__check_auth` (kalepail
|
|
83
|
+
* `webauthn-wallet` `verify.rs`): reconstruct `SHA256(authenticator_data ‖
|
|
84
|
+
* SHA256(client_data_json))`, run `secp256r1_verify` (which does NOT enforce
|
|
85
|
+
* low-S — hence the client-side normalization), and assert challenge-binding
|
|
86
|
+
* (`clientDataJSON.challenge === base64url(signature_payload)`). Lets us prove
|
|
87
|
+
* the assembly without a live Soroban RPC; the real on-chain run is exercised
|
|
88
|
+
* by the kit integration (S17) and the demo (S21).
|
|
89
|
+
*/
|
|
90
|
+
declare function referenceCheckAuth(entry: xdr.SorobanAuthorizationEntry, publicKey: Uint8Array, networkPassphrase: string): CheckAuthResult;
|
|
91
|
+
interface SmartWalletCheckAuthResult {
|
|
92
|
+
success: boolean;
|
|
93
|
+
signers: {
|
|
94
|
+
credentialId: string;
|
|
95
|
+
challengeBound: boolean;
|
|
96
|
+
signatureValid: boolean;
|
|
97
|
+
}[];
|
|
98
|
+
reason?: string;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* A reference model of passkey-kit's smart-wallet `__check_auth`: unwrap the
|
|
102
|
+
* `Signatures(Map<SignerKey, Signature>)` value (`ScVal::Vec([ScVal::Map(...)])`),
|
|
103
|
+
* and for each `SignerKey::Secp256r1(id) => Signature::Secp256r1(struct)` entry,
|
|
104
|
+
* look up that credential id's SEC-1 public key and verify the struct. Succeeds
|
|
105
|
+
* only when the map is non-empty and every signer verifies + is challenge-bound.
|
|
106
|
+
* `publicKeyFor` receives the lowercase-hex credential id.
|
|
107
|
+
*/
|
|
108
|
+
declare function referenceSmartWalletCheckAuth(entry: xdr.SorobanAuthorizationEntry, publicKeyFor: (credentialIdHex: string) => Uint8Array | undefined, networkPassphrase: string): SmartWalletCheckAuthResult;
|
|
109
|
+
|
|
110
|
+
export { type AuthenticatorDataFlags as A, type CheckAuthResult as C, type ParsedAuthenticatorData as P, type SmartWalletCheckAuthResult as S, type VerifyAssertionInput as V, type ClientData as a, parseClientDataJSON as b, referenceSmartWalletCheckAuth as c, decodeChallenge as d, encodeChallenge as e, verifyClientDataJSON as f, verifyRpIdHash as g, parseAuthenticatorData as p, referenceCheckAuth as r, verifyAssertionSignature as v };
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { xdr } from '@stellar/stellar-sdk';
|
|
2
|
+
|
|
3
|
+
/** The subset of clientDataJSON fields we rely on. */
|
|
4
|
+
interface ClientData {
|
|
5
|
+
type: string;
|
|
6
|
+
/** base64url-encoded challenge as embedded by the client. */
|
|
7
|
+
challenge: string;
|
|
8
|
+
origin: string;
|
|
9
|
+
crossOrigin?: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** Encode a raw challenge as the base64url string embedded in clientDataJSON. */
|
|
12
|
+
declare function encodeChallenge(challenge: Uint8Array): string;
|
|
13
|
+
/** Decode the base64url challenge embedded in clientDataJSON back to bytes. */
|
|
14
|
+
declare function decodeChallenge(challenge: string): Uint8Array;
|
|
15
|
+
/** Parse clientDataJSON bytes into a typed, validated-shape object. */
|
|
16
|
+
declare function parseClientDataJSON(clientDataJSON: Uint8Array): ClientData;
|
|
17
|
+
/**
|
|
18
|
+
* Parse and verify clientDataJSON for an authentication (`webauthn.get`)
|
|
19
|
+
* assertion: the ceremony type, the origin (exact match against one or more
|
|
20
|
+
* allowed origins), and the embedded challenge (base64url string).
|
|
21
|
+
*/
|
|
22
|
+
declare function verifyClientDataJSON(clientDataJSON: Uint8Array, expected: {
|
|
23
|
+
origin: string | string[];
|
|
24
|
+
challenge: string;
|
|
25
|
+
}): ClientData;
|
|
26
|
+
|
|
27
|
+
interface AuthenticatorDataFlags {
|
|
28
|
+
/** User Present */
|
|
29
|
+
up: boolean;
|
|
30
|
+
/** User Verified */
|
|
31
|
+
uv: boolean;
|
|
32
|
+
/** Backup Eligible */
|
|
33
|
+
be: boolean;
|
|
34
|
+
/** Backup State */
|
|
35
|
+
bs: boolean;
|
|
36
|
+
/** Attested credential data present */
|
|
37
|
+
at: boolean;
|
|
38
|
+
/** Extension data present */
|
|
39
|
+
ed: boolean;
|
|
40
|
+
/** Raw flags byte. */
|
|
41
|
+
bits: number;
|
|
42
|
+
}
|
|
43
|
+
interface ParsedAuthenticatorData {
|
|
44
|
+
rpIdHash: Uint8Array;
|
|
45
|
+
flags: AuthenticatorDataFlags;
|
|
46
|
+
signCount: number;
|
|
47
|
+
aaguid?: Uint8Array;
|
|
48
|
+
credentialId?: Uint8Array;
|
|
49
|
+
/** Raw CBOR-encoded COSE public key (exact bytes), if attested data present. */
|
|
50
|
+
credentialPublicKey?: Uint8Array;
|
|
51
|
+
}
|
|
52
|
+
/** Parse the authenticatorData byte structure (WebAuthn §6.1). */
|
|
53
|
+
declare function parseAuthenticatorData(authData: Uint8Array): ParsedAuthenticatorData;
|
|
54
|
+
/** Verify that authenticatorData's rpIdHash equals SHA-256(rpId). */
|
|
55
|
+
declare function verifyRpIdHash(authData: Uint8Array, rpId: string): void;
|
|
56
|
+
|
|
57
|
+
interface VerifyAssertionInput {
|
|
58
|
+
/** SEC-1 uncompressed public key (65 bytes, `0x04 ‖ X ‖ Y`). */
|
|
59
|
+
publicKey: Uint8Array;
|
|
60
|
+
authenticatorData: Uint8Array;
|
|
61
|
+
clientDataJSON: Uint8Array;
|
|
62
|
+
/** DER-encoded (≤72 B) or already-compact (64 B) signature. */
|
|
63
|
+
signature: Uint8Array;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Verify a WebAuthn assertion the way the on-chain `secp256r1_verify` does:
|
|
67
|
+
* reconstruct `SHA256(authData ‖ SHA256(cdj))` and check ECDSA. `lowS: false`
|
|
68
|
+
* mirrors the host function, which does NOT enforce low-S (we normalize
|
|
69
|
+
* separately before submitting — see S04/YK-430).
|
|
70
|
+
*/
|
|
71
|
+
declare function verifyAssertionSignature(input: VerifyAssertionInput): boolean;
|
|
72
|
+
|
|
73
|
+
interface CheckAuthResult {
|
|
74
|
+
success: boolean;
|
|
75
|
+
/** clientDataJSON.challenge === base64url(preimage hash). */
|
|
76
|
+
challengeBound: boolean;
|
|
77
|
+
/** secp256r1_verify over SHA256(authData ‖ SHA256(cdj)) passed. */
|
|
78
|
+
signatureValid: boolean;
|
|
79
|
+
reason?: string;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A faithful JavaScript model of the on-chain `__check_auth` (kalepail
|
|
83
|
+
* `webauthn-wallet` `verify.rs`): reconstruct `SHA256(authenticator_data ‖
|
|
84
|
+
* SHA256(client_data_json))`, run `secp256r1_verify` (which does NOT enforce
|
|
85
|
+
* low-S — hence the client-side normalization), and assert challenge-binding
|
|
86
|
+
* (`clientDataJSON.challenge === base64url(signature_payload)`). Lets us prove
|
|
87
|
+
* the assembly without a live Soroban RPC; the real on-chain run is exercised
|
|
88
|
+
* by the kit integration (S17) and the demo (S21).
|
|
89
|
+
*/
|
|
90
|
+
declare function referenceCheckAuth(entry: xdr.SorobanAuthorizationEntry, publicKey: Uint8Array, networkPassphrase: string): CheckAuthResult;
|
|
91
|
+
interface SmartWalletCheckAuthResult {
|
|
92
|
+
success: boolean;
|
|
93
|
+
signers: {
|
|
94
|
+
credentialId: string;
|
|
95
|
+
challengeBound: boolean;
|
|
96
|
+
signatureValid: boolean;
|
|
97
|
+
}[];
|
|
98
|
+
reason?: string;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* A reference model of passkey-kit's smart-wallet `__check_auth`: unwrap the
|
|
102
|
+
* `Signatures(Map<SignerKey, Signature>)` value (`ScVal::Vec([ScVal::Map(...)])`),
|
|
103
|
+
* and for each `SignerKey::Secp256r1(id) => Signature::Secp256r1(struct)` entry,
|
|
104
|
+
* look up that credential id's SEC-1 public key and verify the struct. Succeeds
|
|
105
|
+
* only when the map is non-empty and every signer verifies + is challenge-bound.
|
|
106
|
+
* `publicKeyFor` receives the lowercase-hex credential id.
|
|
107
|
+
*/
|
|
108
|
+
declare function referenceSmartWalletCheckAuth(entry: xdr.SorobanAuthorizationEntry, publicKeyFor: (credentialIdHex: string) => Uint8Array | undefined, networkPassphrase: string): SmartWalletCheckAuthResult;
|
|
109
|
+
|
|
110
|
+
export { type AuthenticatorDataFlags as A, type CheckAuthResult as C, type ParsedAuthenticatorData as P, type SmartWalletCheckAuthResult as S, type VerifyAssertionInput as V, type ClientData as a, parseClientDataJSON as b, referenceSmartWalletCheckAuth as c, decodeChallenge as d, encodeChallenge as e, verifyClientDataJSON as f, verifyRpIdHash as g, parseAuthenticatorData as p, referenceCheckAuth as r, verifyAssertionSignature as v };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { defaultCredentialStorage, browserWebAuthnClient } from './chunk-LB4HOTLV.js';
|
|
2
|
+
|
|
3
|
+
// src/ceremonies/connect.ts
|
|
4
|
+
async function probeConditionalMediation() {
|
|
5
|
+
const pkc = globalThis.PublicKeyCredential;
|
|
6
|
+
if (!pkc?.isConditionalMediationAvailable) return false;
|
|
7
|
+
try {
|
|
8
|
+
return await pkc.isConditionalMediationAvailable();
|
|
9
|
+
} catch {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
async function connect(options) {
|
|
14
|
+
const storage = options.storage ?? defaultCredentialStorage();
|
|
15
|
+
const credentialId = storage.get(options.rpId);
|
|
16
|
+
if (!credentialId) return null;
|
|
17
|
+
const silentSupported = options.silentMediationSupported ?? await probeConditionalMediation();
|
|
18
|
+
if (silentSupported) {
|
|
19
|
+
const webauthn = options.webauthn ?? browserWebAuthnClient();
|
|
20
|
+
try {
|
|
21
|
+
await webauthn.get({
|
|
22
|
+
rpId: options.rpId,
|
|
23
|
+
allowCredentials: [credentialId],
|
|
24
|
+
mediation: "silent"
|
|
25
|
+
});
|
|
26
|
+
} catch {
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const accounts = await options.indexer.resolveByCredential(credentialId);
|
|
30
|
+
const contractId = accounts[0]?.contractId;
|
|
31
|
+
return contractId ? { contractId, credentialId } : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export { connect };
|
|
35
|
+
//# sourceMappingURL=chunk-AHFGTIBY.js.map
|
|
36
|
+
//# sourceMappingUR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;AACrD","file":"chunk-AHFGTIBY.js","sourcesContent":["import type { IndexerAdapter } from '../adapters/types';\nimport { browserWebAuthnClient, defaultCredentialStorage } from './browserClient';\nimport type { CredentialStorage, WebAuthnClient } from './types';\n\nexport interface ConnectOptions {\n rpId: string;\n indexer: IndexerAdapter;\n webauthn?: WebAuthnClient;\n storage?: CredentialStorage;\n /** Override silent-mediation detection (default: probe isConditionalMediationAvailable). */\n silentMediationSupported?: boolean;\n}\n\nexport interface ConnectResult {\n contractId: string;\n credentialId: string;\n}\n\nasync function probeConditionalMediation(): Promise<boolean> {\n const pkc = (\n globalThis as {\n PublicKeyCredential?: { isConditionalMediationAvailable?: () => Promise<boolean> };\n }\n ).PublicKeyCredential;\n if (!pkc?.isConditionalMediationAvailable) return false;\n try {\n return await pkc.isConditionalMediationAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * `connect` — silent reconnect using the stored credential id. Where conditional\n * mediation is available, does a best-effort `mediation:'silent'` liveness check;\n * the C-address is resolved via the IndexerAdapter regardless, so connect\n * degrades gracefully where silent mediation is unsupported. Returns null when\n * there is no stored credential (the caller should `recover`) or no account.\n */\nexport async function connect(options: ConnectOptions): Promise<ConnectResult | null> {\n const storage = options.storage ?? defaultCredentialStorage();\n const credentialId = storage.get(options.rpId);\n if (!credentialId) return null;\n\n const silentSupported = options.silentMediationSupported ?? (await probeConditionalMediation());\n if (silentSupported) {\n const webauthn = options.webauthn ?? browserWebAuthnClient();\n try {\n await webauthn.get({\n rpId: options.rpId,\n allowCredentials: [credentialId],\n mediation: 'silent',\n });\n } catch {\n // A silent get may no-op or reject; resolution is via the indexer.\n }\n }\n\n const accounts = await options.indexer.resolveByCredential(credentialId);\n const contractId = accounts[0]?.contractId;\n return contractId ? { contractId, credentialId } : null;\n}\n"]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var KIT_ERROR_CODES = Object.freeze([
|
|
3
|
+
"USER_CANCELLED",
|
|
4
|
+
"ES256_NOT_SUPPORTED",
|
|
5
|
+
"RP_ID_MISMATCH",
|
|
6
|
+
"ORIGIN_MISMATCH",
|
|
7
|
+
"CHALLENGE_MISMATCH",
|
|
8
|
+
"INVALID_SIGNATURE_DER",
|
|
9
|
+
"INVALID_PUBLIC_KEY",
|
|
10
|
+
"CONTRACT_AUTH_FAILED",
|
|
11
|
+
"NETWORK_ERROR",
|
|
12
|
+
"UNSUPPORTED_AUTHENTICATOR"
|
|
13
|
+
]);
|
|
14
|
+
var KitError = class _KitError extends Error {
|
|
15
|
+
code;
|
|
16
|
+
name = "KitError";
|
|
17
|
+
constructor(code, message, options) {
|
|
18
|
+
super(message ?? code, options);
|
|
19
|
+
this.code = code;
|
|
20
|
+
Object.setPrototypeOf(this, _KitError.prototype);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function isKitError(value) {
|
|
24
|
+
return value instanceof KitError;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export { KIT_ERROR_CODES, KitError, isKitError };
|
|
28
|
+
//# sourceMappingURL=chunk-AMYFJQAC.js.map
|
|
29
|
+
//# sourceMappingURL=chunk-AMYFJQAC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AAIO,IAAM,eAAA,GAAkB,OAAO,MAAA,CAAO;AAAA,EAC3C,gBAAA;AAAA,EACA,qBAAA;AAAA,EACA,gBAAA;AAAA,EACA,iBAAA;AAAA,EACA,oBAAA;AAAA,EACA,uBAAA;AAAA,EACA,oBAAA;AAAA,EACA,sBAAA;AAAA,EACA,eAAA;AAAA,EACA;AACF,CAAU;AAKH,IAAM,QAAA,GAAN,MAAM,SAAA,SAAiB,KAAA,CAAM;AAAA,EACzB,IAAA;AAAA,EACS,IAAA,GAAO,UAAA;AAAA,EAEzB,WAAA,CAAY,IAAA,EAAoB,OAAA,EAAkB,OAAA,EAA+B;AAC/E,IAAA,KAAA,CAAM,OAAA,IAAW,MAAM,OAAO,CAAA;AAC9B,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAGZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,SAAA,CAAS,SAAS,CAAA;AAAA,EAChD;AACF;AAEO,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OAAO,KAAA,YAAiB,QAAA;AAC1B","file":"chunk-AMYFJQAC.js","sourcesContent":["/**\n * The frozen taxonomy of error codes the SDK can throw. This union is\n * deliberately closed — every failure path maps to exactly one of these.\n */\nexport const KIT_ERROR_CODES = Object.freeze([\n 'USER_CANCELLED',\n 'ES256_NOT_SUPPORTED',\n 'RP_ID_MISMATCH',\n 'ORIGIN_MISMATCH',\n 'CHALLENGE_MISMATCH',\n 'INVALID_SIGNATURE_DER',\n 'INVALID_PUBLIC_KEY',\n 'CONTRACT_AUTH_FAILED',\n 'NETWORK_ERROR',\n 'UNSUPPORTED_AUTHENTICATOR',\n] as const);\n\nexport type KitErrorCode = (typeof KIT_ERROR_CODES)[number];\n\n/** Structured error carrying a machine-readable {@link KitErrorCode}. */\nexport class KitError extends Error {\n readonly code: KitErrorCode;\n override readonly name = 'KitError';\n\n constructor(code: KitErrorCode, message?: string, options?: { cause?: unknown }) {\n super(message ?? code, options);\n this.code = code;\n // Restore the prototype chain so `instanceof KitError` works after\n // down-level transpilation to CJS.\n Object.setPrototypeOf(this, KitError.prototype);\n }\n}\n\nexport function isKitError(value: unknown): value is KitError {\n return value instanceof KitError;\n}\n"]}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { sha256, concatBytes, verifyClientDataJSON, parseClientDataJSON, parseAuthenticatorData, verifyRpIdHash } from './chunk-JNJ2FY45.js';
|
|
2
|
+
import { utf8ToBytes, bytesToBase64Url } from './chunk-LB4HOTLV.js';
|
|
3
|
+
import { KitError } from './chunk-AMYFJQAC.js';
|
|
4
|
+
import { p256 } from '@noble/curves/nist';
|
|
5
|
+
import { xdr, hash } from '@stellar/stellar-sdk';
|
|
6
|
+
|
|
7
|
+
var MAX_DER_LENGTH = 72;
|
|
8
|
+
function derToCompact(der) {
|
|
9
|
+
if (der.length > MAX_DER_LENGTH) {
|
|
10
|
+
throw new KitError(
|
|
11
|
+
"INVALID_SIGNATURE_DER",
|
|
12
|
+
`DER signature is ${der.length} bytes, exceeds max ${MAX_DER_LENGTH}`
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
return p256.Signature.fromDER(der).toCompactRawBytes();
|
|
17
|
+
} catch (cause) {
|
|
18
|
+
throw new KitError("INVALID_SIGNATURE_DER", "failed to parse DER signature", { cause });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function assertCompactLength(compactSignature) {
|
|
22
|
+
if (compactSignature.length !== 64) {
|
|
23
|
+
throw new KitError(
|
|
24
|
+
"INVALID_SIGNATURE_DER",
|
|
25
|
+
`compact signature must be 64 bytes, got ${compactSignature.length}`
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function isLowS(compactSignature) {
|
|
30
|
+
assertCompactLength(compactSignature);
|
|
31
|
+
return !p256.Signature.fromCompact(compactSignature).hasHighS();
|
|
32
|
+
}
|
|
33
|
+
function normalizeLowS(compactSignature) {
|
|
34
|
+
assertCompactLength(compactSignature);
|
|
35
|
+
return p256.Signature.fromCompact(compactSignature).normalizeS().toCompactRawBytes();
|
|
36
|
+
}
|
|
37
|
+
function derToCompactLowS(der) {
|
|
38
|
+
return normalizeLowS(derToCompact(der));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// src/webauthn/payload.ts
|
|
42
|
+
function reconstructSignedPayload(input) {
|
|
43
|
+
const clientDataHash = sha256(input.clientDataJSON);
|
|
44
|
+
return sha256(concatBytes(input.authenticatorData, clientDataHash));
|
|
45
|
+
}
|
|
46
|
+
function verifyAssertionSignature(input) {
|
|
47
|
+
const payload = reconstructSignedPayload(input);
|
|
48
|
+
const compact = input.signature.length === 64 ? input.signature : derToCompact(input.signature);
|
|
49
|
+
return p256.verify(compact, payload, input.publicKey, { lowS: false, format: "compact" });
|
|
50
|
+
}
|
|
51
|
+
function authEntryChallengeBytes(entry, networkPassphrase) {
|
|
52
|
+
const credentials = entry.credentials();
|
|
53
|
+
if (credentials.switch().name !== "sorobanCredentialsAddress") {
|
|
54
|
+
throw new KitError("CONTRACT_AUTH_FAILED", "auth entry has no address credentials to sign");
|
|
55
|
+
}
|
|
56
|
+
const address = credentials.address();
|
|
57
|
+
const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(
|
|
58
|
+
new xdr.HashIdPreimageSorobanAuthorization({
|
|
59
|
+
networkId: Buffer.from(hash(Buffer.from(utf8ToBytes(networkPassphrase)))),
|
|
60
|
+
nonce: address.nonce(),
|
|
61
|
+
signatureExpirationLedger: address.signatureExpirationLedger(),
|
|
62
|
+
invocation: entry.rootInvocation()
|
|
63
|
+
})
|
|
64
|
+
);
|
|
65
|
+
return new Uint8Array(hash(preimage.toXDR()));
|
|
66
|
+
}
|
|
67
|
+
function authEntryChallenge(entry, networkPassphrase) {
|
|
68
|
+
return bytesToBase64Url(authEntryChallengeBytes(entry, networkPassphrase));
|
|
69
|
+
}
|
|
70
|
+
function applyAssertionToEntry(entry, assertion) {
|
|
71
|
+
entry.credentials().address().signature(buildSignatureScVal(assertion));
|
|
72
|
+
return entry;
|
|
73
|
+
}
|
|
74
|
+
function buildSignatureScVal(assertion) {
|
|
75
|
+
return xdr.ScVal.scvMap([
|
|
76
|
+
bytesField("authenticator_data", assertion.authenticatorData),
|
|
77
|
+
bytesField("client_data_json", assertion.clientDataJSON),
|
|
78
|
+
bytesField("signature", assertion.signature)
|
|
79
|
+
]);
|
|
80
|
+
}
|
|
81
|
+
function bytesField(name, bytes) {
|
|
82
|
+
return new xdr.ScMapEntry({
|
|
83
|
+
key: xdr.ScVal.scvSymbol(name),
|
|
84
|
+
val: xdr.ScVal.scvBytes(Buffer.from(bytes))
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
function buildSignerKeyScVal(credentialId) {
|
|
88
|
+
return xdr.ScVal.scvVec([
|
|
89
|
+
xdr.ScVal.scvSymbol("Secp256r1"),
|
|
90
|
+
xdr.ScVal.scvBytes(Buffer.from(credentialId))
|
|
91
|
+
]);
|
|
92
|
+
}
|
|
93
|
+
function buildSmartWalletSignatureVariant(assertion) {
|
|
94
|
+
return xdr.ScVal.scvVec([xdr.ScVal.scvSymbol("Secp256r1"), buildSignatureScVal(assertion)]);
|
|
95
|
+
}
|
|
96
|
+
function decomposeSignerKey(key) {
|
|
97
|
+
const vec = key.vec();
|
|
98
|
+
if (!vec || vec.length < 2) {
|
|
99
|
+
throw new KitError("CONTRACT_AUTH_FAILED", "malformed SignerKey (expected an enum vec)");
|
|
100
|
+
}
|
|
101
|
+
const variant = vec[0].sym().toString();
|
|
102
|
+
const el = vec[1];
|
|
103
|
+
const payload = el.switch().name === "scvBytes" ? new Uint8Array(el.bytes()) : new Uint8Array(el.toXDR());
|
|
104
|
+
return { variant, payload };
|
|
105
|
+
}
|
|
106
|
+
function compareBytes(a, b) {
|
|
107
|
+
const n = Math.min(a.length, b.length);
|
|
108
|
+
for (let i = 0; i < n; i++) {
|
|
109
|
+
if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
|
|
110
|
+
}
|
|
111
|
+
return a.length - b.length;
|
|
112
|
+
}
|
|
113
|
+
function compareSignerKeyScVal(a, b) {
|
|
114
|
+
const ka = decomposeSignerKey(a);
|
|
115
|
+
const kb = decomposeSignerKey(b);
|
|
116
|
+
if (ka.variant !== kb.variant) return ka.variant < kb.variant ? -1 : 1;
|
|
117
|
+
return compareBytes(ka.payload, kb.payload);
|
|
118
|
+
}
|
|
119
|
+
function applyAssertionToSmartWalletEntry(entry, assertion) {
|
|
120
|
+
const credentials = entry.credentials();
|
|
121
|
+
if (credentials.switch().name !== "sorobanCredentialsAddress") {
|
|
122
|
+
throw new KitError("CONTRACT_AUTH_FAILED", "auth entry has no address credentials to sign");
|
|
123
|
+
}
|
|
124
|
+
const key = buildSignerKeyScVal(assertion.credentialId);
|
|
125
|
+
const newEntry = new xdr.ScMapEntry({ key, val: buildSmartWalletSignatureVariant(assertion) });
|
|
126
|
+
const current = credentials.address().signature();
|
|
127
|
+
let mapEntries;
|
|
128
|
+
switch (current.switch().name) {
|
|
129
|
+
case "scvVoid":
|
|
130
|
+
mapEntries = [newEntry];
|
|
131
|
+
break;
|
|
132
|
+
case "scvVec": {
|
|
133
|
+
const existing = current.vec()?.[0]?.map() ?? [];
|
|
134
|
+
mapEntries = existing.filter((e) => compareSignerKeyScVal(e.key(), key) !== 0);
|
|
135
|
+
mapEntries.push(newEntry);
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
default:
|
|
139
|
+
throw new KitError(
|
|
140
|
+
"CONTRACT_AUTH_FAILED",
|
|
141
|
+
"unexpected existing signature shape for a smart-wallet entry"
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
mapEntries.sort((a, b) => compareSignerKeyScVal(a.key(), b.key()));
|
|
145
|
+
credentials.address().signature(xdr.ScVal.scvVec([xdr.ScVal.scvMap(mapEntries)]));
|
|
146
|
+
return entry;
|
|
147
|
+
}
|
|
148
|
+
function preflightAssertion(assertion, challenge, verify) {
|
|
149
|
+
let clientData;
|
|
150
|
+
if (verify.origin !== void 0) {
|
|
151
|
+
clientData = verifyClientDataJSON(assertion.clientDataJSON, {
|
|
152
|
+
origin: verify.origin,
|
|
153
|
+
challenge
|
|
154
|
+
});
|
|
155
|
+
} else {
|
|
156
|
+
clientData = parseClientDataJSON(assertion.clientDataJSON);
|
|
157
|
+
if (clientData.type !== "webauthn.get") {
|
|
158
|
+
throw new KitError(
|
|
159
|
+
"UNSUPPORTED_AUTHENTICATOR",
|
|
160
|
+
`clientDataJSON.type "${clientData.type}" is not "webauthn.get"`
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
if (clientData.challenge !== challenge) {
|
|
164
|
+
throw new KitError("CHALLENGE_MISMATCH", "assertion challenge does not match the auth entry");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (clientData.crossOrigin === true && !verify.allowCrossOrigin) {
|
|
168
|
+
throw new KitError(
|
|
169
|
+
"ORIGIN_MISMATCH",
|
|
170
|
+
"assertion was made in a cross-origin context (crossOrigin=true)"
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
const parsed = parseAuthenticatorData(assertion.authenticatorData);
|
|
174
|
+
if (!parsed.flags.up) {
|
|
175
|
+
throw new KitError(
|
|
176
|
+
"UNSUPPORTED_AUTHENTICATOR",
|
|
177
|
+
"assertion is missing the User-Present (UP) flag"
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
if (verify.requireUserVerification && !parsed.flags.uv) {
|
|
181
|
+
throw new KitError(
|
|
182
|
+
"UNSUPPORTED_AUTHENTICATOR",
|
|
183
|
+
"assertion is missing the required User-Verified (UV) flag"
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
if (verify.rpId !== void 0) {
|
|
187
|
+
verifyRpIdHash(assertion.authenticatorData, verify.rpId);
|
|
188
|
+
}
|
|
189
|
+
if (verify.publicKey !== void 0) {
|
|
190
|
+
const ok = verifyAssertionSignature({
|
|
191
|
+
publicKey: verify.publicKey,
|
|
192
|
+
authenticatorData: assertion.authenticatorData,
|
|
193
|
+
clientDataJSON: assertion.clientDataJSON,
|
|
194
|
+
signature: assertion.signature
|
|
195
|
+
});
|
|
196
|
+
if (!ok) {
|
|
197
|
+
throw new KitError(
|
|
198
|
+
"CONTRACT_AUTH_FAILED",
|
|
199
|
+
"assertion signature failed pre-flight verification"
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async function signEntryInPlace(entry, options) {
|
|
205
|
+
if (options.signatureExpirationLedger !== void 0) {
|
|
206
|
+
const creds = entry.credentials();
|
|
207
|
+
if (creds.switch().name === "sorobanCredentialsAddress") {
|
|
208
|
+
creds.address().signatureExpirationLedger(options.signatureExpirationLedger);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const challenge = authEntryChallenge(entry, options.networkPassphrase);
|
|
212
|
+
const assertion = await options.sign(challenge);
|
|
213
|
+
if (options.verify) preflightAssertion(assertion, challenge, options.verify);
|
|
214
|
+
const signature = assertion.signature.length === 64 ? assertion.signature : derToCompactLowS(assertion.signature);
|
|
215
|
+
const normalized = {
|
|
216
|
+
credentialId: assertion.credentialId,
|
|
217
|
+
authenticatorData: assertion.authenticatorData,
|
|
218
|
+
clientDataJSON: assertion.clientDataJSON,
|
|
219
|
+
signature
|
|
220
|
+
};
|
|
221
|
+
if (options.target === "smart-wallet") {
|
|
222
|
+
applyAssertionToSmartWalletEntry(entry, normalized);
|
|
223
|
+
} else {
|
|
224
|
+
applyAssertionToEntry(entry, normalized);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
async function signAuthEntry(entryXdr, options) {
|
|
228
|
+
const entry = xdr.SorobanAuthorizationEntry.fromXDR(entryXdr, "base64");
|
|
229
|
+
await signEntryInPlace(entry, options);
|
|
230
|
+
return entry.toXDR("base64");
|
|
231
|
+
}
|
|
232
|
+
function operationsForSigning(envelope) {
|
|
233
|
+
const kind = envelope.switch().name;
|
|
234
|
+
if (kind === "envelopeTypeTx") return envelope.v1().tx().operations();
|
|
235
|
+
if (kind === "envelopeTypeTxFeeBump") {
|
|
236
|
+
const inner = envelope.feeBump().tx().innerTx();
|
|
237
|
+
if (inner.switch().name !== "envelopeTypeTx") {
|
|
238
|
+
throw new KitError(
|
|
239
|
+
"CONTRACT_AUTH_FAILED",
|
|
240
|
+
"signTransaction: fee-bump inner transaction is not a v1 transaction"
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
return inner.v1().tx().operations();
|
|
244
|
+
}
|
|
245
|
+
throw new KitError(
|
|
246
|
+
"CONTRACT_AUTH_FAILED",
|
|
247
|
+
`signTransaction: unsupported envelope type "${kind}" (expected v1 or fee-bump)`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
async function signTransaction(txXdr, options) {
|
|
251
|
+
const envelope = xdr.TransactionEnvelope.fromXDR(txXdr, "base64");
|
|
252
|
+
for (const op of operationsForSigning(envelope)) {
|
|
253
|
+
if (op.body().switch().name !== "invokeHostFunction") continue;
|
|
254
|
+
const entries = op.body().invokeHostFunctionOp().auth();
|
|
255
|
+
for (const entry of entries) {
|
|
256
|
+
if (entry.credentials().switch().name !== "sorobanCredentialsAddress") continue;
|
|
257
|
+
await signEntryInPlace(entry, options);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return envelope.toXDR("base64");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export { applyAssertionToEntry, applyAssertionToSmartWalletEntry, authEntryChallenge, authEntryChallengeBytes, buildSignerKeyScVal, buildSmartWalletSignatureVariant, compareSignerKeyScVal, derToCompact, derToCompactLowS, isLowS, normalizeLowS, reconstructSignedPayload, signAuthEntry, signTransaction, verifyAssertionSignature };
|
|
264
|
+
//# sourceMappingURL=chunk-BIRF5I6I.js.map
|
|
265
|
+
//# sourceMappingURL=chunk-BIRF5I6I.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webauthn/signature.ts","../src/webauthn/payload.ts","../src/webauthn/verify.ts","../src/soroban/preimage.ts","../src/soroban/assemble.ts","../src/soroban/smartWallet.ts","../src/soroban/sign.ts"],"names":["p256","xdr"],"mappings":";;;;;;AAIA,IAAM,cAAA,GAAiB,EAAA;AAUhB,SAAS,aAAa,GAAA,EAA6B;AACxD,EAAA,IAAI,GAAA,CAAI,SAAS,cAAA,EAAgB;AAC/B,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,uBAAA;AAAA,MACA,CAAA,iBAAA,EAAoB,GAAA,CAAI,MAAM,CAAA,oBAAA,EAAuB,cAAc,CAAA;AAAA,KACrE;AAAA,EACF;AACA,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,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,QAAA;AAAA,IACR,sBAAA;AAAA,IACA,+CAA+C,IAAI,CAAA,2BAAA;AAAA,GACrD;AACF;AAOA,eAAsB,eAAA,CAAgB,OAAe,OAAA,EAA8C;AACjG,EAAA,MAAM,QAAA,GAAWA,GAAAA,CAAI,mBAAA,CAAoB,OAAA,CAAQ,OAAO,QAAQ,CAAA;AAChE,EAAA,KAAA,MAAW,EAAA,IAAM,oBAAA,CAAqB,QAAQ,CAAA,EAAG;AAC/C,IAAA,IAAI,GAAG,IAAA,EAAK,CAAE,MAAA,EAAO,CAAE,SAAS,oBAAA,EAAsB;AACtD,IAAA,MAAM,UAAU,EAAA,CAAG,IAAA,EAAK,CAAE,oBAAA,GAAuB,IAAA,EAAK;AACtD,IAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,MAAA,IAAI,MAAM,WAAA,EAAY,CAAE,MAAA,EAAO,CAAE,SAAS,2BAAA,EAA6B;AACvE,MAAA,MAAM,gBAAA,CAAiB,OAAO,OAAO,CAAA;AAAA,IACvC;AAAA,EACF;AACA,EAAA,OAAO,QAAA,CAAS,MAAM,QAAQ,CAAA;AAChC","file":"chunk-BIRF5I6I.js","sourcesContent":["import { p256 } from '@noble/curves/nist';\nimport { KitError } from '../errors';\n\n/** Maximum DER length of a P-256 ECDSA signature: SEQ + two 33-byte INTEGERs. */\nconst MAX_DER_LENGTH = 72;\n\n/**\n * Convert an ASN.1 DER ECDSA signature to the 64-byte raw `R‖S` form Soroban's\n * `secp256r1_verify` expects, using noble's audited DER parser (R and S are\n * left-padded to 32 bytes big-endian). Rejects malformed or over-long input.\n *\n * Note: this does NOT enforce low-S — that normalization is added in S04\n * (YK-430). The output here mirrors the signature exactly as parsed.\n */\nexport function derToCompact(der: Uint8Array): Uint8Array {\n if (der.length > MAX_DER_LENGTH) {\n throw new KitError(\n 'INVALID_SIGNATURE_DER',\n `DER signature is ${der.length} bytes, exceeds max ${MAX_DER_LENGTH}`,\n );\n }\n try {\n return p256.Signature.fromDER(der).toCompactRawBytes();\n } catch (cause) {\n throw new KitError('INVALID_SIGNATURE_DER', 'failed to parse DER signature', { cause });\n }\n}\n\nfunction assertCompactLength(compactSignature: Uint8Array): void {\n if (compactSignature.length !== 64) {\n throw new KitError(\n 'INVALID_SIGNATURE_DER',\n `compact signature must be 64 bytes, got ${compactSignature.length}`,\n );\n }\n}\n\n/** True if a 64-byte compact signature is in canonical low-S form (S ≤ n/2). */\nexport function isLowS(compactSignature: Uint8Array): boolean {\n assertCompactLength(compactSignature);\n return !p256.Signature.fromCompact(compactSignature).hasHighS();\n}\n\n/**\n * Normalize a 64-byte compact signature to canonical low-S: if S > n/2, replace\n * S with n − S (anchor LOW_S_NORMALIZATION, invariant #2). ~50% of Apple Touch\n * ID / Face ID assertions are high-S and Soroban's `secp256r1_verify` does not\n * enforce low-S, so the SDK MUST emit low-S before a signature reaches a\n * contract. Idempotent: low-S input is returned unchanged.\n */\nexport function normalizeLowS(compactSignature: Uint8Array): Uint8Array {\n assertCompactLength(compactSignature);\n return p256.Signature.fromCompact(compactSignature).normalizeS().toCompactRawBytes();\n}\n\n/** DER → 64-byte canonical low-S compact — the conversion the signing ceremony uses. */\nexport function derToCompactLowS(der: Uint8Array): Uint8Array {\n return normalizeLowS(derToCompact(der));\n}\n","import { sha256 } from '../internal/sha256';\nimport { concatBytes } from '../internal/bytes';\n\n/**\n * Reconstruct the 32-byte payload the authenticator signed and that Soroban's\n * `__check_auth` re-derives on-chain:\n *\n * SHA256( authenticatorData ‖ SHA256(clientDataJSON) )\n */\nexport function reconstructSignedPayload(input: {\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n}): Uint8Array {\n const clientDataHash = sha256(input.clientDataJSON);\n return sha256(concatBytes(input.authenticatorData, clientDataHash));\n}\n","import { p256 } from '@noble/curves/nist';\nimport { reconstructSignedPayload } from './payload';\nimport { derToCompact } from './signature';\n\nexport interface VerifyAssertionInput {\n /** SEC-1 uncompressed public key (65 bytes, `0x04 ‖ X ‖ Y`). */\n publicKey: Uint8Array;\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n /** DER-encoded (≤72 B) or already-compact (64 B) signature. */\n signature: Uint8Array;\n}\n\n/**\n * Verify a WebAuthn assertion the way the on-chain `secp256r1_verify` does:\n * reconstruct `SHA256(authData ‖ SHA256(cdj))` and check ECDSA. `lowS: false`\n * mirrors the host function, which does NOT enforce low-S (we normalize\n * separately before submitting — see S04/YK-430).\n */\nexport function verifyAssertionSignature(input: VerifyAssertionInput): boolean {\n const payload = reconstructSignedPayload(input);\n const compact = input.signature.length === 64 ? input.signature : derToCompact(input.signature);\n // `format: 'compact'` pins the 64-byte interpretation — without it noble tries\n // DER-first and could misread a compact signature that happens to start 0x30.\n return p256.verify(compact, payload, input.publicKey, { lowS: false, format: 'compact' });\n}\n","import { xdr, hash } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { bytesToBase64Url, utf8ToBytes } from '../internal/encoding';\n\n/**\n * Compute the auth-entry preimage hash that `__check_auth` reconstructs and that\n * becomes the WebAuthn `challenge`:\n * SHA256( XDR( HashIdPreimage::SorobanAuthorization{ networkId, nonce,\n * signatureExpirationLedger, invocation } ) )\n * where networkId = SHA256(networkPassphrase).\n */\nexport function authEntryChallengeBytes(\n entry: xdr.SorobanAuthorizationEntry,\n networkPassphrase: string,\n): Uint8Array {\n const credentials = entry.credentials();\n if (credentials.switch().name !== 'sorobanCredentialsAddress') {\n throw new KitError('CONTRACT_AUTH_FAILED', 'auth entry has no address credentials to sign');\n }\n const address = credentials.address();\n const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId: Buffer.from(hash(Buffer.from(utf8ToBytes(networkPassphrase)))),\n nonce: address.nonce(),\n signatureExpirationLedger: address.signatureExpirationLedger(),\n invocation: entry.rootInvocation(),\n }),\n );\n return new Uint8Array(hash(preimage.toXDR()));\n}\n\n/** The base64url challenge string the authenticator signs (43 chars). */\nexport function authEntryChallenge(\n entry: xdr.SorobanAuthorizationEntry,\n networkPassphrase: string,\n): string {\n return bytesToBase64Url(authEntryChallengeBytes(entry, networkPassphrase));\n}\n","import { xdr } from '@stellar/stellar-sdk';\nimport type { AssertionResult } from './sign';\n\n/**\n * Set an address-credential auth entry's signature to the `Secp256r1Signature`\n * struct the on-chain `__check_auth` consumes:\n *\n * ScVal::Map { authenticator_data: Bytes, client_data_json: Bytes, signature: BytesN<64> }\n *\n * Map keys are alphabetical, so the ScMap is canonically sorted as Soroban\n * requires. `signature` MUST already be 64-byte low-S compact (`signAuthEntry`\n * normalizes before calling this). This is the exact shape the audited\n * webauthn-verifier reference expects — proven on testnet by the on-chain\n * integration test (scripts/onchain-e2e.ts).\n */\nexport function applyAssertionToEntry(\n entry: xdr.SorobanAuthorizationEntry,\n assertion: AssertionResult,\n): xdr.SorobanAuthorizationEntry {\n entry.credentials().address().signature(buildSignatureScVal(assertion));\n return entry;\n}\n\n/** The `Secp256r1Signature` ScVal — a contracttype struct → sorted ScMap. */\nexport function buildSignatureScVal(assertion: AssertionResult): xdr.ScVal {\n return xdr.ScVal.scvMap([\n bytesField('authenticator_data', assertion.authenticatorData),\n bytesField('client_data_json', assertion.clientDataJSON),\n bytesField('signature', assertion.signature),\n ]);\n}\n\nfunction bytesField(name: string, bytes: Uint8Array): xdr.ScMapEntry {\n return new xdr.ScMapEntry({\n key: xdr.ScVal.scvSymbol(name),\n val: xdr.ScVal.scvBytes(Buffer.from(bytes)),\n });\n}\n","import { xdr } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { buildSignatureScVal } from './assemble';\nimport type { AssertionResult } from './sign';\n\n/**\n * The passkey-kit / `webauthn-wallet` smart-wallet ABI target.\n *\n * Our own single-signer account declares `type Signature = Secp256r1Signature`\n * and consumes the bare struct (see `assemble.ts`). passkey-kit's smart-wallet\n * declares `type Signature = Signatures`, so authorizing it needs the assertion\n * wrapped as `Signatures(Map<SignerKey, Signature>)`. The exact shape, the raw-\n * credential-id key, and the canonical map ordering below are confirmed by\n * kalepail (passkey-kit author) in issue #32 against v1 / v0.13.0 (Protocol 27,\n * independently audited); the wire shape is unchanged from v0.12.\n */\n\n/**\n * `SignerKey::Secp256r1(Bytes)` → `scvVec([Symbol(\"Secp256r1\"), Bytes(rawId)])`.\n * The key is the RAW WebAuthn credential-id bytes (base64url-decoded `rawId`):\n * never hashed, never the UTF-8 of the base64url string, and never the public\n * key — the SEC-1 public key lives in `SignerVal` on-chain, not in the key.\n */\nexport function buildSignerKeyScVal(credentialId: Uint8Array): xdr.ScVal {\n return xdr.ScVal.scvVec([\n xdr.ScVal.scvSymbol('Secp256r1'),\n xdr.ScVal.scvBytes(Buffer.from(credentialId)),\n ]);\n}\n\n/** `Signature::Secp256r1(Secp256r1Signature)` → `scvVec([Symbol(\"Secp256r1\"), <bare struct map>])`. */\nexport function buildSmartWalletSignatureVariant(assertion: AssertionResult): xdr.ScVal {\n return xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Secp256r1'), buildSignatureScVal(assertion)]);\n}\n\nfunction decomposeSignerKey(key: xdr.ScVal): { variant: string; payload: Uint8Array } {\n const vec = key.vec();\n if (!vec || vec.length < 2) {\n throw new KitError('CONTRACT_AUTH_FAILED', 'malformed SignerKey (expected an enum vec)');\n }\n const variant = vec[0]!.sym().toString();\n const el = vec[1]!;\n // Secp256r1(Bytes) and Ed25519(BytesN<32>) are scvBytes; Policy(Address) falls\n // back to its XDR bytes (rare in a passkey SDK — see the ordering note below).\n const payload =\n el.switch().name === 'scvBytes' ? new Uint8Array(el.bytes()) : new Uint8Array(el.toXDR());\n return { variant, payload };\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n if (a[i] !== b[i]) return a[i]! < b[i]! ? -1 : 1;\n }\n return a.length - b.length;\n}\n\n/**\n * Canonical Soroban-host ordering for `SignerKey` map keys. The host requires\n * `Map<SignerKey, _>` entries sorted by ScVal `Ord` — an **element-wise byte\n * comparison**, NOT a length-major XDR-hex / `localeCompare` string sort. This is\n * the one correctness landmine kalepail flagged in #32: passkey-kit v1 replaced\n * its old string sort with exactly this because the old approach could mis-order\n * same-variant keys of differing length, producing a map the host rejects.\n *\n * We compare the enum variant symbol first, then the payload bytes element-wise,\n * so homogeneous `Secp256r1` keys (the multi-passkey case) sort purely by their\n * raw credential-id bytes. (Ordering across mixed variant types relies on the\n * variant names being capitalized single words, which matches the host's symbol\n * order; a Policy/Address-keyed multi-sig is out of scope for this passkey SDK.)\n */\nexport function compareSignerKeyScVal(a: xdr.ScVal, b: xdr.ScVal): number {\n const ka = decomposeSignerKey(a);\n const kb = decomposeSignerKey(b);\n if (ka.variant !== kb.variant) return ka.variant < kb.variant ? -1 : 1;\n return compareBytes(ka.payload, kb.payload);\n}\n\n/**\n * Assemble/merge a passkey assertion into an address-credential auth entry as the\n * smart-wallet `Signatures(Map<SignerKey, Signature>)` wire shape\n * (`ScVal::Vec([ScVal::Map(...)])`). `assertion.signature` MUST already be 64-byte\n * low-S compact (`signAuthEntry` normalizes first). Existing map entries — a\n * partially-signed multi-sig entry — are preserved; an entry for the same signer\n * key is replaced; then the whole map is canonically sorted.\n *\n * Use this for the passkey-kit / webauthn-wallet ABI. For our own single-signer\n * account (`type Signature = Secp256r1Signature`) use `applyAssertionToEntry`.\n */\nexport function applyAssertionToSmartWalletEntry(\n entry: xdr.SorobanAuthorizationEntry,\n assertion: AssertionResult,\n): xdr.SorobanAuthorizationEntry {\n const credentials = entry.credentials();\n if (credentials.switch().name !== 'sorobanCredentialsAddress') {\n throw new KitError('CONTRACT_AUTH_FAILED', 'auth entry has no address credentials to sign');\n }\n const key = buildSignerKeyScVal(assertion.credentialId);\n const newEntry = new xdr.ScMapEntry({ key, val: buildSmartWalletSignatureVariant(assertion) });\n\n const current = credentials.address().signature();\n let mapEntries: xdr.ScMapEntry[];\n switch (current.switch().name) {\n case 'scvVoid':\n mapEntries = [newEntry];\n break;\n case 'scvVec': {\n // Preserve any existing signatures (partial multi-sig); replace same key.\n const existing = current.vec()?.[0]?.map() ?? [];\n mapEntries = existing.filter((e) => compareSignerKeyScVal(e.key(), key) !== 0);\n mapEntries.push(newEntry);\n break;\n }\n default:\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n 'unexpected existing signature shape for a smart-wallet entry',\n );\n }\n mapEntries.sort((a, b) => compareSignerKeyScVal(a.key(), b.key()));\n credentials.address().signature(xdr.ScVal.scvVec([xdr.ScVal.scvMap(mapEntries)]));\n return entry;\n}\n","import { xdr } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { derToCompactLowS } from '../webauthn/signature';\nimport { parseClientDataJSON, verifyClientDataJSON, type ClientData } from '../webauthn/clientData';\nimport { parseAuthenticatorData, verifyRpIdHash } from '../webauthn/authData';\nimport { verifyAssertionSignature } from '../webauthn/verify';\nimport { authEntryChallenge } from './preimage';\nimport { applyAssertionToEntry } from './assemble';\nimport { applyAssertionToSmartWalletEntry } from './smartWallet';\n\n/**\n * Which contract ABI the assembled signature targets:\n * - `single-signer` (default): the bare `Secp256r1Signature` struct our own\n * webauthn-account consumes (`type Signature = Secp256r1Signature`).\n * - `smart-wallet`: passkey-kit's `Signatures(Map<SignerKey, Signature>)`\n * (`type Signature = Signatures`) — see `smartWallet.ts` / kalepail #32.\n * Both reuse the identical low-S, field-packing, and challenge-binding core;\n * only the outer wrapper differs, so the two stay separate ABI targets behind\n * one signing interface.\n */\nexport type WalletTarget = 'single-signer' | 'smart-wallet';\n\n/** The raw WebAuthn assertion a signer returns for a given challenge. */\nexport interface AssertionResult {\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n /** DER-encoded (≤72B) or already-compact (64B) ECDSA signature. */\n signature: Uint8Array;\n /** base64url credential id → the SignerKey. */\n credentialId: Uint8Array;\n}\n\n/** Produce a WebAuthn assertion over the base64url `challenge` (e.g. navigator.credentials.get). */\nexport type WebAuthnSigner = (challenge: string) => Promise<AssertionResult> | AssertionResult;\n\n/**\n * Opt-in pre-flight validation of the returned assertion, run BEFORE the entry\n * is assembled and submitted. On-chain `__check_auth` is the real gate, but\n * catching these client-side turns an opaque on-chain failure into a typed\n * `KitError` at the call site. Providing this object always enforces the\n * `webauthn.get` type, the User-Present (UP) flag (required by passkey-kit v1),\n * and challenge-binding; `rpId` / `origin` / `publicKey` add their checks when\n * supplied. Omit the object entirely to skip pre-flight (the default).\n */\nexport interface SignVerifyOptions {\n /** Verify `authenticatorData.rpIdHash === SHA-256(rpId)`. */\n rpId?: string;\n /** Verify `clientDataJSON.origin` is one of these exact origins. */\n origin?: string | string[];\n /** SEC-1 (65-byte) public key → verify the ECDSA assertion signature. */\n publicKey?: Uint8Array;\n /** Also require the User-Verified (UV) flag (biometric / PIN). Default false. */\n requireUserVerification?: boolean;\n /** Allow an assertion made in a cross-origin context (crossOrigin=true). Default false. */\n allowCrossOrigin?: boolean;\n}\n\nexport interface SorobanSignOptions {\n networkPassphrase: string;\n sign: WebAuthnSigner;\n /** Contract ABI to assemble for. Defaults to `single-signer` (our account). */\n target?: WalletTarget;\n /** Opt-in pre-flight assertion validation. Omit to skip. */\n verify?: SignVerifyOptions;\n /**\n * Stamp this `signatureExpirationLedger` onto every address-credential auth\n * entry BEFORE the challenge is computed, so the signature binds the exact\n * expiration the contract re-derives in `__check_auth`. Needed for smart-wallet\n * writes (add/remove signer) where the caller learns the ledger at sign time;\n * omit when the entry already carries the intended expiration.\n */\n signatureExpirationLedger?: number;\n}\n\n/** Validate an assertion against the expected challenge + RP context. Throws KitError. */\nfunction preflightAssertion(\n assertion: AssertionResult,\n challenge: string,\n verify: SignVerifyOptions,\n): void {\n // Ceremony type + challenge-binding (+ origin when provided).\n let clientData: ClientData;\n if (verify.origin !== undefined) {\n clientData = verifyClientDataJSON(assertion.clientDataJSON, {\n origin: verify.origin,\n challenge,\n });\n } else {\n clientData = parseClientDataJSON(assertion.clientDataJSON);\n if (clientData.type !== 'webauthn.get') {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n `clientDataJSON.type \"${clientData.type}\" is not \"webauthn.get\"`,\n );\n }\n if (clientData.challenge !== challenge) {\n throw new KitError('CHALLENGE_MISMATCH', 'assertion challenge does not match the auth entry');\n }\n }\n if (clientData.crossOrigin === true && !verify.allowCrossOrigin) {\n throw new KitError(\n 'ORIGIN_MISMATCH',\n 'assertion was made in a cross-origin context (crossOrigin=true)',\n );\n }\n // User-Present is mandatory (passkey-kit v1 hardening); UV is opt-in.\n const parsed = parseAuthenticatorData(assertion.authenticatorData);\n if (!parsed.flags.up) {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n 'assertion is missing the User-Present (UP) flag',\n );\n }\n if (verify.requireUserVerification && !parsed.flags.uv) {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n 'assertion is missing the required User-Verified (UV) flag',\n );\n }\n if (verify.rpId !== undefined) {\n verifyRpIdHash(assertion.authenticatorData, verify.rpId);\n }\n if (verify.publicKey !== undefined) {\n const ok = verifyAssertionSignature({\n publicKey: verify.publicKey,\n authenticatorData: assertion.authenticatorData,\n clientDataJSON: assertion.clientDataJSON,\n signature: assertion.signature,\n });\n if (!ok) {\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n 'assertion signature failed pre-flight verification',\n );\n }\n }\n}\n\nasync function signEntryInPlace(\n entry: xdr.SorobanAuthorizationEntry,\n options: SorobanSignOptions,\n): Promise<void> {\n // Stamp the expiration first: the challenge preimage includes\n // signatureExpirationLedger, so it must be final before we compute it.\n if (options.signatureExpirationLedger !== undefined) {\n const creds = entry.credentials();\n if (creds.switch().name === 'sorobanCredentialsAddress') {\n creds.address().signatureExpirationLedger(options.signatureExpirationLedger);\n }\n }\n const challenge = authEntryChallenge(entry, options.networkPassphrase);\n const assertion = await options.sign(challenge);\n if (options.verify) preflightAssertion(assertion, challenge, options.verify);\n const signature =\n assertion.signature.length === 64 ? assertion.signature : derToCompactLowS(assertion.signature);\n const normalized = {\n credentialId: assertion.credentialId,\n authenticatorData: assertion.authenticatorData,\n clientDataJSON: assertion.clientDataJSON,\n signature,\n };\n if (options.target === 'smart-wallet') {\n applyAssertionToSmartWalletEntry(entry, normalized);\n } else {\n applyAssertionToEntry(entry, normalized);\n }\n}\n\n/**\n * Sign a single `SorobanAuthorizationEntry` (base64 XDR): compute the challenge,\n * obtain a WebAuthn assertion, low-S-normalize, and assemble the contract\n * signature. Returns the signed entry as base64 XDR.\n */\nexport async function signAuthEntry(\n entryXdr: string,\n options: SorobanSignOptions,\n): Promise<string> {\n const entry = xdr.SorobanAuthorizationEntry.fromXDR(entryXdr, 'base64');\n await signEntryInPlace(entry, options);\n return entry.toXDR('base64');\n}\n\n/**\n * The operations whose Soroban auth entries we sign, for a v1 or a fee-bump\n * envelope. (Sign the Soroban auth entries before adding classic tx signatures\n * or fee-bumping; a fee-bump around an already-classic-signed inner tx is the\n * caller's sequencing concern.)\n */\nfunction operationsForSigning(envelope: xdr.TransactionEnvelope): xdr.Operation[] {\n const kind = envelope.switch().name;\n if (kind === 'envelopeTypeTx') return envelope.v1().tx().operations();\n if (kind === 'envelopeTypeTxFeeBump') {\n const inner = envelope.feeBump().tx().innerTx();\n if (inner.switch().name !== 'envelopeTypeTx') {\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n 'signTransaction: fee-bump inner transaction is not a v1 transaction',\n );\n }\n return inner.v1().tx().operations();\n }\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n `signTransaction: unsupported envelope type \"${kind}\" (expected v1 or fee-bump)`,\n );\n}\n\n/**\n * Sign every address-credential Soroban auth entry carried by the InvokeHostFunction\n * operations of a transaction (base64 XDR envelope — v1 or fee-bump). Returns the\n * signed envelope XDR.\n */\nexport async function signTransaction(txXdr: string, options: SorobanSignOptions): Promise<string> {\n const envelope = xdr.TransactionEnvelope.fromXDR(txXdr, 'base64');\n for (const op of operationsForSigning(envelope)) {\n if (op.body().switch().name !== 'invokeHostFunction') continue;\n const entries = op.body().invokeHostFunctionOp().auth();\n for (const entry of entries) {\n if (entry.credentials().switch().name !== 'sorobanCredentialsAddress') continue;\n await signEntryInPlace(entry, options);\n }\n }\n return envelope.toXDR('base64');\n}\n"]}
|