/// SPDX-License-Identifier: GPL-3.0-or-later /// SPDX-FileCopyrightText: Copyright © 2016-2023 Tony Garnock-Jones // 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. import { mac } from './cryptography.js'; 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; 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(v, { canonical: true, includeAnnotations: false, embeddedEncode: neverEmbeddedType, }); } export function sturdyDecode(bs: Bytes): SturdyValue { return decode(bs, { includeAnnotations: false, embeddedDecode: neverEmbeddedType, }); } export async function mint(oid: SturdyValue, secretKey: Bytes): Promise { return S.SturdyRef({ oid, caveatChain: [], sig: await mac(secretKey, sturdyEncode(oid)), }); } async function chainMac(key: Bytes | Promise, caveats: S.Caveat[]): Promise { return caveats.reduce(async (key, c) => mac(await key, sturdyEncode(S.fromCaveat(c))), key); } export async function attenuate(r: S.SturdyRef, ... a: S.Caveat[]): Promise { return S.SturdyRef({ oid: r.oid, caveatChain: [... r.caveatChain, ... a], sig: await chainMac(r.sig, a), }); } export async function validate(r: S.SturdyRef, secretKey: Bytes): Promise { const sig = await chainMac(await mac(secretKey, sturdyEncode(r.oid)), r.caveatChain); return is(sig, r.sig); }