2021-12-01 16:24:29 +00:00
|
|
|
/// SPDX-License-Identifier: GPL-3.0-or-later
|
2022-01-26 13:38:38 +00:00
|
|
|
/// SPDX-FileCopyrightText: Copyright © 2016-2022 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
|
2021-12-01 15:27:06 +00:00
|
|
|
|
|
|
|
// Basically Macaroons [1] in a Dataspace context
|
|
|
|
//
|
|
|
|
// [1]: Birgisson, Arnar, Joe Gibbs Politz, Úlfar Erlingsson, Ankur
|
|
|
|
// Taly, Michael Vrable, and Mark Lentczner. “Macaroons: Cookies with
|
|
|
|
// Contextual Caveats for Decentralized Authorization in the Cloud.”
|
|
|
|
// In Network and Distributed System Security Symposium. San Diego,
|
|
|
|
// California: Internet Society, 2014.
|
|
|
|
|
2021-12-01 16:13:00 +00:00
|
|
|
import { mac } from './cryptography.js';
|
2021-12-01 15:27:06 +00:00
|
|
|
import { Bytes, decode, encode, is, neverEmbeddedType, Value } from '@preserves/core';
|
|
|
|
import * as S from '../gen/sturdy.js';
|
|
|
|
export * from '../gen/sturdy.js';
|
|
|
|
|
|
|
|
export type SturdyValue = Value<S._embedded>;
|
|
|
|
|
|
|
|
export const KEY_LENGTH = 16; // 128 bits
|
|
|
|
|
|
|
|
export function embeddedNotAllowed(): never {
|
|
|
|
throw new Error("Embedded Ref not permitted in SturdyRef");
|
|
|
|
}
|
|
|
|
|
|
|
|
export function sturdyEncode(v: SturdyValue): Bytes {
|
|
|
|
return encode<S._embedded>(v, {
|
|
|
|
canonical: true,
|
|
|
|
includeAnnotations: false,
|
|
|
|
embeddedEncode: neverEmbeddedType,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function sturdyDecode(bs: Bytes): SturdyValue {
|
|
|
|
return decode<S._embedded>(bs, {
|
|
|
|
includeAnnotations: false,
|
|
|
|
embeddedDecode: neverEmbeddedType,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function mint(oid: SturdyValue, secretKey: Bytes): Promise<S.SturdyRef> {
|
|
|
|
return S.SturdyRef({
|
|
|
|
oid,
|
|
|
|
caveatChain: [],
|
|
|
|
sig: await mac(secretKey, sturdyEncode(oid)),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function attenuate(r: S.SturdyRef, ... a: S.Attenuation): Promise<S.SturdyRef> {
|
|
|
|
return S.SturdyRef({
|
|
|
|
oid: r.oid,
|
|
|
|
caveatChain: [... r.caveatChain, a],
|
|
|
|
sig: await mac(r.sig, sturdyEncode(S.fromAttenuation(a)))
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function validate(r: S.SturdyRef, secretKey: Bytes): Promise<boolean> {
|
|
|
|
const sig = await r.caveatChain.reduce(
|
|
|
|
async (sig, a) => mac(await sig, sturdyEncode(S.fromAttenuation(a))),
|
|
|
|
mac(secretKey, sturdyEncode(r.oid)));
|
|
|
|
return is(sig, r.sig);
|
|
|
|
}
|