@self-commerce/core 0.0.0-stage → 0.1.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/README.md +14 -2
- package/index.d.ts +3 -0
- package/index.js +3 -0
- package/objects.d.ts +147 -0
- package/objects.js +74 -0
- package/package.json +17 -4
- package/sign.d.ts +6 -0
- package/sign.js +20 -0
- package/states.d.ts +12 -0
- package/states.js +19 -0
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @self-commerce/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Commerce protocol in one small package: the signed objects an agent sends and receives (Offer, Quote, Order, Accept, Decline, Delivery, Verdict, Dispute, Receipt), their validation, ed25519 signing and checking, and the order state machine. Any agent, in any language, can implement the protocol from `docs/specs/protocol-design.md`; this package is the reference.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
import { signJson, verifyJson, parse, next, sha256Hex } from '@self-commerce/core'
|
|
7
|
+
|
|
8
|
+
const offer = signJson({ v: 1, type: 'offer', id: 'off_1', version: 1, seller: publicKeyB64, /* … */ }, privateKeyPkcs8B64)
|
|
9
|
+
verifyJson(offer, publicKeyB64) // true
|
|
10
|
+
parse(offer) // { ok: true, value } or { ok: false, error }
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
A signature is over the object's JSON text in its own key order, so keep the order you signed. Keys are ed25519: public keys base64 SPKI, private keys base64 PKCS8.
|
|
14
|
+
|
|
15
|
+
Licence: Apache-2.0 (proposed; the owner confirms it, with the licence text, before the first publish).
|
package/index.d.ts
ADDED
package/index.js
ADDED
package/objects.d.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { Type, type Static } from 'typebox';
|
|
2
|
+
export declare const HOLD_S = 432000;
|
|
3
|
+
export declare const Quote: Type.TObject<{
|
|
4
|
+
v: Type.TLiteral<1>;
|
|
5
|
+
type: Type.TLiteral<"quote">;
|
|
6
|
+
signature: Type.TString;
|
|
7
|
+
offer: Type.TString;
|
|
8
|
+
seller: Type.TString;
|
|
9
|
+
buyer: Type.TString;
|
|
10
|
+
input_hash: Type.TString;
|
|
11
|
+
amount: Type.TInteger;
|
|
12
|
+
expires: Type.TInteger;
|
|
13
|
+
}>;
|
|
14
|
+
export declare const Offer: Type.TObject<{
|
|
15
|
+
v: Type.TLiteral<1>;
|
|
16
|
+
type: Type.TLiteral<"offer">;
|
|
17
|
+
signature: Type.TString;
|
|
18
|
+
id: Type.TString;
|
|
19
|
+
version: Type.TInteger;
|
|
20
|
+
seller: Type.TString;
|
|
21
|
+
title: Type.TString;
|
|
22
|
+
description: Type.TString;
|
|
23
|
+
kind: Type.TUnion<[Type.TLiteral<"task">, Type.TLiteral<"good">]>;
|
|
24
|
+
price: Type.TUnion<[Type.TObject<{
|
|
25
|
+
amount: Type.TInteger;
|
|
26
|
+
currency: Type.TString;
|
|
27
|
+
}>, Type.TObject<{
|
|
28
|
+
quote: Type.TLiteral<true>;
|
|
29
|
+
}>]>;
|
|
30
|
+
input: Type.TRecord<"^.*$", Type.TUnknown>;
|
|
31
|
+
output: Type.TRecord<"^.*$", Type.TUnknown>;
|
|
32
|
+
deadline_s: Type.TInteger;
|
|
33
|
+
accept: Type.TUnion<[Type.TObject<{
|
|
34
|
+
mode: Type.TLiteral<"buyer">;
|
|
35
|
+
window_s: Type.TInteger;
|
|
36
|
+
}>, Type.TObject<{
|
|
37
|
+
mode: Type.TLiteral<"check">;
|
|
38
|
+
}>]>;
|
|
39
|
+
terms: Type.TOptional<Type.TString>;
|
|
40
|
+
negotiable: Type.TOptional<Type.TBoolean>;
|
|
41
|
+
a2a: Type.TOptional<Type.TString>;
|
|
42
|
+
}>;
|
|
43
|
+
export declare const Order: Type.TObject<{
|
|
44
|
+
v: Type.TLiteral<1>;
|
|
45
|
+
type: Type.TLiteral<"order">;
|
|
46
|
+
signature: Type.TString;
|
|
47
|
+
id: Type.TString;
|
|
48
|
+
offer: Type.TString;
|
|
49
|
+
offer_version: Type.TInteger;
|
|
50
|
+
quote: Type.TOptional<Type.TObject<{
|
|
51
|
+
v: Type.TLiteral<1>;
|
|
52
|
+
type: Type.TLiteral<"quote">;
|
|
53
|
+
signature: Type.TString;
|
|
54
|
+
offer: Type.TString;
|
|
55
|
+
seller: Type.TString;
|
|
56
|
+
buyer: Type.TString;
|
|
57
|
+
input_hash: Type.TString;
|
|
58
|
+
amount: Type.TInteger;
|
|
59
|
+
expires: Type.TInteger;
|
|
60
|
+
}>>;
|
|
61
|
+
buyer: Type.TString;
|
|
62
|
+
input: Type.TUnknown;
|
|
63
|
+
max_amount: Type.TInteger;
|
|
64
|
+
nonce: Type.TString;
|
|
65
|
+
expires: Type.TInteger;
|
|
66
|
+
}>;
|
|
67
|
+
export declare const Accept: Type.TObject<{
|
|
68
|
+
v: Type.TLiteral<1>;
|
|
69
|
+
type: Type.TLiteral<"accept">;
|
|
70
|
+
signature: Type.TString;
|
|
71
|
+
order: Type.TString;
|
|
72
|
+
seller: Type.TString;
|
|
73
|
+
}>;
|
|
74
|
+
export declare const Decline: Type.TObject<{
|
|
75
|
+
v: Type.TLiteral<1>;
|
|
76
|
+
type: Type.TLiteral<"decline">;
|
|
77
|
+
signature: Type.TString;
|
|
78
|
+
order: Type.TString;
|
|
79
|
+
seller: Type.TString;
|
|
80
|
+
reason: Type.TOptional<Type.TString>;
|
|
81
|
+
}>;
|
|
82
|
+
export declare const Delivery: Type.TUnion<[Type.TObject<{
|
|
83
|
+
v: Type.TLiteral<1>;
|
|
84
|
+
type: Type.TLiteral<"delivery">;
|
|
85
|
+
signature: Type.TString;
|
|
86
|
+
order: Type.TString;
|
|
87
|
+
seller: Type.TString;
|
|
88
|
+
output_hash: Type.TString;
|
|
89
|
+
output: Type.TUnknown;
|
|
90
|
+
}>, Type.TObject<{
|
|
91
|
+
v: Type.TLiteral<1>;
|
|
92
|
+
type: Type.TLiteral<"delivery">;
|
|
93
|
+
signature: Type.TString;
|
|
94
|
+
order: Type.TString;
|
|
95
|
+
seller: Type.TString;
|
|
96
|
+
output_hash: Type.TString;
|
|
97
|
+
output_url: Type.TString;
|
|
98
|
+
}>]>;
|
|
99
|
+
export declare const Verdict: Type.TObject<{
|
|
100
|
+
v: Type.TLiteral<1>;
|
|
101
|
+
type: Type.TLiteral<"verdict">;
|
|
102
|
+
signature: Type.TString;
|
|
103
|
+
order: Type.TString;
|
|
104
|
+
buyer: Type.TString;
|
|
105
|
+
ok: Type.TBoolean;
|
|
106
|
+
reason: Type.TOptional<Type.TString>;
|
|
107
|
+
}>;
|
|
108
|
+
export declare const Dispute: Type.TObject<{
|
|
109
|
+
v: Type.TLiteral<1>;
|
|
110
|
+
type: Type.TLiteral<"dispute">;
|
|
111
|
+
signature: Type.TString;
|
|
112
|
+
order: Type.TString;
|
|
113
|
+
buyer: Type.TString;
|
|
114
|
+
reason: Type.TString;
|
|
115
|
+
}>;
|
|
116
|
+
export declare const STATES: readonly ['ordered', 'accepted', 'delivered', 'settled', 'cancelled', 'expired', 'disputed', 'refunded'];
|
|
117
|
+
export declare const Receipt: Type.TObject<{
|
|
118
|
+
v: Type.TLiteral<1>;
|
|
119
|
+
type: Type.TLiteral<"receipt">;
|
|
120
|
+
signature: Type.TString;
|
|
121
|
+
order: Type.TString;
|
|
122
|
+
market: Type.TString;
|
|
123
|
+
state: Type.TEnum<["ordered", "accepted", "delivered", "settled", "cancelled", "expired", "disputed", "refunded"]>;
|
|
124
|
+
amount: Type.TInteger;
|
|
125
|
+
fee: Type.TInteger;
|
|
126
|
+
platform_fee: Type.TInteger;
|
|
127
|
+
payout: Type.TInteger;
|
|
128
|
+
captured_at: Type.TInteger;
|
|
129
|
+
}>;
|
|
130
|
+
export type Offer = Static<typeof Offer>;
|
|
131
|
+
export type Quote = Static<typeof Quote>;
|
|
132
|
+
export type Order = Static<typeof Order>;
|
|
133
|
+
export type Accept = Static<typeof Accept>;
|
|
134
|
+
export type Decline = Static<typeof Decline>;
|
|
135
|
+
export type Delivery = Static<typeof Delivery>;
|
|
136
|
+
export type Verdict = Static<typeof Verdict>;
|
|
137
|
+
export type Dispute = Static<typeof Dispute>;
|
|
138
|
+
export type Receipt = Static<typeof Receipt>;
|
|
139
|
+
export type CommerceObject = Offer | Quote | Order | Accept | Decline | Delivery | Verdict | Dispute | Receipt;
|
|
140
|
+
export declare const sha256Hex: (bytes: Uint8Array | string) => string;
|
|
141
|
+
export declare const parse: (obj: unknown) => {
|
|
142
|
+
ok: true;
|
|
143
|
+
value: CommerceObject;
|
|
144
|
+
} | {
|
|
145
|
+
ok: false;
|
|
146
|
+
error: string;
|
|
147
|
+
};
|
package/objects.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { Type } from 'typebox';
|
|
3
|
+
import { Value } from 'typebox/value';
|
|
4
|
+
import { verifyJson } from './sign.js';
|
|
5
|
+
const Str = Type.String({ minLength: 1 });
|
|
6
|
+
const Key = Str; // base64 spki
|
|
7
|
+
const Cents = Type.Integer({ minimum: 0 });
|
|
8
|
+
const Charge = Type.Integer({ minimum: 50 }); // Stripe's smallest charge: a price below it cannot be authorised
|
|
9
|
+
const Currency = Type.String({ pattern: '^[a-z]{3}$' });
|
|
10
|
+
const Time = Type.Integer({ minimum: 0 }); // ms since epoch
|
|
11
|
+
const Json = Type.Record(Type.String(), Type.Unknown());
|
|
12
|
+
const Hash = Type.String({ pattern: '^[0-9a-f]{64}$' });
|
|
13
|
+
// 5 days: the card hold (Stripe keeps one 7 days) must outlive the deadline and the buyer's window together
|
|
14
|
+
export const HOLD_S = 432000;
|
|
15
|
+
const head = (type) => ({ v: Type.Literal(1), type: Type.Literal(type), signature: Str });
|
|
16
|
+
export const Quote = Type.Object({ ...head('quote'), offer: Str, seller: Key, buyer: Key, input_hash: Hash, amount: Charge, expires: Time });
|
|
17
|
+
export const Offer = Type.Object({
|
|
18
|
+
...head('offer'), id: Str, version: Type.Integer({ minimum: 1 }), seller: Key, title: Str, description: Type.String(),
|
|
19
|
+
kind: Type.Union([Type.Literal('task'), Type.Literal('good')]),
|
|
20
|
+
price: Type.Union([Type.Object({ amount: Charge, currency: Currency }), Type.Object({ quote: Type.Literal(true) })]),
|
|
21
|
+
input: Json, output: Json,
|
|
22
|
+
deadline_s: Type.Integer({ minimum: 1, maximum: HOLD_S }),
|
|
23
|
+
accept: Type.Union([
|
|
24
|
+
Type.Object({ mode: Type.Literal('buyer'), window_s: Type.Integer({ minimum: 1 }) }),
|
|
25
|
+
Type.Object({ mode: Type.Literal('check') }),
|
|
26
|
+
]),
|
|
27
|
+
terms: Type.Optional(Type.String({ maxLength: 2048 })),
|
|
28
|
+
negotiable: Type.Optional(Type.Boolean()),
|
|
29
|
+
a2a: Type.Optional(Type.String({ pattern: '^https?://', maxLength: 2048 })),
|
|
30
|
+
});
|
|
31
|
+
export const Order = Type.Object({
|
|
32
|
+
...head('order'), id: Str, offer: Str, offer_version: Type.Integer({ minimum: 1 }), quote: Type.Optional(Quote),
|
|
33
|
+
buyer: Key, input: Type.Unknown(), max_amount: Charge, nonce: Str, expires: Time,
|
|
34
|
+
});
|
|
35
|
+
export const Accept = Type.Object({ ...head('accept'), order: Str, seller: Key });
|
|
36
|
+
export const Decline = Type.Object({ ...head('decline'), order: Str, seller: Key, reason: Type.Optional(Type.String()) });
|
|
37
|
+
// exactly one of output / output_url: the union arms forbid the other field
|
|
38
|
+
const deliveryBase = { ...head('delivery'), order: Str, seller: Key, output_hash: Hash };
|
|
39
|
+
export const Delivery = Type.Union([
|
|
40
|
+
Type.Object({ ...deliveryBase, output: Type.Unknown() }, { additionalProperties: false }),
|
|
41
|
+
Type.Object({ ...deliveryBase, output_url: Str }, { additionalProperties: false }),
|
|
42
|
+
]);
|
|
43
|
+
export const Verdict = Type.Object({ ...head('verdict'), order: Str, buyer: Key, ok: Type.Boolean(), reason: Type.Optional(Type.String()) });
|
|
44
|
+
export const Dispute = Type.Object({ ...head('dispute'), order: Str, buyer: Key, reason: Str });
|
|
45
|
+
export const STATES = ['ordered', 'accepted', 'delivered', 'settled', 'cancelled', 'expired', 'disputed', 'refunded'];
|
|
46
|
+
export const Receipt = Type.Object({
|
|
47
|
+
...head('receipt'), order: Str, market: Key, state: Type.Enum(STATES), amount: Cents, fee: Cents, platform_fee: Cents, payout: Cents, captured_at: Time,
|
|
48
|
+
});
|
|
49
|
+
// signer: which field names the key that verifies the object
|
|
50
|
+
const KINDS = {
|
|
51
|
+
offer: { schema: Offer, signer: 'seller' }, quote: { schema: Quote, signer: 'seller' },
|
|
52
|
+
accept: { schema: Accept, signer: 'seller' }, decline: { schema: Decline, signer: 'seller' },
|
|
53
|
+
delivery: { schema: Delivery, signer: 'seller' }, order: { schema: Order, signer: 'buyer' },
|
|
54
|
+
verdict: { schema: Verdict, signer: 'buyer' }, dispute: { schema: Dispute, signer: 'buyer' },
|
|
55
|
+
receipt: { schema: Receipt, signer: 'market' },
|
|
56
|
+
};
|
|
57
|
+
export const sha256Hex = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
58
|
+
export const parse = (obj) => {
|
|
59
|
+
const type = typeof obj === 'object' && obj !== null ? String(obj.type) : '';
|
|
60
|
+
// hasOwn: an inherited name ('toString', '__proto__') is not a kind
|
|
61
|
+
const kind = Object.hasOwn(KINDS, type) ? KINDS[type] : undefined;
|
|
62
|
+
if (!kind)
|
|
63
|
+
return { ok: false, error: 'unknown_type' };
|
|
64
|
+
if (!Value.Check(kind.schema, obj)) {
|
|
65
|
+
const e = Value.Errors(kind.schema, obj)[0];
|
|
66
|
+
return { ok: false, error: `invalid:${e?.instancePath ?? ''}` };
|
|
67
|
+
}
|
|
68
|
+
const o = obj;
|
|
69
|
+
if (o.type === 'offer' && o.accept.mode === 'buyer' && o.deadline_s + o.accept.window_s > HOLD_S)
|
|
70
|
+
return { ok: false, error: 'invalid:/accept/window_s' };
|
|
71
|
+
if (!verifyJson(o, o[kind.signer]))
|
|
72
|
+
return { ok: false, error: 'bad_signature' };
|
|
73
|
+
return { ok: true, value: o };
|
|
74
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@self-commerce/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The Commerce protocol: signed offers, quotes, orders, deliveries, verdicts and receipts, and the order state machine.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./index.js",
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./index.d.ts",
|
|
12
|
+
"import": "./index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"typebox": "^1.3"
|
|
17
|
+
},
|
|
18
|
+
"sideEffects": false
|
|
19
|
+
}
|
package/sign.d.ts
ADDED
package/sign.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
|
|
2
|
+
/** The signed bytes: the object as JSON, without its signature field. */
|
|
3
|
+
const payload = (obj) => {
|
|
4
|
+
const { signature: _signature, ...rest } = obj;
|
|
5
|
+
return Buffer.from(JSON.stringify(rest));
|
|
6
|
+
};
|
|
7
|
+
export const signJson = (obj, privateKeyPkcs8B64) => {
|
|
8
|
+
const key = createPrivateKey({ key: Buffer.from(privateKeyPkcs8B64, 'base64'), format: 'der', type: 'pkcs8' });
|
|
9
|
+
return { ...obj, signature: sign(null, payload(obj), key).toString('base64') };
|
|
10
|
+
};
|
|
11
|
+
export const verifyJson = (obj, publicKeySpkiB64) => {
|
|
12
|
+
try {
|
|
13
|
+
const key = createPublicKey({ key: Buffer.from(publicKeySpkiB64, 'base64'), format: 'der', type: 'spki' });
|
|
14
|
+
return verify(null, payload(obj), key, Buffer.from(obj.signature, 'base64'));
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// silent: a malformed key or signature is a failed check, not an error to surface
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
};
|
package/states.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { STATES } from './objects.ts';
|
|
2
|
+
export type State = (typeof STATES)[number];
|
|
3
|
+
export type Event = 'accept' | 'decline' | 'seller_silent' | 'deliver' | 'verdict_ok' | 'verdict_refuse' | 'window_lapsed' | 'check_passed' | 'check_failed' | 'deadline_passed' | 'capture_failed' | 'dispute' | 'dispute_expired';
|
|
4
|
+
export type Effect = 'void' | 'capture' | 'none';
|
|
5
|
+
export declare const next: (state: State, event: Event) => {
|
|
6
|
+
ok: true;
|
|
7
|
+
state: State;
|
|
8
|
+
effect: Effect;
|
|
9
|
+
} | {
|
|
10
|
+
ok: false;
|
|
11
|
+
error: 'invalid_transition';
|
|
12
|
+
};
|
package/states.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// settled + capture_failed: capture runs after the state change, so a failed capture still expires the order.
|
|
2
|
+
// disputed + dispute_expired: until the phase-6 judge, a dispute lapses after 48 h by voiding the hold; `refunded`
|
|
3
|
+
// because nothing was captured, so the buyer keeps the money and no money moves
|
|
4
|
+
const table = {
|
|
5
|
+
ordered: { accept: ['accepted', 'none'], decline: ['cancelled', 'void'], seller_silent: ['cancelled', 'void'] },
|
|
6
|
+
accepted: { deliver: ['delivered', 'none'], deadline_passed: ['expired', 'void'] },
|
|
7
|
+
delivered: {
|
|
8
|
+
verdict_ok: ['settled', 'capture'], window_lapsed: ['settled', 'capture'], check_passed: ['settled', 'capture'],
|
|
9
|
+
verdict_refuse: ['disputed', 'none'], check_failed: ['disputed', 'none'], dispute: ['disputed', 'none'],
|
|
10
|
+
capture_failed: ['expired', 'void'],
|
|
11
|
+
},
|
|
12
|
+
settled: { capture_failed: ['expired', 'void'] },
|
|
13
|
+
disputed: { dispute_expired: ['refunded', 'void'] },
|
|
14
|
+
cancelled: {}, expired: {}, refunded: {},
|
|
15
|
+
};
|
|
16
|
+
export const next = (state, event) => {
|
|
17
|
+
const row = table[state][event];
|
|
18
|
+
return row ? { ok: true, state: row[0], effect: row[1] } : { ok: false, error: 'invalid_transition' };
|
|
19
|
+
};
|