@ixo/action-protocol 0.0.0-stage → 0.5.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.
@@ -0,0 +1,181 @@
1
+ const string = (minLength = 1, maxLength = 200) => ({
2
+ type: "string",
3
+ minLength,
4
+ maxLength,
5
+ });
6
+ const enumeration = (...values) => ({ enum: values });
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 });
11
+ const object = (properties) => ({
12
+ type: "object",
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]),
20
+ additionalProperties: false,
21
+ });
22
+ const fields = object({
23
+ id: { ...string(1, 40), pattern: "^[a-z][a-z0-9_]{0,39}$" },
24
+ label: string(1, 120),
25
+ type: enumeration("text", "email", "tel", "textarea"),
26
+ required: { type: "boolean" },
27
+ value: string(0, 1000),
28
+ source: enumeration("user", "record", "suggestion"),
29
+ });
30
+ const scopes = {
31
+ type: "array",
32
+ items: string(1, 300),
33
+ maxItems: 30,
34
+ uniqueItems: true,
35
+ };
36
+ const instant = {
37
+ ...string(20, 40),
38
+ pattern:
39
+ "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?(?:Z|[+-]\\d{2}:\\d{2})$",
40
+ };
41
+ const hex = { ...string(64, 64), pattern: "^[a-f0-9]{64}$" };
42
+ // One ASCII mailbox only; no display names, address lists or header characters.
43
+ const mailbox = {
44
+ ...string(3, 254),
45
+ pattern:
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])?$",
47
+ };
48
+ const registry = {
49
+ "form.submit.v1": {
50
+ formId: string(1, 120),
51
+ destination: string(1, 200),
52
+ fields: { type: "array", items: fields, minItems: 1, maxItems: 20 },
53
+ declaration: nullable(string(1, 120)),
54
+ },
55
+ "ixo.bank.send.v1": {
56
+ chainId: string(1, 100),
57
+ network: enumeration("ixo mainnet", "ixo testnet", "ixo devnet"),
58
+ fromAddress: string(),
59
+ toAddress: string(),
60
+ amountBaseUnits: { ...string(), pattern: "^[1-9][0-9]*$" },
61
+ // 0.5.0: any Cosmos denom (absent = uixo); the fee is Hub-simulated, so an
62
+ // oracle fee is optional and ignored.
63
+ denom: optional({ ...string(3, 128), pattern: "^[a-zA-Z][a-zA-Z0-9/:._-]{2,127}$" }),
64
+ feeBaseUnits: optional({ ...string(), pattern: "^(0|[1-9][0-9]*)$" }),
65
+ memo: string(0, 256),
66
+ },
67
+ "resource.read.v1": {
68
+ resourceId: string(),
69
+ ownerDid: string(),
70
+ url: string(1, 2000),
71
+ version: string(),
72
+ contentDigest: hex,
73
+ },
74
+ "statement.sign.v1": {
75
+ statement: string(0, 8192),
76
+ purpose: string(1, 120),
77
+ audienceId: string(1, 100),
78
+ },
79
+ "gmail.connect.v1": {
80
+ purpose: string(1, 120),
81
+ connectionId: nullable(string(1, 100)),
82
+ accountLabel: nullable(mailbox),
83
+ scopes,
84
+ },
85
+ "gmail.disconnect.v1": {
86
+ connectionId: string(1, 100),
87
+ accountLabel: mailbox,
88
+ },
89
+ "gmail.message.send.v1": {
90
+ connectionId: string(1, 100),
91
+ accountLabel: mailbox,
92
+ to: mailbox,
93
+ subject: {
94
+ ...string(1, 200),
95
+ pattern: "^[^\\u0000-\\u001f\\u007f-\\u009f]+$(?![\\s\\S])",
96
+ },
97
+ body: { ...string(1, 8192), pattern: "^[^\\r\\u0000]+$(?![\\s\\S])" },
98
+ },
99
+ "calendar.connect.v1": {
100
+ purpose: string(1, 120),
101
+ connectionId: nullable(string(1, 100)),
102
+ accountLabel: nullable(string()),
103
+ scopes,
104
+ },
105
+ "calendar.disconnect.v1": {
106
+ connectionId: string(1, 100),
107
+ accountLabel: string(),
108
+ },
109
+ "calendar.event.create.v1": {
110
+ connectionId: string(1, 100),
111
+ accountLabel: string(),
112
+ calendarId: { const: "primary" },
113
+ title: string(1, 120),
114
+ description: string(0, 2000),
115
+ startsAt: instant,
116
+ endsAt: instant,
117
+ timeZone: string(1, 100),
118
+ },
119
+ "vfs.access.request.v1": {
120
+ targetId: string(1, 100),
121
+ title: string(),
122
+ ability: { const: "read" },
123
+ purpose: string(1, 500),
124
+ },
125
+ "vfs.text.save.v1": {
126
+ filename: {
127
+ ...string(5, 80),
128
+ pattern: "^[A-Za-z0-9][A-Za-z0-9 _.-]*\\.txt$",
129
+ },
130
+ text: string(0, 8192),
131
+ },
132
+ };
133
+ export const operationKinds = Object.freeze(Object.keys(registry));
134
+ export const operationJsonSchema = Object.freeze({
135
+ $schema: "https://json-schema.org/draft/2020-12/schema",
136
+ oneOf: Object.entries(registry).map(([kind, properties]) =>
137
+ object({ kind: { const: kind }, ...properties }),
138
+ ),
139
+ });
140
+ function matches(value, schema) {
141
+ if (schema.anyOf) return schema.anyOf.some((s) => matches(value, s));
142
+ if ("const" in schema) return value === schema.const;
143
+ if (schema.enum) return schema.enum.includes(value);
144
+ if (schema.type === "null") return value === null;
145
+ if (schema.type === "boolean") return typeof value === "boolean";
146
+ if (schema.type === "string")
147
+ return (
148
+ typeof value === "string" &&
149
+ value.length >= schema.minLength &&
150
+ value.length <= schema.maxLength &&
151
+ (!schema.pattern || new RegExp(schema.pattern).test(value))
152
+ );
153
+ if (schema.type === "array")
154
+ return (
155
+ Array.isArray(value) &&
156
+ value.length >= (schema.minItems ?? 0) &&
157
+ value.length <= schema.maxItems &&
158
+ (!schema.uniqueItems || new Set(value).size === value.length) &&
159
+ value.every((v) => matches(v, schema.items))
160
+ );
161
+ if (schema.type === "object")
162
+ return (
163
+ value !== null &&
164
+ typeof value === "object" &&
165
+ !Array.isArray(value) &&
166
+ Object.keys(value).every(
167
+ (k) =>
168
+ Object.hasOwn(schema.properties, k) &&
169
+ matches(value[k], schema.properties[k]),
170
+ ) &&
171
+ schema.required.every((k) => Object.hasOwn(value, k))
172
+ );
173
+ return false;
174
+ }
175
+ export function validateOperationSchema(value) {
176
+ const schema = operationJsonSchema.oneOf.find(
177
+ (s) => s.properties.kind.const === value.kind,
178
+ );
179
+ if (!schema || !matches(value, schema))
180
+ throw new TypeError("Invalid operation");
181
+ }
@@ -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
+ }