@k9o/gate 0.0.0-stage → 1.0.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 +41 -0
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +110 -2
- package/dist/chunk-LZQ7MBXS.js +41 -0
- package/dist/chunk-LZQ7MBXS.js.map +1 -0
- package/dist/chunk-PEW6HZFB.js +51 -0
- package/dist/chunk-PEW6HZFB.js.map +1 -0
- package/dist/chunk-ZNFI2CQA.js +125 -0
- package/dist/chunk-ZNFI2CQA.js.map +1 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.js +9 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +717 -0
- package/dist/index.js +614 -0
- package/dist/index.js.map +1 -0
- package/dist/jwt.d.ts +84 -0
- package/dist/jwt.js +12 -0
- package/dist/jwt.js.map +1 -0
- package/dist/mode.d.ts +82 -0
- package/dist/mode.js +13 -0
- package/dist/mode.js.map +1 -0
- package/dist/types.d.ts +250 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -0
- package/package.json +59 -4
- package/src/client-factory.ts +39 -0
- package/src/client.ts +175 -0
- package/src/errors.ts +117 -0
- package/src/gate.ts +385 -0
- package/src/idp-providers/identity-providers.ts +244 -0
- package/src/index.ts +62 -0
- package/src/jwt.ts +229 -0
- package/src/magic-link-redirects.ts +103 -0
- package/src/mode.ts +115 -0
- package/src/paths.ts +21 -0
- package/src/region.ts +85 -0
- package/src/types.ts +264 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@k9o/gate` are documented here.
|
|
4
|
+
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
### Removed (breaking)
|
|
8
|
+
|
|
9
|
+
- `gate.idpProviders.ldap.credentials.{create, list, rotate, revoke}` and the types `LdapBridgeCredentialMetadata`, `CreateLdapCredentialInput`, `RotateLdapCredentialInput`, `ListLdapCredentialsOpts`, `RevokeResult` and `LdapCredentialsNamespace`. The four gateway routes they wrapped are retired (they answer 404), so the bindings are removed with them. `gate.idpProviders` no longer exists.
|
|
10
|
+
|
|
11
|
+
## [0.3.0] — v2.5.58 — LDAP-bridge sub-namespace
|
|
12
|
+
|
|
13
|
+
- `gate.idpProviders.ldap.credentials.{create, list, rotate, revoke}` sub-namespace
|
|
14
|
+
- Wraps the LDAP-bridge credentials gateway API shipped in `services/gateway` v2.5.57
|
|
15
|
+
- Type-safe bindings to the 4 endpoints under `/v2/projects/{projectId}/auth/idp-providers/{idpId}/ldap-credentials`
|
|
16
|
+
- New public types: `LdapBridgeCredentialMetadata` / `CreateLdapCredentialInput` / `RotateLdapCredentialInput` / `ListLdapCredentialsOpts` / `RevokeResult` / `LdapCredentialsNamespace`
|
|
17
|
+
- Closes the Gate Studio LDAPEditor standing blocker (step 3 of 3)
|
|
18
|
+
- Passwords are sent over TLS to the gateway, encrypted-at-rest via AES-256-GCM, and never returned to clients
|
|
19
|
+
|
|
20
|
+
## [0.2.1] — v2.5.56 — Shipping config
|
|
21
|
+
|
|
22
|
+
- Removed `"private": true`; package is now publishable (pending internal npm registry config; consumption via workspace path or git+subdirectory until then)
|
|
23
|
+
- Added `files` allowlist (src + README + CHANGELOG)
|
|
24
|
+
- Added `publishConfig.access = "restricted"` for future internal-registry publish
|
|
25
|
+
- Added `repository` field pointing at canonical k9o-core source
|
|
26
|
+
- Added per-module export entries (`./types`, `./errors`, `./jwt`, `./mode`) for tree-shake-friendly imports
|
|
27
|
+
- Added README "Installation" section with workspace + cross-repo git+subdirectory patterns
|
|
28
|
+
- No API change; 56/56 tests pass; tsc clean
|
|
29
|
+
|
|
30
|
+
## [0.2.0] — v2.5.21 — Marquee `gate.*` namespace
|
|
31
|
+
|
|
32
|
+
- `gate.signUp` / `gate.signIn` / `gate.signOut` / `gate.whoami` / `gate.refreshToken` / `gate.verifySession`
|
|
33
|
+
- Project-scoped `/v2/projects/{projectId}/gate/*` path family per ch01 §12.1
|
|
34
|
+
- Standalone vs Native mode plumbing (`configureGate` / `getGateConfig` / `resetGateConfig`)
|
|
35
|
+
- Standalone JWT primitives (`verifyJwt` / `extractClaims` / `requireScope`)
|
|
36
|
+
- `GateError` + closed `GateErrorCode` taxonomy per ch01 §2
|
|
37
|
+
|
|
38
|
+
## [0.1.0] — Pre-shipping baseline
|
|
39
|
+
|
|
40
|
+
- Initial package scaffold
|
|
41
|
+
- Type-only surface declarations
|
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
package/README.md
CHANGED
|
@@ -1,3 +1,111 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@k9o/gate`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Gate — the Identity-Aware Kernel SDK. The standalone identity capability that
|
|
4
|
+
Kilimanjaro v2 ships as both a standalone Auth0-parity surface and a composed
|
|
5
|
+
capability available through `@k9o/core` per ch01 §11 of the v2 idealised
|
|
6
|
+
specification.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
### Bun monorepo workspace (Kilimanjaro internal)
|
|
11
|
+
|
|
12
|
+
Add to the consumer's `package.json`:
|
|
13
|
+
|
|
14
|
+
```json
|
|
15
|
+
{
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@k9o/gate": "workspace:*"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
### Installing
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@k9o/gate": "^1.0.0"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Future npm install (post-launch)
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npm install @k9o/gate
|
|
36
|
+
# or
|
|
37
|
+
bun add @k9o/gate
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Internal npm registry publication is targeted post v2 launch.
|
|
41
|
+
|
|
42
|
+
This package implements the canonical Gate SDK surface declared in ch01 §12:
|
|
43
|
+
|
|
44
|
+
| Sub-namespace | At v0.1.0 |
|
|
45
|
+
| ----------------------------- | ------------------------------------------ |
|
|
46
|
+
| `gate.*` (marquee) | scaffolded — `signUp` / `signIn` / `signOut` / `whoami` / `refreshToken` / `verifySession` |
|
|
47
|
+
| `gate.passwordless.*` | scaffolded at v0.2.0 — `requestOtp` / `verifyOtp` / `requestMagicLink` / `verifyMagicLink` (gateway endpoints land in subsequent v2.4.x cycle) |
|
|
48
|
+
| `gate.social.*` | deferred to v0.2.x |
|
|
49
|
+
| `gate.passkeys.*` | deferred to v0.2.x |
|
|
50
|
+
| `gate.mfa.*` | deferred to v0.3.x |
|
|
51
|
+
| `gate.password.*` | deferred to v0.2.x |
|
|
52
|
+
| `gate.users.*` | deferred to v0.3.x |
|
|
53
|
+
| `gate.email.*` / `gate.sms.*` | deferred to v0.3.x |
|
|
54
|
+
| `gate.federation.*` | deferred (Ridge+ tier-gated; post-v1) |
|
|
55
|
+
| `gate.admin.*` | deferred to v0.3.x |
|
|
56
|
+
|
|
57
|
+
The package also ships standalone JWT-verification primitives (`verifyJwt`,
|
|
58
|
+
`extractClaims`, `requireScope`) for external apps consuming Gate-issued
|
|
59
|
+
tokens without the full SDK shape.
|
|
60
|
+
|
|
61
|
+
## Standalone vs Native mode
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { configureGate, gate } from "@k9o/gate";
|
|
65
|
+
|
|
66
|
+
// Standalone mode — Gate handles JWT issuance + verification only.
|
|
67
|
+
// Customer's data stays in their own infrastructure.
|
|
68
|
+
configureGate({
|
|
69
|
+
mode: "standalone",
|
|
70
|
+
projectId: "proj_abc123",
|
|
71
|
+
baseUrl: "https://api.k9o.io",
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// Native mode — calls run against Kilimanjaro Data Peak as the signed-in end
|
|
75
|
+
// user (composed import via @k9o/core is the typical entry; standalone import
|
|
76
|
+
// works too).
|
|
77
|
+
configureGate({
|
|
78
|
+
mode: "native",
|
|
79
|
+
projectId: "proj_abc123",
|
|
80
|
+
baseUrl: "https://api.k9o.io",
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const { data } = await gate.signIn({ email, password });
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
SDK ergonomics are identical across modes per ch01 §12.4; the mode boundary
|
|
87
|
+
is a deployment-time decision and not visible in the surface shape.
|
|
88
|
+
|
|
89
|
+
## Wire envelope
|
|
90
|
+
|
|
91
|
+
Every Gate function returns the standard envelope per ch01 §1:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
type Envelope<T> = { data: T; meta: Record<string, unknown> };
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Failures throw a `KError`-compatible object carrying the closed-taxonomy
|
|
98
|
+
`code` field per ch01 §2 — `GateError` is a typed subtype that downstream
|
|
99
|
+
catch blocks can `instanceof`-narrow without import friction.
|
|
100
|
+
|
|
101
|
+
## Compose with `@k9o/core`
|
|
102
|
+
|
|
103
|
+
Native customers reach the same surface via the composed entry:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { gate } from "@k9o/core"; // re-exports @k9o/gate per ch01 §11.2
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Both forms are equivalent at type level and runtime behavior. Standalone
|
|
110
|
+
customers install only `@k9o/gate`; Native-mode customers install
|
|
111
|
+
`@k9o/core` (which transitively requires the composed capabilities).
|
|
@@ -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, v2.5.68 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-LZQ7MBXS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mode.ts"],"sourcesContent":["/**\n * Standalone vs Native mode wiring per ch01 §12.4.\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 * per ch02; 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 per ch01 §1)\n * - Error taxonomy (identical per ch01 §2)\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 v2.5.68 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 v2.5.68 §5.4. */\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 per ch02.\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, v2.5.68 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":[]}
|
|
@@ -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-PEW6HZFB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Gate error shapes. `GateError` is `KError`-compatible per ch01 §2 —\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 v0.1.0 closed set; additions follow the\n * ch11 error-catalogue freeze cycle.\n */\n\n/**\n * Closed-taxonomy error code per ch01 §2. 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 added at v0.3.0 — surfaced by the\n // gate.idpProviders.* sub-namespaces (project-membership gate +\n // resource-existence checks per gateway v2.5.57 RBAC + NOT_FOUND\n // paths).\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 * per ch01 §2.1 — `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_*` per the ch11 error namespace);\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":";AA4CO,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,125 @@
|
|
|
1
|
+
import {
|
|
2
|
+
GateError
|
|
3
|
+
} from "./chunk-PEW6HZFB.js";
|
|
4
|
+
|
|
5
|
+
// src/jwt.ts
|
|
6
|
+
import { createRemoteJWKSet, jwtVerify, errors as joseErrors } from "jose";
|
|
7
|
+
var DEFAULT_ALLOWED_ALGORITHMS = ["RS256", "ES256"];
|
|
8
|
+
var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
|
|
9
|
+
async function verifyJwt(opts) {
|
|
10
|
+
if (opts.jwksUrl !== void 0 && opts.jwks !== void 0) {
|
|
11
|
+
throw new GateError({
|
|
12
|
+
code: "INVALID_FIELD_VALUE",
|
|
13
|
+
message: "verifyJwt: pass either jwksUrl OR jwks, not both",
|
|
14
|
+
context: {},
|
|
15
|
+
recommendation: null
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
if (opts.jwksUrl === void 0 && opts.jwks === void 0) {
|
|
19
|
+
throw new GateError({
|
|
20
|
+
code: "INVALID_FIELD_VALUE",
|
|
21
|
+
message: "verifyJwt: must pass exactly one of {jwksUrl, jwks}",
|
|
22
|
+
context: {},
|
|
23
|
+
recommendation: null
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const allowedAlgorithms = opts.allowedAlgorithms ?? DEFAULT_ALLOWED_ALGORITHMS;
|
|
27
|
+
const clockTolerance = opts.clockToleranceSeconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS;
|
|
28
|
+
let keyResolver;
|
|
29
|
+
if (opts.jwksUrl !== void 0) {
|
|
30
|
+
keyResolver = createRemoteJWKSet(new URL(opts.jwksUrl));
|
|
31
|
+
} else {
|
|
32
|
+
keyResolver = makeLocalJwksResolver(opts.jwks);
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
const result = await jwtVerify(opts.token, keyResolver, {
|
|
36
|
+
...opts.expectedIssuer !== void 0 ? { issuer: opts.expectedIssuer } : {},
|
|
37
|
+
...opts.expectedAudience !== void 0 ? { audience: opts.expectedAudience } : {},
|
|
38
|
+
algorithms: allowedAlgorithms,
|
|
39
|
+
clockTolerance
|
|
40
|
+
});
|
|
41
|
+
return { valid: true, claims: result.payload };
|
|
42
|
+
} catch (e) {
|
|
43
|
+
return { valid: false, reason: classifyJoseFailure(e) };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function extractClaims(token) {
|
|
47
|
+
const parts = token.split(".");
|
|
48
|
+
if (parts.length !== 3) {
|
|
49
|
+
throw new GateError({
|
|
50
|
+
code: "INVALID_FIELD_VALUE",
|
|
51
|
+
message: `Malformed JWT: expected 3 dot-separated parts, got ${parts.length}`,
|
|
52
|
+
context: {},
|
|
53
|
+
recommendation: null
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const payloadJson = base64UrlDecode(parts[1]);
|
|
58
|
+
return JSON.parse(payloadJson);
|
|
59
|
+
} catch (e) {
|
|
60
|
+
throw new GateError({
|
|
61
|
+
code: "INVALID_FIELD_VALUE",
|
|
62
|
+
message: `Malformed JWT payload: ${e instanceof Error ? e.message : String(e)}`,
|
|
63
|
+
context: {},
|
|
64
|
+
recommendation: null
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function requireScope(claims, requiredScopes) {
|
|
69
|
+
const present = new Set(claims.scopes ?? []);
|
|
70
|
+
const missing = requiredScopes.filter((s) => !present.has(s));
|
|
71
|
+
if (missing.length > 0) {
|
|
72
|
+
throw new GateError({
|
|
73
|
+
code: "RBAC_DENY",
|
|
74
|
+
message: `Required scopes missing: ${missing.join(", ")}`,
|
|
75
|
+
context: { missingScopes: missing, presentScopes: Array.from(present) },
|
|
76
|
+
recommendation: null
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function classifyJoseFailure(e) {
|
|
81
|
+
if (e instanceof joseErrors.JWSSignatureVerificationFailed) return "INVALID_SIGNATURE";
|
|
82
|
+
if (e instanceof joseErrors.JWTExpired) return "EXPIRED";
|
|
83
|
+
if (e instanceof joseErrors.JWTClaimValidationFailed) {
|
|
84
|
+
const claim = e.claim;
|
|
85
|
+
if (claim === "aud") return "AUDIENCE_MISMATCH";
|
|
86
|
+
if (claim === "iss") return "ISSUER_MISMATCH";
|
|
87
|
+
if (claim === "nbf") return "NOT_YET_VALID";
|
|
88
|
+
return "MALFORMED";
|
|
89
|
+
}
|
|
90
|
+
if (e instanceof joseErrors.JOSEAlgNotAllowed) return "ALGORITHM_NOT_ALLOWED";
|
|
91
|
+
return "MALFORMED";
|
|
92
|
+
}
|
|
93
|
+
function base64UrlDecode(input) {
|
|
94
|
+
const padded = input + "=".repeat((4 - input.length % 4) % 4);
|
|
95
|
+
const standard = padded.replace(/-/g, "+").replace(/_/g, "/");
|
|
96
|
+
const binary = globalThis.atob(standard);
|
|
97
|
+
const bytes = new Uint8Array(binary.length);
|
|
98
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
99
|
+
return new TextDecoder("utf-8").decode(bytes);
|
|
100
|
+
}
|
|
101
|
+
function makeLocalJwksResolver(jwks) {
|
|
102
|
+
return async (header) => {
|
|
103
|
+
const { importJWK } = await import("jose");
|
|
104
|
+
const kid = header.kid;
|
|
105
|
+
let match;
|
|
106
|
+
if (kid !== void 0) {
|
|
107
|
+
match = jwks.keys.find((k) => k["kid"] === kid);
|
|
108
|
+
}
|
|
109
|
+
if (match === void 0 && jwks.keys.length === 1) {
|
|
110
|
+
match = jwks.keys[0];
|
|
111
|
+
}
|
|
112
|
+
if (match === void 0) {
|
|
113
|
+
throw new joseErrors.JWKSNoMatchingKey("No matching key in inline JWKS for kid");
|
|
114
|
+
}
|
|
115
|
+
const alg = header.alg ?? match["alg"];
|
|
116
|
+
return importJWK(match, alg);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export {
|
|
121
|
+
verifyJwt,
|
|
122
|
+
extractClaims,
|
|
123
|
+
requireScope
|
|
124
|
+
};
|
|
125
|
+
//# sourceMappingURL=chunk-ZNFI2CQA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/jwt.ts"],"sourcesContent":["/**\n * JWT verification primitives for external-app standalone consumption.\n *\n * Standalone-mode customers consume Gate-issued JWTs in their own\n * application code without needing the full SDK shape — they just need\n * to verify the signature, extract claims, and (optionally) check\n * scopes. This module is the canonical entry for that surface.\n *\n * Backed by `jose` (already a peer dependency in the gateway via the\n * same library; chose `jose` for consistency + JWK fetch support out\n * of the box).\n *\n * Native-mode customers don't typically reach for this directly — the\n * gateway verifies project-issued tokens on every request and rehydrates\n * `subject.*` claims per ch06 §3.2. But the same primitives are\n * portable: Native customers running their own services downstream of\n * the gateway can verify Gate-issued JWTs identically.\n */\n\nimport { createRemoteJWKSet, jwtVerify, errors as joseErrors } from \"jose\";\nimport type { GateJwtClaims, VerifyJwtFailure, VerifyJwtResult } from \"./types.ts\";\nimport { GateError } from \"./errors.ts\";\n\n/**\n * Configuration for `verifyJwt`. The verifier can resolve signing keys\n * via either a remote JWKS URL (the typical Gate deployment shape) or\n * an inline key set (for tests + air-gapped deployments).\n */\nexport type VerifyJwtOptions = {\n token: string;\n /**\n * JWKS endpoint URL — the gateway exposes `/@<projectSlug>/gate/.well-known/jwks.json`\n * by convention. Either `jwksUrl` or `jwks` must be set; not both.\n */\n jwksUrl?: string;\n /**\n * Inline JWK set — used by tests + integration scenarios that want to\n * avoid the network hop. The shape is the standard JWKS `{keys: [...]}`\n * envelope; pass through unchanged to `jose`.\n */\n jwks?: { keys: ReadonlyArray<Record<string, unknown>> };\n /** Expected issuer (`iss` claim). Strict comparison. */\n expectedIssuer?: string;\n /** Expected audience (`aud` claim). Accepts either string or array per RFC 7519. */\n expectedAudience?: string;\n /**\n * Allowed signing algorithms. Defaults to `[\"RS256\", \"ES256\"]` per the\n * standard Gate issuer config. Reject anything outside this set\n * (defense against alg-confusion attacks).\n */\n allowedAlgorithms?: ReadonlyArray<string>;\n /**\n * Clock-skew tolerance in seconds. Defaults to 30. Applies to both\n * `exp` and `nbf` checks.\n */\n clockToleranceSeconds?: number;\n};\n\nconst DEFAULT_ALLOWED_ALGORITHMS = [\"RS256\", \"ES256\"] as const;\nconst DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;\n\n/**\n * Verify a Gate-issued JWT. Returns a typed result; does NOT throw on\n * verification failure (a `valid: false` result carries the reason).\n *\n * Throws `GateError` only when:\n * - `jwksUrl` and `jwks` are both unset or both set\n * - the JWKS fetch fails for transport reasons (UPSTREAM_UNAVAILABLE)\n */\nexport async function verifyJwt(opts: VerifyJwtOptions): Promise<VerifyJwtResult> {\n if (opts.jwksUrl !== undefined && opts.jwks !== undefined) {\n throw new GateError({\n code: \"INVALID_FIELD_VALUE\",\n message: \"verifyJwt: pass either jwksUrl OR jwks, not both\",\n context: {},\n recommendation: null,\n });\n }\n if (opts.jwksUrl === undefined && opts.jwks === undefined) {\n throw new GateError({\n code: \"INVALID_FIELD_VALUE\",\n message: \"verifyJwt: must pass exactly one of {jwksUrl, jwks}\",\n context: {},\n recommendation: null,\n });\n }\n\n const allowedAlgorithms = opts.allowedAlgorithms ?? DEFAULT_ALLOWED_ALGORITHMS;\n const clockTolerance = opts.clockToleranceSeconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS;\n\n let keyResolver: Parameters<typeof jwtVerify>[1];\n if (opts.jwksUrl !== undefined) {\n keyResolver = createRemoteJWKSet(new URL(opts.jwksUrl));\n } else {\n // Inline JWKS — implement the resolver inline since `jose`'s\n // `createLocalJWKSet` import path varies across versions.\n keyResolver = makeLocalJwksResolver(opts.jwks!);\n }\n\n try {\n const result = await jwtVerify(opts.token, keyResolver, {\n ...(opts.expectedIssuer !== undefined ? { issuer: opts.expectedIssuer } : {}),\n ...(opts.expectedAudience !== undefined ? { audience: opts.expectedAudience } : {}),\n algorithms: allowedAlgorithms as string[],\n clockTolerance,\n });\n return { valid: true, claims: result.payload as GateJwtClaims };\n } catch (e) {\n return { valid: false, reason: classifyJoseFailure(e) };\n }\n}\n\n/**\n * Extract claims from a JWT WITHOUT verifying the signature. Used by\n * SDK consumers that want to read claim data in client code where\n * signature verification has already happened at a trusted hop (e.g.,\n * a reverse proxy). Caller is responsible for confirming the upstream\n * trust path before consuming these claims for security decisions.\n *\n * Throws `GateError` on malformed input.\n */\nexport function extractClaims(token: string): GateJwtClaims {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n throw new GateError({\n code: \"INVALID_FIELD_VALUE\",\n message: `Malformed JWT: expected 3 dot-separated parts, got ${parts.length}`,\n context: {},\n recommendation: null,\n });\n }\n try {\n const payloadJson = base64UrlDecode(parts[1]!);\n return JSON.parse(payloadJson) as GateJwtClaims;\n } catch (e) {\n throw new GateError({\n code: \"INVALID_FIELD_VALUE\",\n message: `Malformed JWT payload: ${e instanceof Error ? e.message : String(e)}`,\n context: {},\n recommendation: null,\n });\n }\n}\n\n/**\n * Assert that the given claim set contains all of the required scopes.\n * Throws `GateError` with `code: \"RBAC_DENY\"` if any scope is missing.\n * Returns nothing on success — caller uses the throw-or-pass shape.\n */\nexport function requireScope(\n claims: GateJwtClaims,\n requiredScopes: ReadonlyArray<string>,\n): void {\n const present = new Set(claims.scopes ?? []);\n const missing = requiredScopes.filter((s) => !present.has(s));\n if (missing.length > 0) {\n throw new GateError({\n code: \"RBAC_DENY\",\n message: `Required scopes missing: ${missing.join(\", \")}`,\n context: { missingScopes: missing, presentScopes: Array.from(present) },\n recommendation: null,\n });\n }\n}\n\n// ----------------------------------------------------------------------\n// Internals\n// ----------------------------------------------------------------------\n\nfunction classifyJoseFailure(e: unknown): VerifyJwtFailure {\n // Map `jose`'s typed errors to our closed reason set per `VerifyJwtFailure`.\n if (e instanceof joseErrors.JWSSignatureVerificationFailed) return \"INVALID_SIGNATURE\";\n if (e instanceof joseErrors.JWTExpired) return \"EXPIRED\";\n if (e instanceof joseErrors.JWTClaimValidationFailed) {\n const claim = (e as { claim?: string }).claim;\n if (claim === \"aud\") return \"AUDIENCE_MISMATCH\";\n if (claim === \"iss\") return \"ISSUER_MISMATCH\";\n if (claim === \"nbf\") return \"NOT_YET_VALID\";\n return \"MALFORMED\";\n }\n if (e instanceof joseErrors.JOSEAlgNotAllowed) return \"ALGORITHM_NOT_ALLOWED\";\n // Fallback — `jose` raises other errors (parse failures, KID mismatches,\n // etc.) that we lump into `MALFORMED` rather than leaking the per-version\n // taxonomy.\n return \"MALFORMED\";\n}\n\nfunction base64UrlDecode(input: string): string {\n // Pad to a multiple of 4 + swap urlsafe alphabet -> standard alphabet.\n const padded = input + \"=\".repeat((4 - (input.length % 4)) % 4);\n const standard = padded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Bun + Node 18+ + browsers all expose `atob`.\n const binary = globalThis.atob(standard);\n // Reassemble bytes back to UTF-8 text.\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder(\"utf-8\").decode(bytes);\n}\n\n/**\n * Build a key resolver compatible with `jose.jwtVerify` from an inline\n * JWKS object. `jose` exports `createLocalJWKSet` from its main module\n * but the import path / type shape can shift across minors; reimplement\n * the minimal resolver here for stability.\n */\nfunction makeLocalJwksResolver(\n jwks: { keys: ReadonlyArray<Record<string, unknown>> },\n): Parameters<typeof jwtVerify>[1] {\n // The `jose` resolver signature is `(header, token) => Promise<KeyLike>`\n // — pull the kid from the header, match against the JWKS, and import.\n return async (header) => {\n const { importJWK } = await import(\"jose\");\n const kid = (header as { kid?: string }).kid;\n let match: Record<string, unknown> | undefined;\n if (kid !== undefined) {\n match = jwks.keys.find((k) => k[\"kid\"] === kid);\n }\n if (match === undefined && jwks.keys.length === 1) {\n // Single-key JWKS — return the only key. Tests typically ship one\n // key in the inline set and may not bother with `kid`.\n match = jwks.keys[0];\n }\n if (match === undefined) {\n throw new joseErrors.JWKSNoMatchingKey(\"No matching key in inline JWKS for kid\");\n }\n const alg = (header as { alg?: string }).alg ?? (match[\"alg\"] as string | undefined);\n return importJWK(match as unknown as Parameters<typeof importJWK>[0], alg);\n };\n}\n"],"mappings":"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","names":[]}
|