@ixo/action-protocol 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/README.md +190 -0
- package/package.json +3 -2
- package/src/index.d.ts +286 -4
- package/src/index.js +573 -24
- package/src/operation-schema.js +93 -8
- package/src/outcome-signature.js +217 -0
package/src/operation-schema.js
CHANGED
|
@@ -5,10 +5,18 @@ const string = (minLength = 1, maxLength = 200) => ({
|
|
|
5
5
|
});
|
|
6
6
|
const enumeration = (...values) => ({ enum: values });
|
|
7
7
|
const nullable = (schema) => ({ anyOf: [schema, { type: "null" }] });
|
|
8
|
+
const OPTIONAL = Symbol("optional");
|
|
9
|
+
// `optional(schema)` marks a property that may be absent (validated when present).
|
|
10
|
+
const optional = (schema) => ({ ...schema, [OPTIONAL]: true });
|
|
8
11
|
const object = (properties) => ({
|
|
9
12
|
type: "object",
|
|
10
|
-
properties
|
|
11
|
-
|
|
13
|
+
properties: Object.fromEntries(
|
|
14
|
+
Object.entries(properties).map(([key, schema]) => {
|
|
15
|
+
const { [OPTIONAL]: _optional, ...rest } = schema;
|
|
16
|
+
return [key, rest];
|
|
17
|
+
}),
|
|
18
|
+
),
|
|
19
|
+
required: Object.keys(properties).filter((key) => !properties[key][OPTIONAL]),
|
|
12
20
|
additionalProperties: false,
|
|
13
21
|
});
|
|
14
22
|
const fields = object({
|
|
@@ -37,6 +45,67 @@ const mailbox = {
|
|
|
37
45
|
pattern:
|
|
38
46
|
"^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$",
|
|
39
47
|
};
|
|
48
|
+
// 0.6.0 chain transactions (`ixo.chain.tx.v1`): the shapes only. The field
|
|
49
|
+
// parser (`chainTxIssue` in index.js) checks addresses, DIDs and byte lengths,
|
|
50
|
+
// and the Hub enforces signer, network and chain rules.
|
|
51
|
+
const baseUnits = { ...string(1, 78), pattern: "^[1-9][0-9]*$" };
|
|
52
|
+
// The chain's DID segments (x/iid): [A-Za-z0-9._-] or `%` + two hex digits.
|
|
53
|
+
const didTail =
|
|
54
|
+
"(?:(?:[A-Za-z0-9._-]|%[0-9A-Fa-f]{2})*:)*(?:[A-Za-z0-9._-]|%[0-9A-Fa-f]{2})+";
|
|
55
|
+
const ixoDid = { ...string(9, 200), pattern: `^did:ixo:${didTail}$` };
|
|
56
|
+
const anyDid = { ...string(7, 200), pattern: `^did:[a-z0-9]+:${didTail}$` };
|
|
57
|
+
// uint64, no leading zeros (the field parser also checks the uint64 maximum).
|
|
58
|
+
const collectionId = { ...string(1, 20), pattern: "^(0|[1-9][0-9]{0,19})$" };
|
|
59
|
+
// A 20-byte ixo account address (the Hub also checks the bech32 checksum).
|
|
60
|
+
const account = { ...string(42, 42), pattern: "^ixo1[023456789acdefghjklmnpqrstuvwxyz]{38}$" };
|
|
61
|
+
// Claim ids, impact token ids and verification proofs.
|
|
62
|
+
const chainText = (min, max) => ({
|
|
63
|
+
...string(min, max),
|
|
64
|
+
pattern: min > 0 ? "^[A-Za-z0-9:._/-]+$" : "^[A-Za-z0-9:._/-]*$",
|
|
65
|
+
});
|
|
66
|
+
const chainTxMessage = {
|
|
67
|
+
anyOf: [
|
|
68
|
+
object({
|
|
69
|
+
type: { const: "cosmos.bank.send" },
|
|
70
|
+
toAddress: account,
|
|
71
|
+
amountBaseUnits: baseUnits,
|
|
72
|
+
denom: optional({ ...string(3, 128), pattern: "^[a-zA-Z][a-zA-Z0-9/:._-]{2,127}$" }),
|
|
73
|
+
}),
|
|
74
|
+
object({
|
|
75
|
+
type: { const: "ixo.claims.submit" },
|
|
76
|
+
collectionId,
|
|
77
|
+
claimId: chainText(1, 256),
|
|
78
|
+
agentDid: ixoDid,
|
|
79
|
+
adminAddress: account,
|
|
80
|
+
useIntent: optional({ type: "boolean" }),
|
|
81
|
+
}),
|
|
82
|
+
object({
|
|
83
|
+
type: { const: "ixo.claims.evaluate" },
|
|
84
|
+
claimId: chainText(1, 256),
|
|
85
|
+
collectionId,
|
|
86
|
+
oracle: anyDid,
|
|
87
|
+
agentDid: ixoDid,
|
|
88
|
+
agentAddress: account,
|
|
89
|
+
adminAddress: account,
|
|
90
|
+
// EvaluationStatus 1 approved, 2 rejected, 3 disputed, 4 invalidated
|
|
91
|
+
// (0 pending and 5 flagged are refused).
|
|
92
|
+
status: enumeration(1, 2, 3, 4),
|
|
93
|
+
// uint32 code defined by the evaluator (the chain has no enum for it).
|
|
94
|
+
reason: optional({ type: "integer", minimum: 0, maximum: 4294967295 }),
|
|
95
|
+
verificationProof: optional(chainText(1, 300)),
|
|
96
|
+
}),
|
|
97
|
+
object({
|
|
98
|
+
type: { const: "ixo.token.transfer" },
|
|
99
|
+
recipient: account,
|
|
100
|
+
tokens: {
|
|
101
|
+
type: "array",
|
|
102
|
+
items: object({ id: chainText(1, 128), amount: baseUnits }),
|
|
103
|
+
minItems: 1,
|
|
104
|
+
maxItems: 32,
|
|
105
|
+
},
|
|
106
|
+
}),
|
|
107
|
+
],
|
|
108
|
+
};
|
|
40
109
|
const registry = {
|
|
41
110
|
"form.submit.v1": {
|
|
42
111
|
formId: string(1, 120),
|
|
@@ -50,8 +119,10 @@ const registry = {
|
|
|
50
119
|
fromAddress: string(),
|
|
51
120
|
toAddress: string(),
|
|
52
121
|
amountBaseUnits: { ...string(), pattern: "^[1-9][0-9]*$" },
|
|
53
|
-
|
|
54
|
-
|
|
122
|
+
// 0.5.0: any Cosmos denom (absent = uixo); the fee is Hub-simulated, so an
|
|
123
|
+
// oracle fee is optional and ignored.
|
|
124
|
+
denom: optional({ ...string(3, 128), pattern: "^[a-zA-Z][a-zA-Z0-9/:._-]{2,127}$" }),
|
|
125
|
+
feeBaseUnits: optional({ ...string(), pattern: "^(0|[1-9][0-9]*)$" }),
|
|
55
126
|
memo: string(0, 256),
|
|
56
127
|
},
|
|
57
128
|
"resource.read.v1": {
|
|
@@ -119,6 +190,13 @@ const registry = {
|
|
|
119
190
|
},
|
|
120
191
|
text: string(0, 8192),
|
|
121
192
|
},
|
|
193
|
+
"ixo.chain.tx.v1": {
|
|
194
|
+
chainId: string(1, 100),
|
|
195
|
+
network: enumeration("ixo mainnet", "ixo testnet", "ixo devnet"),
|
|
196
|
+
signer: account,
|
|
197
|
+
memo: string(0, 256),
|
|
198
|
+
messages: { type: "array", items: chainTxMessage, minItems: 1, maxItems: 8 },
|
|
199
|
+
},
|
|
122
200
|
};
|
|
123
201
|
export const operationKinds = Object.freeze(Object.keys(registry));
|
|
124
202
|
export const operationJsonSchema = Object.freeze({
|
|
@@ -133,6 +211,12 @@ function matches(value, schema) {
|
|
|
133
211
|
if (schema.enum) return schema.enum.includes(value);
|
|
134
212
|
if (schema.type === "null") return value === null;
|
|
135
213
|
if (schema.type === "boolean") return typeof value === "boolean";
|
|
214
|
+
if (schema.type === "integer")
|
|
215
|
+
return (
|
|
216
|
+
Number.isSafeInteger(value) &&
|
|
217
|
+
value >= (schema.minimum ?? Number.MIN_SAFE_INTEGER) &&
|
|
218
|
+
value <= (schema.maximum ?? Number.MAX_SAFE_INTEGER)
|
|
219
|
+
);
|
|
136
220
|
if (schema.type === "string")
|
|
137
221
|
return (
|
|
138
222
|
typeof value === "string" &&
|
|
@@ -153,11 +237,12 @@ function matches(value, schema) {
|
|
|
153
237
|
value !== null &&
|
|
154
238
|
typeof value === "object" &&
|
|
155
239
|
!Array.isArray(value) &&
|
|
156
|
-
Object.keys(value).every(
|
|
157
|
-
schema.required.every(
|
|
240
|
+
Object.keys(value).every(
|
|
158
241
|
(k) =>
|
|
159
|
-
Object.hasOwn(
|
|
160
|
-
|
|
242
|
+
Object.hasOwn(schema.properties, k) &&
|
|
243
|
+
matches(value[k], schema.properties[k]),
|
|
244
|
+
) &&
|
|
245
|
+
schema.required.every((k) => Object.hasOwn(value, k))
|
|
161
246
|
);
|
|
162
247
|
return false;
|
|
163
248
|
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// Signed outcome callbacks (0.3.0 / 0.5.0).
|
|
2
|
+
//
|
|
3
|
+
// The Hub signs every `ixo.auth-outcome/*` callback with its own service DID
|
|
4
|
+
// key (the Ed25519 key in https://<hub>/.well-known/did.json). Receivers verify
|
|
5
|
+
// with this SAME code: WebCrypto Ed25519 only, no dependencies.
|
|
6
|
+
//
|
|
7
|
+
// x-auth-hub-timestamp: unix seconds
|
|
8
|
+
// x-auth-hub-key-id: the Hub DID URL of the key, e.g. did:web:auth.ixo.earth#key-0
|
|
9
|
+
// x-auth-hub-signature: base64url(Ed25519(`${timestamp}.${audience}.${sha256hex(rawBody)}`))
|
|
10
|
+
//
|
|
11
|
+
// `audience` is the receiving oracle's https origin (the origin of the
|
|
12
|
+
// account's oracle URL), so a callback signed for one oracle cannot be replayed
|
|
13
|
+
// to another. It is not sent: the receiver supplies its own public origin from
|
|
14
|
+
// configuration as `expectedAudience`.
|
|
15
|
+
//
|
|
16
|
+
// Receivers must reject a timestamp more than OUTCOME_SIGNATURE_MAX_SKEW_SECONDS
|
|
17
|
+
// away from their clock, must resolve the key id against the Hub DID they were
|
|
18
|
+
// configured with (never a DID taken from the request), and must dedupe by the
|
|
19
|
+
// outcome's event id (a valid callback can be delivered again within the skew
|
|
20
|
+
// window, and the Hub retries until it gets the exact acknowledgement).
|
|
21
|
+
|
|
22
|
+
export const OUTCOME_SIGNATURE_HEADERS = Object.freeze({
|
|
23
|
+
timestamp: "x-auth-hub-timestamp",
|
|
24
|
+
keyId: "x-auth-hub-key-id",
|
|
25
|
+
signature: "x-auth-hub-signature",
|
|
26
|
+
});
|
|
27
|
+
export const OUTCOME_SIGNATURE_MAX_SKEW_SECONDS = 300;
|
|
28
|
+
|
|
29
|
+
const encoder = new TextEncoder();
|
|
30
|
+
const bytesOf = (body) =>
|
|
31
|
+
typeof body === "string" ? encoder.encode(body) : new Uint8Array(body);
|
|
32
|
+
|
|
33
|
+
async function sha256Hex(bytes) {
|
|
34
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
35
|
+
return Array.from(new Uint8Array(digest), (b) =>
|
|
36
|
+
b.toString(16).padStart(2, "0"),
|
|
37
|
+
).join("");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function toBase64Url(bytes) {
|
|
41
|
+
let binary = "";
|
|
42
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
43
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
44
|
+
}
|
|
45
|
+
function fromBase64Url(value) {
|
|
46
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value))
|
|
47
|
+
throw new TypeError("Invalid signature encoding");
|
|
48
|
+
const padded = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
49
|
+
const binary = atob(padded + "=".repeat((4 - (padded.length % 4)) % 4));
|
|
50
|
+
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** An https origin exactly as `new URL(x).origin` prints it (no path, no slash). */
|
|
54
|
+
export function outcomeAudience(value) {
|
|
55
|
+
let url;
|
|
56
|
+
try {
|
|
57
|
+
url = new URL(value);
|
|
58
|
+
} catch {
|
|
59
|
+
throw new TypeError("Invalid audience");
|
|
60
|
+
}
|
|
61
|
+
if (
|
|
62
|
+
url.protocol !== "https:" ||
|
|
63
|
+
url.origin !== value ||
|
|
64
|
+
url.username ||
|
|
65
|
+
url.password
|
|
66
|
+
)
|
|
67
|
+
throw new TypeError("Invalid audience");
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The exact bytes that are signed: `${timestamp}.${audience}.${sha256hex(rawBody)}`. */
|
|
72
|
+
export async function outcomeSigningPayload(timestamp, audience, rawBody) {
|
|
73
|
+
if (!Number.isSafeInteger(timestamp) || timestamp <= 0)
|
|
74
|
+
throw new TypeError("Invalid timestamp");
|
|
75
|
+
outcomeAudience(audience);
|
|
76
|
+
return encoder.encode(
|
|
77
|
+
`${timestamp}.${audience}.${await sha256Hex(bytesOf(rawBody))}`,
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Sign a raw callback body for one receiver. `privateKey` is a WebCrypto
|
|
83
|
+
* Ed25519 CryptoKey (usage "sign"); `audience` is the receiver's https origin.
|
|
84
|
+
* Returns the three headers to send with the body unchanged.
|
|
85
|
+
*/
|
|
86
|
+
export async function signOutcomeRequest({
|
|
87
|
+
privateKey,
|
|
88
|
+
keyId,
|
|
89
|
+
audience,
|
|
90
|
+
rawBody,
|
|
91
|
+
timestamp = Math.floor(Date.now() / 1000),
|
|
92
|
+
}) {
|
|
93
|
+
if (typeof keyId !== "string" || !keyId.includes("#"))
|
|
94
|
+
throw new TypeError("Invalid key id");
|
|
95
|
+
const signature = new Uint8Array(
|
|
96
|
+
await crypto.subtle.sign(
|
|
97
|
+
{ name: "Ed25519" },
|
|
98
|
+
privateKey,
|
|
99
|
+
await outcomeSigningPayload(timestamp, audience, rawBody),
|
|
100
|
+
),
|
|
101
|
+
);
|
|
102
|
+
return {
|
|
103
|
+
[OUTCOME_SIGNATURE_HEADERS.timestamp]: String(timestamp),
|
|
104
|
+
[OUTCOME_SIGNATURE_HEADERS.keyId]: keyId,
|
|
105
|
+
[OUTCOME_SIGNATURE_HEADERS.signature]: toBase64Url(signature),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Verify a received callback. `headers` is a Headers object or a plain object;
|
|
111
|
+
* `publicKey` is a raw 32-byte Ed25519 key (Uint8Array) or a CryptoKey;
|
|
112
|
+
* `expectedKeyId` is the Hub key id the receiver trusts; `expectedAudience`
|
|
113
|
+
* (required) is the receiver's own public https origin from configuration.
|
|
114
|
+
* Returns true only for a valid signature from that key, for that audience,
|
|
115
|
+
* within the skew window. Dedupe accepted callbacks by event id.
|
|
116
|
+
*/
|
|
117
|
+
export async function verifyOutcomeRequest({
|
|
118
|
+
rawBody,
|
|
119
|
+
headers,
|
|
120
|
+
publicKey,
|
|
121
|
+
expectedKeyId,
|
|
122
|
+
expectedAudience,
|
|
123
|
+
now = Math.floor(Date.now() / 1000),
|
|
124
|
+
maxSkewSeconds = OUTCOME_SIGNATURE_MAX_SKEW_SECONDS,
|
|
125
|
+
}) {
|
|
126
|
+
// A missing audience is a configuration error, not a failed signature.
|
|
127
|
+
outcomeAudience(expectedAudience);
|
|
128
|
+
const get = (name) =>
|
|
129
|
+
typeof headers?.get === "function" ? headers.get(name) : headers?.[name];
|
|
130
|
+
const timestampText = get(OUTCOME_SIGNATURE_HEADERS.timestamp);
|
|
131
|
+
const keyId = get(OUTCOME_SIGNATURE_HEADERS.keyId);
|
|
132
|
+
const signatureText = get(OUTCOME_SIGNATURE_HEADERS.signature);
|
|
133
|
+
if (
|
|
134
|
+
typeof timestampText !== "string" ||
|
|
135
|
+
!/^[1-9][0-9]{0,15}$/.test(timestampText) ||
|
|
136
|
+
typeof signatureText !== "string" ||
|
|
137
|
+
keyId !== expectedKeyId
|
|
138
|
+
)
|
|
139
|
+
return false;
|
|
140
|
+
const timestamp = Number(timestampText);
|
|
141
|
+
if (Math.abs(now - timestamp) > maxSkewSeconds) return false;
|
|
142
|
+
let signature;
|
|
143
|
+
try {
|
|
144
|
+
signature = fromBase64Url(signatureText);
|
|
145
|
+
} catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
if (signature.length !== 64) return false;
|
|
149
|
+
const key =
|
|
150
|
+
publicKey instanceof Uint8Array
|
|
151
|
+
? await crypto.subtle.importKey(
|
|
152
|
+
"raw",
|
|
153
|
+
publicKey,
|
|
154
|
+
{ name: "Ed25519" },
|
|
155
|
+
false,
|
|
156
|
+
["verify"],
|
|
157
|
+
)
|
|
158
|
+
: publicKey;
|
|
159
|
+
return crypto.subtle.verify(
|
|
160
|
+
{ name: "Ed25519" },
|
|
161
|
+
key,
|
|
162
|
+
signature,
|
|
163
|
+
await outcomeSigningPayload(timestamp, expectedAudience, rawBody),
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
168
|
+
function base58Decode(text) {
|
|
169
|
+
let value = 0n;
|
|
170
|
+
for (const char of text) {
|
|
171
|
+
const digit = BASE58.indexOf(char);
|
|
172
|
+
if (digit < 0) throw new TypeError("Invalid base58");
|
|
173
|
+
value = value * 58n + BigInt(digit);
|
|
174
|
+
}
|
|
175
|
+
const bytes = [];
|
|
176
|
+
while (value > 0n) {
|
|
177
|
+
bytes.unshift(Number(value & 0xffn));
|
|
178
|
+
value >>= 8n;
|
|
179
|
+
}
|
|
180
|
+
for (const char of text) {
|
|
181
|
+
if (char !== "1") break;
|
|
182
|
+
bytes.unshift(0);
|
|
183
|
+
}
|
|
184
|
+
return Uint8Array.from(bytes);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Raw Ed25519 public key from a `publicKeyMultibase` value
|
|
189
|
+
* (base58btc `z…` with the 0xed01 multicodec prefix, as in the Hub DID document).
|
|
190
|
+
*/
|
|
191
|
+
export function ed25519PublicKeyFromMultibase(multibase) {
|
|
192
|
+
if (typeof multibase !== "string" || !multibase.startsWith("z"))
|
|
193
|
+
throw new TypeError("Invalid publicKeyMultibase");
|
|
194
|
+
const bytes = base58Decode(multibase.slice(1));
|
|
195
|
+
if (bytes.length !== 34 || bytes[0] !== 0xed || bytes[1] !== 0x01)
|
|
196
|
+
throw new TypeError("Invalid publicKeyMultibase");
|
|
197
|
+
return bytes.slice(2);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The raw Ed25519 key for `keyId` in a did:web document (the Hub's
|
|
202
|
+
* /.well-known/did.json). The key id must belong to the document's DID.
|
|
203
|
+
*/
|
|
204
|
+
export function publicKeyFromDidDocument(document, keyId) {
|
|
205
|
+
if (
|
|
206
|
+
!document ||
|
|
207
|
+
typeof document.id !== "string" ||
|
|
208
|
+
typeof keyId !== "string" ||
|
|
209
|
+
!keyId.startsWith(`${document.id}#`) ||
|
|
210
|
+
!Array.isArray(document.verificationMethod)
|
|
211
|
+
)
|
|
212
|
+
throw new TypeError("Invalid DID document or key id");
|
|
213
|
+
const method = document.verificationMethod.find((m) => m?.id === keyId);
|
|
214
|
+
if (!method || typeof method.publicKeyMultibase !== "string")
|
|
215
|
+
throw new TypeError("Key not found in DID document");
|
|
216
|
+
return ed25519PublicKeyFromMultibase(method.publicKeyMultibase);
|
|
217
|
+
}
|