@kition/sync 0.0.0-stage → 0.2.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,82 @@
1
+ /**
2
+ * Leases for coordinated objects (`kition-sync/1` 1.5, Kition platform docs/platform/reference/sync-protocol.md section 8): a
3
+ * session takes a short lease on a scope (a KDM object id, a kit-named scope, or `*` for the whole
4
+ * document) before an edit that does not merge meaningfully, and hears every room's lease list.
5
+ * `SyncClient.leases` is one of these, wired to the client's connection.
6
+ */
7
+ import { type Lease } from './protocol.js';
8
+ /** What the lease side needs from the client it belongs to. */
9
+ export type LeaseLink = {
10
+ request: (method: string, params: Record<string, unknown>) => Promise<unknown>;
11
+ /** Whether the connection is up and the server listed the `leases` capability. */
12
+ available: () => boolean;
13
+ setTimeout?: (run: () => void, ms: number) => unknown;
14
+ clearTimeout?: (handle: unknown) => void;
15
+ };
16
+ /** A lease kept alive (`SyncLeases.hold`) until released or lost with the connection. */
17
+ export type LeaseHold = {
18
+ readonly lease: Lease;
19
+ /** Ends the lease (`lease/release`) and stops renewing it. */
20
+ release: () => Promise<void>;
21
+ /** Hears the lease being lost (the connection dropped, or a renewal was refused). */
22
+ onLost: (listener: () => void) => () => void;
23
+ };
24
+ /** The lease that holds a colliding scope, from a refused `lease/acquire` (`conflict`). */
25
+ export declare function leaseHolder(error: unknown): Lease | undefined;
26
+ /** Whether two scopes collide: equal, or either is `*` (the whole document). */
27
+ export declare function scopesCollide(a: string, b: string): boolean;
28
+ export declare class SyncLeases {
29
+ private readonly link;
30
+ private readonly lists;
31
+ private readonly listeners;
32
+ private readonly holds;
33
+ /** This connection's session, learned from the first lease it was granted; reset with the connection. */
34
+ private session;
35
+ constructor(link: LeaseLink);
36
+ /** Whether the server keeps leases and the connection is up: without, there is nobody to coordinate with. */
37
+ get available(): boolean;
38
+ /** Takes (or renews) the lease on `scope` for `ttl` ms. Rejects `conflict` (see `leaseHolder`) when another session holds it. */
39
+ acquire(docId: string, scope: string, ttl?: number): Promise<Lease>;
40
+ /** Ends this session's lease on `scope` (harmless when it holds none). */
41
+ release(docId: string, scope: string): Promise<void>;
42
+ /**
43
+ * Takes the lease on `scope` and renews it at half its `ttl` until `release` (or the connection
44
+ * drops, which loses it: the server ends a session's leases with the session). Holding a scope
45
+ * already held renews it and answers a new hold that replaces the old one.
46
+ */
47
+ hold(docId: string, scope: string, ttl?: number): Promise<LeaseHold>;
48
+ /** The room's leases as last heard (`lease/changed`); empty before any and while offline. */
49
+ list(docId: string): Lease[];
50
+ /** Hears `docId`'s lease list each time it changes; answers an unsubscribe. */
51
+ onChanged(docId: string, listener: (leases: Lease[]) => void): () => void;
52
+ /** Whether `lease` is this connection's own. */
53
+ mine(lease: Lease): boolean;
54
+ /** `lease/changed` from the server (the client routes it here). */
55
+ receive(params: Record<string, unknown>): void;
56
+ /** The connection dropped: the server ended this session's leases, and the lists are stale. */
57
+ disconnected(): void;
58
+ /** Left `docId`'s room: its list no longer applies, and nothing there is held any more. */
59
+ left(docId: string): void;
60
+ private set;
61
+ }
62
+ /**
63
+ * One document's leases as an editor's host serves them to its kit: `acquire` holds a scope
64
+ * (renewed until released), `release` ends it, and `dispose` (the editor closed) releases what is
65
+ * still held. Without a server that keeps leases, or while offline, there is nobody to coordinate
66
+ * with: `acquire` answers `null` and the edit goes ahead (an edit made then lands as a conflict
67
+ * object if someone else held the lease meanwhile). A refusal rejects as `lease/acquire` did
68
+ * (`conflict` with the holder, see `leaseHolder`; `forbidden` for a viewer).
69
+ */
70
+ export declare class DocumentLeases {
71
+ private readonly leases;
72
+ readonly docId: string;
73
+ private readonly holds;
74
+ constructor(leases: SyncLeases, docId: string);
75
+ acquire(scope: string, ttl?: number): Promise<Lease | null>;
76
+ release(scope: string): Promise<void>;
77
+ list(): Lease[];
78
+ onChanged(listener: (leases: Lease[]) => void): () => void;
79
+ mine(lease: Lease): boolean;
80
+ /** Releases every lease still held for this editor. */
81
+ dispose(): void;
82
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Open tokens (`ko1.`), managed co-editing (Kition platform docs/platform/managed-collab.md,
3
+ * section 1): a host signs one person's permissions on one file version; Kition Server and the
4
+ * kit host verify them offline against the host's public keys. The Rust twin is the
5
+ * `kition-open-token` crate; both are held to `crates/kition-open-token/tests/vectors.json`.
6
+ *
7
+ * `ko1.` base64url(claims JSON) `.` base64url(Ed25519 signature over the middle segment's ASCII).
8
+ * Uses WebCrypto (`crypto.subtle`, Ed25519 and SHA-256): browsers and Node 20+.
9
+ */
10
+ import type { Role } from './protocol.js';
11
+ export declare const OPEN_TOKEN_PREFIX = "ko1.";
12
+ export declare const OPEN_TOKEN_TYPE = "kition-open";
13
+ export declare const OPEN_TOKEN_MAX_TTL = 3600;
14
+ export declare const OPEN_TOKEN_CLOCK_SKEW = 60;
15
+ /** What the person may do with the file (OT1, OT5): `edit` implies `comment`. */
16
+ export type OpenPerms = {
17
+ edit: boolean;
18
+ comment: boolean;
19
+ download: boolean;
20
+ share: boolean;
21
+ export: boolean;
22
+ };
23
+ export type OpenTokenClaims = {
24
+ v: 1;
25
+ typ: typeof OPEN_TOKEN_TYPE;
26
+ kid: string;
27
+ /** The host that signed it (`[A-Za-z0-9._-]`); its keys name it (I2). */
28
+ iss: string;
29
+ /** The Kition Server it is for (I2). */
30
+ aud: string;
31
+ tenant: string;
32
+ /** The person: the host's user id. */
33
+ sub: string;
34
+ name: string;
35
+ /** The host's immutable resource id of the file. */
36
+ file: string;
37
+ /** The host content revision the session opens. */
38
+ version: string;
39
+ /** The co-editing generation: one room per `(tenant, file, doc_key)`. */
40
+ doc_key: string;
41
+ perms: OpenPerms;
42
+ watermark: {
43
+ text: string;
44
+ } | null;
45
+ iat: number;
46
+ exp: number;
47
+ jti?: string;
48
+ };
49
+ /** A host's public key (raw 32-byte Ed25519, base64url): it signs only for `tenant`, as `iss` (OT2, I2). */
50
+ export type OpenTokenKey = {
51
+ kid: string;
52
+ publicKey: string;
53
+ tenant: string;
54
+ iss: string;
55
+ };
56
+ export type OpenTokenErrorCode = 'malformed' | 'version' | 'unknown-key' | 'signature' | 'issuer' | 'audience' | 'duplicate-key' | 'claims' | 'expired' | 'not-yet-valid';
57
+ export declare class OpenTokenError extends Error {
58
+ readonly code: OpenTokenErrorCode;
59
+ constructor(code: OpenTokenErrorCode);
60
+ }
61
+ /** Whether `tenant` is a tenant name: 2 to 40 lowercase letters, digits, and inner hyphens. */
62
+ export declare function isTenant(tenant: string): boolean;
63
+ /** Refuses a key set with two keys of one `(tenant, kid)` (I3), as the Rust crate's `HostKeys::new` does. */
64
+ export declare function checkOpenTokenKeys(keys: readonly OpenTokenKey[]): void;
65
+ /** Verifies `token` for the server `audience` at `now` (Unix seconds) against `keys` (OT3, I2); throws `OpenTokenError`. */
66
+ export declare function verifyOpenToken(token: string, keys: readonly OpenTokenKey[], audience: string, now?: number): Promise<OpenTokenClaims>;
67
+ /**
68
+ * The claims of `token` without checking its signature or times: for a page that shows what its
69
+ * token says (the watermark, which buttons to offer), never for deciding what it allows.
70
+ */
71
+ export declare function decodeOpenToken(token: string): OpenTokenClaims;
72
+ /** Whether `token` is an open token by its prefix (a `ks1.` sync token is not). */
73
+ export declare function isOpenToken(token: unknown): token is string;
74
+ /** The Server principal of verified claims, `t:<tenant>:<iss>:<sub>` (I2). */
75
+ export declare function openTokenPrincipal(claims: Pick<OpenTokenClaims, 'tenant' | 'iss' | 'sub'>): string;
76
+ /** The sync role `perms` grant (OT1): `editor`, `commenter`, or `viewer`; never `owner`. */
77
+ export declare function openTokenRole(perms: OpenPerms): Exclude<Role, 'owner'>;
78
+ /**
79
+ * The `doc_key` of `file`'s co-editing `generation` (section 1.3): the first 32 characters of
80
+ * base64url(SHA-256("kition-doc-key\n" + file + "\n" + generation)).
81
+ */
82
+ export declare function deriveDocKey(file: string, generation: number): Promise<string>;
83
+ /**
84
+ * Signs `claims` (for a host server in Node: Kition One uses the Rust crate instead) with an
85
+ * Ed25519 `privateKey` (a WebCrypto key with `sign`). `v`, `typ` and `kid` are set here; the
86
+ * claims are checked first and written with sorted keys.
87
+ */
88
+ export declare function signOpenToken(claims: Omit<OpenTokenClaims, 'v' | 'typ' | 'kid'>, kid: string, privateKey: CryptoKey): Promise<string>;
89
+ /**
90
+ * What a kit host opens the kit with for a verified token (Kit UI protocol 2.6): read-only
91
+ * without `edit`, comments without `comment`, the display permissions, and the watermark.
92
+ */
93
+ export declare function openTokenDocument(claims: Pick<OpenTokenClaims, 'perms' | 'watermark'>): {
94
+ readOnly: boolean;
95
+ canComment: boolean;
96
+ permissions: {
97
+ download: boolean;
98
+ export: boolean;
99
+ share: boolean;
100
+ };
101
+ watermark: {
102
+ text: string;
103
+ } | null;
104
+ };
@@ -0,0 +1,201 @@
1
+ const p = "ko1.", E = "kition-open", P = 3600, L = 60;
2
+ class r extends Error {
3
+ constructor(t) {
4
+ super(`open token refused: ${t}`), this.code = t;
5
+ }
6
+ }
7
+ const g = ["edit", "comment", "download", "share", "export"];
8
+ function k(e) {
9
+ if (!/^[A-Za-z0-9_-]*$/.test(e) || e.length % 4 === 1) throw new r("malformed");
10
+ let t;
11
+ try {
12
+ const n = atob(e.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - e.length % 4) % 4));
13
+ t = Uint8Array.from(n, (o) => o.charCodeAt(0));
14
+ } catch {
15
+ throw new r("malformed");
16
+ }
17
+ if (y(t) !== e) throw new r("malformed");
18
+ return t;
19
+ }
20
+ function K(e) {
21
+ let t = 0;
22
+ const n = () => {
23
+ for (; t < e.length && `
24
+ \r`.includes(e[t]); ) t += 1;
25
+ }, o = () => {
26
+ if (e[t] !== '"') return null;
27
+ const c = t;
28
+ for (t += 1; t < e.length && e[t] !== '"'; ) t += e[t] === "\\" ? 2 : 1;
29
+ if (t >= e.length) return null;
30
+ t += 1;
31
+ try {
32
+ return JSON.parse(e.slice(c, t));
33
+ } catch {
34
+ return null;
35
+ }
36
+ }, i = (c) => {
37
+ if (c > 8) return !1;
38
+ n();
39
+ const s = e[t];
40
+ if (s === "{") {
41
+ t += 1;
42
+ const f = /* @__PURE__ */ new Set();
43
+ if (n(), e[t] === "}")
44
+ return t += 1, !0;
45
+ for (; ; ) {
46
+ n();
47
+ const a = o();
48
+ if (a === null || f.has(a) || (f.add(a), n(), e[t] !== ":") || (t += 1, !i(c + 1))) return !1;
49
+ if (n(), e[t] === ",") {
50
+ t += 1;
51
+ continue;
52
+ }
53
+ return e[t] !== "}" ? !1 : (t += 1, !0);
54
+ }
55
+ }
56
+ if (s === "[") {
57
+ if (t += 1, n(), e[t] === "]")
58
+ return t += 1, !0;
59
+ for (; ; ) {
60
+ if (!i(c + 1)) return !1;
61
+ if (n(), e[t] === ",") {
62
+ t += 1;
63
+ continue;
64
+ }
65
+ return e[t] !== "]" ? !1 : (t += 1, !0);
66
+ }
67
+ }
68
+ if (s === '"') return o() !== null;
69
+ const u = /^(?:-?(?:0|[1-9][0-9]*)(?![.eE0-9])|true|false|null)/.exec(e.slice(t));
70
+ return u ? (t += u[0].length, !0) : !1;
71
+ };
72
+ return i(0) ? (n(), t === e.length) : !1;
73
+ }
74
+ function y(e) {
75
+ let t = "";
76
+ for (const n of e) t += String.fromCharCode(n);
77
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
78
+ }
79
+ function T(e) {
80
+ if (typeof e != "string" || !e.startsWith(p)) throw new r("malformed");
81
+ const t = e.slice(p.length).split(".");
82
+ if (t.length !== 2 || !t[0] || !t[1]) throw new r("malformed");
83
+ return [t[0], t[1]];
84
+ }
85
+ const $ = (e) => typeof e == "boolean", d = (e) => typeof e == "string", O = (e) => typeof e == "number" && Number.isSafeInteger(e) && e >= 0;
86
+ function b(e) {
87
+ let t;
88
+ try {
89
+ const a = new TextDecoder("utf-8", { fatal: !0 }).decode(k(e));
90
+ if (!K(a)) throw new r("malformed");
91
+ t = JSON.parse(a);
92
+ } catch {
93
+ throw new r("malformed");
94
+ }
95
+ if (!t || typeof t != "object" || Array.isArray(t)) throw new r("malformed");
96
+ const n = t.perms, o = !!n && typeof n == "object" && !Array.isArray(n) && Object.keys(n).every((a) => g.includes(a)) && g.every((a) => $(n[a])), i = t.watermark ?? null, c = i === null || typeof i == "object" && !Array.isArray(i) && Object.keys(i).length === 1 && d(i.text), s = t.name === void 0 ? "" : t.name;
97
+ if (!(typeof t.v == "number" && d(t.typ) && ["kid", "iss", "aud", "tenant", "sub", "file", "version", "doc_key"].every((a) => d(t[a])) && d(s) && o && c && O(t.iat) && O(t.exp) && (t.jti === void 0 || t.jti === null || d(t.jti)))) throw new r("malformed");
98
+ const f = { ...t, name: s, watermark: i };
99
+ return t.jti === null && delete f.jti, f;
100
+ }
101
+ function v(e) {
102
+ return /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])$/.test(e);
103
+ }
104
+ const _ = /[\u0000-\u001f\u007f-\u009f]/, N = (e) => new TextEncoder().encode(e).length, l = (e, t) => e.length > 0 && N(e) <= t && !_.test(e), m = (e, t) => e.length >= 1 && e.length <= 128 && new RegExp(`^[A-Za-z0-9._${t}-]+$`).test(e);
105
+ function x(e) {
106
+ if (!(v(e.tenant) && l(e.kid, 128) && m(e.iss, "") && l(e.aud, 256) && l(e.sub, 128) && N(e.name) <= 128 && !_.test(e.name) && m(e.file, ":") && l(e.version, 128) && m(e.doc_key, "") && (!e.perms.edit || e.perms.comment) && (e.watermark === null || l(e.watermark.text, 256)) && (e.jti === void 0 || l(e.jti, 128)))) throw new r("claims");
107
+ }
108
+ function S(e, t) {
109
+ if (e.exp <= e.iat || e.exp - e.iat > 3600) throw new r("expired");
110
+ if (e.iat > t + 60) throw new r("not-yet-valid");
111
+ if (t >= e.exp) throw new r("expired");
112
+ }
113
+ function C(e) {
114
+ const t = /* @__PURE__ */ new Set();
115
+ for (const n of e) {
116
+ const o = `${n.tenant}\0${n.kid}`;
117
+ if (t.has(o)) throw new r("duplicate-key");
118
+ t.add(o);
119
+ }
120
+ }
121
+ async function z(e, t, n, o = Math.floor(Date.now() / 1e3)) {
122
+ C(t);
123
+ const [i, c] = T(e), s = b(i);
124
+ if (s.v !== 1 || s.typ !== E) throw new r("version");
125
+ const u = t.find((w) => w.kid === s.kid && w.tenant === s.tenant);
126
+ if (!u) throw new r("unknown-key");
127
+ const f = k(u.publicKey), a = k(c);
128
+ if (f.length !== 32 || a.length !== 64) throw new r("malformed");
129
+ let h = !1;
130
+ try {
131
+ const w = await crypto.subtle.importKey("raw", f, { name: "Ed25519" }, !1, ["verify"]);
132
+ h = await crypto.subtle.verify({ name: "Ed25519" }, w, a, new TextEncoder().encode(i));
133
+ } catch {
134
+ h = !1;
135
+ }
136
+ if (!h) throw new r("signature");
137
+ if (u.iss !== s.iss) throw new r("issuer");
138
+ if (s.aud !== n) throw new r("audience");
139
+ return x(s), S(s, o), s;
140
+ }
141
+ function B(e) {
142
+ return b(T(e)[0]);
143
+ }
144
+ function M(e) {
145
+ return typeof e == "string" && e.startsWith(p);
146
+ }
147
+ function R(e) {
148
+ return `t:${e.tenant}:${e.iss}:${e.sub}`;
149
+ }
150
+ function U(e) {
151
+ return e.edit ? "editor" : e.comment ? "commenter" : "viewer";
152
+ }
153
+ async function D(e, t) {
154
+ const n = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`kition-doc-key
155
+ ${e}
156
+ ${t}`));
157
+ return y(new Uint8Array(n)).slice(0, 32);
158
+ }
159
+ function A(e) {
160
+ return !e || typeof e != "object" || Array.isArray(e) ? e : Object.fromEntries(
161
+ Object.keys(e).sort().map((t) => [t, A(e[t])])
162
+ );
163
+ }
164
+ async function J(e, t, n) {
165
+ const o = { ...e, v: 1, typ: E, kid: t };
166
+ if (x(o), o.exp <= o.iat || o.exp - o.iat > 3600) throw new r("expired");
167
+ const i = y(new TextEncoder().encode(JSON.stringify(A(o))));
168
+ let c;
169
+ try {
170
+ c = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, n, new TextEncoder().encode(i)));
171
+ } catch {
172
+ throw new r("signature");
173
+ }
174
+ return `${p}${i}.${y(c)}`;
175
+ }
176
+ function W(e) {
177
+ const { perms: t } = e;
178
+ return {
179
+ readOnly: !t.edit,
180
+ canComment: t.comment,
181
+ permissions: { download: t.download, export: t.export, share: t.share },
182
+ watermark: e.watermark ? { text: e.watermark.text } : null
183
+ };
184
+ }
185
+ export {
186
+ L as OPEN_TOKEN_CLOCK_SKEW,
187
+ P as OPEN_TOKEN_MAX_TTL,
188
+ p as OPEN_TOKEN_PREFIX,
189
+ E as OPEN_TOKEN_TYPE,
190
+ r as OpenTokenError,
191
+ C as checkOpenTokenKeys,
192
+ B as decodeOpenToken,
193
+ D as deriveDocKey,
194
+ M as isOpenToken,
195
+ v as isTenant,
196
+ W as openTokenDocument,
197
+ R as openTokenPrincipal,
198
+ U as openTokenRole,
199
+ J as signOpenToken,
200
+ z as verifyOpenToken
201
+ };