@decryption/webauthn 0.0.0-stage → 0.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # @decryption/webauthn
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/decryption/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/decryption/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/decryption/blob/main/LICENSE">
12
+ <img height="20" alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue.svg" />
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@decryption/webauthn"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/decryption?filename=packages%2Fwebauthn%2Fpackage.json"/></a>
15
+ </p>
16
+
17
+ A software WebAuthn authenticator. A passkey is not a stored password — it is a P-256 keypair whose
18
+ private half never leaves the machine, and whose signature covers the site that asked for it. This
19
+ package makes those keys, signs the challenges a relying party issues, and keeps the private half in
20
+ the encrypted [dcrypt vault](https://www.npmjs.com/package/@decryption/vault).
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install @decryption/webauthn
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ```typescript
31
+ import { PasskeyStore } from '@decryption/webauthn';
32
+ import { Vault, defaultModulePath } from '@decryption/vault';
33
+
34
+ const vault = await Vault.open({ file, passphrase, modulePath: defaultModulePath() });
35
+ const passkeys = new PasskeyStore(vault);
36
+
37
+ // registration: the challenge comes from the relying party
38
+ const { record, response } = await passkeys.register({
39
+ rpId: 'auth.example.com',
40
+ origin: 'https://auth.example.com',
41
+ challenge, // base64url, from webauthn_begin_registration
42
+ userName: 'dev@example.com',
43
+ });
44
+
45
+ // sign-in: sign the challenge the site issued, and nothing else
46
+ const assertion = await passkeys.assert(record.itemId, { origin, challenge });
47
+ ```
48
+
49
+ `response` and `assertion` are shaped exactly as `navigator.credentials.create()` and `.get()`
50
+ resolve, so a relying party — `@simplewebauthn/server`, or Constructive's `auth:passkey`
51
+ procedures behind one — verifies them without knowing dcrypt exists.
52
+
53
+ Without a vault, `createPasskey` and `assertPasskey` do the same work in memory and hand back the
54
+ key for the caller to store.
55
+
56
+ ## What is stored
57
+
58
+ A passkey is a `passkey` vault item. Only the private key is concealed: a site name and a sign count
59
+ are not secrets, and leaving them readable is what lets a list render without decrypting anything.
60
+
61
+ | Field | Purpose |
62
+ | --------------- | ------------------------------------------------------------- |
63
+ | `rp_id` | The site the key signs for, and no other |
64
+ | `credential_id` | What the site calls this key |
65
+ | `user_handle` | Opaque user id, so a site can sign you in without a username |
66
+ | `user_name` | The account it belongs to |
67
+ | `sign_count` | Advanced and persisted on every assertion |
68
+ | `private_key`\* | The 32-byte P-256 scalar |
69
+
70
+ \* concealed. Because it is a vault item, a passkey is covered by the master passphrase, by lock and
71
+ by backup and restore — so unlike a hardware key it survives a lost laptop.
72
+
73
+ ## What it does not claim
74
+
75
+ Attestation is `none` with an all-zero AAGUID: this is software, and it says so. A relying party that
76
+ requires hardware attestation should reject it, which is the correct outcome.
77
+
78
+ ## License
79
+
80
+ MIT
81
+
82
+ ## Credits
83
+
84
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
85
+
86
+ ## Disclaimer
87
+
88
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
89
+
90
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
91
+
92
+ ---
93
+
94
+ ## Development
95
+
96
+ ### Setup
97
+
98
+ 1. Clone the repository:
99
+
100
+ ```bash
101
+ git clone https://github.com/constructive-io/decryption.git
102
+ ```
103
+
104
+ 2. Install dependencies:
105
+
106
+ ```bash
107
+ cd decryption
108
+ pnpm install
109
+ pnpm build
110
+ ```
111
+
112
+ 3. Test the package of interest:
113
+
114
+ ```bash
115
+ cd packages/<packagename>
116
+ pnpm test:watch
117
+ ```
118
+
119
+ ## Credits
120
+
121
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
122
+
123
+ ## Disclaimer
124
+
125
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
126
+
127
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
@@ -0,0 +1,23 @@
1
+ import type { Assertion, AssertionRequest, Passkey, Registration, RegistrationRequest } from './types';
2
+ /** ES256: ECDSA with P-256 and SHA-256, the algorithm every site accepts. */
3
+ export declare const ES256 = -7;
4
+ /** The uncompressed point, as a COSE_Key — the form a relying party stores. */
5
+ export declare const coseKey: (publicKey: Uint8Array) => Uint8Array;
6
+ /**
7
+ * Mint a passkey for a site. The private key never leaves the return value —
8
+ * the caller's job is to put it straight into the vault.
9
+ */
10
+ export declare const createPasskey: (request: RegistrationRequest) => Registration;
11
+ /**
12
+ * Sign a site's challenge with a passkey. The returned passkey carries the
13
+ * incremented sign count, which the caller must persist: a site that sees the
14
+ * count fail to advance is entitled to conclude the key has been cloned.
15
+ */
16
+ export declare const assertPasskey: (passkey: Passkey, request: AssertionRequest) => Assertion;
17
+ /**
18
+ * Check an assertion's signature. This is only the cryptographic half of what a
19
+ * relying party does — it still owes the challenge, origin, RP id hash and sign
20
+ * count checks — but a round trip whose signature is never verified proves
21
+ * nothing, which is what the tests are for.
22
+ */
23
+ export declare const verifyAssertion: (publicKey: Uint8Array, authData: Uint8Array, clientDataJSON: Uint8Array, signature: Uint8Array) => boolean;
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyAssertion = exports.assertPasskey = exports.createPasskey = exports.coseKey = exports.ES256 = void 0;
4
+ const base_1 = require("@decryption/base");
5
+ const nist_1 = require("@decryption/curves/nist");
6
+ const sha2_1 = require("@decryption/hashes/sha2");
7
+ const cbor_1 = require("./cbor");
8
+ /** ES256: ECDSA with P-256 and SHA-256, the algorithm every site accepts. */
9
+ exports.ES256 = -7;
10
+ /**
11
+ * Authenticators identify their make and model with an AAGUID. A software
12
+ * authenticator is required to report all-zero, which also says honestly that
13
+ * this key is not shielded by tamper-resistant hardware.
14
+ */
15
+ const AAGUID = new Uint8Array(16);
16
+ const FLAG = {
17
+ userPresent: 0x01,
18
+ userVerified: 0x04,
19
+ /** The key is one that can be backed up — the vault is a file you can copy. */
20
+ backupEligible: 0x08,
21
+ backedUp: 0x10,
22
+ attestedCredentialData: 0x40,
23
+ };
24
+ const concat = (...chunks) => {
25
+ const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));
26
+ let at = 0;
27
+ for (const chunk of chunks) {
28
+ out.set(chunk, at);
29
+ at += chunk.length;
30
+ }
31
+ return out;
32
+ };
33
+ const uint32 = (value) => Uint8Array.from([(value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff]);
34
+ /** The uncompressed point, as a COSE_Key — the form a relying party stores. */
35
+ const coseKey = (publicKey) => (0, cbor_1.encode)(new Map([
36
+ [1, 2], // kty: EC2
37
+ [3, exports.ES256], // alg
38
+ [-1, 1], // crv: P-256
39
+ [-2, publicKey.slice(1, 33)], // x
40
+ [-3, publicKey.slice(33, 65)], // y
41
+ ]));
42
+ exports.coseKey = coseKey;
43
+ /**
44
+ * `authenticatorData`: which site, what the user did, how many times this key
45
+ * has signed — and on registration, the credential itself.
46
+ */
47
+ const authenticatorData = (rpId, signCount, attested) => {
48
+ const flags = FLAG.userPresent |
49
+ FLAG.userVerified |
50
+ FLAG.backupEligible |
51
+ FLAG.backedUp |
52
+ (attested ? FLAG.attestedCredentialData : 0);
53
+ const head = concat((0, sha2_1.sha256)(new TextEncoder().encode(rpId)), Uint8Array.from([flags]), uint32(signCount));
54
+ if (!attested)
55
+ return head;
56
+ const { credentialId, publicKey } = attested;
57
+ return concat(head, AAGUID, Uint8Array.from([(credentialId.length >> 8) & 0xff, credentialId.length & 0xff]), credentialId, (0, exports.coseKey)(publicKey));
58
+ };
59
+ /**
60
+ * What the browser would have shown the authenticator: the challenge it is
61
+ * signing, and the origin it is signing it for. The origin is in here rather
62
+ * than in the signature's own fields, which is what makes a passkey
63
+ * unphishable — a site cannot get a signature naming a different origin.
64
+ */
65
+ const clientData = (type, challenge, origin) => new TextEncoder().encode(JSON.stringify({ type, challenge, origin, crossOrigin: false }));
66
+ /** ECDSA over `authenticatorData || sha256(clientDataJSON)`, DER as WebAuthn wants. */
67
+ const sign = (privateKey, authData, clientDataJSON) => nist_1.p256.Signature.fromBytes(nist_1.p256.sign(concat(authData, (0, sha2_1.sha256)(clientDataJSON)), privateKey)).toBytes('der');
68
+ /**
69
+ * Mint a passkey for a site. The private key never leaves the return value —
70
+ * the caller's job is to put it straight into the vault.
71
+ */
72
+ const createPasskey = (request) => {
73
+ const privateKey = nist_1.p256.utils.randomSecretKey();
74
+ const publicKey = nist_1.p256.getPublicKey(privateKey, false);
75
+ const credentialId = crypto.getRandomValues(new Uint8Array(32));
76
+ const userHandle = request.userHandle ?? base_1.base64urlnopad.encode(crypto.getRandomValues(new Uint8Array(32)));
77
+ const authData = authenticatorData(request.rpId, 0, { credentialId, publicKey });
78
+ const clientDataJSON = clientData('webauthn.create', request.challenge, request.origin);
79
+ // fmt 'none': a software authenticator attests to nothing about its hardware,
80
+ // and claiming otherwise is exactly the lie attestation exists to catch
81
+ const attestationObject = (0, cbor_1.encode)(new Map([
82
+ ['fmt', 'none'],
83
+ ['attStmt', new Map()],
84
+ ['authData', authData],
85
+ ]));
86
+ const id = base_1.base64urlnopad.encode(credentialId);
87
+ return {
88
+ passkey: {
89
+ credentialId: id,
90
+ rpId: request.rpId,
91
+ privateKey: base_1.base64urlnopad.encode(privateKey),
92
+ userHandle,
93
+ userName: request.userName,
94
+ signCount: 0,
95
+ },
96
+ response: {
97
+ id,
98
+ rawId: id,
99
+ type: 'public-key',
100
+ clientExtensionResults: {},
101
+ authenticatorAttachment: 'platform',
102
+ response: {
103
+ clientDataJSON: base_1.base64urlnopad.encode(clientDataJSON),
104
+ attestationObject: base_1.base64urlnopad.encode(attestationObject),
105
+ transports: ['internal', 'hybrid'],
106
+ publicKey: base_1.base64urlnopad.encode((0, exports.coseKey)(publicKey)),
107
+ publicKeyAlgorithm: exports.ES256,
108
+ authenticatorData: base_1.base64urlnopad.encode(authData),
109
+ },
110
+ },
111
+ };
112
+ };
113
+ exports.createPasskey = createPasskey;
114
+ /**
115
+ * Sign a site's challenge with a passkey. The returned passkey carries the
116
+ * incremented sign count, which the caller must persist: a site that sees the
117
+ * count fail to advance is entitled to conclude the key has been cloned.
118
+ */
119
+ const assertPasskey = (passkey, request) => {
120
+ const signCount = passkey.signCount + 1;
121
+ const authData = authenticatorData(passkey.rpId, signCount);
122
+ const clientDataJSON = clientData('webauthn.get', request.challenge, request.origin);
123
+ const signature = sign(base_1.base64urlnopad.decode(passkey.privateKey), authData, clientDataJSON);
124
+ return {
125
+ passkey: { ...passkey, signCount },
126
+ response: {
127
+ id: passkey.credentialId,
128
+ rawId: passkey.credentialId,
129
+ type: 'public-key',
130
+ clientExtensionResults: {},
131
+ authenticatorAttachment: 'platform',
132
+ response: {
133
+ clientDataJSON: base_1.base64urlnopad.encode(clientDataJSON),
134
+ authenticatorData: base_1.base64urlnopad.encode(authData),
135
+ signature: base_1.base64urlnopad.encode(signature),
136
+ userHandle: passkey.userHandle,
137
+ },
138
+ },
139
+ };
140
+ };
141
+ exports.assertPasskey = assertPasskey;
142
+ /**
143
+ * Check an assertion's signature. This is only the cryptographic half of what a
144
+ * relying party does — it still owes the challenge, origin, RP id hash and sign
145
+ * count checks — but a round trip whose signature is never verified proves
146
+ * nothing, which is what the tests are for.
147
+ */
148
+ const verifyAssertion = (publicKey, authData, clientDataJSON, signature) => nist_1.p256.verify(signature, concat(authData, (0, sha2_1.sha256)(clientDataJSON)), publicKey, { format: 'der' });
149
+ exports.verifyAssertion = verifyAssertion;
package/cbor.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Just enough CBOR for WebAuthn: canonical (CTAP2) encoding of the maps and
3
+ * byte strings an authenticator emits, and decoding of the same. A passkey
4
+ * only ever needs integers, byte strings, text, arrays and maps — no tags, no
5
+ * floats, no indefinite lengths — so a full CBOR library would be a dependency
6
+ * carrying far more than it is asked to do.
7
+ */
8
+ export type CborValue = number | string | boolean | null | Uint8Array | CborValue[] | Map<CborValue, CborValue>;
9
+ export declare const encode: (value: CborValue) => Uint8Array;
10
+ export declare const decode: (bytes: Uint8Array) => CborValue;
package/cbor.js ADDED
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decode = exports.encode = void 0;
4
+ const head = (major, length) => {
5
+ if (length < 24)
6
+ return Uint8Array.from([(major << 5) | length]);
7
+ if (length < 0x100)
8
+ return Uint8Array.from([(major << 5) | 24, length]);
9
+ if (length < 0x10000) {
10
+ return Uint8Array.from([(major << 5) | 25, length >> 8, length & 0xff]);
11
+ }
12
+ return Uint8Array.from([
13
+ (major << 5) | 26,
14
+ (length >>> 24) & 0xff,
15
+ (length >>> 16) & 0xff,
16
+ (length >>> 8) & 0xff,
17
+ length & 0xff,
18
+ ]);
19
+ };
20
+ const concat = (chunks) => {
21
+ const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));
22
+ let at = 0;
23
+ for (const chunk of chunks) {
24
+ out.set(chunk, at);
25
+ at += chunk.length;
26
+ }
27
+ return out;
28
+ };
29
+ /**
30
+ * Canonical ordering per CTAP2: shorter keys first, then bytewise. Relying
31
+ * parties re-encode the COSE key to compare it, so the order is not cosmetic.
32
+ */
33
+ const canonical = (entries) => [...entries].sort(([a], [b]) => {
34
+ const left = (0, exports.encode)(a);
35
+ const right = (0, exports.encode)(b);
36
+ if (left.length !== right.length)
37
+ return left.length - right.length;
38
+ for (let i = 0; i < left.length; i += 1) {
39
+ if (left[i] !== right[i])
40
+ return left[i] - right[i];
41
+ }
42
+ return 0;
43
+ });
44
+ const encode = (value) => {
45
+ if (value === null)
46
+ return Uint8Array.from([0xf6]);
47
+ if (typeof value === 'boolean')
48
+ return Uint8Array.from([value ? 0xf5 : 0xf4]);
49
+ if (typeof value === 'number') {
50
+ if (!Number.isInteger(value))
51
+ throw new Error('cbor: only integers are supported');
52
+ return value < 0 ? head(1, -value - 1) : head(0, value);
53
+ }
54
+ if (value instanceof Uint8Array)
55
+ return concat([head(2, value.length), value]);
56
+ if (typeof value === 'string') {
57
+ const bytes = new TextEncoder().encode(value);
58
+ return concat([head(3, bytes.length), bytes]);
59
+ }
60
+ if (Array.isArray(value)) {
61
+ return concat([head(4, value.length), ...value.map(exports.encode)]);
62
+ }
63
+ const entries = canonical([...value.entries()]);
64
+ return concat([
65
+ head(5, entries.length),
66
+ ...entries.map(([key, item]) => concat([(0, exports.encode)(key), (0, exports.encode)(item)])),
67
+ ]);
68
+ };
69
+ exports.encode = encode;
70
+ const readLength = (cursor, extra) => {
71
+ if (extra < 24)
72
+ return extra;
73
+ const width = extra === 24 ? 1 : extra === 25 ? 2 : extra === 26 ? 4 : 0;
74
+ if (!width)
75
+ throw new Error('cbor: unsupported length encoding');
76
+ let length = 0;
77
+ for (let i = 0; i < width; i += 1) {
78
+ length = length * 256 + cursor.bytes[cursor.at + i];
79
+ }
80
+ cursor.at += width;
81
+ return length;
82
+ };
83
+ const readValue = (cursor) => {
84
+ const byte = cursor.bytes[cursor.at];
85
+ cursor.at += 1;
86
+ const major = byte >> 5;
87
+ const extra = byte & 0x1f;
88
+ switch (major) {
89
+ case 0:
90
+ return readLength(cursor, extra);
91
+ case 1:
92
+ return -1 - readLength(cursor, extra);
93
+ case 2: {
94
+ const length = readLength(cursor, extra);
95
+ const slice = cursor.bytes.slice(cursor.at, cursor.at + length);
96
+ cursor.at += length;
97
+ return slice;
98
+ }
99
+ case 3: {
100
+ const length = readLength(cursor, extra);
101
+ const slice = cursor.bytes.slice(cursor.at, cursor.at + length);
102
+ cursor.at += length;
103
+ return new TextDecoder().decode(slice);
104
+ }
105
+ case 4: {
106
+ const length = readLength(cursor, extra);
107
+ return Array.from({ length }, () => readValue(cursor));
108
+ }
109
+ case 5: {
110
+ const length = readLength(cursor, extra);
111
+ const map = new Map();
112
+ for (let i = 0; i < length; i += 1) {
113
+ const key = readValue(cursor);
114
+ map.set(key, readValue(cursor));
115
+ }
116
+ return map;
117
+ }
118
+ case 7:
119
+ if (extra === 20)
120
+ return false;
121
+ if (extra === 21)
122
+ return true;
123
+ if (extra === 22)
124
+ return null;
125
+ throw new Error('cbor: unsupported simple value');
126
+ default:
127
+ throw new Error(`cbor: unsupported major type ${major}`);
128
+ }
129
+ };
130
+ const decode = (bytes) => readValue({ bytes, at: 0 });
131
+ exports.decode = decode;
@@ -0,0 +1,142 @@
1
+ import { base64urlnopad } from '@decryption/base';
2
+ import { p256 } from '@decryption/curves/nist';
3
+ import { sha256 } from '@decryption/hashes/sha2';
4
+ import { encode } from './cbor';
5
+ /** ES256: ECDSA with P-256 and SHA-256, the algorithm every site accepts. */
6
+ export const ES256 = -7;
7
+ /**
8
+ * Authenticators identify their make and model with an AAGUID. A software
9
+ * authenticator is required to report all-zero, which also says honestly that
10
+ * this key is not shielded by tamper-resistant hardware.
11
+ */
12
+ const AAGUID = new Uint8Array(16);
13
+ const FLAG = {
14
+ userPresent: 0x01,
15
+ userVerified: 0x04,
16
+ /** The key is one that can be backed up — the vault is a file you can copy. */
17
+ backupEligible: 0x08,
18
+ backedUp: 0x10,
19
+ attestedCredentialData: 0x40,
20
+ };
21
+ const concat = (...chunks) => {
22
+ const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));
23
+ let at = 0;
24
+ for (const chunk of chunks) {
25
+ out.set(chunk, at);
26
+ at += chunk.length;
27
+ }
28
+ return out;
29
+ };
30
+ const uint32 = (value) => Uint8Array.from([(value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff]);
31
+ /** The uncompressed point, as a COSE_Key — the form a relying party stores. */
32
+ export const coseKey = (publicKey) => encode(new Map([
33
+ [1, 2], // kty: EC2
34
+ [3, ES256], // alg
35
+ [-1, 1], // crv: P-256
36
+ [-2, publicKey.slice(1, 33)], // x
37
+ [-3, publicKey.slice(33, 65)], // y
38
+ ]));
39
+ /**
40
+ * `authenticatorData`: which site, what the user did, how many times this key
41
+ * has signed — and on registration, the credential itself.
42
+ */
43
+ const authenticatorData = (rpId, signCount, attested) => {
44
+ const flags = FLAG.userPresent |
45
+ FLAG.userVerified |
46
+ FLAG.backupEligible |
47
+ FLAG.backedUp |
48
+ (attested ? FLAG.attestedCredentialData : 0);
49
+ const head = concat(sha256(new TextEncoder().encode(rpId)), Uint8Array.from([flags]), uint32(signCount));
50
+ if (!attested)
51
+ return head;
52
+ const { credentialId, publicKey } = attested;
53
+ return concat(head, AAGUID, Uint8Array.from([(credentialId.length >> 8) & 0xff, credentialId.length & 0xff]), credentialId, coseKey(publicKey));
54
+ };
55
+ /**
56
+ * What the browser would have shown the authenticator: the challenge it is
57
+ * signing, and the origin it is signing it for. The origin is in here rather
58
+ * than in the signature's own fields, which is what makes a passkey
59
+ * unphishable — a site cannot get a signature naming a different origin.
60
+ */
61
+ const clientData = (type, challenge, origin) => new TextEncoder().encode(JSON.stringify({ type, challenge, origin, crossOrigin: false }));
62
+ /** ECDSA over `authenticatorData || sha256(clientDataJSON)`, DER as WebAuthn wants. */
63
+ const sign = (privateKey, authData, clientDataJSON) => p256.Signature.fromBytes(p256.sign(concat(authData, sha256(clientDataJSON)), privateKey)).toBytes('der');
64
+ /**
65
+ * Mint a passkey for a site. The private key never leaves the return value —
66
+ * the caller's job is to put it straight into the vault.
67
+ */
68
+ export const createPasskey = (request) => {
69
+ const privateKey = p256.utils.randomSecretKey();
70
+ const publicKey = p256.getPublicKey(privateKey, false);
71
+ const credentialId = crypto.getRandomValues(new Uint8Array(32));
72
+ const userHandle = request.userHandle ?? base64urlnopad.encode(crypto.getRandomValues(new Uint8Array(32)));
73
+ const authData = authenticatorData(request.rpId, 0, { credentialId, publicKey });
74
+ const clientDataJSON = clientData('webauthn.create', request.challenge, request.origin);
75
+ // fmt 'none': a software authenticator attests to nothing about its hardware,
76
+ // and claiming otherwise is exactly the lie attestation exists to catch
77
+ const attestationObject = encode(new Map([
78
+ ['fmt', 'none'],
79
+ ['attStmt', new Map()],
80
+ ['authData', authData],
81
+ ]));
82
+ const id = base64urlnopad.encode(credentialId);
83
+ return {
84
+ passkey: {
85
+ credentialId: id,
86
+ rpId: request.rpId,
87
+ privateKey: base64urlnopad.encode(privateKey),
88
+ userHandle,
89
+ userName: request.userName,
90
+ signCount: 0,
91
+ },
92
+ response: {
93
+ id,
94
+ rawId: id,
95
+ type: 'public-key',
96
+ clientExtensionResults: {},
97
+ authenticatorAttachment: 'platform',
98
+ response: {
99
+ clientDataJSON: base64urlnopad.encode(clientDataJSON),
100
+ attestationObject: base64urlnopad.encode(attestationObject),
101
+ transports: ['internal', 'hybrid'],
102
+ publicKey: base64urlnopad.encode(coseKey(publicKey)),
103
+ publicKeyAlgorithm: ES256,
104
+ authenticatorData: base64urlnopad.encode(authData),
105
+ },
106
+ },
107
+ };
108
+ };
109
+ /**
110
+ * Sign a site's challenge with a passkey. The returned passkey carries the
111
+ * incremented sign count, which the caller must persist: a site that sees the
112
+ * count fail to advance is entitled to conclude the key has been cloned.
113
+ */
114
+ export const assertPasskey = (passkey, request) => {
115
+ const signCount = passkey.signCount + 1;
116
+ const authData = authenticatorData(passkey.rpId, signCount);
117
+ const clientDataJSON = clientData('webauthn.get', request.challenge, request.origin);
118
+ const signature = sign(base64urlnopad.decode(passkey.privateKey), authData, clientDataJSON);
119
+ return {
120
+ passkey: { ...passkey, signCount },
121
+ response: {
122
+ id: passkey.credentialId,
123
+ rawId: passkey.credentialId,
124
+ type: 'public-key',
125
+ clientExtensionResults: {},
126
+ authenticatorAttachment: 'platform',
127
+ response: {
128
+ clientDataJSON: base64urlnopad.encode(clientDataJSON),
129
+ authenticatorData: base64urlnopad.encode(authData),
130
+ signature: base64urlnopad.encode(signature),
131
+ userHandle: passkey.userHandle,
132
+ },
133
+ },
134
+ };
135
+ };
136
+ /**
137
+ * Check an assertion's signature. This is only the cryptographic half of what a
138
+ * relying party does — it still owes the challenge, origin, RP id hash and sign
139
+ * count checks — but a round trip whose signature is never verified proves
140
+ * nothing, which is what the tests are for.
141
+ */
142
+ export const verifyAssertion = (publicKey, authData, clientDataJSON, signature) => p256.verify(signature, concat(authData, sha256(clientDataJSON)), publicKey, { format: 'der' });
package/esm/cbor.js ADDED
@@ -0,0 +1,126 @@
1
+ const head = (major, length) => {
2
+ if (length < 24)
3
+ return Uint8Array.from([(major << 5) | length]);
4
+ if (length < 0x100)
5
+ return Uint8Array.from([(major << 5) | 24, length]);
6
+ if (length < 0x10000) {
7
+ return Uint8Array.from([(major << 5) | 25, length >> 8, length & 0xff]);
8
+ }
9
+ return Uint8Array.from([
10
+ (major << 5) | 26,
11
+ (length >>> 24) & 0xff,
12
+ (length >>> 16) & 0xff,
13
+ (length >>> 8) & 0xff,
14
+ length & 0xff,
15
+ ]);
16
+ };
17
+ const concat = (chunks) => {
18
+ const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));
19
+ let at = 0;
20
+ for (const chunk of chunks) {
21
+ out.set(chunk, at);
22
+ at += chunk.length;
23
+ }
24
+ return out;
25
+ };
26
+ /**
27
+ * Canonical ordering per CTAP2: shorter keys first, then bytewise. Relying
28
+ * parties re-encode the COSE key to compare it, so the order is not cosmetic.
29
+ */
30
+ const canonical = (entries) => [...entries].sort(([a], [b]) => {
31
+ const left = encode(a);
32
+ const right = encode(b);
33
+ if (left.length !== right.length)
34
+ return left.length - right.length;
35
+ for (let i = 0; i < left.length; i += 1) {
36
+ if (left[i] !== right[i])
37
+ return left[i] - right[i];
38
+ }
39
+ return 0;
40
+ });
41
+ export const encode = (value) => {
42
+ if (value === null)
43
+ return Uint8Array.from([0xf6]);
44
+ if (typeof value === 'boolean')
45
+ return Uint8Array.from([value ? 0xf5 : 0xf4]);
46
+ if (typeof value === 'number') {
47
+ if (!Number.isInteger(value))
48
+ throw new Error('cbor: only integers are supported');
49
+ return value < 0 ? head(1, -value - 1) : head(0, value);
50
+ }
51
+ if (value instanceof Uint8Array)
52
+ return concat([head(2, value.length), value]);
53
+ if (typeof value === 'string') {
54
+ const bytes = new TextEncoder().encode(value);
55
+ return concat([head(3, bytes.length), bytes]);
56
+ }
57
+ if (Array.isArray(value)) {
58
+ return concat([head(4, value.length), ...value.map(encode)]);
59
+ }
60
+ const entries = canonical([...value.entries()]);
61
+ return concat([
62
+ head(5, entries.length),
63
+ ...entries.map(([key, item]) => concat([encode(key), encode(item)])),
64
+ ]);
65
+ };
66
+ const readLength = (cursor, extra) => {
67
+ if (extra < 24)
68
+ return extra;
69
+ const width = extra === 24 ? 1 : extra === 25 ? 2 : extra === 26 ? 4 : 0;
70
+ if (!width)
71
+ throw new Error('cbor: unsupported length encoding');
72
+ let length = 0;
73
+ for (let i = 0; i < width; i += 1) {
74
+ length = length * 256 + cursor.bytes[cursor.at + i];
75
+ }
76
+ cursor.at += width;
77
+ return length;
78
+ };
79
+ const readValue = (cursor) => {
80
+ const byte = cursor.bytes[cursor.at];
81
+ cursor.at += 1;
82
+ const major = byte >> 5;
83
+ const extra = byte & 0x1f;
84
+ switch (major) {
85
+ case 0:
86
+ return readLength(cursor, extra);
87
+ case 1:
88
+ return -1 - readLength(cursor, extra);
89
+ case 2: {
90
+ const length = readLength(cursor, extra);
91
+ const slice = cursor.bytes.slice(cursor.at, cursor.at + length);
92
+ cursor.at += length;
93
+ return slice;
94
+ }
95
+ case 3: {
96
+ const length = readLength(cursor, extra);
97
+ const slice = cursor.bytes.slice(cursor.at, cursor.at + length);
98
+ cursor.at += length;
99
+ return new TextDecoder().decode(slice);
100
+ }
101
+ case 4: {
102
+ const length = readLength(cursor, extra);
103
+ return Array.from({ length }, () => readValue(cursor));
104
+ }
105
+ case 5: {
106
+ const length = readLength(cursor, extra);
107
+ const map = new Map();
108
+ for (let i = 0; i < length; i += 1) {
109
+ const key = readValue(cursor);
110
+ map.set(key, readValue(cursor));
111
+ }
112
+ return map;
113
+ }
114
+ case 7:
115
+ if (extra === 20)
116
+ return false;
117
+ if (extra === 21)
118
+ return true;
119
+ if (extra === 22)
120
+ return null;
121
+ throw new Error('cbor: unsupported simple value');
122
+ default:
123
+ throw new Error(`cbor: unsupported major type ${major}`);
124
+ }
125
+ };
126
+ export const decode = (bytes) => readValue({ bytes, at: 0 });
package/esm/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './authenticator';
2
+ export * from './cbor';
3
+ export * from './store';
4
+ export * from './types';
package/esm/store.js ADDED
@@ -0,0 +1,98 @@
1
+ import { assertPasskey, createPasskey } from './authenticator';
2
+ const FIELDS = {
3
+ rpId: 'rp_id',
4
+ credentialId: 'credential_id',
5
+ userHandle: 'user_handle',
6
+ userName: 'user_name',
7
+ signCount: 'sign_count',
8
+ privateKey: 'private_key',
9
+ };
10
+ export class PasskeyError extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = 'PasskeyError';
14
+ }
15
+ }
16
+ /**
17
+ * Passkeys kept as vault items: dcrypt is the authenticator, and the vault is
18
+ * its secure element. The private key is the only concealed field — a site
19
+ * name and a sign count are not secrets, and leaving them readable is what
20
+ * lets the list render without decrypting anything.
21
+ *
22
+ * A passkey is therefore covered by the master passphrase, by lock, and by
23
+ * backup/restore, and unlike a hardware key it can be restored onto a new
24
+ * machine from a backup.
25
+ */
26
+ export class PasskeyStore {
27
+ vault;
28
+ constructor(vault) {
29
+ this.vault = vault;
30
+ }
31
+ /**
32
+ * Mint a passkey for a site and return the registration the relying party
33
+ * verifies. The key is written to the vault before the response is handed
34
+ * back, so a site can never end up holding a public key whose private half
35
+ * was lost.
36
+ */
37
+ async register(request) {
38
+ const { passkey, response } = createPasskey(request);
39
+ const item = await this.vault.createItem('passkey', `${request.userName} @ ${request.rpId}`);
40
+ await this.write(item.id, passkey);
41
+ return { record: await this.read(item), response };
42
+ }
43
+ async list(rpId) {
44
+ const items = await this.vault.listItems({ kind: 'passkey' });
45
+ const records = await Promise.all(items.map((item) => this.read(item)));
46
+ return rpId ? records.filter((record) => record.rpId === rpId) : records;
47
+ }
48
+ /**
49
+ * Sign a site's challenge, and persist the advanced sign count before
50
+ * returning: a site that later sees the count fail to advance concludes the
51
+ * key was cloned, so losing the write is worse than losing the assertion.
52
+ */
53
+ async assert(itemId, request) {
54
+ const passkey = await this.reveal(itemId);
55
+ const assertion = assertPasskey(passkey, request);
56
+ await this.vault.setField(itemId, FIELDS.signCount, 'text', String(assertion.passkey.signCount), false);
57
+ return assertion.response;
58
+ }
59
+ /** Delete the key. The site keeps its credential; it will simply never match. */
60
+ async forget(itemId) {
61
+ await this.vault.deleteItemForever(itemId);
62
+ }
63
+ async write(itemId, passkey) {
64
+ await this.vault.setField(itemId, FIELDS.rpId, 'url', passkey.rpId, false);
65
+ await this.vault.setField(itemId, FIELDS.credentialId, 'text', passkey.credentialId, false);
66
+ await this.vault.setField(itemId, FIELDS.userHandle, 'text', passkey.userHandle, false);
67
+ await this.vault.setField(itemId, FIELDS.userName, 'username', passkey.userName, false);
68
+ await this.vault.setField(itemId, FIELDS.signCount, 'text', String(passkey.signCount), false);
69
+ await this.vault.setField(itemId, FIELDS.privateKey, 'private_key', passkey.privateKey);
70
+ }
71
+ /** The whole passkey, private key and all — only used to sign. */
72
+ async reveal(itemId) {
73
+ const item = await this.vault.getItem(itemId);
74
+ if (!item || item.kind !== 'passkey') {
75
+ throw new PasskeyError(`item ${itemId} is not a passkey`);
76
+ }
77
+ const record = await this.read(item);
78
+ return {
79
+ credentialId: record.credentialId,
80
+ rpId: record.rpId,
81
+ privateKey: await this.vault.revealField(itemId, FIELDS.privateKey),
82
+ userHandle: await this.vault.revealField(itemId, FIELDS.userHandle),
83
+ userName: record.userName,
84
+ signCount: record.signCount,
85
+ };
86
+ }
87
+ async read(item) {
88
+ const value = async (name) => this.vault.revealField(item.id, name);
89
+ return {
90
+ itemId: item.id,
91
+ rpId: await value(FIELDS.rpId),
92
+ credentialId: await value(FIELDS.credentialId),
93
+ userName: await value(FIELDS.userName),
94
+ signCount: Number(await value(FIELDS.signCount)),
95
+ createdAt: item.createdAt,
96
+ };
97
+ }
98
+ }
package/esm/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './authenticator';
2
+ export * from './cbor';
3
+ export * from './store';
4
+ export * from './types';
package/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./authenticator"), exports);
18
+ __exportStar(require("./cbor"), exports);
19
+ __exportStar(require("./store"), exports);
20
+ __exportStar(require("./types"), exports);
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@decryption/webauthn",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "A software WebAuthn authenticator: passkeys whose private keys live in the dcrypt vault",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/decryption",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/decryption"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/decryption/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "makage assets",
24
+ "clean": "makage clean",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "makage build",
27
+ "lint": "eslint . --fix",
28
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
29
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
30
+ },
31
+ "keywords": [
32
+ "webauthn",
33
+ "passkey",
34
+ "authenticator",
35
+ "fido2",
36
+ "vault",
37
+ "local-first"
38
+ ],
39
+ "dependencies": {
40
+ "@decryption/base": "0.4.0",
41
+ "@decryption/curves": "0.4.0",
42
+ "@decryption/hashes": "0.4.0",
43
+ "@decryption/vault": "0.4.1"
44
+ },
45
+ "devDependencies": {
46
+ "makage": "0.3.0"
47
+ },
48
+ "gitHead": "d29d5f2e516edf049a285b30f868360d3b996db0"
49
+ }
package/store.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { Vault } from '@decryption/vault';
2
+ import type { AssertionRequest, AssertionResponse, RegistrationRequest, RegistrationResponse } from './types';
3
+ /** A stored passkey, as the UI and CLI list it — no private key in sight. */
4
+ export interface PasskeyRecord {
5
+ itemId: string;
6
+ rpId: string;
7
+ credentialId: string;
8
+ userName: string;
9
+ signCount: number;
10
+ createdAt: string;
11
+ }
12
+ export declare class PasskeyError extends Error {
13
+ constructor(message: string);
14
+ }
15
+ /**
16
+ * Passkeys kept as vault items: dcrypt is the authenticator, and the vault is
17
+ * its secure element. The private key is the only concealed field — a site
18
+ * name and a sign count are not secrets, and leaving them readable is what
19
+ * lets the list render without decrypting anything.
20
+ *
21
+ * A passkey is therefore covered by the master passphrase, by lock, and by
22
+ * backup/restore, and unlike a hardware key it can be restored onto a new
23
+ * machine from a backup.
24
+ */
25
+ export declare class PasskeyStore {
26
+ private readonly vault;
27
+ constructor(vault: Vault);
28
+ /**
29
+ * Mint a passkey for a site and return the registration the relying party
30
+ * verifies. The key is written to the vault before the response is handed
31
+ * back, so a site can never end up holding a public key whose private half
32
+ * was lost.
33
+ */
34
+ register(request: RegistrationRequest): Promise<{
35
+ record: PasskeyRecord;
36
+ response: RegistrationResponse;
37
+ }>;
38
+ list(rpId?: string): Promise<PasskeyRecord[]>;
39
+ /**
40
+ * Sign a site's challenge, and persist the advanced sign count before
41
+ * returning: a site that later sees the count fail to advance concludes the
42
+ * key was cloned, so losing the write is worse than losing the assertion.
43
+ */
44
+ assert(itemId: string, request: AssertionRequest): Promise<AssertionResponse>;
45
+ /** Delete the key. The site keeps its credential; it will simply never match. */
46
+ forget(itemId: string): Promise<void>;
47
+ private write;
48
+ /** The whole passkey, private key and all — only used to sign. */
49
+ private reveal;
50
+ private read;
51
+ }
package/store.js ADDED
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PasskeyStore = exports.PasskeyError = void 0;
4
+ const authenticator_1 = require("./authenticator");
5
+ const FIELDS = {
6
+ rpId: 'rp_id',
7
+ credentialId: 'credential_id',
8
+ userHandle: 'user_handle',
9
+ userName: 'user_name',
10
+ signCount: 'sign_count',
11
+ privateKey: 'private_key',
12
+ };
13
+ class PasskeyError extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = 'PasskeyError';
17
+ }
18
+ }
19
+ exports.PasskeyError = PasskeyError;
20
+ /**
21
+ * Passkeys kept as vault items: dcrypt is the authenticator, and the vault is
22
+ * its secure element. The private key is the only concealed field — a site
23
+ * name and a sign count are not secrets, and leaving them readable is what
24
+ * lets the list render without decrypting anything.
25
+ *
26
+ * A passkey is therefore covered by the master passphrase, by lock, and by
27
+ * backup/restore, and unlike a hardware key it can be restored onto a new
28
+ * machine from a backup.
29
+ */
30
+ class PasskeyStore {
31
+ vault;
32
+ constructor(vault) {
33
+ this.vault = vault;
34
+ }
35
+ /**
36
+ * Mint a passkey for a site and return the registration the relying party
37
+ * verifies. The key is written to the vault before the response is handed
38
+ * back, so a site can never end up holding a public key whose private half
39
+ * was lost.
40
+ */
41
+ async register(request) {
42
+ const { passkey, response } = (0, authenticator_1.createPasskey)(request);
43
+ const item = await this.vault.createItem('passkey', `${request.userName} @ ${request.rpId}`);
44
+ await this.write(item.id, passkey);
45
+ return { record: await this.read(item), response };
46
+ }
47
+ async list(rpId) {
48
+ const items = await this.vault.listItems({ kind: 'passkey' });
49
+ const records = await Promise.all(items.map((item) => this.read(item)));
50
+ return rpId ? records.filter((record) => record.rpId === rpId) : records;
51
+ }
52
+ /**
53
+ * Sign a site's challenge, and persist the advanced sign count before
54
+ * returning: a site that later sees the count fail to advance concludes the
55
+ * key was cloned, so losing the write is worse than losing the assertion.
56
+ */
57
+ async assert(itemId, request) {
58
+ const passkey = await this.reveal(itemId);
59
+ const assertion = (0, authenticator_1.assertPasskey)(passkey, request);
60
+ await this.vault.setField(itemId, FIELDS.signCount, 'text', String(assertion.passkey.signCount), false);
61
+ return assertion.response;
62
+ }
63
+ /** Delete the key. The site keeps its credential; it will simply never match. */
64
+ async forget(itemId) {
65
+ await this.vault.deleteItemForever(itemId);
66
+ }
67
+ async write(itemId, passkey) {
68
+ await this.vault.setField(itemId, FIELDS.rpId, 'url', passkey.rpId, false);
69
+ await this.vault.setField(itemId, FIELDS.credentialId, 'text', passkey.credentialId, false);
70
+ await this.vault.setField(itemId, FIELDS.userHandle, 'text', passkey.userHandle, false);
71
+ await this.vault.setField(itemId, FIELDS.userName, 'username', passkey.userName, false);
72
+ await this.vault.setField(itemId, FIELDS.signCount, 'text', String(passkey.signCount), false);
73
+ await this.vault.setField(itemId, FIELDS.privateKey, 'private_key', passkey.privateKey);
74
+ }
75
+ /** The whole passkey, private key and all — only used to sign. */
76
+ async reveal(itemId) {
77
+ const item = await this.vault.getItem(itemId);
78
+ if (!item || item.kind !== 'passkey') {
79
+ throw new PasskeyError(`item ${itemId} is not a passkey`);
80
+ }
81
+ const record = await this.read(item);
82
+ return {
83
+ credentialId: record.credentialId,
84
+ rpId: record.rpId,
85
+ privateKey: await this.vault.revealField(itemId, FIELDS.privateKey),
86
+ userHandle: await this.vault.revealField(itemId, FIELDS.userHandle),
87
+ userName: record.userName,
88
+ signCount: record.signCount,
89
+ };
90
+ }
91
+ async read(item) {
92
+ const value = async (name) => this.vault.revealField(item.id, name);
93
+ return {
94
+ itemId: item.id,
95
+ rpId: await value(FIELDS.rpId),
96
+ credentialId: await value(FIELDS.credentialId),
97
+ userName: await value(FIELDS.userName),
98
+ signCount: Number(await value(FIELDS.signCount)),
99
+ createdAt: item.createdAt,
100
+ };
101
+ }
102
+ }
103
+ exports.PasskeyStore = PasskeyStore;
package/types.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ /** A passkey as dcrypt holds it: a P-256 key and what the site needs to find it. */
2
+ export interface Passkey {
3
+ /** base64url, as a relying party sends and receives it. */
4
+ credentialId: string;
5
+ /** The site the key belongs to — a passkey signs for nothing else. */
6
+ rpId: string;
7
+ /** base64url-encoded 32-byte P-256 scalar. Only this is a secret. */
8
+ privateKey: string;
9
+ /** The user handle the site knows, base64url. Enables usernameless sign-in. */
10
+ userHandle: string;
11
+ userName: string;
12
+ /** How many assertions this key has made; a site rejects a count going backwards. */
13
+ signCount: number;
14
+ }
15
+ /** What a site asks for when a passkey is created. */
16
+ export interface RegistrationRequest {
17
+ rpId: string;
18
+ origin: string;
19
+ /** base64url, from `webauthn_begin_registration`. */
20
+ challenge: string;
21
+ userName: string;
22
+ /** base64url; generated when absent. */
23
+ userHandle?: string;
24
+ }
25
+ /** What a site asks for when a passkey is used. */
26
+ export interface AssertionRequest {
27
+ origin: string;
28
+ /** base64url, from `webauthn_begin_sign_in`. */
29
+ challenge: string;
30
+ }
31
+ /**
32
+ * The shape `navigator.credentials.create()` resolves to, as a relying party
33
+ * such as `@simplewebauthn/server` expects to receive it over the wire.
34
+ */
35
+ export interface RegistrationResponse {
36
+ id: string;
37
+ rawId: string;
38
+ type: 'public-key';
39
+ clientExtensionResults: Record<string, never>;
40
+ authenticatorAttachment: 'platform';
41
+ response: {
42
+ clientDataJSON: string;
43
+ attestationObject: string;
44
+ transports: string[];
45
+ publicKey: string;
46
+ publicKeyAlgorithm: number;
47
+ authenticatorData: string;
48
+ };
49
+ }
50
+ /** The shape `navigator.credentials.get()` resolves to. */
51
+ export interface AssertionResponse {
52
+ id: string;
53
+ rawId: string;
54
+ type: 'public-key';
55
+ clientExtensionResults: Record<string, never>;
56
+ authenticatorAttachment: 'platform';
57
+ response: {
58
+ clientDataJSON: string;
59
+ authenticatorData: string;
60
+ signature: string;
61
+ userHandle: string;
62
+ };
63
+ }
64
+ /** A new passkey, plus the one-off response that registers it with the site. */
65
+ export interface Registration {
66
+ passkey: Passkey;
67
+ response: RegistrationResponse;
68
+ }
69
+ /** An assertion, and the passkey with its sign count moved on. */
70
+ export interface Assertion {
71
+ passkey: Passkey;
72
+ response: AssertionResponse;
73
+ }
package/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });