forked from cloudflare/privacypass-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriv_verif_token.ts
More file actions
304 lines (252 loc) · 9.02 KB
/
Copy pathpriv_verif_token.ts
File metadata and controls
304 lines (252 loc) · 9.02 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright (c) 2023 Cloudflare, Inc.
// Licensed under the Apache-2.0 license found in the LICENSE file or at https://opensource.org/licenses/Apache-2.0
import type { FinalizeData } from '@cloudflare/voprf-ts';
import {
Evaluation,
EvaluationRequest,
Oprf,
VOPRFClient,
VOPRFServer,
generateKeyPair,
type DLEQParams,
type Group,
type SuiteID,
type HashID,
DLEQProof,
} from '@cloudflare/voprf-ts';
import {
AuthenticatorInput,
Token,
TokenChallenge,
type TokenTypeEntry,
} from './auth_scheme/private_token.js';
import { joinAll } from './util.js';
export interface VOPRFExtraParams {
suite: SuiteID;
group: Group;
Ne: number;
Ns: number;
Nk: number;
hash: HashID;
dleqParams: DLEQParams;
}
const VOPRF_SUITE = Oprf.Suite.P384_SHA384;
const VOPRF_GROUP = Oprf.getGroup(VOPRF_SUITE);
const VOPRF_HASH = Oprf.getHash(VOPRF_SUITE);
const VOPRF_EXTRA_PARAMS: VOPRFExtraParams = {
suite: VOPRF_SUITE,
group: VOPRF_GROUP,
Ne: VOPRF_GROUP.eltSize(),
Ns: VOPRF_GROUP.scalarSize(),
Nk: Oprf.getOprfSize(VOPRF_SUITE),
hash: VOPRF_HASH,
dleqParams: {
group: VOPRF_GROUP.id,
hash: VOPRF_HASH,
dst: new Uint8Array(),
},
} as const;
// Token Type Entry Update:
// - Token Type VOPRF (P-384, SHA-384)
//
// https://datatracker.ietf.org/doc/html/draft-ietf-privacypass-protocol-16#name-token-type-voprf-p-384-sha-
export const VOPRF: Readonly<TokenTypeEntry> & VOPRFExtraParams = {
value: 0x0001,
name: 'VOPRF (P-384, SHA-384)',
Nid: 32,
publicVerifiable: false,
publicMetadata: false,
privateMetadata: false,
...VOPRF_EXTRA_PARAMS,
} as const;
export function keyGen(): Promise<{ privateKey: Uint8Array; publicKey: Uint8Array }> {
return generateKeyPair(VOPRF.suite);
}
async function getTokenKeyID(publicKey: Uint8Array): Promise<Uint8Array> {
return new Uint8Array(await crypto.subtle.digest('SHA-256', publicKey));
}
export class TokenRequest {
// struct {
// uint16_t token_type = 0x0001; /* Type VOPRF(P-384, SHA-384) */
// uint8_t truncated_token_key_id;
// uint8_t blinded_msg[Ne];
// } TokenRequest;
tokenType: number;
constructor(
public readonly truncatedTokenKeyId: number,
public readonly blindedMsg: Uint8Array,
) {
if (blindedMsg.length !== VOPRF.Ne) {
throw new Error('blinded message has invalide size');
}
this.tokenType = VOPRF.value;
}
static deserialize(bytes: Uint8Array): TokenRequest {
let offset = 0;
const input = new DataView(bytes.buffer);
const type = input.getUint16(offset);
offset += 2;
if (type !== VOPRF.value) {
throw new Error('mismatch of token type');
}
const truncatedTokenKeyId = input.getUint8(offset);
offset += 1;
const len = VOPRF.Ne;
const blindedMsg = new Uint8Array(input.buffer.slice(offset, offset + len));
offset += len;
return new TokenRequest(truncatedTokenKeyId, blindedMsg);
}
serialize(): Uint8Array {
const output = new Array<ArrayBuffer>();
let b = new ArrayBuffer(2);
new DataView(b).setUint16(0, this.tokenType);
output.push(b);
b = new ArrayBuffer(1);
new DataView(b).setUint8(0, this.truncatedTokenKeyId);
output.push(b);
b = this.blindedMsg.buffer;
output.push(b);
return new Uint8Array(joinAll(output));
}
}
export class TokenResponse {
// struct {
// uint8_t evaluate_msg[Ne];
// uint8_t evaluate_proof[Ns+Ns];
// } TokenResponse;
constructor(
public readonly evaluateMsg: Uint8Array,
public readonly evaluateProof: Uint8Array,
) {
if (evaluateMsg.length !== VOPRF.Ne) {
throw new Error('evaluate_msg has invalid size');
}
if (evaluateProof.length !== 2 * VOPRF.Ns) {
throw new Error('evaluate_proof has invalid size');
}
}
static deserialize(bytes: Uint8Array): TokenResponse {
let offset = 0;
let len = VOPRF.Ne;
const evaluateMsg = new Uint8Array(bytes.slice(offset, offset + len));
offset += len;
len = 2 * VOPRF.Ns;
const evaluateProof = new Uint8Array(bytes.slice(offset, offset + len));
return new TokenResponse(evaluateMsg, evaluateProof);
}
serialize(): Uint8Array {
return new Uint8Array(joinAll([this.evaluateMsg, this.evaluateProof]));
}
length(): number {
return this.evaluateMsg.length + this.evaluateProof.length;
}
}
export function verifyToken(token: Token, privateKeyIssuer: Uint8Array): Promise<boolean> {
const vServer = new VOPRFServer(VOPRF.suite, privateKeyIssuer);
const authInput = token.authInput.serialize();
return vServer.verifyFinalize(authInput, token.authenticator);
}
export class Issuer {
private vServer: VOPRFServer;
constructor(
public name: string,
private privateKey: Uint8Array,
public publicKey: Uint8Array,
) {
this.vServer = new VOPRFServer(VOPRF.suite, this.privateKey);
}
async issue(tokReq: TokenRequest): Promise<TokenResponse> {
const blindedElt = VOPRF.group.desElt(tokReq.blindedMsg);
const evalReq = new EvaluationRequest([blindedElt]);
const evaluation = await this.vServer.blindEvaluate(evalReq);
if (evaluation.evaluated.length !== 1) {
throw new Error('evaluation is of a non-single element');
}
const evaluateMsg = evaluation.evaluated[0].serialize();
if (typeof evaluation.proof === 'undefined') {
throw new Error('evaluation has no DLEQ proof');
}
const evaluateProof = evaluation.proof.serialize();
return new TokenResponse(evaluateMsg, evaluateProof);
}
tokenKeyID(): Promise<Uint8Array> {
return getTokenKeyID(this.publicKey);
}
verify(token: Token): Promise<boolean> {
const authInput = token.authInput.serialize();
return this.vServer.verifyFinalize(authInput, token.authenticator);
}
}
export class Client {
private finData?: {
vClient: VOPRFClient;
authInput: AuthenticatorInput;
finData: FinalizeData;
};
async createTokenRequest(
tokChl: TokenChallenge,
issuerPublicKey: Uint8Array,
): Promise<TokenRequest> {
const nonce = crypto.getRandomValues(new Uint8Array(32));
const challengeDigest = new Uint8Array(
await crypto.subtle.digest('SHA-256', tokChl.serialize()),
);
const tokenKeyId = await getTokenKeyID(issuerPublicKey);
const authInput = new AuthenticatorInput(
VOPRF,
VOPRF.value,
nonce,
challengeDigest,
tokenKeyId,
);
const tokenInput = authInput.serialize();
const vClient = new VOPRFClient(VOPRF.suite, issuerPublicKey);
const [finData, evalReq] = await vClient.blind([tokenInput]);
if (evalReq.blinded.length !== 1) {
throw new Error('created a non-single blinded element');
}
const blindedMsg = evalReq.blinded[0].serialize();
// "truncated_token_key_id" is the least significant byte of the
// token_key_id in network byte order (in other words, the
// last 8 bits of token_key_id).
const truncatedTokenKeyId = tokenKeyId[tokenKeyId.length - 1];
const tokenRequest = new TokenRequest(truncatedTokenKeyId, blindedMsg);
this.finData = { vClient, authInput, finData };
return tokenRequest;
}
deserializeTokenResponse(bytes: Uint8Array): TokenResponse {
return TokenResponse.deserialize(bytes);
}
async finalize(tokRes: TokenResponse): Promise<Token> {
if (!this.finData) {
throw new Error('no token request was created yet');
}
const proof = DLEQProof.deserialize(VOPRF_GROUP.id, tokRes.evaluateProof);
const evaluateMsg = VOPRF.group.desElt(tokRes.evaluateMsg);
const evaluation = new Evaluation(Oprf.Mode.VOPRF, [evaluateMsg], proof);
const [authenticator] = await this.finData.vClient.finalize(
this.finData.finData,
evaluation,
);
const token = new Token(VOPRF, this.finData.authInput, authenticator);
this.finData = undefined;
return token;
}
}
export class Origin {
private tokenType = VOPRF;
constructor(public readonly originInfo?: string[]) {}
async verify(token: Token, privateKeyIssuer: Uint8Array): Promise<boolean> {
const vServer = new VOPRFServer(VOPRF.suite, privateKeyIssuer);
const authInput = token.authInput.serialize();
return vServer.verifyFinalize(authInput, token.authenticator);
}
createTokenChallenge(issuerName: string, redemptionContext: Uint8Array): TokenChallenge {
return new TokenChallenge(
this.tokenType.value,
issuerName,
redemptionContext,
this.originInfo,
);
}
}