Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | import { CharSize } from 'keystore-idb/types'
import localforage from 'localforage'
import utils from 'keystore-idb/utils'
import * as common from './common'
import * as identifiers from './common/identifiers'
import * as keystore from './keystore'
import * as ucan from './ucan/internal'
import * as ucanPermissions from './ucan/permissions'
import { USERNAME_STORAGE_KEY, Maybe } from './common'
import { Permissions } from './ucan/permissions'
import { loadFileSystem } from './filesystem'
import FileSystem from './fs'
import fsClass from './fs'
// SCENARIO
export enum Scenario {
NotAuthorised = "NOT_AUTHORISED",
AuthSucceeded = "AUTH_SUCCEEDED",
AuthCancelled = "AUTH_CANCELLED",
Continuation = "CONTINUATION"
}
// STATE
export type State
= NotAuthorised
| AuthSucceeded
| AuthCancelled
| Continuation
export type NotAuthorised = {
scenario: Scenario.NotAuthorised
permissions: Maybe<Permissions>
authenticated: false
}
export type AuthSucceeded = {
scenario: Scenario.AuthSucceeded
permissions: Maybe<Permissions>
authenticated: true
newUser: boolean
throughLobby: true
username: string
fs?: FileSystem
}
export type AuthCancelled = {
scenario: Scenario.AuthCancelled
permissions: Maybe<Permissions>
authenticated: false
cancellationReason: string
throughLobby: true
}
export type Continuation = {
scenario: Scenario.Continuation
permissions: Maybe<Permissions>
authenticated: true
newUser: false,
throughLobby: false
username: string
fs?: FileSystem
}
// ERRORS
/**
* Initialisation error
*/
export enum InitialisationError {
InsecureContext = "INSECURE_CONTEXT",
UnsupportedBrowser = "UNSUPPORTED_BROWSER"
}
// INTIALISE
/**
* Check if we're authenticated, process any lobby query-parameters present in the URL,
* and initiate the user's file system if authenticated (can be disabled).
*
* See `loadFileSystem` if you want to load the user's file system yourself.
* NOTE: Only works on the main/ui thread, as it uses `window.location`.
*/
export async function initialise(
options: {
permissions?: Permissions
// Options
autoRemoveUrlParams?: boolean
loadFileSystem?: boolean
rootKey?: string
}
): Promise<State> {
options = options || {}
const permissions = options.permissions || null
const { autoRemoveUrlParams = true, rootKey } = options
const { app, fs } = permissions || {}
const maybeLoadFs = async (username: string): Promise<undefined | FileSystem> => {
return options.loadFileSystem === false
? undefined
: await loadFileSystem(permissions, username, rootKey)
}
// Check if browser is supported
if (globalThis.isSecureContext === false) throw InitialisationError.InsecureContext
if (await isSupported() === false) throw InitialisationError.UnsupportedBrowser
// URL things
const url = new URL(window.location.href)
const cancellation = url.searchParams.get("cancelled")
const ucans = url.searchParams.get("ucans")
// Add UCANs to the storage
await ucan.store(ucans ? ucans.split(",") : [])
// Determine scenario
if (ucans) {
const newUser = url.searchParams.get("newUser") === "t"
const username = url.searchParams.get("username") || ""
const classifiedParam = url.searchParams.get("classified")
await importClassifiedInfo(classifiedParam)
await localforage.setItem(USERNAME_STORAGE_KEY, username)
if (autoRemoveUrlParams) {
url.searchParams.delete("classified")
url.searchParams.delete("newUser")
url.searchParams.delete("ucans")
url.searchParams.delete("username")
history.replaceState(null, document.title, url.toString())
}
if (permissions && await validateSecrets(permissions) === false) {
return scenarioNotAuthorised(permissions)
}
if (permissions && ucan.validatePermissions(permissions, username) === false) {
return scenarioNotAuthorised(permissions)
}
return scenarioAuthSucceeded(
permissions,
newUser,
username,
await maybeLoadFs(username)
)
} else if (cancellation) {
const c = (_ => { switch (cancellation) {
case "DENIED": return "User denied authorisation"
default: return "Unknown reason"
}})()
return scenarioAuthCancelled(permissions, c)
}
const authedUsername = await common.authenticatedUsername()
return (
authedUsername &&
(permissions ? ucan.validatePermissions(permissions, authedUsername) : true)
)
? scenarioContinuation(permissions, authedUsername, await maybeLoadFs(authedUsername))
: scenarioNotAuthorised(permissions)
}
/**
* Alias for `initialise`.
*/
export { initialise as initialize }
// SUPPORTED
export async function isSupported(): Promise<boolean> {
return localforage.supports(localforage.INDEXEDDB)
// Firefox in private mode can't use indexedDB properly,
// so we test if we can actually make a database.
&& await (() => new Promise(resolve => {
const db = indexedDB.open("testDatabase")
db.onsuccess = () => resolve(true)
db.onerror = () => resolve(false)
}))() as boolean
}
// EXPORT
export * from './auth'
export * from './filesystem'
export const fs = fsClass
export * as apps from './apps'
export * as dataRoot from './data-root'
export * as did from './did'
export * as errors from './errors'
export * as lobby from './lobby'
export * as setup from './setup'
export * as ucan from './ucan'
export * as dns from './dns'
export * as ipfs from './ipfs'
export * as keystore from './keystore'
// ㊙️ ⚛ SCENARIOS
function scenarioAuthSucceeded(
permissions: Maybe<Permissions>,
newUser: boolean,
username: string,
fs: FileSystem | undefined
): AuthSucceeded {
return {
scenario: Scenario.AuthSucceeded,
permissions,
authenticated: true,
throughLobby: true,
fs,
newUser,
username
}
}
function scenarioAuthCancelled(
permissions: Maybe<Permissions>,
cancellationReason: string
): AuthCancelled {
return {
scenario: Scenario.AuthCancelled,
permissions,
authenticated: false,
throughLobby: true,
cancellationReason
}
}
function scenarioContinuation(
permissions: Maybe<Permissions>,
username: string,
fs: FileSystem | undefined
): Continuation {
return {
scenario: Scenario.Continuation,
permissions,
authenticated: true,
newUser: false,
throughLobby: false,
fs,
username
}
}
function scenarioNotAuthorised(
permissions: Maybe<Permissions>
): NotAuthorised {
return {
scenario: Scenario.NotAuthorised,
permissions,
authenticated: false
}
}
// ㊙️
async function importClassifiedInfo(
classifiedParam: Maybe<string>
): Promise<void> {
if (!classifiedParam) return
const ks = await keystore.get()
const classifiedInfo = JSON.parse(common.base64.urlDecode(classifiedParam))
// Extract session key and its iv
const iv = utils.base64ToArrBuf(classifiedInfo.iv)
const rawSessionKey = await ks.decrypt(classifiedInfo.sessionKey)
const sessionKey = await crypto.subtle.importKey(
"raw",
utils.base64ToArrBuf(rawSessionKey),
"AES-GCM",
false,
[ "encrypt", "decrypt" ]
)
// Decrypt secrets
const secrets: Record<string, { key: string, bareNameFilter: string }> =
JSON.parse(utils.arrBufToStr(await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
sessionKey,
utils.base64ToArrBuf(classifiedInfo.secrets)
), CharSize.B8))
// Import read keys and bare name filters
await Promise.all(
Object.entries(secrets).map(async ([ path, { bareNameFilter, key } ]) => {
const readKeyId = await identifiers.readKey({ path })
const bareNameFilterId = await identifiers.bareNameFilter({ path })
await ks.importSymmKey(key, readKeyId)
await localforage.setItem(bareNameFilterId, bareNameFilter)
})
)
}
async function validateSecrets(permissions: Permissions): Promise<boolean> {
const ks = await keystore.get()
return ucanPermissions.paths(permissions).reduce(
(acc, path) => acc.then(async bool => {
if (bool === false) return bool
if (path.startsWith('/public')) return true
const keyName = await identifiers.readKey({ path })
return await ks.keyExists(keyName)
}),
Promise.resolve(true)
)
}
|