@ferrule-io/ok-fine 0.0.0-stage → 0.3.6

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/LICENSE ADDED
@@ -0,0 +1,202 @@
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
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ # ok-fine
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
+ A knowledge repository for AI agents. ok-fine stores project knowledge as
4
+ [Open Knowledge Format (OKF) v0.2](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)
5
+ bundles and serves it over **MCP** (stdio or Streamable HTTP) and a **REST JSON API**, protected by OAuth 2.1 bearer tokens
6
+ from your own identity provider.
7
+
8
+ - One OKF bundle per project; one markdown concept per file with YAML frontmatter.
9
+ - Every change is a git commit, attributed to the writing agent or human, with optional two-way sync to a remote.
10
+ - Full-text keyword search (BM25), trust tiers (`unverified` → `machine-confirmed` → `human-reviewed`), staleness,
11
+ link graph, and OKF conformance linting.
12
+ - Ships as an npm package (`npx @ferrule-io/ok-fine`), a container image, and a Helm chart.
13
+
14
+ ## Quick start (local)
15
+
16
+ Requires Node.js 24+ and git. Add ok-fine to Claude Code as a local stdio server (knowledge lives in `~/.ok-fine`):
17
+
18
+ ```sh
19
+ claude mcp add --scope user ok-fine -- npx -y @ferrule-io/ok-fine
20
+ ```
21
+
22
+ Other harnesses: [Coding agents](https://github.com/ferrule-io/ok-fine/wiki/Coding-Agents#local-setup-stdio). Git
23
+ remotes, flags, and several concurrent sessions: [Running locally](https://github.com/ferrule-io/ok-fine/wiki/Running-Locally).
24
+
25
+ ### HTTP server (REST + MCP)
26
+
27
+ > **Warning:** `--no-auth` / `AUTH_MODE=none` disables authentication completely and gives every caller full admin access. Never expose it beyond localhost.
28
+
29
+ ```sh
30
+ npx -y @ferrule-io/ok-fine serve --no-auth
31
+ ```
32
+
33
+ Or with Docker (requires Docker):
34
+
35
+ ```sh
36
+ docker run --rm -p 127.0.0.1:8080:8080 -e AUTH_MODE=none -e PUBLIC_BASE_URL=http://localhost:8080 -v okf-data:/data ghcr.io/ferrule-io/ok-fine:latest
37
+ ```
38
+
39
+ Or, from a checkout, with Docker Compose (pulls the published image, or builds it from source when the pull fails):
40
+
41
+ ```sh
42
+ docker compose up -d
43
+ ```
44
+
45
+ Create a project, write a concept, and search:
46
+
47
+ ```sh
48
+ curl -s -X POST localhost:8080/api/v1/projects \
49
+ -H 'x-okf-actor: cli/1.0' \
50
+ -H 'content-type: application/json' \
51
+ -d '{"project":"demo","title":"Demo"}'
52
+
53
+ cat > orders.md <<'EOF'
54
+ ---
55
+ type: Reference
56
+ title: Orders
57
+ description: One row per completed customer order.
58
+ tags: [sales]
59
+ ---
60
+
61
+ # Orders
62
+
63
+ Joined with [customers](/tables/customers.md) on `customer_id`.
64
+ EOF
65
+
66
+ curl -s -X PUT localhost:8080/api/v1/projects/demo/concepts/tables/orders \
67
+ -H 'x-okf-actor: cli/1.0' \
68
+ -H 'content-type: text/markdown' --data-binary @orders.md
69
+
70
+ curl -s "localhost:8080/api/v1/search?q=orders"
71
+ ```
72
+
73
+ Next, [connect an MCP client](https://github.com/ferrule-io/ok-fine/wiki/Connecting-an-MCP-Client) to `http://localhost:8080/mcp`.
74
+
75
+ ## Documentation
76
+
77
+ The [wiki](https://github.com/ferrule-io/ok-fine/wiki) covers everything else:
78
+
79
+ - [Running locally](https://github.com/ferrule-io/ok-fine/wiki/Running-Locally): npm CLI, stdio, flags, git credentials
80
+ - [How it works](https://github.com/ferrule-io/ok-fine/wiki/How-It-Works): data layout, concepts, actors, trust tiers
81
+ - [Connecting an MCP client](https://github.com/ferrule-io/ok-fine/wiki/Connecting-an-MCP-Client)
82
+ - [Using ok-fine from coding agents](https://github.com/ferrule-io/ok-fine/wiki/Coding-Agents): agent package, lifecycle, per-harness setup
83
+ - [MCP tools](https://github.com/ferrule-io/ok-fine/wiki/MCP-Tools)
84
+ - [REST API](https://github.com/ferrule-io/ok-fine/wiki/REST-API)
85
+ - [Authentication and authorization](https://github.com/ferrule-io/ok-fine/wiki/Authentication-and-Authorization)
86
+ - [Git storage and remote sync](https://github.com/ferrule-io/ok-fine/wiki/Git-Storage-and-Remote-Sync)
87
+ - [Configuration](https://github.com/ferrule-io/ok-fine/wiki/Configuration): environment variables
88
+ - [Deploying with Helm](https://github.com/ferrule-io/ok-fine/wiki/Deploying-with-Helm)
89
+ - [Development](https://github.com/ferrule-io/ok-fine/wiki/Development): build, test, layout, CI and releases
90
+
91
+ ## License
92
+
93
+ [Apache License 2.0](LICENSE).
@@ -0,0 +1,56 @@
1
+ import { z } from "zod";
2
+ const DiscoveryMetadata = z
3
+ .object({
4
+ issuer: z.string(),
5
+ jwks_uri: z.string().optional(),
6
+ })
7
+ .passthrough();
8
+ /**
9
+ * Discovers authorization server metadata via RFC 8414 or OIDC Discovery.
10
+ * Candidate URLs in order:
11
+ * 1. origin + "/.well-known/oauth-authorization-server" + p (RFC 8414)
12
+ * 2. base + "/.well-known/openid-configuration" (OIDC)
13
+ */
14
+ export async function discoverAuthorizationServer(issuer, options) {
15
+ const timeoutMs = options?.timeoutMs ?? 5000;
16
+ const base = issuer.replace(/\/+$/, "");
17
+ const parsed = new URL(issuer);
18
+ const origin = parsed.origin;
19
+ const p = parsed.pathname.replace(/\/+$/, "");
20
+ const candidateUrls = [
21
+ `${origin}/.well-known/oauth-authorization-server${p}`,
22
+ `${base}/.well-known/openid-configuration`,
23
+ ];
24
+ let metadata = null;
25
+ let discoveredJwksUri;
26
+ for (const candidateUrl of candidateUrls) {
27
+ try {
28
+ const res = await fetch(candidateUrl, {
29
+ signal: AbortSignal.timeout(timeoutMs),
30
+ headers: { Accept: "application/json" },
31
+ });
32
+ if (res.status !== 200) {
33
+ continue;
34
+ }
35
+ const data = await res.json();
36
+ const parsedMeta = DiscoveryMetadata.safeParse(data);
37
+ if (parsedMeta.success && parsedMeta.data.issuer === issuer) {
38
+ metadata = parsedMeta.data;
39
+ discoveredJwksUri = parsedMeta.data.jwks_uri;
40
+ break;
41
+ }
42
+ }
43
+ catch {
44
+ // Try next candidate
45
+ }
46
+ }
47
+ if (!metadata) {
48
+ throw new Error(`authorization server discovery failed for ${issuer}`);
49
+ }
50
+ const jwksUri = options?.jwksUri ?? discoveredJwksUri;
51
+ if (!jwksUri) {
52
+ throw new Error(`authorization server discovery failed for ${issuer}: missing jwks_uri`);
53
+ }
54
+ return { metadata, jwksUri };
55
+ }
56
+ //# sourceMappingURL=discovery.js.map
@@ -0,0 +1,50 @@
1
+ import { bearerAuthChallengeResponse, OAuthError, OAuthErrorCode, verifyBearerToken, } from "@modelcontextprotocol/server";
2
+ import { principalFromAuthInfo } from "./verifier.js";
3
+ function makeChallengeResponse(error, requiredScopes, resourceMetadataUrl) {
4
+ const response = bearerAuthChallengeResponse(error, {
5
+ requiredScopes,
6
+ resourceMetadataUrl,
7
+ });
8
+ const authHeader = response.headers.get("www-authenticate");
9
+ if (authHeader && !authHeader.includes("scope=")) {
10
+ const scopeVal = requiredScopes.join(" ");
11
+ const updatedHeaders = new Headers(response.headers);
12
+ updatedHeaders.set("www-authenticate", `${authHeader}, scope="${scopeVal}"`);
13
+ return new Response(response.body, {
14
+ status: response.status,
15
+ statusText: response.statusText,
16
+ headers: updatedHeaders,
17
+ });
18
+ }
19
+ return response;
20
+ }
21
+ /**
22
+ * Creates an authenticator for HTTP requests that validates Bearer tokens
23
+ * against the verifier and produces standard RFC 9728 / RFC 6750 challenge responses.
24
+ */
25
+ export function createAuthenticator(options) {
26
+ const { verifier, resourceMetadataUrl, scopeNames } = options;
27
+ async function authenticate(authorizationHeader) {
28
+ try {
29
+ const authInfo = await verifyBearerToken(authorizationHeader, {
30
+ verifier,
31
+ resourceMetadataUrl,
32
+ });
33
+ const principal = principalFromAuthInfo(authInfo, scopeNames);
34
+ if (!principal.canRead) {
35
+ const response = makeChallengeResponse(new OAuthError(OAuthErrorCode.InsufficientScope, "token carries no ok-fine scope"), [scopeNames.read], resourceMetadataUrl);
36
+ return { ok: false, response };
37
+ }
38
+ return { ok: true, authInfo, principal };
39
+ }
40
+ catch (err) {
41
+ const response = makeChallengeResponse(err, [scopeNames.read, scopeNames.write], resourceMetadataUrl);
42
+ return { ok: false, response };
43
+ }
44
+ }
45
+ function insufficientScope(scopeName) {
46
+ return makeChallengeResponse(new OAuthError(OAuthErrorCode.InsufficientScope, `requires ${scopeName}`), [scopeName], resourceMetadataUrl);
47
+ }
48
+ return { authenticate, insufficientScope };
49
+ }
50
+ //# sourceMappingURL=http-auth.js.map
@@ -0,0 +1,133 @@
1
+ import { OAuthError, OAuthErrorCode } from "@modelcontextprotocol/server";
2
+ import { createRemoteJWKSet, errors, jwtVerify } from "jose";
3
+ /**
4
+ * Validates JWT access tokens against a remote JWKS.
5
+ */
6
+ export class JwtTokenVerifier {
7
+ issuer;
8
+ audiences;
9
+ identityClaims;
10
+ jwks;
11
+ constructor(options) {
12
+ this.issuer = options.issuer;
13
+ this.audiences = options.audiences;
14
+ this.identityClaims = options.identityClaims;
15
+ this.jwks = createRemoteJWKSet(new URL(options.jwksUri), {
16
+ cooldownDuration: 30000,
17
+ cacheMaxAge: 600000,
18
+ timeoutDuration: 5000,
19
+ });
20
+ }
21
+ async verifyAccessToken(token) {
22
+ let result;
23
+ try {
24
+ result = await jwtVerify(token, this.jwks, {
25
+ issuer: this.issuer,
26
+ audience: this.audiences,
27
+ clockTolerance: 30,
28
+ });
29
+ }
30
+ catch (err) {
31
+ if (err instanceof errors.JWTExpired) {
32
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "token expired");
33
+ }
34
+ if (err instanceof errors.JWTClaimValidationFailed) {
35
+ const claim = err.claim || "claim";
36
+ throw new OAuthError(OAuthErrorCode.InvalidToken, `invalid ${claim} claim`);
37
+ }
38
+ if (err instanceof errors.JWKSTimeout) {
39
+ throw new OAuthError(OAuthErrorCode.ServerError, "JWKS fetch timed out");
40
+ }
41
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "invalid token");
42
+ }
43
+ const payload = result.payload;
44
+ if (typeof payload.exp !== "number") {
45
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "token has no exp");
46
+ }
47
+ const scopeSet = new Set();
48
+ if (typeof payload.scope === "string") {
49
+ for (const s of payload.scope.trim().split(/\s+/)) {
50
+ if (s.length > 0) {
51
+ scopeSet.add(s);
52
+ }
53
+ }
54
+ }
55
+ if (typeof payload.scp === "string") {
56
+ for (const s of payload.scp.trim().split(/\s+/)) {
57
+ if (s.length > 0) {
58
+ scopeSet.add(s);
59
+ }
60
+ }
61
+ }
62
+ else if (Array.isArray(payload.scp)) {
63
+ for (const s of payload.scp) {
64
+ if (typeof s === "string" && s.trim().length > 0) {
65
+ scopeSet.add(s.trim());
66
+ }
67
+ }
68
+ }
69
+ if (Array.isArray(payload.permissions)) {
70
+ for (const p of payload.permissions) {
71
+ if (typeof p === "string" && p.trim().length > 0) {
72
+ scopeSet.add(p.trim());
73
+ }
74
+ }
75
+ }
76
+ const scopes = Array.from(scopeSet);
77
+ let clientId = "unknown";
78
+ for (const field of ["azp", "client_id", "cid"]) {
79
+ const val = payload[field];
80
+ if (typeof val === "string" && val.length > 0) {
81
+ clientId = val;
82
+ break;
83
+ }
84
+ }
85
+ let identity = null;
86
+ for (const claim of this.identityClaims) {
87
+ const val = payload[claim];
88
+ if (typeof val === "string" && val.trim().length > 0) {
89
+ identity = val.trim();
90
+ break;
91
+ }
92
+ }
93
+ return {
94
+ token,
95
+ clientId,
96
+ scopes,
97
+ expiresAt: payload.exp,
98
+ extra: {
99
+ sub: typeof payload.sub === "string" ? payload.sub : "unknown",
100
+ identity,
101
+ },
102
+ };
103
+ }
104
+ }
105
+ /**
106
+ * Computes a Principal from an AuthInfo and configured scope names.
107
+ * Hierarchy:
108
+ * - canAdmin = has admin scope
109
+ * - canWrite = write or admin
110
+ * - canRead = read, write, or admin
111
+ */
112
+ export function principalFromAuthInfo(info, scopeNames) {
113
+ const hasAdmin = info.scopes.includes(scopeNames.admin);
114
+ const hasWrite = info.scopes.includes(scopeNames.write);
115
+ const hasRead = info.scopes.includes(scopeNames.read);
116
+ const canAdmin = hasAdmin;
117
+ const canWrite = hasWrite || hasAdmin;
118
+ const canRead = hasRead || hasWrite || hasAdmin;
119
+ const extraSub = info.extra?.sub;
120
+ const extraIdentity = info.extra?.identity;
121
+ const sub = typeof extraSub === "string" ? extraSub : "unknown";
122
+ const identity = typeof extraIdentity === "string" ? extraIdentity : null;
123
+ return {
124
+ subject: sub,
125
+ clientId: info.clientId,
126
+ identity,
127
+ scopes: info.scopes,
128
+ canRead,
129
+ canWrite,
130
+ canAdmin,
131
+ };
132
+ }
133
+ //# sourceMappingURL=verifier.js.map
@@ -0,0 +1,99 @@
1
+ import { join, resolve } from "node:path";
2
+ import { parseArgs } from "node:util";
3
+ export const USAGE = `Usage: ok-fine [stdio|serve] [options]
4
+
5
+ Commands:
6
+ stdio (default) Serve MCP over stdin/stdout for one local client
7
+ serve Serve MCP and the REST API over HTTP
8
+
9
+ Options:
10
+ --data-dir <path> Knowledge repository location (DATA_DIR, default ~/.ok-fine)
11
+ --remote <url> Git remote to sync with, using your git credentials (GIT_REMOTE_URL)
12
+ --branch <name> Git branch (GIT_BRANCH, default main)
13
+ --sync-interval <sec> Periodic sync interval, 0 disables (GIT_SYNC_INTERVAL_SECONDS, default 60)
14
+ --log-level <level> fatal|error|warn|info|debug|trace|silent (LOG_LEVEL, default info)
15
+ -h, --help Show this help
16
+ -v, --version Print the version
17
+
18
+ serve options:
19
+ --port <port> PORT, default 8080
20
+ --host <addr> HOST, default 127.0.0.1
21
+ --public-base-url <url> PUBLIC_BASE_URL, default http://localhost:<port>
22
+ --no-auth AUTH_MODE=none: no authentication, every caller is admin; localhost only
23
+
24
+ Every variable in https://github.com/ferrule-io/ok-fine/wiki/Configuration also works; flags win.
25
+ `;
26
+ const FLAG_ENV = {
27
+ "data-dir": "DATA_DIR",
28
+ remote: "GIT_REMOTE_URL",
29
+ branch: "GIT_BRANCH",
30
+ "sync-interval": "GIT_SYNC_INTERVAL_SECONDS",
31
+ "log-level": "LOG_LEVEL",
32
+ port: "PORT",
33
+ host: "HOST",
34
+ "public-base-url": "PUBLIC_BASE_URL",
35
+ };
36
+ const SERVE_ONLY_FLAGS = ["port", "host", "public-base-url", "no-auth"];
37
+ /** Pure: maps argv and the process env to a command and the env its config loader reads. Throws on bad usage. */
38
+ export function parseCli(argv, env, homeDir) {
39
+ // --help/--version win over everything else, including unknown flags and bad commands.
40
+ const flags = argv.includes("--") ? argv.slice(0, argv.indexOf("--")) : argv;
41
+ if (flags.includes("--help") || flags.includes("-h"))
42
+ return { command: "help", env };
43
+ if (flags.includes("--version") || flags.includes("-v"))
44
+ return { command: "version", env };
45
+ const { values, positionals } = parseArgs({
46
+ args: argv,
47
+ allowPositionals: true,
48
+ strict: true,
49
+ options: {
50
+ "data-dir": { type: "string" },
51
+ remote: { type: "string" },
52
+ branch: { type: "string" },
53
+ "sync-interval": { type: "string" },
54
+ "log-level": { type: "string" },
55
+ port: { type: "string" },
56
+ host: { type: "string" },
57
+ "public-base-url": { type: "string" },
58
+ "no-auth": { type: "boolean" },
59
+ },
60
+ });
61
+ let command;
62
+ if (positionals.length === 0 || (positionals.length === 1 && positionals[0] === "stdio")) {
63
+ command = "stdio";
64
+ }
65
+ else if (positionals.length === 1 && positionals[0] === "serve") {
66
+ command = "serve";
67
+ }
68
+ else {
69
+ throw new Error(`unknown command "${positionals.join(" ")}"`);
70
+ }
71
+ if (command === "stdio") {
72
+ for (const name of SERVE_ONLY_FLAGS) {
73
+ if (values[name] !== undefined)
74
+ throw new Error(`--${name} only applies to "ok-fine serve"`);
75
+ }
76
+ }
77
+ const flagEnv = {};
78
+ for (const [flag, envName] of Object.entries(FLAG_ENV)) {
79
+ const value = values[flag];
80
+ if (typeof value === "string")
81
+ flagEnv[envName] = value;
82
+ }
83
+ const dataDirFlag = values["data-dir"];
84
+ if (dataDirFlag !== undefined) {
85
+ const expanded = dataDirFlag === "~" ? homeDir : dataDirFlag.startsWith("~/") ? join(homeDir, dataDirFlag.slice(2)) : dataDirFlag;
86
+ flagEnv.DATA_DIR = resolve(expanded);
87
+ }
88
+ if (values["no-auth"])
89
+ flagEnv.AUTH_MODE = "none";
90
+ const defaults = { DATA_DIR: join(homeDir, ".ok-fine") };
91
+ if (command === "serve")
92
+ defaults.HOST = "127.0.0.1";
93
+ const merged = { ...defaults, ...env, ...flagEnv };
94
+ if (command === "serve" && merged.PUBLIC_BASE_URL === undefined) {
95
+ merged.PUBLIC_BASE_URL = `http://localhost:${merged.PORT ?? "8080"}`;
96
+ }
97
+ return { command, env: merged };
98
+ }
99
+ //# sourceMappingURL=cli-options.js.map