-
Notifications
You must be signed in to change notification settings - Fork 12
/
token.ts
286 lines (246 loc) · 6.87 KB
/
token.ts
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
import * as uint8arrays from 'uint8arrays'
import * as base64 from "./base64"
import * as util from './util'
import * as did from './did'
import { verifySignature } from "./did/validation"
import { validAttenuation } from './attenuation'
import { Keypair, KeyType, Capability, Fact, Ucan, UcanHeader, UcanPayload } from "./types"
/**
* Create a UCAN, User Controlled Authorization Networks, JWT.
* This JWT can be used for authorization.
*
* ### Header
*
* `alg`, Algorithm, the type of signature.
* `typ`, Type, the type of this data structure, JWT.
* `ucv`, UCAN version.
*
* ### Payload
*
* `aud`, Audience, the ID of who it's intended for.
* `exp`, Expiry, unix timestamp of when the jwt is no longer valid.
* `fct`, Facts, an array of extra facts or information to attach to the jwt.
* `iss`, Issuer, the ID of who sent this.
* `nbf`, Not Before, unix timestamp of when the jwt becomes valid.
* `nnc`, Nonce, a randomly generated string, used to ensure the uniqueness of the jwt.
* `prf`, Proof, an optional nested token with equal or greater privileges.
* `att`, Attenuation, a list of resources and capabilities that the ucan grants.
*
*/
export async function build(params: {
// to/from
audience: string
issuer: Keypair
// capabilities
capabilities?: Array<Capability>
// time bounds
lifetimeInSeconds?: number // expiration overrides lifetimeInSeconds
expiration?: number
notBefore?: number
// proof / other info
facts?: Array<Fact>
proof?: string
addNonce?: boolean
// in the weeds
ucanVersion?: string
}): Promise<Ucan> {
const keypair = params.issuer
const didStr = did.publicKeyBytesToDid(keypair.publicKey, keypair.keyType)
const { header, payload } = buildParts({
...params,
issuer: didStr,
keyType: keypair.keyType
})
return sign(header, payload, keypair)
}
export function buildParts(params: {
// to/from
audience: string
issuer: string
keyType: KeyType
// capabilities
capabilities?: Array<Capability>
// time bounds
lifetimeInSeconds?: number // expiration overrides lifetimeInSeconds
expiration?: number
notBefore?: number
// proof / other info
facts?: Array<Fact>
proof?: string
addNonce?: boolean
// in the weeds
ucanVersion?: string
}): { header: UcanHeader, payload: UcanPayload } {
const {
audience,
issuer,
capabilities = [],
keyType,
lifetimeInSeconds = 30,
expiration,
notBefore,
facts,
proof = null,
addNonce = false,
ucanVersion = "0.7.0"
} = params
// Timestamps
const currentTimeInSeconds = Math.floor(Date.now() / 1000)
let exp = expiration || (currentTimeInSeconds + lifetimeInSeconds)
let nbf = notBefore || currentTimeInSeconds - 60
const header = {
alg: jwtAlgorithm(keyType),
typ: "JWT",
ucv: ucanVersion,
} as UcanHeader
const payload = {
aud: audience,
att: capabilities,
exp,
fct: facts,
iss: issuer,
nbf,
prf: proof,
} as UcanPayload
if (addNonce) {
payload.nnc = util.generateNonce()
}
return { header, payload }
}
/**
* Try to decode a UCAN.
* Will throw if it fails.
*
* @param ucan The encoded UCAN to decode
*/
export function decode(ucan: string): Ucan {
const split = ucan.split(".")
const header = JSON.parse(base64.urlDecode(split[0]))
const payload = JSON.parse(base64.urlDecode(split[1]))
return {
header,
payload,
signature: split[2] || null
}
}
/**
* Encode a UCAN.
*
* @param ucan The UCAN to encode
*/
export function encode(ucan: Ucan): string {
const encodedHeader = encodeHeader(ucan.header)
const encodedPayload = encodePayload(ucan.payload)
return encodedHeader + "." +
encodedPayload + "." +
ucan.signature
}
/**
* Encode the header of a UCAN.
*
* @param header The UcanHeader to encode
*/
export function encodeHeader(header: UcanHeader): string {
return base64.urlEncode(JSON.stringify(header))
}
/**
* Encode the payload of a UCAN.
*
* @param payload The UcanPayload to encode
*/
export function encodePayload(payload: UcanPayload): string {
return base64.urlEncode(JSON.stringify({
...payload
}))
}
/**
* Check if a UCAN is expired.
*
* @param ucan The UCAN to validate
*/
export function isExpired(ucan: Ucan): boolean {
return ucan.payload.exp <= Math.floor(Date.now() / 1000)
}
/**
* Check if a UCAN is not active yet.
*
* @param ucan The UCAN to validate
*/
export const isTooEarly = (ucan: Ucan): boolean => {
return ucan.payload.nbf > Math.floor(Date.now() / 1000)
}
/**
* Check if a UCAN is valid.
*
* @param ucan The decoded UCAN
* @param did The DID associated with the signature of the UCAN
*/
export async function isValid(ucan: Ucan): Promise<boolean> {
const encodedHeader = encodeHeader(ucan.header)
const encodedPayload = encodePayload(ucan.payload)
const data = uint8arrays.fromString(`${encodedHeader}.${encodedPayload}`)
const sig = uint8arrays.fromString(ucan.signature, 'base64urlpad')
const valid = await verifySignature(data, sig, ucan.payload.iss)
if (!valid) return false
if (!ucan.payload.prf) return true
// Verify proofs
const prf = decode(ucan.payload.prf)
if (prf.payload.aud !== ucan.payload.iss) return false
// Check attenuation
if(!validAttenuation(prf.payload.att, ucan.payload.att)) return false
return await isValid(prf)
}
/**
* Given a UCAN, lookup the root issuer.
*
* Throws when given an improperly formatted UCAN.
* This could be a nested UCAN (ie. proof).
*
* @param ucan A UCAN.
* @returns The root issuer.
*/
export function rootIssuer(ucan: string, level = 0): string {
const p = extractPayload(ucan, level)
if (p.prf) return rootIssuer(p.prf, level + 1)
return p.iss
}
/**
* Generate UCAN signature.
*/
export async function sign(header: UcanHeader, payload: UcanPayload, key: Keypair): Promise<Ucan> {
return addSignature(header, payload, (data) => key.sign(data))
}
export async function addSignature(header: UcanHeader, payload: UcanPayload, signFn: (data: Uint8Array) => Promise<Uint8Array>): Promise<Ucan> {
const encodedHeader = encodeHeader(header)
const encodedPayload = encodePayload(payload)
const toSign = uint8arrays.fromString(`${encodedHeader}.${encodedPayload}`)
const sig = await signFn(toSign)
return {
header,
payload,
signature: uint8arrays.toString(sig, 'base64urlpad')
}
}
// ㊙️
/**
* JWT algorithm to be used in a JWT header.
*/
function jwtAlgorithm(keyType: KeyType): string | null {
switch (keyType) {
case 'ed25519': return "EdDSA"
case 'rsa': return "RS256"
default: return null
}
}
/**
* Extract the payload of a UCAN.
*
* Throws when given an improperly formatted UCAN.
*/
function extractPayload(ucan: string, level: number): { iss: string; prf: string | null } {
try {
return JSON.parse(base64.urlDecode(ucan.split(".")[1]))
} catch (_) {
throw new Error(`Invalid UCAN (${level} level${level === 1 ? "" : "s"} deep): \`${ucan}\``)
}
}