dag-jose
Version:
Typescript implementation of the IPLD dag-jose format
88 lines • 2.53 kB
JavaScript
import * as signing from './signing.js';
import * as encryption from './encryption.js';
import * as cbor from '@ipld/dag-cbor';
export const name = 'dag-jose';
export const code = 133;
function isDagJWS(jose) {
return ('payload' in jose &&
typeof jose.payload === 'string' &&
'signatures' in jose &&
Array.isArray(jose.signatures));
}
function isEncodedJWS(jose) {
return ('payload' in jose &&
jose.payload instanceof Uint8Array &&
'signatures' in jose &&
Array.isArray(jose.signatures));
}
function isEncodedJWE(jose) {
return ('ciphertext' in jose &&
jose.ciphertext instanceof Uint8Array &&
'iv' in jose &&
jose.iv instanceof Uint8Array &&
'protected' in jose &&
jose.protected instanceof Uint8Array &&
'tag' in jose &&
jose.tag instanceof Uint8Array);
}
function isDagJWE(jose) {
return ('ciphertext' in jose &&
typeof jose.ciphertext === 'string' &&
'iv' in jose &&
typeof jose.iv === 'string' &&
'protected' in jose &&
typeof jose.protected === 'string' &&
'tag' in jose &&
typeof jose.tag === 'string');
}
export function toGeneral(jose) {
if (typeof jose === 'string') {
const split = jose.split('.');
if (split.length === 3) {
return signing.fromSplit(split);
}
else if (split.length === 5) {
return encryption.fromSplit(split);
}
throw new Error('Not a valid JOSE string');
}
if (isDagJWS(jose) || isDagJWE(jose)) {
return jose;
}
throw new Error('Not a valid unencoded JOSE object');
}
export function encode(obj) {
if (typeof obj === 'string') {
obj = toGeneral(obj);
}
let encodedJose;
if (isDagJWS(obj)) {
encodedJose = signing.encode(obj);
}
else if (isDagJWE(obj)) {
encodedJose = encryption.encode(obj);
}
else {
throw new Error('Not a valid JOSE object');
}
return new Uint8Array(cbor.encode(encodedJose));
}
export function decode(data) {
let encoded;
try {
encoded = cbor.decode(data);
}
catch (e) {
throw new Error('Not a valid DAG-JOSE object');
}
if (isEncodedJWS(encoded)) {
return signing.decode(encoded);
}
else if (isEncodedJWE(encoded)) {
return encryption.decode(encoded);
}
else {
throw new Error('Not a valid DAG-JOSE object');
}
}
//# sourceMappingURL=index.js.map