/
PubKey.mjs
213 lines (199 loc) · 8.52 KB
/
PubKey.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/**
* A model to handle events related to user authentication with public key.
* @namespace Fl32_Auth_Front_Mod_PubKey
*/
// MODULE'S VARS
const CRED_ALG = -7; // 'ES256' as registered in the IANA COSE Algorithms registry
const CRED_TRANS_INT = 'internal';
const CRED_TYPE = 'public-key';
const TIMEOUT = 360000; // 6 minutes
const TXT_ENCODER = new TextEncoder();
// MODULE'S CLASSES
export default class Fl32_Auth_Front_Mod_PubKey {
constructor(spec) {
// DEPS
/** @type {Fl32_Auth_Front_Defaults} */
const DEF = spec['Fl32_Auth_Front_Defaults$'];
/** @type {TeqFw_Core_Shared_Api_Logger} */
const logger = spec['TeqFw_Core_Shared_Api_Logger$$']; // instance
/** @type {Fl32_Auth_Front_Util_Codec.b64UrlToBin|function} */
const b64UrlToBin = spec['Fl32_Auth_Front_Util_Codec.b64UrlToBin'];
/** @type {Fl32_Auth_Front_Util_Codec.binToB64Url|function} */
const binToB64Url = spec['Fl32_Auth_Front_Util_Codec.binToB64Url'];
/** @type {TeqFw_Web_Api_Front_Web_Connect} */
const connApi = spec['TeqFw_Web_Api_Front_Web_Connect$'];
/** @type {Fl32_Auth_Shared_Dto_Attest} */
const dtoCred = spec['Fl32_Auth_Shared_Dto_Attest$'];
/** @type {Fl32_Auth_Shared_Web_Api_Attest} */
const apiAttest = spec['Fl32_Auth_Shared_Web_Api_Attest$'];
/** @type {Fl32_Auth_Shared_Web_Api_Assert_Challenge} */
const apiAssertChl = spec['Fl32_Auth_Shared_Web_Api_Assert_Challenge$'];
/** @type {Fl32_Auth_Shared_Web_Api_Assert_Validate} */
const apiAssertValid = spec['Fl32_Auth_Shared_Web_Api_Assert_Validate$'];
/** @type {Fl32_Auth_Front_Mod_Session} */
const modSess = spec['Fl32_Auth_Front_Mod_Session$'];
// MAIN
logger.setNamespace(this.constructor.name);
const STORE_KEY = `${DEF.SHARED.NAME}/attestation`;
// FUNCS
/**
* Read attestation ID from local storage.
* @return {string}
*/
function attestIdRead() {
const stored = window.localStorage.getItem(STORE_KEY);
if (stored) {
const json = JSON.parse(stored);
return json?.id ? json.id : null;
}
return null;
}
/**
* Write attestation ID to local storage.
* @param {string} id
*/
function attestIdWrite(id) {
window.localStorage.setItem(STORE_KEY, JSON.stringify({id}));
}
// INSTANCE METHODS
/**
* Get assertion challenge from backend.
* @return {Promise<Fl32_Auth_Shared_Web_Api_Assert_Challenge.Response>}
*/
this.assertChallenge = async function () {
try {
// parse input data
const req = apiAssertChl.createReq();
req.attestationId = attestIdRead();
// noinspection JSValidateTypes
return await connApi.send(req, apiAssertChl);
} catch (e) {
// timeout or error
logger.error(`Cannot create a new assertion challenge on the backend. Error: ${e?.message}`);
}
return null;
};
/**
* Validate the new attestation on the backend and save the user's public key if it is validated.
*
* @param {PublicKeyCredential} attestation
* @returns {Promise<Fl32_Auth_Shared_Web_Api_Attest.Response>}
*/
this.attest = async function ({attestation}) {
try {
// parse input data
// noinspection JSValidateTypes
/** @type {AuthenticatorAttestationResponse} */
const response = attestation.response;
const attestationObj = response.attestationObject;
const clientData = response.clientDataJSON;
// prepare API request
const cred = dtoCred.createDto();
cred.attestationId = attestation.id;
cred.attestationObj = binToB64Url(attestationObj);
cred.clientData = binToB64Url(clientData);
const req = apiAttest.createReq();
req.cred = cred;
// noinspection JSValidateTypes
/** @type {Fl32_Auth_Shared_Web_Api_Attest.Response} */
const res = await connApi.send(req, apiAttest);
if (res?.attestationId) attestIdWrite(res.attestationId);
if (res?.sessionData) modSess.setData(res?.sessionData);
return res;
} catch (e) {
// timeout or error
logger.error(`Cannot register attestation for a new user on the backend. Error: ${e?.message}`);
}
return null;
};
/**
* Compose `publicKey` options for CredentialsContainer.create() method.
* @param {string} challenge base64 url encoded binary (32 bytes)
* @param {string} rpName relying party name
* @param {string} userName
* @param {string} userUuid
* @returns {Object}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create (publicKey)
*/
this.composeOptPkCreate = function ({challenge, rpName, userName, userUuid}) {
const userIdBytes = TXT_ENCODER.encode(userUuid);
const user = {
id: userIdBytes,
name: userName,
displayName: userName,
};
const challengeBin = b64UrlToBin(challenge);
return {
// Relying Party:
rp: {
// id: RELYING_PARTY_ID, // origin for Relying Party - host.com
name: rpName,
},
// User:
user,
challenge: challengeBin, // The challenge is produced by the server
pubKeyCredParams: [ // This Relying Party will accept an ES256 credential
{
type: CRED_TYPE,
alg: CRED_ALG,
}
],
timeout: TIMEOUT,
excludeCredentials: [],
authenticatorSelection: {
authenticatorAttachment: 'platform',
// Try to use UV if possible. This is also the default.
userVerification: 'preferred'
},
};
};
/**
* Compose `publicKey` options for CredentialsContainer.create() method.
* @param {string} challenge base64 url encoded binary (32 bytes)
* @param {string} attestationId
* @returns {Object}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get
*/
this.composeOptPkGet = function ({challenge, attestationId}) {
const challengeBin = b64UrlToBin(challenge);
const rawId = b64UrlToBin(attestationId);
return {
challenge: challengeBin,
allowCredentials: [{
id: rawId,
type: CRED_TYPE,
transports: [CRED_TRANS_INT]
}],
};
};
/**
* @return {Promise<boolean>}
*/
this.isPublicKeyAvailable = async function () {
return await window?.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
};
/**
* Validate the user's assertion using the public key.
* @param {AuthenticatorAssertionResponse} assert
* @returns {Promise<Fl32_Auth_Shared_Web_Api_Assert_Validate.Response>}
*/
this.validate = async function (assert) {
try {
const req = apiAssertValid.createReq();
req.authenticatorData = binToB64Url(assert.authenticatorData);
req.clientData = binToB64Url(assert.clientDataJSON);
req.signature = binToB64Url(assert.signature);
// noinspection JSValidateTypes
/** @type {Fl32_Auth_Shared_Web_Api_Assert_Validate.Response} */
const res = await connApi.send(req, apiAssertValid);
// set session data to the session model
if (res?.success) modSess.setData(res?.sessionData);
return res;
} catch (e) {
// timeout or error
logger.error(`Cannot get validate public key assertion on backend. Error: ${e?.message}`);
}
return null;
};
}
}