-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo-simple.js
More file actions
103 lines (89 loc) · 2.33 KB
/
Copy pathdemo-simple.js
File metadata and controls
103 lines (89 loc) · 2.33 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
import Hwtr from 'https://jsr.io/@hwt/hwtr-js/0.1.4/hwtr.js';
/*
from Deno:
import Hwtr from 'jsr:@hwt/hwtr-js'
or install and use in Node/bun with:
npx jsr add @hwt/hwtr-js
or copy and use locally:
import Hwtr from './hwtr.js';
deno run ./demo-basic.js
outputs token, public config and key files for .well-known, and private key file
*/
const KID = 'demo-example';
const ISS = 'https://example.com';
const LIFETIME = 60 * 60 * 24 * 30;
// generate a fresh Ed25519 key pair
const keyConfig = await Hwtr.generateKeys({
type: 'Ed25519',
current: KID,
});
const hwtr = await Hwtr.factory({
expiresInSeconds: LIFETIME,
maxTokenLifetimeSeconds: LIFETIME,
}, keyConfig);
// demo token
const token = await hwtr.create({
iss: ISS,
sub: 'demo:user',
authz: { scheme: 'RBAC/1.0.2', roles: ['user'] },
});
if (!token) {
throw new Error('token creation failed')
}
// export public key as SPKI base64url, then convert to JWK for the well-known endpoint
const publicKeys = await hwtr.getPublicKeys();
// { 'demo-example': '<base64url SPKI>' }
const spkiBase64 = publicKeys[KID];
const spkiBuffer = Hwtr.base64urlToUint8Array(spkiBase64);
const cryptoKey = await crypto.subtle.importKey(
'spki',
spkiBuffer,
{ name: 'Ed25519' },
true,
['verify'],
);
const jwk = await crypto.subtle.exportKey('jwk', cryptoKey);
const jwks = {
keys: [
{
kty: jwk.kty, // 'OKP'
kid: KID,
use: 'sig',
alg: 'EdDSA',
crv: jwk.crv, // 'Ed25519'
x: jwk.x, // base64url raw public key
},
],
}
// verify the token round-trips correctly before printing
const verifier = await Hwtr.factory({}, {
type: 'Ed25519',
keys: [],
publicKeys: { [KID]: spkiBase64 },
})
const check = await verifier.verify(token)
const hwtConfig = {
issuer: ISS,
hwt_version: '0.7',
authz_schemas: ['RBAC/1.0.2'],
};
console.log(`
demo-example...
`,
`
token ${ check.ok ? 'verified':`invalid ${ check.error }` }, expires: ${ new Date(check.expires * 1000).toISOString() }
`,
JSON.stringify({token}),
`
/.well-known/hwt-keys.json`, JSON.stringify(jwks, null, '\t'),
`
/.well-known/hwt.json`, JSON.stringify(hwtConfig, null, '\t'),
`
PRIVATE key config (store securely)`, JSON.stringify(keyConfig, null, '\t'),
`
NOTE can add keys into existing config array to continue using all.
`
);
if (!check.ok) {
console.warn(`verification failed`, check);
}