@k9o/gate 0.0.0-stage → 1.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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0 — 2026-10-25
4
+
5
+ - Documentation rewritten with runnable examples and expected output; internal cross-references removed from the published sources. No change to the public API.
6
+
7
+ ## 1.0.0 — 2026-10-23
8
+
9
+ First public release. See the README for the full API overview.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Kilimanjaro SDK
2
+ Copyright 2026 Formelo Inc.
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,271 @@
1
- # Temporary Holding Version
1
+ # @k9o/gate
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
+ Identity for your app's end users on Kilimanjaro. Sign-up, sign-in, sessions, one-time codes, magic links and JWT verification.
4
+
5
+ ## Contents
6
+
7
+ - [Install](#install)
8
+ - [Quick start](#quick-start)
9
+ - [Client setup](#client-setup)
10
+ - [Signing users in](#signing-users-in)
11
+ - [Verifying tokens](#verifying-tokens)
12
+ - [Handling errors](#handling-errors)
13
+ - [Regional hosts](#regional-hosts)
14
+ - [Appendix](#appendix)
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @k9o/gate
20
+ ```
21
+
22
+ ```bash
23
+ bun add @k9o/gate
24
+ ```
25
+
26
+ ```bash
27
+ pnpm add @k9o/gate
28
+ ```
29
+
30
+ Requires Node.js 18+, Bun 1.1+ or a browser with a global `fetch`. See [Requirements](#requirements).
31
+
32
+ ## Quick start
33
+
34
+ ```ts
35
+ import { createGateClient } from "@k9o/gate";
36
+
37
+ const gate = createGateClient({
38
+ mode: "native",
39
+ baseUrl: "https://acme.api.k9o.io",
40
+ projectSlug: "member-portal",
41
+ });
42
+
43
+ const result = await gate.signIn({ email: "ada@example.com", password: "a-long-passphrase" });
44
+ const user = result.data.user;
45
+
46
+ console.log(user.email);
47
+ ```
48
+
49
+ ```text
50
+ ada@example.com
51
+ ```
52
+
53
+ Every method resolves to `{ data, meta }`.
54
+
55
+ ## Client setup
56
+
57
+ The client is bound to one project. See [Client options](#client-options) for every option.
58
+
59
+ | Option | Meaning |
60
+ | --- | --- |
61
+ | `mode` | `"native"` or `"standalone"`. Required. |
62
+ | `projectSlug` | The project whose end users you manage. Required. |
63
+ | `baseUrl` | Gateway host. Required. |
64
+
65
+ - `createGateClient` returns an independent client. Create one per tenant if you need several.
66
+ - Inside `@k9o/core`, the same client is `client.gate`. It reuses the core client's host, project and API key.
67
+ - To share one config, see [Shared configuration](#shared-configuration).
68
+
69
+ ## Signing users in
70
+
71
+ Create a user, then sign in with a password. The session holds the access and refresh tokens.
72
+
73
+ ```ts
74
+ const signedUp = await gate.signUp({ email: "grace@example.com", password: "another-long-passphrase" });
75
+ const session = signedUp.data.session;
76
+
77
+ const refreshed = await gate.refreshToken({ refreshToken: session.refreshToken });
78
+ ```
79
+
80
+ - Passwordless sign-in uses `passwordless.requestOtp` then `passwordless.verifyOtp`.
81
+ - Browser sign-in with a provider uses `signInWithProvider`.
82
+ - See [Methods](#methods) for everything else.
83
+
84
+ ```ts
85
+ await gate.passwordless.requestOtp({ email: "ada@example.com" });
86
+ const verified = await gate.passwordless.verifyOtp({ email: "ada@example.com", code: "123456" });
87
+ ```
88
+
89
+ A magic-link `redirectUrl` must exactly match an entry in the project's allowlist.
90
+
91
+ ## Verifying tokens
92
+
93
+ Backends can verify Gate tokens without creating a client. `verifyJwt` returns a result and does not throw for a bad token.
94
+
95
+ ```ts
96
+ import { verifyJwt } from "@k9o/gate";
97
+
98
+ const verification = await verifyJwt({
99
+ token: accessToken,
100
+ jwksUrl: "https://acme.api.k9o.io/@member-portal/gate/.well-known/jwks.json",
101
+ });
102
+
103
+ if (verification.valid) {
104
+ console.log(verification.claims.sub);
105
+ } else {
106
+ console.warn(verification.reason);
107
+ }
108
+ ```
109
+
110
+ - Set exactly one of `jwksUrl` or `jwks`. See [Verification options](#verification-options).
111
+ - A failed check returns one of the [Failure reasons](#failure-reasons).
112
+ - `requireScope(claims, scopes)` throws `RBAC_DENY` if a scope is missing.
113
+
114
+ ## Handling errors
115
+
116
+ Failures throw `GateError`. Switch on `code`.
117
+
118
+ ```ts
119
+ import { GateError } from "@k9o/gate";
120
+
121
+ try {
122
+ await gate.signIn({ email: "ada@example.com", password: "wrong" });
123
+ } catch (error) {
124
+ if (error instanceof GateError && error.code === "INVALID_CREDENTIALS") {
125
+ console.warn("Wrong email or password");
126
+ } else {
127
+ throw error;
128
+ }
129
+ }
130
+ ```
131
+
132
+ See [Error codes](#error-codes) for the full list. The full wire code is kept in `context.originalCode`.
133
+
134
+ ## Regional hosts
135
+
136
+ - On an organization host such as `https://acme.api.k9o.io`, the client sends one `HEAD` request first.
137
+ - The request carries no credentials. It finds the regional host for your organization.
138
+ - All later requests go to that host. The answer is cached.
139
+ - Any other `baseUrl` is used as given. If the lookup fails, the configured host is used.
140
+
141
+ ## Appendix
142
+
143
+ ### Requirements
144
+
145
+ | Requirement | Version |
146
+ | --- | --- |
147
+ | Node.js | 18 or newer |
148
+ | Bun | 1.1 or newer |
149
+ | TypeScript (optional) | 5.6 or newer |
150
+ | Browser | Any with a global `fetch` |
151
+
152
+ Token verification uses the `jose` library, which installs with the package.
153
+
154
+ ### Client options
155
+
156
+ | Option | Meaning |
157
+ | --- | --- |
158
+ | `mode` | `"native"` or `"standalone"`. Required. |
159
+ | `projectSlug` | The project whose end users you manage. Required. |
160
+ | `baseUrl` | Gateway host, such as `https://acme.api.k9o.io`. Required. |
161
+ | `partnerToken` | Bearer token sent with requests that need one. |
162
+ | `fetch` | Custom `fetch` implementation. |
163
+
164
+ An invalid `mode`, or a missing `projectSlug` or `baseUrl`, throws a `TypeError`.
165
+
166
+ ### Shared configuration
167
+
168
+ | Function | What it does |
169
+ | --- | --- |
170
+ | `configureGate(config)` | Sets the config used by the exported `gate` singleton. |
171
+ | `getGateConfig()` | Reads the shared config. |
172
+ | `resetGateConfig()` | Clears the shared config. |
173
+
174
+ ### Methods
175
+
176
+ | Method | What it does |
177
+ | --- | --- |
178
+ | `signUp({ email, password, displayName? })` | Creates an end user and a session. |
179
+ | `signIn({ email, password })` | Authenticates with a password. |
180
+ | `signOut({ refreshToken? })` | Revokes the current session. |
181
+ | `whoami()` | Returns the signed-in user. |
182
+ | `refreshToken({ refreshToken })` | Exchanges a refresh token for a new session. |
183
+ | `verifySession()` | Checks whether the current session is valid. |
184
+ | `hosted()` | Returns the hosted sign-in page and WebAuthn `rpId`. |
185
+ | `signInWithProvider({ provider, redirectUri })` | Sends the browser to a provider. |
186
+ | `parseSignInCallback(hash)` | Reads tokens from the redirect URL fragment. |
187
+ | `passwordless.requestOtp({ email, purpose? })` | Emails a one-time code. |
188
+ | `passwordless.verifyOtp({ email, code, purpose? })` | Redeems the code and returns a session. |
189
+ | `passwordless.requestMagicLink({ email, redirectUrl? })` | Emails a magic link. |
190
+ | `passwordless.verifyMagicLink(input)` | Redeems the link and returns a session. |
191
+ | `identityProviders` | Project admins create end-user identity providers. |
192
+ | `magicLinkRedirects` | Project admins manage the redirect allowlist. |
193
+
194
+ - `provider` is `"google"`, `"github"`, `"microsoft"`, `"oidc"` or `"saml"`.
195
+ - Generic OIDC is not wired yet. Use a hosted provider.
196
+
197
+ ### Token helpers
198
+
199
+ | Function | What it does |
200
+ | --- | --- |
201
+ | `verifyJwt(options)` | Verifies a token and returns a result. |
202
+ | `extractClaims(token)` | Decodes claims without verifying them. |
203
+ | `requireScope(claims, scopes)` | Throws `RBAC_DENY` if a scope is missing. |
204
+
205
+ ### Verification options
206
+
207
+ | Option | Meaning |
208
+ | --- | --- |
209
+ | `token` | The JWT to verify. |
210
+ | `jwksUrl` | Remote key set URL. Set this or `jwks`. |
211
+ | `jwks` | Inline key set. Set this or `jwksUrl`. |
212
+ | `expectedIssuer` | Required `iss` claim. |
213
+ | `expectedAudience` | Required `aud` claim. |
214
+ | `allowedAlgorithms` | Defaults to `RS256` and `ES256`. |
215
+ | `clockToleranceSeconds` | Defaults to 30. |
216
+
217
+ ### Failure reasons
218
+
219
+ | Reason | Meaning |
220
+ | --- | --- |
221
+ | `INVALID_SIGNATURE` | The signature does not match. |
222
+ | `EXPIRED` | The token has expired. |
223
+ | `NOT_YET_VALID` | The token is not valid yet. |
224
+ | `AUDIENCE_MISMATCH` | The audience differs. |
225
+ | `ISSUER_MISMATCH` | The issuer differs. |
226
+ | `MALFORMED` | The token cannot be parsed. |
227
+ | `ALGORITHM_NOT_ALLOWED` | The algorithm is not in the allowed list. |
228
+
229
+ ### Error fields
230
+
231
+ | Field | Meaning |
232
+ | --- | --- |
233
+ | `code` | Stable string. Switch on this. |
234
+ | `message` | Human-readable explanation. |
235
+ | `context` | Per-code details. |
236
+ | `recommendation` | Suggested next step. |
237
+
238
+ ### Error codes
239
+
240
+ Codes have no `K9O_` prefix.
241
+
242
+ | Code | Meaning |
243
+ | --- | --- |
244
+ | `UNAUTHENTICATED` | No valid credential was supplied. |
245
+ | `INVALID_CREDENTIALS` | Email or password is wrong. |
246
+ | `EMAIL_ALREADY_REGISTERED` | The email already has an account. |
247
+ | `INVALID_FIELD_VALUE` | Input failed validation. |
248
+ | `SESSION_EXPIRED` | The session has expired. |
249
+ | `REFRESH_TOKEN_INVALID` | The refresh token was rejected. |
250
+ | `RBAC_DENY` | The caller lacks a required role or scope. |
251
+ | `FORBIDDEN` | The caller may not do this. |
252
+ | `NOT_FOUND` | The resource does not exist. |
253
+ | `TIER_FEATURE_GATED` | The project's plan does not include this. |
254
+ | `GATE_REDIRECT_NOT_ALLOWED` | The redirect URL is not on the allowlist. |
255
+ | `POLICY_AUTHORING_AUTHORITY_INSUFFICIENT` | The caller may not author this policy. |
256
+ | `UPSTREAM_UNAVAILABLE` | The gateway could not be reached. |
257
+ | `INTERNAL_ERROR` | Unexpected failure, including unknown codes. |
258
+
259
+ ### Related packages
260
+
261
+ | Package | What it does |
262
+ | --- | --- |
263
+ | `@k9o/core` | The full platform client. Exposes this package as `client.gate`. |
264
+ | `@k9o/extensions` | Typed bindings for platform extensions. |
265
+ | `@k9o/kibo` | Vault and key operations. |
266
+
267
+ Platform apex: https://api.k9o.io. Documentation: https://kilimanjaro.dev.
268
+
269
+ ## License
270
+
271
+ Apache-2.0 © Formelo Inc. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,51 @@
1
+ // src/errors.ts
2
+ var GateError = class extends Error {
3
+ code;
4
+ context;
5
+ recommendation;
6
+ /** HTTP status the gateway returned (if the error came from a wire response). */
7
+ status;
8
+ constructor(init) {
9
+ super(init.message);
10
+ this.name = "GateError";
11
+ this.code = init.code;
12
+ this.context = Object.freeze({ ...init.context ?? {} });
13
+ this.recommendation = init.recommendation ?? null;
14
+ this.status = init.status ?? null;
15
+ }
16
+ };
17
+ function gateErrorFromWire(wire, status) {
18
+ const knownCodes = [
19
+ "UNAUTHENTICATED",
20
+ "INVALID_FIELD_VALUE",
21
+ "EMAIL_ALREADY_REGISTERED",
22
+ "INVALID_CREDENTIALS",
23
+ "SESSION_EXPIRED",
24
+ "REFRESH_TOKEN_INVALID",
25
+ "TIER_FEATURE_GATED",
26
+ "RBAC_DENY",
27
+ "FORBIDDEN",
28
+ "NOT_FOUND",
29
+ "GATE_REDIRECT_NOT_ALLOWED",
30
+ "POLICY_AUTHORING_AUTHORITY_INSUFFICIENT",
31
+ "UPSTREAM_UNAVAILABLE",
32
+ "INTERNAL_ERROR"
33
+ ];
34
+ const stripped = wire.code.replace(/^K9O_/, "");
35
+ const isKnown = knownCodes.includes(stripped);
36
+ const code = isKnown ? stripped : "INTERNAL_ERROR";
37
+ const context = { ...wire.context ?? {}, originalCode: wire.code };
38
+ return new GateError({
39
+ code,
40
+ message: wire.message,
41
+ context,
42
+ recommendation: wire.recommendation ?? null,
43
+ status
44
+ });
45
+ }
46
+
47
+ export {
48
+ GateError,
49
+ gateErrorFromWire
50
+ };
51
+ //# sourceMappingURL=chunk-JEV37YEC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Gate error shapes. `GateError` is `KError`-compatible —\n * downstream catch blocks can `instanceof GateError`-narrow without\n * importing the gateway's `KError` class directly (the SDK is a customer-\n * facing dependency; reaching across to the gateway's internal error\n * type would be a layering violation).\n *\n * The taxonomy below is the closed set; additions follow the\n * error-catalogue freeze cycle.\n */\n\n/**\n * Closed-taxonomy error code. Strings are the wire format —\n * camelCase-cased KError families per the convention.\n */\nexport type GateErrorCode =\n | \"UNAUTHENTICATED\"\n | \"INVALID_FIELD_VALUE\"\n | \"EMAIL_ALREADY_REGISTERED\"\n | \"INVALID_CREDENTIALS\"\n | \"SESSION_EXPIRED\"\n | \"REFRESH_TOKEN_INVALID\"\n | \"TIER_FEATURE_GATED\"\n | \"RBAC_DENY\"\n // FORBIDDEN + NOT_FOUND are surfaced by the gate.idpProviders.*\n // sub-namespaces (project-membership gate + resource-existence checks).\n | \"FORBIDDEN\"\n | \"NOT_FOUND\"\n // GATE_REDIRECT_NOT_ALLOWED — magic-link `redirectUrl` not in the project's\n // redirect allowlist (open-redirect-safe exact-match, per-project\n // allowlist capability).\n | \"GATE_REDIRECT_NOT_ALLOWED\"\n | \"POLICY_AUTHORING_AUTHORITY_INSUFFICIENT\"\n | \"UPSTREAM_UNAVAILABLE\"\n | \"INTERNAL_ERROR\";\n\n/**\n * Surface error thrown by the SDK. Mirrors the gateway's `KError` shape\n * — `code` (closed taxonomy), `message` (human-readable),\n * `context` (structured per-code payload), `recommendation` (action the\n * caller can take, or null when there's no canonical recommendation).\n */\nexport class GateError extends Error {\n readonly code: GateErrorCode;\n readonly context: Readonly<Record<string, unknown>>;\n readonly recommendation: string | null;\n /** HTTP status the gateway returned (if the error came from a wire response). */\n readonly status: number | null;\n\n constructor(init: {\n code: GateErrorCode;\n message: string;\n context?: Record<string, unknown>;\n recommendation?: string | null;\n status?: number | null;\n }) {\n super(init.message);\n this.name = \"GateError\";\n this.code = init.code;\n this.context = Object.freeze({ ...(init.context ?? {}) });\n this.recommendation = init.recommendation ?? null;\n this.status = init.status ?? null;\n }\n}\n\n/**\n * Wire-shape sentinel matching the gateway's `KError` JSON payload. The\n * client uses this to recognise gateway responses and rehydrate them\n * into a `GateError` instance with the right code + context preserved.\n */\nexport type KErrorWire = {\n code: string;\n message: string;\n context?: Record<string, unknown>;\n recommendation?: string | null;\n};\n\n/**\n * Narrow a wire `KError` to a strongly-typed `GateError`. Unknown codes\n * pass through as `INTERNAL_ERROR` with the original code preserved in\n * `context.originalCode` so consumers don't lose telemetry when the\n * server-side taxonomy outpaces the SDK's bundled enum.\n */\nexport function gateErrorFromWire(wire: KErrorWire, status: number): GateError {\n const knownCodes: ReadonlyArray<GateErrorCode> = [\n \"UNAUTHENTICATED\",\n \"INVALID_FIELD_VALUE\",\n \"EMAIL_ALREADY_REGISTERED\",\n \"INVALID_CREDENTIALS\",\n \"SESSION_EXPIRED\",\n \"REFRESH_TOKEN_INVALID\",\n \"TIER_FEATURE_GATED\",\n \"RBAC_DENY\",\n \"FORBIDDEN\",\n \"NOT_FOUND\",\n \"GATE_REDIRECT_NOT_ALLOWED\",\n \"POLICY_AUTHORING_AUTHORITY_INSUFFICIENT\",\n \"UPSTREAM_UNAVAILABLE\",\n \"INTERNAL_ERROR\",\n ];\n // Wire codes are platform-namespaced (`K9O_*`);\n // strip the prefix to match the SDK's bundled bare-code enum. The full wire\n // code is always preserved in `context.originalCode` for telemetry.\n const stripped = wire.code.replace(/^K9O_/, \"\");\n const isKnown = (knownCodes as ReadonlyArray<string>).includes(stripped);\n const code: GateErrorCode = isKnown ? (stripped as GateErrorCode) : \"INTERNAL_ERROR\";\n const context = { ...(wire.context ?? {}), originalCode: wire.code };\n return new GateError({\n code,\n message: wire.message,\n context,\n recommendation: wire.recommendation ?? null,\n status,\n });\n}\n"],"mappings":";AA0CO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAMT;AACD,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,OAAO,KAAK;AACjB,SAAK,UAAU,OAAO,OAAO,EAAE,GAAI,KAAK,WAAW,CAAC,EAAG,CAAC;AACxD,SAAK,iBAAiB,KAAK,kBAAkB;AAC7C,SAAK,SAAS,KAAK,UAAU;AAAA,EAC/B;AACF;AAoBO,SAAS,kBAAkB,MAAkB,QAA2B;AAC7E,QAAM,aAA2C;AAAA,IAC/C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAIA,QAAM,WAAW,KAAK,KAAK,QAAQ,SAAS,EAAE;AAC9C,QAAM,UAAW,WAAqC,SAAS,QAAQ;AACvE,QAAM,OAAsB,UAAW,WAA6B;AACpE,QAAM,UAAU,EAAE,GAAI,KAAK,WAAW,CAAC,GAAI,cAAc,KAAK,KAAK;AACnE,SAAO,IAAI,UAAU;AAAA,IACnB;AAAA,IACA,SAAS,KAAK;AAAA,IACd;AAAA,IACA,gBAAgB,KAAK,kBAAkB;AAAA,IACvC;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -0,0 +1,41 @@
1
+ // src/mode.ts
2
+ var _config = null;
3
+ function configureGate(config) {
4
+ validateGateConfig(config);
5
+ _config = { ...config };
6
+ }
7
+ function validateGateConfig(config) {
8
+ if (config.mode !== "standalone" && config.mode !== "native") {
9
+ throw new TypeError(
10
+ `Invalid Gate mode "${config.mode}"; expected "standalone" or "native"`
11
+ );
12
+ }
13
+ const hasSlug = typeof config.projectSlug === "string" && config.projectSlug.length > 0;
14
+ if (!hasSlug) {
15
+ throw new TypeError(
16
+ `Gate config missing projectSlug (required, slug grammar \u2014 project ids are internal-only and never customer-facing)`
17
+ );
18
+ }
19
+ if (typeof config.baseUrl !== "string" || config.baseUrl.length === 0) {
20
+ throw new TypeError(`Invalid baseUrl "${config.baseUrl}"; expected non-empty string`);
21
+ }
22
+ }
23
+ function getGateConfig() {
24
+ if (_config === null) {
25
+ throw new Error(
26
+ "@k9o/gate: SDK is not configured. Call configureGate({ mode, projectSlug, baseUrl }) before invoking gate functions."
27
+ );
28
+ }
29
+ return _config;
30
+ }
31
+ function resetGateConfig() {
32
+ _config = null;
33
+ }
34
+
35
+ export {
36
+ configureGate,
37
+ validateGateConfig,
38
+ getGateConfig,
39
+ resetGateConfig
40
+ };
41
+ //# sourceMappingURL=chunk-XP6U5QKF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mode.ts"],"sourcesContent":["/**\n * Standalone vs Native mode wiring.\n *\n * The SDK surface is identical across modes; mode determines gateway-\n * side behavior (whether the end-user row scope applies on read/write paths),\n * not SDK ergonomics. The mode boundary is a deployment-time decision\n *; the SDK does not branch behavior at function-call time.\n *\n * What mode affects (today + forward):\n *\n * - **Billing-identity routing** (commission callout):\n * Standalone customers are billed under the partner-credentialled\n * contract (Gate as Auth0/Clerk/Okta alternative — Trojan Horse\n * motion); Native customers compose with the broader Kilimanjaro\n * billing model. The SDK records the mode on every wire request via\n * the `X-Gate-Mode` header so the gateway routes consumption to the\n * correct billing surface without per-function branching.\n * - **Auto-scoping expectations** in marketing copy + docs hub copy\n * (per memory `feedback_gate_iak_brand_architecture.md` marketing-\n * honesty discipline). Standalone mode delivers Sovereign Ingress +\n * Hardware-Attested Identity + Forensic Attribution + Unlimited MAUs;\n * Native mode adds Automatic Identity-Aware Scoping on top.\n *\n * What mode does NOT affect:\n *\n * - Function names + signatures (identical across modes)\n * - Wire-envelope shape (identical)\n * - Error taxonomy (identical)\n */\n\n/**\n * Two-mode discriminant. The third candidate \"Hybrid\" was rejected per\n * memory `feedback_gate_iak_brand_architecture.md` — modes are\n * orthogonal deployment shapes, not interleaved.\n */\nexport type GateMode = \"standalone\" | \"native\";\n\n/**\n * Gate SDK configuration. Returned by `getGateConfig()` and consumed\n * internally by the HTTP client + JWT verifier. Set via `configureGate`\n * at process boot or per-test in unit tests.\n */\nexport type GateConfig = {\n mode: GateMode;\n /** Project slug per the URL grammar (e.g. `partner-console-staging`).\n * The only customer-facing project addressing form; routes resolve to\n * `/@<slug>/gate/...` (`feedback_slug_addressing_v2_5_68`). Required. */\n projectSlug: string;\n /** Gateway base URL — e.g. `https://<orgSlug>.api.k9o.io` per the URL grammar */\n baseUrl: string;\n /**\n * Optional partner-credentialled JWT for Standalone mode — used as the\n * default Authorization header when no per-call bearer is supplied.\n * Not required in Native mode; the gateway resolves credentials from\n * the standard project context.\n */\n partnerToken?: string;\n /**\n * Optional fetch override for testing + non-browser environments. The\n * SDK defaults to global `fetch` (available in Bun + Node 18+ +\n * browsers) when not set.\n */\n fetch?: typeof fetch;\n};\n\nlet _config: GateConfig | null = null;\n\n/**\n * Initialise the SDK. Must be called before any `gate.*` invocation.\n * Re-calling replaces the prior config wholesale (no per-field merge —\n * keeps the config-set-at-boot ergonomic clean).\n */\nexport function configureGate(config: GateConfig): void {\n validateGateConfig(config);\n _config = { ...config };\n}\n\n/**\n * Validate a config shape. Exposed for `createGateClient` so per-instance\n * configs go through identical checks as the singleton.\n */\nexport function validateGateConfig(config: GateConfig): void {\n if (config.mode !== \"standalone\" && config.mode !== \"native\") {\n throw new TypeError(\n `Invalid Gate mode \"${config.mode as string}\"; expected \"standalone\" or \"native\"`,\n );\n }\n const hasSlug = typeof config.projectSlug === \"string\" && config.projectSlug.length > 0;\n if (!hasSlug) {\n throw new TypeError(\n `Gate config missing projectSlug (required, slug grammar — project ids are internal-only and never customer-facing)`,\n );\n }\n if (typeof config.baseUrl !== \"string\" || config.baseUrl.length === 0) {\n throw new TypeError(`Invalid baseUrl \"${config.baseUrl}\"; expected non-empty string`);\n }\n}\n\n/**\n * Read the active config. Throws when called before `configureGate(...)`.\n * Tests can call `resetGateConfig()` to clear between cases.\n */\nexport function getGateConfig(): GateConfig {\n if (_config === null) {\n throw new Error(\n \"@k9o/gate: SDK is not configured. Call configureGate({ mode, projectSlug, baseUrl }) before invoking gate functions.\",\n );\n }\n return _config;\n}\n\n/** Reset the singleton — used by tests + by app-shutdown teardown paths. */\nexport function resetGateConfig(): void {\n _config = null;\n}\n"],"mappings":";AAiEA,IAAI,UAA6B;AAO1B,SAAS,cAAc,QAA0B;AACtD,qBAAmB,MAAM;AACzB,YAAU,EAAE,GAAG,OAAO;AACxB;AAMO,SAAS,mBAAmB,QAA0B;AAC3D,MAAI,OAAO,SAAS,gBAAgB,OAAO,SAAS,UAAU;AAC5D,UAAM,IAAI;AAAA,MACR,sBAAsB,OAAO,IAAc;AAAA,IAC7C;AAAA,EACF;AACA,QAAM,UAAU,OAAO,OAAO,gBAAgB,YAAY,OAAO,YAAY,SAAS;AACtF,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,MAAI,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,WAAW,GAAG;AACrE,UAAM,IAAI,UAAU,oBAAoB,OAAO,OAAO,8BAA8B;AAAA,EACtF;AACF;AAMO,SAAS,gBAA4B;AAC1C,MAAI,YAAY,MAAM;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,kBAAwB;AACtC,YAAU;AACZ;","names":[]}