@astrox/identity 0.0.24 → 0.0.30

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. package/lib/cjs/buffer.d.ts +10 -0
  2. package/lib/cjs/buffer.js +21 -0
  3. package/lib/cjs/buffer.js.map +1 -0
  4. package/lib/cjs/identity/delegation.d.ts +131 -0
  5. package/lib/cjs/identity/delegation.js +244 -0
  6. package/lib/cjs/identity/delegation.js.map +1 -0
  7. package/lib/cjs/identity/der.d.ts +35 -0
  8. package/lib/cjs/identity/der.js +178 -0
  9. package/lib/cjs/identity/der.js.map +1 -0
  10. package/lib/cjs/identity/ed25519.d.ts +45 -0
  11. package/lib/cjs/identity/ed25519.js +134 -0
  12. package/lib/cjs/identity/ed25519.js.map +1 -0
  13. package/lib/cjs/identity/secp256k1.d.ts +73 -0
  14. package/lib/cjs/identity/secp256k1.js +156 -0
  15. package/lib/cjs/identity/secp256k1.js.map +1 -0
  16. package/lib/cjs/identity/webauthn.d.ts +40 -0
  17. package/lib/cjs/identity/webauthn.js +205 -0
  18. package/lib/cjs/identity/webauthn.js.map +1 -0
  19. package/lib/cjs/index.d.ts +4 -0
  20. package/lib/cjs/index.js +18 -0
  21. package/lib/cjs/index.js.map +1 -0
  22. package/lib/esm/buffer.d.ts +10 -0
  23. package/lib/esm/buffer.js +16 -0
  24. package/lib/esm/buffer.js.map +1 -0
  25. package/lib/esm/identity/delegation.d.ts +131 -0
  26. package/lib/esm/identity/delegation.js +219 -0
  27. package/lib/esm/identity/delegation.js.map +1 -0
  28. package/lib/esm/identity/der.d.ts +35 -0
  29. package/lib/esm/identity/der.js +168 -0
  30. package/lib/esm/identity/der.js.map +1 -0
  31. package/lib/esm/identity/ed25519.d.ts +45 -0
  32. package/lib/esm/identity/ed25519.js +110 -0
  33. package/lib/esm/identity/ed25519.js.map +1 -0
  34. package/lib/esm/identity/secp256k1.d.ts +73 -0
  35. package/lib/esm/identity/secp256k1.js +148 -0
  36. package/lib/esm/identity/secp256k1.js.map +1 -0
  37. package/lib/esm/identity/webauthn.d.ts +40 -0
  38. package/lib/esm/identity/webauthn.js +178 -0
  39. package/lib/esm/identity/webauthn.js.map +1 -0
  40. package/lib/esm/index.d.ts +4 -0
  41. package/lib/esm/index.js +5 -0
  42. package/lib/esm/index.js.map +1 -0
  43. package/lib/tsconfig-cjs.tsbuildinfo +2451 -0
  44. package/lib/tsconfig.tsbuildinfo +2441 -0
  45. package/package.json +20 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webauthn.js","sourceRoot":"","sources":["../../../src/identity/webauthn.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAAwF;AACxF,gDAAwB;AACxB,qDAAuC;AACvC,sCAAuD;AACvD,+BAA8C;AAE9C,SAAS,qBAAqB,CAAC,IAAiB;IAC9C,OAAO,aAAO,CAAC,IAAI,EAAE,kBAAY,CAAC,CAAC,MAA6B,CAAC;AACnE,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,eAAe,CAAC,QAAqB;IAC5C,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,MAAM,UAAU,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC1C,CAAC,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3E,MAAM,kBAAkB,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAEjD,6BAA6B;IAC7B,OAAO,QAAQ,CAAC,KAAK,CAAC,EAAE,GAAG,kBAAkB,CAAC,CAAC;AACjD,CAAC;AAED,MAAa,aAAa;IAExB,YAA6B,KAAkB;QAAlB,UAAK,GAAL,KAAK,CAAa;QAC7C,IAAI,CAAC,WAAW,GAAG,qB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C;SACpD;IACH,CAAC;IAED;;OAEG;IACI,MAAM;QACX,OAAO;YACL,SAAS,EAAE,oBAAW,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;YACjD,KAAK,EAAE,oBAAW,CAAC,IAAI,CAAC,KAAK,CAAC;SAC/B,CAAC;IACJ,CAAC;CACF;AA9FD,4CA8FC"}
@@ -0,0 +1,4 @@
1
+ export { Ed25519KeyIdentity, Ed25519PublicKey } from './identity/ed25519';
2
+ export { Delegation, DelegationIdentity, DelegationChain, SignedDelegation, } from './identity/delegation';
3
+ export { WebAuthnIdentity } from './identity/webauthn';
4
+ export { wrapDER, unwrapDER, DER_COSE_OID, ED25519_OID } from './identity/der';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ED25519_OID = exports.DER_COSE_OID = exports.unwrapDER = exports.wrapDER = exports.WebAuthnIdentity = exports.DelegationChain = exports.DelegationIdentity = exports.Delegation = exports.Ed25519PublicKey = exports.Ed25519KeyIdentity = void 0;
4
+ var ed25519_1 = require("./identity/ed25519");
5
+ Object.defineProperty(exports, "Ed25519KeyIdentity", { enumerable: true, get: function () { return ed25519_1.Ed25519KeyIdentity; } });
6
+ Object.defineProperty(exports, "Ed25519PublicKey", { enumerable: true, get: function () { return ed25519_1.Ed25519PublicKey; } });
7
+ var delegation_1 = require("./identity/delegation");
8
+ Object.defineProperty(exports, "Delegation", { enumerable: true, get: function () { return delegation_1.Delegation; } });
9
+ Object.defineProperty(exports, "DelegationIdentity", { enumerable: true, get: function () { return delegation_1.DelegationIdentity; } });
10
+ Object.defineProperty(exports, "DelegationChain", { enumerable: true, get: function () { return delegation_1.DelegationChain; } });
11
+ var webauthn_1 = require("./identity/webauthn");
12
+ Object.defineProperty(exports, "WebAuthnIdentity", { enumerable: true, get: function () { return webauthn_1.WebAuthnIdentity; } });
13
+ var der_1 = require("./identity/der");
14
+ Object.defineProperty(exports, "wrapDER", { enumerable: true, get: function () { return der_1.wrapDER; } });
15
+ Object.defineProperty(exports, "unwrapDER", { enumerable: true, get: function () { return der_1.unwrapDER; } });
16
+ Object.defineProperty(exports, "DER_COSE_OID", { enumerable: true, get: function () { return der_1.DER_COSE_OID; } });
17
+ Object.defineProperty(exports, "ED25519_OID", { enumerable: true, get: function () { return der_1.ED25519_OID; } });
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,8CAA0E;AAAjE,6GAAA,kBAAkB,OAAA;AAAE,2GAAA,gBAAgB,OAAA;AAC7C,oDAK+B;AAJ7B,wGAAA,UAAU,OAAA;AACV,gHAAA,kBAAkB,OAAA;AAClB,6GAAA,eAAe,OAAA;AAGjB,gDAAuD;AAA9C,4GAAA,gBAAgB,OAAA;AACzB,sCAA+E;AAAtE,8FAAA,OAAO,OAAA;AAAE,gGAAA,SAAS,OAAA;AAAE,mGAAA,YAAY,OAAA;AAAE,kGAAA,WAAW,OAAA"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Return an array buffer from its hexadecimal representation.
3
+ * @param hexString The hexadecimal string.
4
+ */
5
+ export declare function fromHexString(hexString: string): ArrayBuffer;
6
+ /**
7
+ * Returns an hexadecimal representation of an array buffer.
8
+ * @param bytes The array buffer.
9
+ */
10
+ export declare function toHexString(bytes: ArrayBuffer): string;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Return an array buffer from its hexadecimal representation.
3
+ * @param hexString The hexadecimal string.
4
+ */
5
+ export function fromHexString(hexString) {
6
+ var _a;
7
+ return new Uint8Array(((_a = hexString.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : []).map(byte => parseInt(byte, 16))).buffer;
8
+ }
9
+ /**
10
+ * Returns an hexadecimal representation of an array buffer.
11
+ * @param bytes The array buffer.
12
+ */
13
+ export function toHexString(bytes) {
14
+ return new Uint8Array(bytes).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
15
+ }
16
+ //# sourceMappingURL=buffer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buffer.js","sourceRoot":"","sources":["../../src/buffer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,SAAiB;;IAC7C,OAAO,IAAI,UAAU,CAAC,CAAC,MAAA,SAAS,CAAC,KAAK,CAAC,SAAS,CAAC,mCAAI,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AACnG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,KAAkB;IAC5C,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;AACnG,CAAC"}
@@ -0,0 +1,131 @@
1
+ import { DerEncodedPublicKey, HttpAgentRequest, PublicKey, Signature, SignIdentity } from '@astrox/agent';
2
+ import { Principal } from '@astrox/principal';
3
+ import * as cbor from 'simple-cbor';
4
+ /**
5
+ * A single delegation object that is signed by a private key. This is constructed by
6
+ * `DelegationChain.create()`.
7
+ *
8
+ * {@see DelegationChain}
9
+ */
10
+ export declare class Delegation {
11
+ readonly pubkey: ArrayBuffer;
12
+ readonly expiration: bigint;
13
+ readonly targets?: Principal[] | undefined;
14
+ constructor(pubkey: ArrayBuffer, expiration: bigint, targets?: Principal[] | undefined);
15
+ toCBOR(): cbor.CborValue;
16
+ toJSON(): JsonnableDelegation;
17
+ }
18
+ /**
19
+ * Type of ReturnType<Delegation.toJSON>.
20
+ * The goal here is to stringify all non-JSON-compatible types to some bytes representation we can
21
+ * stringify as hex.
22
+ * (Hex shouldn't be ambiguous ever, because you can encode as DER with semantic OIDs).
23
+ */
24
+ interface JsonnableDelegation {
25
+ expiration: string;
26
+ pubkey: string;
27
+ targets?: string[];
28
+ }
29
+ /**
30
+ * A signed delegation, which lends its identity to the public key in the delegation
31
+ * object. This is constructed by `DelegationChain.create()`.
32
+ *
33
+ * {@see DelegationChain}
34
+ */
35
+ export interface SignedDelegation {
36
+ delegation: Delegation;
37
+ signature: Signature;
38
+ }
39
+ export interface JsonnableDelegationChain {
40
+ publicKey: string;
41
+ delegations: Array<{
42
+ signature: string;
43
+ delegation: {
44
+ pubkey: string;
45
+ expiration: string;
46
+ targets?: string[];
47
+ };
48
+ }>;
49
+ }
50
+ /**
51
+ * A chain of delegations. This is JSON Serializable.
52
+ * This is the object to serialize and pass to a DelegationIdentity. It does not keep any
53
+ * private keys.
54
+ */
55
+ export declare class DelegationChain {
56
+ readonly delegations: SignedDelegation[];
57
+ readonly publicKey: DerEncodedPublicKey;
58
+ /**
59
+ * Create a delegation chain between two (or more) keys. By default, the expiration time
60
+ * will be very short (15 minutes).
61
+ *
62
+ * To build a chain of more than 2 identities, this function needs to be called multiple times,
63
+ * passing the previous delegation chain into the options argument. For example:
64
+ *
65
+ * @example
66
+ * const rootKey = createKey();
67
+ * const middleKey = createKey();
68
+ * const bottomeKey = createKey();
69
+ *
70
+ * const rootToMiddle = await DelegationChain.create(
71
+ * root, middle.getPublicKey(), Date.parse('2100-01-01'),
72
+ * );
73
+ * const middleToBottom = await DelegationChain.create(
74
+ * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle },
75
+ * );
76
+ *
77
+ * // We can now use a delegation identity that uses the delegation above:
78
+ * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom);
79
+ *
80
+ * @param from The identity that will delegate.
81
+ * @param to The identity that gets delegated. It can now sign messages as if it was the
82
+ * identity above.
83
+ * @param expiration The length the delegation is valid. By default, 15 minutes from calling
84
+ * this function.
85
+ * @param options A set of options for this delegation. expiration and previous
86
+ * @param options.previous - Another DelegationChain that this chain should start with.
87
+ * @param options.targets - targets that scope the delegation (e.g. Canister Principals)
88
+ */
89
+ static create(from: SignIdentity, to: PublicKey, expiration?: Date, options?: {
90
+ previous?: DelegationChain;
91
+ targets?: Principal[];
92
+ }): Promise<DelegationChain>;
93
+ /**
94
+ * Creates a DelegationChain object from a JSON string.
95
+ *
96
+ * @param json The JSON string to parse.
97
+ */
98
+ static fromJSON(json: string | JsonnableDelegationChain): DelegationChain;
99
+ /**
100
+ * Creates a DelegationChain object from a list of delegations and a DER-encoded public key.
101
+ *
102
+ * @param delegations The list of delegations.
103
+ * @param publicKey The DER-encoded public key of the key-pair signing the first delegation.
104
+ */
105
+ static fromDelegations(delegations: SignedDelegation[], publicKey: DerEncodedPublicKey): DelegationChain;
106
+ protected constructor(delegations: SignedDelegation[], publicKey: DerEncodedPublicKey);
107
+ toJSON(): JsonnableDelegationChain;
108
+ }
109
+ /**
110
+ * An Identity that adds delegation to a request. Everywhere in this class, the name
111
+ * innerKey refers to the SignIdentity that is being used to sign the requests, while
112
+ * originalKey is the identity that is being borrowed. More identities can be used
113
+ * in the middle to delegate.
114
+ */
115
+ export declare class DelegationIdentity extends SignIdentity {
116
+ private _inner;
117
+ private _delegation;
118
+ /**
119
+ * Create a delegation without having access to delegateKey.
120
+ *
121
+ * @param key The key used to sign the reqyests.
122
+ * @param delegation A delegation object created using `createDelegation`.
123
+ */
124
+ static fromDelegation(key: Pick<SignIdentity, 'sign'>, delegation: DelegationChain): DelegationIdentity;
125
+ protected constructor(_inner: Pick<SignIdentity, 'sign'>, _delegation: DelegationChain);
126
+ getDelegation(): DelegationChain;
127
+ getPublicKey(): PublicKey;
128
+ sign(blob: ArrayBuffer): Promise<Signature>;
129
+ transformRequest(request: HttpAgentRequest): Promise<unknown>;
130
+ }
131
+ export {};
@@ -0,0 +1,219 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ import { requestIdOf, SignIdentity, } from '@astrox/agent';
13
+ import { Principal } from '@astrox/principal';
14
+ import * as cbor from 'simple-cbor';
15
+ import { fromHexString, toHexString } from '../buffer';
16
+ const domainSeparator = new TextEncoder().encode('\x1Aic-request-auth-delegation');
17
+ const requestDomainSeparator = new TextEncoder().encode('\x0Aic-request');
18
+ function _parseBlob(value) {
19
+ if (typeof value !== 'string' || value.length < 64) {
20
+ throw new Error('Invalid public key.');
21
+ }
22
+ return fromHexString(value);
23
+ }
24
+ /**
25
+ * A single delegation object that is signed by a private key. This is constructed by
26
+ * `DelegationChain.create()`.
27
+ *
28
+ * {@see DelegationChain}
29
+ */
30
+ export class Delegation {
31
+ constructor(pubkey, expiration, targets) {
32
+ this.pubkey = pubkey;
33
+ this.expiration = expiration;
34
+ this.targets = targets;
35
+ }
36
+ toCBOR() {
37
+ // Expiration field needs to be encoded as a u64 specifically.
38
+ return cbor.value.map(Object.assign({ pubkey: cbor.value.bytes(this.pubkey), expiration: cbor.value.u64(this.expiration.toString(16), 16) }, (this.targets && {
39
+ targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toUint8Array()))),
40
+ })));
41
+ }
42
+ toJSON() {
43
+ // every string should be hex and once-de-hexed,
44
+ // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER
45
+ // with an OID). After de-hex, if it's not obvious what it is, it's an ArrayBuffer.
46
+ return Object.assign({ expiration: this.expiration.toString(16), pubkey: toHexString(this.pubkey) }, (this.targets && { targets: this.targets.map(p => p.toHex()) }));
47
+ }
48
+ }
49
+ /**
50
+ * Sign a single delegation object for a period of time.
51
+ *
52
+ * @param from The identity that lends its delegation.
53
+ * @param to The identity that receives the delegation.
54
+ * @param expiration An expiration date for this delegation.
55
+ * @param targets Limit this delegation to the target principals.
56
+ */
57
+ async function _createSingleDelegation(from, to, expiration, targets) {
58
+ const delegation = new Delegation(to.toDer(), BigInt(+expiration) * BigInt(1000000), // In nanoseconds.
59
+ targets);
60
+ // The signature is calculated by signing the concatenation of the domain separator
61
+ // and the message.
62
+ // Note: To ensure Safari treats this as a user gesture, ensure to not use async methods
63
+ // besides the actualy webauthn functionality (such as `sign`). Safari will de-register
64
+ // a user gesture if you await an async call thats not fetch, xhr, or setTimeout.
65
+ const challenge = new Uint8Array([
66
+ ...domainSeparator,
67
+ ...new Uint8Array(requestIdOf(delegation)),
68
+ ]);
69
+ const signature = await from.sign(challenge);
70
+ return {
71
+ delegation,
72
+ signature,
73
+ };
74
+ }
75
+ /**
76
+ * A chain of delegations. This is JSON Serializable.
77
+ * This is the object to serialize and pass to a DelegationIdentity. It does not keep any
78
+ * private keys.
79
+ */
80
+ export class DelegationChain {
81
+ constructor(delegations, publicKey) {
82
+ this.delegations = delegations;
83
+ this.publicKey = publicKey;
84
+ }
85
+ /**
86
+ * Create a delegation chain between two (or more) keys. By default, the expiration time
87
+ * will be very short (15 minutes).
88
+ *
89
+ * To build a chain of more than 2 identities, this function needs to be called multiple times,
90
+ * passing the previous delegation chain into the options argument. For example:
91
+ *
92
+ * @example
93
+ * const rootKey = createKey();
94
+ * const middleKey = createKey();
95
+ * const bottomeKey = createKey();
96
+ *
97
+ * const rootToMiddle = await DelegationChain.create(
98
+ * root, middle.getPublicKey(), Date.parse('2100-01-01'),
99
+ * );
100
+ * const middleToBottom = await DelegationChain.create(
101
+ * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle },
102
+ * );
103
+ *
104
+ * // We can now use a delegation identity that uses the delegation above:
105
+ * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom);
106
+ *
107
+ * @param from The identity that will delegate.
108
+ * @param to The identity that gets delegated. It can now sign messages as if it was the
109
+ * identity above.
110
+ * @param expiration The length the delegation is valid. By default, 15 minutes from calling
111
+ * this function.
112
+ * @param options A set of options for this delegation. expiration and previous
113
+ * @param options.previous - Another DelegationChain that this chain should start with.
114
+ * @param options.targets - targets that scope the delegation (e.g. Canister Principals)
115
+ */
116
+ static async create(from, to, expiration = new Date(Date.now() + 15 * 60 * 1000), options = {}) {
117
+ var _a, _b;
118
+ const delegation = await _createSingleDelegation(from, to, expiration, options.targets);
119
+ return new DelegationChain([...(((_a = options.previous) === null || _a === void 0 ? void 0 : _a.delegations) || []), delegation], ((_b = options.previous) === null || _b === void 0 ? void 0 : _b.publicKey) || from.getPublicKey().toDer());
120
+ }
121
+ /**
122
+ * Creates a DelegationChain object from a JSON string.
123
+ *
124
+ * @param json The JSON string to parse.
125
+ */
126
+ static fromJSON(json) {
127
+ const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;
128
+ if (!Array.isArray(delegations)) {
129
+ throw new Error('Invalid delegations.');
130
+ }
131
+ const parsedDelegations = delegations.map(signedDelegation => {
132
+ const { delegation, signature } = signedDelegation;
133
+ const { pubkey, expiration, targets } = delegation;
134
+ if (targets !== undefined && !Array.isArray(targets)) {
135
+ throw new Error('Invalid targets.');
136
+ }
137
+ return {
138
+ delegation: new Delegation(_parseBlob(pubkey), BigInt(`0x${expiration}`), // expiration in JSON is an hexa string (See toJSON() below).
139
+ targets &&
140
+ targets.map((t) => {
141
+ if (typeof t !== 'string') {
142
+ throw new Error('Invalid target.');
143
+ }
144
+ return Principal.fromHex(t);
145
+ })),
146
+ signature: _parseBlob(signature),
147
+ };
148
+ });
149
+ return new this(parsedDelegations, _parseBlob(publicKey));
150
+ }
151
+ /**
152
+ * Creates a DelegationChain object from a list of delegations and a DER-encoded public key.
153
+ *
154
+ * @param delegations The list of delegations.
155
+ * @param publicKey The DER-encoded public key of the key-pair signing the first delegation.
156
+ */
157
+ static fromDelegations(delegations, publicKey) {
158
+ return new this(delegations, publicKey);
159
+ }
160
+ toJSON() {
161
+ return {
162
+ delegations: this.delegations.map(signedDelegation => {
163
+ const { delegation, signature } = signedDelegation;
164
+ const { targets } = delegation;
165
+ return {
166
+ delegation: Object.assign({ expiration: delegation.expiration.toString(16), pubkey: toHexString(delegation.pubkey) }, (targets && {
167
+ targets: targets.map(t => t.toHex()),
168
+ })),
169
+ signature: toHexString(signature),
170
+ };
171
+ }),
172
+ publicKey: toHexString(this.publicKey),
173
+ };
174
+ }
175
+ }
176
+ /**
177
+ * An Identity that adds delegation to a request. Everywhere in this class, the name
178
+ * innerKey refers to the SignIdentity that is being used to sign the requests, while
179
+ * originalKey is the identity that is being borrowed. More identities can be used
180
+ * in the middle to delegate.
181
+ */
182
+ export class DelegationIdentity extends SignIdentity {
183
+ constructor(_inner, _delegation) {
184
+ super();
185
+ this._inner = _inner;
186
+ this._delegation = _delegation;
187
+ }
188
+ /**
189
+ * Create a delegation without having access to delegateKey.
190
+ *
191
+ * @param key The key used to sign the reqyests.
192
+ * @param delegation A delegation object created using `createDelegation`.
193
+ */
194
+ static fromDelegation(key, delegation) {
195
+ return new this(key, delegation);
196
+ }
197
+ getDelegation() {
198
+ return this._delegation;
199
+ }
200
+ getPublicKey() {
201
+ return {
202
+ toDer: () => this._delegation.publicKey,
203
+ };
204
+ }
205
+ sign(blob) {
206
+ return this._inner.sign(blob);
207
+ }
208
+ async transformRequest(request) {
209
+ const { body } = request, fields = __rest(request, ["body"]);
210
+ const requestId = await requestIdOf(body);
211
+ return Object.assign(Object.assign({}, fields), { body: {
212
+ content: body,
213
+ sender_sig: await this.sign(new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)])),
214
+ sender_delegation: this._delegation.delegations,
215
+ sender_pubkey: this._delegation.publicKey,
216
+ } });
217
+ }
218
+ }
219
+ //# sourceMappingURL=delegation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation.js","sourceRoot":"","s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BAC/C,aAAa,EAAE,IAAI,CAAC,WAAW,CAAC,SAAS;aAC1C,IACD;IACJ,CAAC;CACF"}
@@ -0,0 +1,35 @@
1
+ export declare const bufEquals: (b1: ArrayBuffer, b2: ArrayBuffer) => boolean;
2
+ export declare const encodeLenBytes: (len: number) => number;
3
+ export declare const encodeLen: (buf: Uint8Array, offset: number, len: number) => number;
4
+ export declare const decodeLenBytes: (buf: Uint8Array, offset: number) => number;
5
+ export declare const decodeLen: (buf: Uint8Array, offset: number) => number;
6
+ /**
7
+ * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE
8
+ */
9
+ export declare const DER_COSE_OID: Uint8Array;
10
+ /**
11
+ * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm
12
+ */
13
+ export declare const ED25519_OID: Uint8Array;
14
+ /**
15
+ * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm
16
+ */
17
+ export declare const SECP256K1_OID: Uint8Array;
18
+ /**
19
+ * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:
20
+ * `SEQUENCE(oid, BITSTRING(payload))`
21
+ *
22
+ * @param payload The payload to encode as the bit string
23
+ * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with
24
+ */
25
+ export declare function wrapDER(payload: ArrayBuffer, oid: Uint8Array): Uint8Array;
26
+ /**
27
+ * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.
28
+ *
29
+ * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`
30
+ *
31
+ * @param derEncoded The DER encoded and tagged data
32
+ * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID
33
+ * @returns The unwrapped payload
34
+ */
35
+ export declare const unwrapDER: (derEncoded: ArrayBuffer, oid: Uint8Array) => Uint8Array;
@@ -0,0 +1,168 @@
1
+ export const bufEquals = (b1, b2) => {
2
+ if (b1.byteLength !== b2.byteLength)
3
+ return false;
4
+ const u1 = new Uint8Array(b1);
5
+ const u2 = new Uint8Array(b2);
6
+ for (let i = 0; i < u1.length; i++) {
7
+ if (u1[i] !== u2[i])
8
+ return false;
9
+ }
10
+ return true;
11
+ };
12
+ export const encodeLenBytes = (len) => {
13
+ if (len <= 0x7f) {
14
+ return 1;
15
+ }
16
+ else if (len <= 0xff) {
17
+ return 2;
18
+ }
19
+ else if (len <= 0xffff) {
20
+ return 3;
21
+ }
22
+ else if (len <= 0xffffff) {
23
+ return 4;
24
+ }
25
+ else {
26
+ throw new Error('Length too long (> 4 bytes)');
27
+ }
28
+ };
29
+ export const encodeLen = (buf, offset, len) => {
30
+ if (len <= 0x7f) {
31
+ buf[offset] = len;
32
+ return 1;
33
+ }
34
+ else if (len <= 0xff) {
35
+ buf[offset] = 0x81;
36
+ buf[offset + 1] = len;
37
+ return 2;
38
+ }
39
+ else if (len <= 0xffff) {
40
+ buf[offset] = 0x82;
41
+ buf[offset + 1] = len >> 8;
42
+ buf[offset + 2] = len;
43
+ return 3;
44
+ }
45
+ else if (len <= 0xffffff) {
46
+ buf[offset] = 0x83;
47
+ buf[offset + 1] = len >> 16;
48
+ buf[offset + 2] = len >> 8;
49
+ buf[offset + 3] = len;
50
+ return 4;
51
+ }
52
+ else {
53
+ throw new Error('Length too long (> 4 bytes)');
54
+ }
55
+ };
56
+ export const decodeLenBytes = (buf, offset) => {
57
+ if (buf[offset] < 0x80)
58
+ return 1;
59
+ if (buf[offset] === 0x80)
60
+ throw new Error('Invalid length 0');
61
+ if (buf[offset] === 0x81)
62
+ return 2;
63
+ if (buf[offset] === 0x82)
64
+ return 3;
65
+ if (buf[offset] === 0x83)
66
+ return 4;
67
+ throw new Error('Length too long (> 4 bytes)');
68
+ };
69
+ export const decodeLen = (buf, offset) => {
70
+ const lenBytes = decodeLenBytes(buf, offset);
71
+ if (lenBytes === 1)
72
+ return buf[offset];
73
+ else if (lenBytes === 2)
74
+ return buf[offset + 1];
75
+ else if (lenBytes === 3)
76
+ return (buf[offset + 1] << 8) + buf[offset + 2];
77
+ else if (lenBytes === 4)
78
+ return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];
79
+ throw new Error('Length too long (> 4 bytes)');
80
+ };
81
+ /**
82
+ * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE
83
+ */
84
+ export const DER_COSE_OID = Uint8Array.from([
85
+ ...[0x30, 0x0c],
86
+ ...[0x06, 0x0a],
87
+ ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE
88
+ ]);
89
+ /**
90
+ * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm
91
+ */
92
+ export const ED25519_OID = Uint8Array.from([
93
+ ...[0x30, 0x05],
94
+ ...[0x06, 0x03],
95
+ ...[0x2b, 0x65, 0x70], // id-Ed25519 OID
96
+ ]);
97
+ /**
98
+ * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm
99
+ */
100
+ export const SECP256K1_OID = Uint8Array.from([
101
+ ...[0x30, 0x10],
102
+ ...[0x06, 0x07],
103
+ ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01],
104
+ ...[0x06, 0x05],
105
+ ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1
106
+ ]);
107
+ /**
108
+ * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:
109
+ * `SEQUENCE(oid, BITSTRING(payload))`
110
+ *
111
+ * @param payload The payload to encode as the bit string
112
+ * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with
113
+ */
114
+ export function wrapDER(payload, oid) {
115
+ // The Bit String header needs to include the unused bit count byte in its length
116
+ const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);
117
+ const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;
118
+ let offset = 0;
119
+ const buf = new Uint8Array(1 + encodeLenBytes(len) + len);
120
+ // Sequence
121
+ buf[offset++] = 0x30;
122
+ // Sequence Length
123
+ offset += encodeLen(buf, offset, len);
124
+ // OID
125
+ buf.set(oid, offset);
126
+ offset += oid.byteLength;
127
+ // Bit String Header
128
+ buf[offset++] = 0x03;
129
+ offset += encodeLen(buf, offset, payload.byteLength + 1);
130
+ // 0 padding
131
+ buf[offset++] = 0x00;
132
+ buf.set(new Uint8Array(payload), offset);
133
+ return buf;
134
+ }
135
+ /**
136
+ * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.
137
+ *
138
+ * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`
139
+ *
140
+ * @param derEncoded The DER encoded and tagged data
141
+ * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID
142
+ * @returns The unwrapped payload
143
+ */
144
+ export const unwrapDER = (derEncoded, oid) => {
145
+ let offset = 0;
146
+ const expect = (n, msg) => {
147
+ if (buf[offset++] !== n) {
148
+ throw new Error('Expected: ' + msg);
149
+ }
150
+ };
151
+ const buf = new Uint8Array(derEncoded);
152
+ expect(0x30, 'sequence');
153
+ offset += decodeLenBytes(buf, offset);
154
+ if (!bufEquals(buf.slice(offset, offset + oid.byteLength), oid)) {
155
+ throw new Error('Not the expected OID.');
156
+ }
157
+ offset += oid.byteLength;
158
+ expect(0x03, 'bit string');
159
+ const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding
160
+ offset += decodeLenBytes(buf, offset);
161
+ expect(0x00, '0 padding');
162
+ const result = buf.slice(offset);
163
+ if (payloadLen !== result.length) {
164
+ throw new Error(`DER payload mismatch: Expected length ${payloadLen} actual length ${result.length}`);
165
+ }
166
+ return result;
167
+ };
168
+ //# sourceMappingURL=der.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"der.js","sourceRoot":"","sources":["../../../src/identity/der.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,EAAe,EAAE,EAAe,EAAW,EAAE;IACrE,IAAI,EAAE,CAAC,UAAU,KAAK,EAAE,CAAC,UAAU;QAAE,OAAO,KAAK,CAAC;IAClD,MA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