@kition/doc-service 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 CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # @kition/doc-service
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Kits document service, for URL embedding: your page frames a URL your server minted, and the
4
+ service shows a Kition kit editor there (the Note kit today; other kits are not published yet), reading and
5
+ writing the file through HMAC-signed HTTP callbacks to your server. It keeps no document.
6
+ Single-user; for co-editing see `@kition/embed`. An ES module with type declarations, for Node 20.6
7
+ or later, and a `kition-doc-service` command.
8
+
9
+ ```sh
10
+ npm i @kition/doc-service
11
+ ```
12
+
13
+ ```ts
14
+ import { startDocService } from '@kition/doc-service'
15
+
16
+ const service = await startDocService({
17
+ id: 'docs-example', // the `aud` your open tokens name
18
+ secret: process.env.DOC_SESSION_SECRET!, // at least 32 characters, signs the page's sessions
19
+ integrators: [{
20
+ iss: 'acme.app', // the `iss` your open tokens name
21
+ keys: [{ kid: 'acme-1', publicKey: '<base64url Ed25519>', tenant: 'acme', iss: 'acme.app' }],
22
+ callbackUrl: 'https://app.acme.com/kition',
23
+ secret: process.env.ACME_CALLBACK_SECRET!, // shared with your server; signs every callback
24
+ origins: ['https://app.acme.com'], // who may frame the editor
25
+ }],
26
+ kits: [{ id: 'kit.note', path: 'note-ui/', extensions: ['.md'] }], // one entry per kit package you serve
27
+ kitsUrl: 'https://kits.example.com/', // the kit packages, on another origin (or kitsDir and kitsPort)
28
+ host: '0.0.0.0', // default 127.0.0.1
29
+ port: 8080,
30
+ })
31
+ console.log(service.url)
32
+ ```
33
+
34
+ `createDocService(config)` is the same as a Node `http` handler for your own server. The editor
35
+ page's module is the installed `@kition/embed` (a dependency); `embedDir` points elsewhere.
36
+
37
+ Or run it from a config file with those options (`.json`, or a module whose default export they are):
38
+
39
+ ```sh
40
+ npx @kition/doc-service ./doc-service.config.mjs
41
+ ```
42
+
43
+ Your server signs the iframe URL's open token with `signOpenToken` from `@kition/sync/openToken`,
44
+ and checks each callback with `verifyCallback` from `@kition/doc-service/callbacks` (it needs only
45
+ `node:crypto`). TypeScript projects need `@types/node`.
46
+
47
+ Documentation: https://dev.kition.ai/url
48
+
49
+ License: Apache-2.0
package/dist/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,30 @@
1
+ export declare const SIGNATURE_HEADER = "x-kition-signature";
2
+ export declare const TIMESTAMP_HEADER = "x-kition-timestamp";
3
+ export declare const SUBJECT_HEADER = "x-kition-subject";
4
+ export declare const DOC_KEY_HEADER = "x-kition-doc-key";
5
+ export declare const VERSION_HEADER = "x-kition-version";
6
+ export declare const NAME_HEADER = "x-kition-name";
7
+ /** How far a callback's timestamp may be from the verifier's clock, seconds. */
8
+ export declare const CALLBACK_SKEW_SECS = 300;
9
+ /** The signature of one callback. */
10
+ export declare function signCallback(secret: string, method: string, path: string, timestamp: number, body?: Uint8Array | null): string;
11
+ /** The headers a callback carries: its signature, timestamp, the person, and the file generation. */
12
+ export declare function callbackHeaders(secret: string, method: string, path: string, body: Uint8Array | null, who: {
13
+ subject: string;
14
+ docKey: string;
15
+ }, now?: number): {
16
+ "x-kition-timestamp": string;
17
+ "x-kition-signature": string;
18
+ "x-kition-subject": string;
19
+ "x-kition-doc-key": string;
20
+ };
21
+ /**
22
+ * Whether a request the integrator received is the document service's: its signature matches and
23
+ * its timestamp is within `CALLBACK_SKEW_SECS` of `now`. `headers` are lower-cased names.
24
+ */
25
+ export declare function verifyCallback(secret: string, request: {
26
+ method: string;
27
+ path: string;
28
+ headers: Record<string, string | string[] | undefined>;
29
+ body?: Uint8Array | null;
30
+ }, now?: number): boolean;
@@ -0,0 +1,37 @@
1
+ import { createHmac as h, createHash as A, timingSafeEqual as d } from "node:crypto";
2
+ const E = "x-kition-signature", f = "x-kition-timestamp", l = "x-kition-subject", g = "x-kition-doc-key", x = "x-kition-version", H = "x-kition-name", b = 300, k = (n) => A("sha256").update(n ?? new Uint8Array()).digest("hex");
3
+ function u(n, t, r, a, e) {
4
+ return `v1=${h("sha256", n).update(`${t.toUpperCase()}
5
+ ${r}
6
+ ${a}
7
+ ${k(e)}`).digest("hex")}`;
8
+ }
9
+ function S(n, t, r, a, e, o = Math.floor(Date.now() / 1e3)) {
10
+ return {
11
+ [f]: String(o),
12
+ [E]: u(n, t, r, o, a),
13
+ [l]: e.subject,
14
+ [g]: e.docKey
15
+ };
16
+ }
17
+ function D(n, t, r = Math.floor(Date.now() / 1e3)) {
18
+ const a = (m) => {
19
+ const i = t.headers[m];
20
+ return Array.isArray(i) ? i[0] : i;
21
+ }, e = Number(a(f)), o = a(E);
22
+ if (!Number.isSafeInteger(e) || Math.abs(r - e) > b || !o) return !1;
23
+ const s = Buffer.from(u(n, t.method, t.path, e, t.body)), c = Buffer.from(o);
24
+ return s.length === c.length && d(s, c);
25
+ }
26
+ export {
27
+ b as CALLBACK_SKEW_SECS,
28
+ g as DOC_KEY_HEADER,
29
+ H as NAME_HEADER,
30
+ E as SIGNATURE_HEADER,
31
+ l as SUBJECT_HEADER,
32
+ f as TIMESTAMP_HEADER,
33
+ x as VERSION_HEADER,
34
+ S as callbackHeaders,
35
+ u as signCallback,
36
+ D as verifyCallback
37
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import { readFile as c } from "node:fs/promises";
3
+ import { resolve as a } from "node:path";
4
+ import { pathToFileURL as l } from "node:url";
5
+ import { startDocService as f } from "./index.js";
6
+ const r = `Usage: kition-doc-service <config.json | config.mjs>
7
+
8
+ Runs the Kits document service for URL embedding (https://dev.kition.ai/url).
9
+ The config holds startDocService's options: id, secret, integrators, kits,
10
+ kitsUrl (or kitsDir and kitsPort), and optionally port, host, embedDir.`, o = process.argv[2];
11
+ (!o || o === "--help" || o === "-h") && (console.log(r), process.exit(o ? 0 : 1));
12
+ const s = a(o), n = s.endsWith(".json") ? JSON.parse(await c(s, "utf8")) : (await import(l(s).href)).default, t = ["id", "secret", "integrators", "kits"].filter((e) => !n?.[e]);
13
+ t.length && (console.error(`${o} names no ${t.join(", ")}
14
+
15
+ ${r}`), process.exit(1));
16
+ const i = await f(n);
17
+ console.log(`document service: ${i.url}`);
18
+ console.log(`kit packages: ${i.kitsUrl}`);
19
+ for (const e of ["SIGINT", "SIGTERM"]) process.once(e, () => void i.close().then(() => process.exit(0)));
@@ -0,0 +1,19 @@
1
+ import { type DocServiceConfig } from './server.js';
2
+ export { createDocService, type DocServiceConfig, type Integrator, type KitRoute } from './server.js';
3
+ export { callbackHeaders, signCallback, verifyCallback, CALLBACK_SKEW_SECS } from './callbacks.js';
4
+ export { makeSession, readSession, type Session } from './session.js';
5
+ /**
6
+ * Listens on `port` (0: any free one). With `kitsDir`, also serves the kit packages there on
7
+ * `kitsPort`, another origin, and `kitsUrl` defaults to it.
8
+ */
9
+ export declare function startDocService(config: Omit<DocServiceConfig, 'kitsUrl'> & {
10
+ kitsUrl?: string;
11
+ port?: number;
12
+ host?: string;
13
+ kitsDir?: string;
14
+ kitsPort?: number;
15
+ }): Promise<{
16
+ url: string;
17
+ kitsUrl: string;
18
+ close: () => Promise<void>;
19
+ }>;
package/dist/index.js ADDED
@@ -0,0 +1,272 @@
1
+ import { createServer as H } from "node:http";
2
+ import { readFile as O } from "node:fs/promises";
3
+ import { dirname as W, extname as D, normalize as I, sep as S, join as B } from "node:path";
4
+ import { timingSafeEqual as G, createHmac as K, randomBytes as N } from "node:crypto";
5
+ import { fileURLToPath as J } from "node:url";
6
+ import { decodeOpenToken as M, OpenTokenError as A, verifyOpenToken as V } from "@kition/sync/openToken";
7
+ import { NAME_HEADER as _, VERSION_HEADER as E, callbackHeaders as z } from "./callbacks.js";
8
+ import { CALLBACK_SKEW_SECS as he, signCallback as pe, verifyCallback as ue } from "./callbacks.js";
9
+ const R = (e) => JSON.stringify(e).replace(/</g, "\\u003c"), F = (e) => e.replace(/[&<>"']/g, (n) => `&#${n.charCodeAt(0)};`);
10
+ function X({ session: e, claims: n, kitUrl: c, embedModule: l, nonce: f, title: b }) {
11
+ const { perms: d } = n, p = {
12
+ session: e,
13
+ kit: { id: n.kit, url: c },
14
+ file: { id: n.file, name: b },
15
+ user: { id: n.sub, name: n.name || n.sub },
16
+ mode: d.edit ? "edit" : d.comment ? "comment" : "view",
17
+ display: { permissions: { download: d.download, export: d.export, share: d.share }, watermark: n.watermark }
18
+ };
19
+ return `<!doctype html>
20
+ <html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><title>${F(b)}</title>
21
+ <style nonce="${f}">html,body,#editor{margin:0;height:100%;overflow:hidden}</style></head>
22
+ <body><div id="editor"></div>
23
+ <script type="application/json" id="kition-config">${R(p)}<\/script>
24
+ <script type="module" nonce="${f}">
25
+ import { KitionEmbed, EmbedConflictError } from ${R(l)}
26
+ const config = JSON.parse(document.getElementById('kition-config').textContent)
27
+ // The open token stays out of the page's address, history and referrers.
28
+ history.replaceState(null, '', location.pathname)
29
+ const auth = { authorization: 'Bearer ' + config.session }
30
+ async function failed(response) {
31
+ throw new Error('the document service answered ' + response.status)
32
+ }
33
+ const replica = {
34
+ read: async () => {
35
+ const response = await fetch('/v1/replica', { headers: auth })
36
+ if (response.status === 404 || response.status === 501) return null
37
+ if (!response.ok) return failed(response)
38
+ const body = new Uint8Array(await response.arrayBuffer())
39
+ const length = new DataView(body.buffer, body.byteOffset).getUint32(0)
40
+ return { snapshot: body.slice(4, 4 + length).buffer, blobs: body.slice(4 + length).buffer, fileStamp: response.headers.get('x-kition-file-stamp') }
41
+ },
42
+ write: async (_id, stored) => {
43
+ const snapshot = new Uint8Array(stored.snapshot), blobs = new Uint8Array(stored.blobs)
44
+ const body = new Uint8Array(4 + snapshot.length + blobs.length)
45
+ new DataView(body.buffer).setUint32(0, snapshot.length)
46
+ body.set(snapshot, 4)
47
+ body.set(blobs, 4 + snapshot.length)
48
+ const response = await fetch('/v1/replica', { method: 'PUT', headers: { ...auth, 'x-kition-file-stamp': stored.fileStamp }, body })
49
+ if (!response.ok && response.status !== 501) return failed(response)
50
+ },
51
+ }
52
+ const storage = {
53
+ read: async () => {
54
+ const response = await fetch('/v1/file', { headers: auth })
55
+ if (!response.ok) return failed(response)
56
+ return { bytes: new Uint8Array(await response.arrayBuffer()), version: response.headers.get('x-kition-version') }
57
+ },
58
+ stamp: async () => {
59
+ const response = await fetch('/v1/file/stamp', { headers: auth })
60
+ if (!response.ok) return failed(response)
61
+ return (await response.json()).version
62
+ },
63
+ write: async (fileId, bytes, { expectedVersion }) => {
64
+ const response = await fetch('/v1/file', { method: 'PUT', headers: { ...auth, ...(expectedVersion ? { 'if-match': expectedVersion } : {}) }, body: bytes })
65
+ if (response.status === 409) throw new EmbedConflictError(fileId, response.headers.get('x-kition-version'))
66
+ if (!response.ok) return failed(response)
67
+ return await response.json()
68
+ },
69
+ replica,
70
+ }
71
+ const editor = await KitionEmbed.mount(document.getElementById('editor'), {
72
+ kit: config.kit,
73
+ file: config.file,
74
+ storage,
75
+ identity: { user: () => config.user },
76
+ permissions: { mode: config.mode },
77
+ display: config.display,
78
+ })
79
+ editor.on('saved', (saved) => parent.postMessage({ kitionDocument: 1, event: 'saved', version: saved.version }, '*'))
80
+ await editor.ready()
81
+ parent.postMessage({ kitionDocument: 1, event: 'ready' }, '*')
82
+ <\/script></body></html>`;
83
+ }
84
+ const T = "kds1.", C = (e) => e.toString("base64url"), L = (e, n) => K("sha256", e).update(`kition-doc-session
85
+ ${n}`).digest();
86
+ function Y(e, n) {
87
+ const c = C(Buffer.from(JSON.stringify(n)));
88
+ return `${T}${c}.${C(L(e, c))}`;
89
+ }
90
+ function Q(e, n, c = Math.floor(Date.now() / 1e3)) {
91
+ if (!n?.startsWith(T)) return null;
92
+ const [l, f, b] = n.slice(T.length).split(".");
93
+ if (!l || !f || b !== void 0) return null;
94
+ const d = L(e, l), p = Buffer.from(f, "base64url");
95
+ if (p.length !== d.length || !G(p, d)) return null;
96
+ try {
97
+ const g = JSON.parse(Buffer.from(l, "base64url").toString("utf8"));
98
+ return typeof g.exp == "number" && c < g.exp ? g : null;
99
+ } catch {
100
+ return null;
101
+ }
102
+ }
103
+ const Z = { ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".map": "application/json", ".css": "text/css", ".wasm": "application/wasm", ".json": "application/json" };
104
+ function q() {
105
+ try {
106
+ return W(J(import.meta.resolve("@kition/embed")));
107
+ } catch {
108
+ throw new Error("@kition/embed is not installed next to @kition/doc-service: install it, or set embedDir");
109
+ }
110
+ }
111
+ class a extends Error {
112
+ constructor(n, c) {
113
+ super(c), this.status = n;
114
+ }
115
+ }
116
+ async function ee(e, n) {
117
+ const c = [];
118
+ let l = 0;
119
+ for await (const f of e) {
120
+ if (l += f.length, l > n) throw new a(413, "too large");
121
+ c.push(f);
122
+ }
123
+ return new Uint8Array(Buffer.concat(c));
124
+ }
125
+ function te(e) {
126
+ if (e.secret.length < 32) throw new Error("the session secret needs at least 32 characters");
127
+ const n = new URL(e.kitsUrl).origin, c = e.fetch ?? fetch, l = e.now ?? (() => Math.floor(Date.now() / 1e3)), f = e.maxBytes ?? 256 * 1024 * 1024, b = e.embedDir ?? q(), d = (o) => e.integrators.find((s) => s.iss === o);
128
+ async function p(o, s, t, i, h = {}) {
129
+ const m = d(o.iss);
130
+ if (!m) throw new a(401, "unknown integrator");
131
+ const r = new URL(`${m.callbackUrl.replace(/\/$/, "")}/files/${encodeURIComponent(o.file)}${t}`), u = z(m.secret, s, r.pathname + r.search, i, { subject: o.sub, docKey: o.docKey }, l());
132
+ return c(r, { method: s, headers: { ...h, ...u }, ...i ? { body: i } : {} });
133
+ }
134
+ async function g(o, s) {
135
+ if (!o) throw new a(400, "no token");
136
+ let t;
137
+ try {
138
+ const w = d(M(o).iss);
139
+ if (!w) throw new A("unknown-key");
140
+ t = await V(o, w.keys, e.id, l());
141
+ } catch (w) {
142
+ throw new a(401, w instanceof A ? `open token refused: ${w.code}` : "open token refused");
143
+ }
144
+ const i = d(t.iss), h = { iss: t.iss, tenant: t.tenant, sub: t.sub, name: t.name, file: t.file, version: t.version, docKey: t.doc_key, perms: t.perms, watermark: t.watermark, kit: "", exp: 0 }, m = await p(h, "HEAD", "", null);
145
+ if (m.status === 404) throw new a(404, "no such file");
146
+ if (!m.ok) throw new a(502, `the integrator answered ${m.status}`);
147
+ const r = m.headers.get(_) || t.file, u = D(r).toLowerCase(), v = e.kits.find((w) => w.extensions.includes(u));
148
+ if (!v) throw new a(415, `no kit opens ${u || "this file"}`);
149
+ const U = { ...h, version: m.headers.get(E) ?? t.version, kit: v.id, exp: l() + (e.sessionTtl ?? 8 * 3600) }, x = N(16).toString("base64"), k = X({ session: Y(e.secret, U), claims: U, kitUrl: new URL(v.path, e.kitsUrl).href, embedModule: "/assets/embed/index.js", nonce: x, title: r });
150
+ s.writeHead(200, {
151
+ "content-type": "text/html; charset=utf-8",
152
+ "cache-control": "no-store",
153
+ "referrer-policy": "no-referrer",
154
+ "x-content-type-options": "nosniff",
155
+ "content-security-policy": [
156
+ "default-src 'none'",
157
+ `script-src 'self' 'nonce-${x}' 'wasm-unsafe-eval'`,
158
+ `style-src 'nonce-${x}'`,
159
+ "connect-src 'self'",
160
+ `frame-src ${n}`,
161
+ "img-src 'self' data: blob:",
162
+ "base-uri 'none'",
163
+ "form-action 'none'",
164
+ `frame-ancestors ${i.origins.length ? i.origins.join(" ") : "'none'"}`
165
+ ].join("; ")
166
+ }), s.end(k);
167
+ }
168
+ async function $(o, s, t) {
169
+ const i = /^Bearer (\S+)$/.exec(o.headers.authorization ?? "")?.[1], h = Q(e.secret, i, l());
170
+ if (!h) throw new a(401, "no session");
171
+ const m = h.perms.edit || h.perms.comment;
172
+ if (o.method === "GET" && t === "/v1/file") {
173
+ const r = await p(h, "GET", "", null);
174
+ if (!r.ok) throw new a(r.status === 404 ? 404 : 502, `the integrator answered ${r.status}`);
175
+ s.writeHead(200, { "content-type": "application/octet-stream", "cache-control": "no-store", [E]: r.headers.get(E) ?? "" }), s.end(Buffer.from(await r.arrayBuffer()));
176
+ return;
177
+ }
178
+ if (o.method === "GET" && t === "/v1/file/stamp") {
179
+ const r = await p(h, "HEAD", "", null);
180
+ if (r.status === 404) return j(s, 200, { version: null });
181
+ if (!r.ok) throw new a(502, `the integrator answered ${r.status}`);
182
+ return j(s, 200, { version: r.headers.get(E) });
183
+ }
184
+ if (o.method === "PUT" && (t === "/v1/file" || t === "/v1/replica")) {
185
+ if (!m) throw new a(403, "this session is read-only");
186
+ const r = await ee(o, f), u = t === "/v1/replica", v = {}, U = o.headers["if-match"];
187
+ !u && typeof U == "string" && (v["if-match"] = U);
188
+ const x = o.headers["x-kition-file-stamp"];
189
+ u && typeof x == "string" && (v["x-kition-file-stamp"] = x);
190
+ const k = await p(h, "PUT", u ? "/replica" : "", r, v);
191
+ if (k.status === 409) {
192
+ s.writeHead(409, { [E]: k.headers.get(E) ?? "" }), s.end();
193
+ return;
194
+ }
195
+ if (u && k.status === 501) throw new a(501, "the integrator keeps no replicas");
196
+ if (!k.ok) throw new a(502, `the integrator answered ${k.status}`);
197
+ const w = u ? {} : await k.json().catch(() => ({}));
198
+ if (!u && typeof w.version != "string") throw new a(502, "the integrator answered no version");
199
+ return j(s, 200, u ? {} : { version: w.version });
200
+ }
201
+ if (o.method === "GET" && t === "/v1/replica") {
202
+ const r = await p(h, "GET", "/replica", null);
203
+ if (r.status === 404 || r.status === 501) throw new a(r.status, "no replica");
204
+ if (!r.ok) throw new a(502, `the integrator answered ${r.status}`);
205
+ s.writeHead(200, { "content-type": "application/octet-stream", "cache-control": "no-store", "x-kition-file-stamp": r.headers.get("x-kition-file-stamp") ?? "" }), s.end(Buffer.from(await r.arrayBuffer()));
206
+ return;
207
+ }
208
+ throw new a(404, "not found");
209
+ }
210
+ async function y(o, s) {
211
+ const t = I(decodeURIComponent(o.slice(14)));
212
+ if (t.startsWith("..") || t.includes(`${S}..`) || t.startsWith(S)) throw new a(404, "not found");
213
+ const i = await O(B(b, t)).catch(() => null);
214
+ if (!i) throw new a(404, "not found");
215
+ s.writeHead(200, { "content-type": Z[D(t)] ?? "application/octet-stream", "x-content-type-options": "nosniff", "cache-control": "public, max-age=300" }), s.end(i);
216
+ }
217
+ return async function(s, t) {
218
+ try {
219
+ const i = new URL(s.url ?? "/", "http://service");
220
+ if (s.method === "GET" && i.pathname === "/v1/open") return await g(i.searchParams.get("token"), t);
221
+ if (i.pathname.startsWith("/v1/")) return await $(s, t, i.pathname);
222
+ if (s.method === "GET" && i.pathname.startsWith("/assets/embed/")) return await y(i.pathname, t);
223
+ throw new a(404, "not found");
224
+ } catch (i) {
225
+ const h = i instanceof a ? i.status : 500;
226
+ i instanceof a || console.error("[kition-doc-service]", i), t.headersSent ? t.end() : j(t, h, { error: i instanceof a ? i.message : "failed" });
227
+ }
228
+ };
229
+ }
230
+ function j(e, n, c) {
231
+ e.writeHead(n, { "content-type": "application/json", "cache-control": "no-store" }), e.end(JSON.stringify(c));
232
+ }
233
+ const P = (e, n, c) => new Promise((l, f) => {
234
+ e.once("error", f), e.listen(n, c, () => l(e.address().port));
235
+ });
236
+ async function le(e) {
237
+ const n = e.host ?? "127.0.0.1";
238
+ let c = null, l = e.kitsUrl;
239
+ if (e.kitsDir) {
240
+ const d = e.kitsDir;
241
+ c = H(async (g, $) => {
242
+ const y = I(decodeURIComponent(new URL(g.url ?? "/", "http://kits").pathname)).replace(/^[/\\]+/, ""), o = y.startsWith("..") || y.includes(`${S}..`) ? null : await O(B(d, y.endsWith(S) || !y ? B(y, "index.html") : y)).catch(() => null);
243
+ if (!o) {
244
+ $.writeHead(404).end();
245
+ return;
246
+ }
247
+ const s = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".mjs": "text/javascript", ".css": "text/css", ".wasm": "application/wasm", ".json": "application/json" }[D(y) || ".html"];
248
+ $.writeHead(200, { "content-type": s ?? "application/octet-stream", "x-content-type-options": "nosniff" }), $.end(o);
249
+ });
250
+ const p = await P(c, e.kitsPort ?? 0, n);
251
+ l ??= `http://${n}:${p}/`;
252
+ }
253
+ if (!l) throw new Error("kitsUrl or kitsDir is needed");
254
+ const f = H(te({ ...e, kitsUrl: l })), b = await P(f, e.port ?? 0, n);
255
+ return {
256
+ url: `http://${n}:${b}`,
257
+ kitsUrl: l,
258
+ close: async () => {
259
+ await new Promise((d) => f.close(d)), c && await new Promise((d) => c.close(d));
260
+ }
261
+ };
262
+ }
263
+ export {
264
+ he as CALLBACK_SKEW_SECS,
265
+ z as callbackHeaders,
266
+ te as createDocService,
267
+ Y as makeSession,
268
+ Q as readSession,
269
+ pe as signCallback,
270
+ le as startDocService,
271
+ ue as verifyCallback
272
+ };
package/dist/page.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The editor page the service answers `GET /v1/open` with: `@kition/embed` mounting the kit for the
3
+ * session's file, its storage provider the service's own `/v1/file` and `/v1/replica`, with the
4
+ * session as the bearer. Nothing in it is trusted by the service: every call is checked again.
5
+ */
6
+ import type { Session } from './session.js';
7
+ export type PageOptions = {
8
+ session: string;
9
+ claims: Session;
10
+ kitUrl: string;
11
+ embedModule: string;
12
+ nonce: string;
13
+ title: string;
14
+ };
15
+ export declare function editorPage({ session, claims, kitUrl, embedModule, nonce, title }: PageOptions): string;
@@ -0,0 +1,39 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type OpenTokenKey } from '@kition/sync/openToken';
3
+ export type Integrator = {
4
+ /** The issuer its open tokens name (`iss`). */
5
+ iss: string;
6
+ /** Its keys: each bound to its tenant and to `iss`. */
7
+ keys: OpenTokenKey[];
8
+ /** Where its callbacks are (`{callbackUrl}/files/{file}`). */
9
+ callbackUrl: string;
10
+ /** The secret callbacks are signed with (shared with the integrator). */
11
+ secret: string;
12
+ /** Origins allowed to frame the editor (`frame-ancestors`). */
13
+ origins: string[];
14
+ };
15
+ export type KitRoute = {
16
+ id: string;
17
+ path: string;
18
+ extensions: string[];
19
+ };
20
+ export type DocServiceConfig = {
21
+ /** The service's id: the `aud` its open tokens name. */
22
+ id: string;
23
+ /** Signs sessions; at least 32 characters, never shared. */
24
+ secret: string;
25
+ integrators: Integrator[];
26
+ /** Which kit opens which files, by name extension; `path` is the kit package under `kitsUrl`. */
27
+ kits: KitRoute[];
28
+ /** Where kit packages are served: another origin than the service's (EM4). */
29
+ kitsUrl: string;
30
+ /** `@kition/embed`'s built module directory (its `dist`); default: the installed `@kition/embed`'s. */
31
+ embedDir?: string;
32
+ /** A session's life, seconds (default 8 hours). */
33
+ sessionTtl?: number;
34
+ /** The largest document or replica a page may write, bytes (default 256 MiB). */
35
+ maxBytes?: number;
36
+ fetch?: typeof fetch;
37
+ now?: () => number;
38
+ };
39
+ export declare function createDocService(config: DocServiceConfig): (request: IncomingMessage, response: ServerResponse) => Promise<void>;
@@ -0,0 +1,22 @@
1
+ import type { OpenPerms } from '@kition/sync/openToken';
2
+ export type Session = {
3
+ /** The integrator (`iss`) and its tenant. */
4
+ iss: string;
5
+ tenant: string;
6
+ sub: string;
7
+ name: string;
8
+ file: string;
9
+ version: string;
10
+ docKey: string;
11
+ perms: OpenPerms;
12
+ watermark: {
13
+ text: string;
14
+ } | null;
15
+ /** The kit the page opens. */
16
+ kit: string;
17
+ /** Unix seconds. */
18
+ exp: number;
19
+ };
20
+ export declare function makeSession(secret: string, session: Session): string;
21
+ /** The session `token` names, or `null` when it is not one of ours, was changed, or expired. */
22
+ export declare function readSession(secret: string, token: string | null | undefined, now?: number): Session | null;
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@kition/doc-service",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "The Kits document service: serves single-user kit editor pages for iframe URLs carrying a signed open token, reading and writing through the integrator's HMAC-signed HTTP callbacks (URL embedding, L8).",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ },
12
+ "./callbacks": {
13
+ "types": "./dist/callbacks.d.ts",
14
+ "import": "./dist/callbacks.js"
15
+ }
16
+ },
17
+ "bin": {
18
+ "kition-doc-service": "./dist/cli.js"
19
+ },
20
+ "engines": {
21
+ "node": ">=20.6"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "dependencies": {
27
+ "@kition/sync": "0.1.0",
28
+ "@kition/embed": "0.1.0"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/KitionAI/kition-sdk.git",
33
+ "directory": "packages/doc-service"
34
+ },
35
+ "types": "./dist/index.d.ts",
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "main": "./dist/index.js",
40
+ "scripts": {
41
+ "build": "node ../../tools/build-package.mjs"
42
+ }
6
43
  }