1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00
denoland-deno/js/permissions.ts
2019-03-09 12:30:38 -05:00

74 lines
2.3 KiB
TypeScript

// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import * as msg from "gen/msg_generated";
import * as flatbuffers from "./flatbuffers";
import * as dispatch from "./dispatch";
import { assert } from "./util";
/** Permissions as granted by the caller */
export interface Permissions {
read: boolean;
write: boolean;
net: boolean;
env: boolean;
run: boolean;
// NOTE: Keep in sync with src/permissions.rs
}
export type Permission = keyof Permissions;
function getReq(): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] {
const builder = flatbuffers.createBuilder();
msg.Permissions.startPermissions(builder);
const inner = msg.Permissions.endPermissions(builder);
return [builder, msg.Any.Permissions, inner];
}
function createPermissions(inner: msg.PermissionsRes): Permissions {
return {
read: inner.read(),
write: inner.write(),
net: inner.net(),
env: inner.env(),
run: inner.run()
};
}
/** Inspect granted permissions for the current program.
*
* if (Deno.permissions().read) {
* const file = await Deno.readFile("example.test");
* // ...
* }
*/
export function permissions(): Permissions {
const baseRes = dispatch.sendSync(...getReq())!;
assert(msg.Any.PermissionsRes === baseRes.innerType());
const res = new msg.PermissionsRes();
assert(baseRes.inner(res) != null);
// TypeScript cannot track assertion above, therefore not null assertion
return createPermissions(res);
}
function revokeReq(
permission: string
): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] {
const builder = flatbuffers.createBuilder();
const permission_ = builder.createString(permission);
msg.PermissionRevoke.startPermissionRevoke(builder);
msg.PermissionRevoke.addPermission(builder, permission_);
const inner = msg.PermissionRevoke.endPermissionRevoke(builder);
return [builder, msg.Any.PermissionRevoke, inner];
}
/** Revoke a permission. When the permission was already revoked nothing changes
*
* if (Deno.permissions().read) {
* const file = await Deno.readFile("example.test");
* Deno.revokePermission('read');
* }
* Deno.readFile("example.test"); // -> error or permission prompt
*/
export function revokePermission(permission: Permission): void {
dispatch.sendSync(...revokeReq(permission));
}