generated from fission-codes/project-template
-
Notifications
You must be signed in to change notification settings - Fork 24
/
token.ts
251 lines (217 loc) · 5.94 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
import * as Uint8arrays from "uint8arrays"
import * as Crypto from "../components/crypto/implementation.js"
import { Potency, Fact, Resource, Ucan, UcanHeader, UcanPayload } from "./types.js"
import { base64 } from "../common/index.js"
import { didToPublicKey } from "../did/transformers.js"
/**
* 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.
* `uav`, 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.
* `iss`, Issuer, the ID of who sent this.
* `nbf`, Not Before, unix timestamp of when the jwt becomes valid.
* `prf`, Proof, an optional nested token with equal or greater privileges.
* `ptc`, Potency, which rights come with the token.
* `rsc`, Resource, the involved resource.
*
*/
export async function build({
addSignature = true,
audience,
dependencies,
facts = [],
issuer,
lifetimeInSeconds = 30,
expiration,
potency = "APPEND",
proof,
resource
}: {
addSignature?: boolean
audience: string
dependencies: { crypto: Crypto.Implementation }
facts?: Array<Fact>
issuer: string
lifetimeInSeconds?: number
expiration?: number
potency?: Potency
proof?: string | Ucan
resource?: Resource
}): Promise<Ucan> {
const currentTimeInSeconds = Math.floor(Date.now() / 1000)
const decodedProof = proof
? (typeof proof === "string" ? decode(proof) : proof)
: null
// Header
const header = {
alg: await dependencies.crypto.keystore.getUcanAlgorithm(),
typ: "JWT",
uav: "1.0.0" // actually 0.3.1 but server isn't updated yet
}
// Timestamps
let exp = expiration || (currentTimeInSeconds + lifetimeInSeconds)
let nbf = currentTimeInSeconds - 60
if (decodedProof) {
const prf = decodedProof.payload
exp = Math.min(prf.exp, exp)
nbf = Math.max(prf.nbf, nbf)
}
// Payload
const payload = {
aud: audience,
exp: exp,
fct: facts,
iss: issuer,
nbf: nbf,
prf: proof ? (typeof proof === "string" ? proof : encode(proof)) : null,
ptc: potency,
rsc: resource ? resource : (decodedProof ? decodedProof.payload.rsc : "*"),
}
const signature = addSignature ? await sign(dependencies.crypto, header, payload) : null
return {
header,
payload,
signature
}
}
/**
* 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 self-signed.
*/
export function isSelfSigned(ucan: Ucan): boolean {
return ucan.payload.iss === ucan.payload.aud
}
/**
* 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(crypto: Crypto.Implementation, ucan: Ucan): Promise<boolean> {
try {
const encodedHeader = encodeHeader(ucan.header)
const encodedPayload = encodePayload(ucan.payload)
const { publicKey, type } = didToPublicKey(crypto, ucan.payload.iss)
const algo = crypto.did.keyTypes[ type ]
const a = await algo.verify({
publicKey,
message: Uint8arrays.fromString(`${encodedHeader}.${encodedPayload}`, "utf8"),
signature: Uint8arrays.fromString(ucan.signature || "", "base64url")
})
if (!a) return a
if (!ucan.payload.prf) return true
// Verify proofs
const prf = decode(ucan.payload.prf)
const b = prf.payload.aud === ucan.payload.iss
if (!b) return b
return await isValid(crypto, prf)
} catch {
return false
}
}
/**
* 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 | Ucan, level = 0): string {
const p = typeof ucan === "string" ? extractPayload(ucan, level) : ucan.payload
if (p.prf) return rootIssuer(p.prf, level + 1)
return p.iss
}
/**
* Generate UCAN signature.
*/
export async function sign(
crypto: Crypto.Implementation,
header: UcanHeader,
payload: UcanPayload
): Promise<string> {
const encodedHeader = encodeHeader(header)
const encodedPayload = encodePayload(payload)
return Uint8arrays.toString(
await crypto.keystore.sign(
Uint8arrays.fromString(`${encodedHeader}.${encodedPayload}`, "utf8")
),
"base64url"
)
}
// ㊙️
/**
* 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}\``)
}
}