@k9o/gate 1.0.0 → 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 +4 -36
- package/README.md +236 -76
- package/dist/{chunk-PEW6HZFB.js → chunk-JEV37YEC.js} +1 -1
- package/dist/chunk-JEV37YEC.js.map +1 -0
- package/dist/{chunk-LZQ7MBXS.js → chunk-XP6U5QKF.js} +2 -2
- package/dist/chunk-XP6U5QKF.js.map +1 -0
- package/dist/{chunk-ZNFI2CQA.js → chunk-YINWOWJC.js} +2 -2
- package/dist/chunk-YINWOWJC.js.map +1 -0
- package/dist/errors.d.ts +5 -5
- package/dist/errors.js +1 -1
- package/dist/index.d.ts +28 -30
- package/dist/index.js +14 -15
- package/dist/index.js.map +1 -1
- package/dist/jwt.d.ts +1 -1
- package/dist/jwt.js +2 -2
- package/dist/mode.d.ts +7 -7
- package/dist/mode.js +1 -1
- package/dist/types.d.ts +21 -21
- package/package.json +1 -1
- package/src/client-factory.ts +2 -2
- package/src/client.ts +4 -4
- package/src/errors.ts +8 -10
- package/src/gate.ts +14 -15
- package/src/idp-providers/identity-providers.ts +7 -7
- package/src/index.ts +1 -1
- package/src/jwt.ts +1 -1
- package/src/mode.ts +8 -8
- package/src/paths.ts +1 -1
- package/src/types.ts +21 -21
- package/dist/chunk-LZQ7MBXS.js.map +0 -1
- package/dist/chunk-PEW6HZFB.js.map +0 -1
- package/dist/chunk-ZNFI2CQA.js.map +0 -1
package/dist/mode.js
CHANGED
package/dist/types.d.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@k9o/gate`
|
|
2
|
+
* `@k9o/gate` — public type surface.
|
|
3
3
|
*
|
|
4
|
-
* The shapes here track
|
|
5
|
-
* prefix
|
|
6
|
-
*
|
|
4
|
+
* The shapes here track verbatim. End-user IDs carry the `eu_`
|
|
5
|
+
* prefix; role and group identifiers compose against the
|
|
6
|
+
* role lattice (Trust-Zone-separate `PROJECT_END_USER` for project-
|
|
7
7
|
* level end-user identities). Sessions, passkeys, MFA factors, federation
|
|
8
8
|
* links, and the rest of the Gate-managed resources receive their per-
|
|
9
|
-
* resource prefixes as the
|
|
9
|
+
* resource prefixes as the end-user table family is specified.
|
|
10
10
|
*
|
|
11
|
-
* Envelope shape (`data` + `meta`) matches
|
|
11
|
+
* Envelope shape (`data` + `meta`) matches; failures land via
|
|
12
12
|
* the `GateError` family per `errors.ts`, which is `KError`-compatible
|
|
13
|
-
|
|
13
|
+
*.
|
|
14
14
|
*/
|
|
15
15
|
/**
|
|
16
|
-
* Standard
|
|
16
|
+
* Standard envelope. Generic over the `data` shape per function.
|
|
17
17
|
* Returned by every successful SDK call.
|
|
18
18
|
*/
|
|
19
19
|
type Envelope<T> = {
|
|
@@ -21,21 +21,21 @@ type Envelope<T> = {
|
|
|
21
21
|
meta: Record<string, unknown>;
|
|
22
22
|
};
|
|
23
23
|
/**
|
|
24
|
-
* Project-level end-user identity (the customers OF the customer
|
|
25
|
-
*
|
|
26
|
-
* `eu_<base62>` prefix
|
|
24
|
+
* Project-level end-user identity (the customers OF the customer as
|
|
25
|
+
* the `PROJECT_END_USER` 7th canonical role). End-user IDs carry the
|
|
26
|
+
* `eu_<base62>` prefix.
|
|
27
27
|
*/
|
|
28
28
|
type EndUser = {
|
|
29
|
-
/** `eu_<base62>` — see
|
|
29
|
+
/** `eu_<base62>` — see. */
|
|
30
30
|
id: string;
|
|
31
31
|
email: string;
|
|
32
32
|
status: "active" | "pending" | "disabled";
|
|
33
33
|
createdAt: string;
|
|
34
34
|
updatedAt: string | null;
|
|
35
35
|
lastSigninAt: string | null;
|
|
36
|
-
/** Project-level roles
|
|
36
|
+
/** Project-level roles; `PROJECT_END_USER` is the floor membership. */
|
|
37
37
|
roles: ReadonlyArray<string>;
|
|
38
|
-
/** Project-level group memberships
|
|
38
|
+
/** Project-level group memberships `_sys.end_user_groups`. */
|
|
39
39
|
groups: ReadonlyArray<string>;
|
|
40
40
|
};
|
|
41
41
|
/**
|
|
@@ -52,7 +52,7 @@ type Session = {
|
|
|
52
52
|
expiresAt: string;
|
|
53
53
|
};
|
|
54
54
|
/**
|
|
55
|
-
* Marquee sign-up / sign-in shape
|
|
55
|
+
* Marquee sign-up / sign-in shape:
|
|
56
56
|
* `{ user, session }`
|
|
57
57
|
*/
|
|
58
58
|
type AuthResult = {
|
|
@@ -60,7 +60,7 @@ type AuthResult = {
|
|
|
60
60
|
session: Session;
|
|
61
61
|
};
|
|
62
62
|
/**
|
|
63
|
-
* `gate.whoami()` shape
|
|
63
|
+
* `gate.whoami()` shape:
|
|
64
64
|
* `{ user }` — no fresh session is minted by `whoami` (it reflects the
|
|
65
65
|
* caller's current session).
|
|
66
66
|
*/
|
|
@@ -116,7 +116,7 @@ type OtpPurpose = "signin" | "magic_link" | "password_reset" | "mfa_challenge";
|
|
|
116
116
|
/**
|
|
117
117
|
* `gate.passwordless.requestOtp` input — emails an OTP code to the
|
|
118
118
|
* given address. Idempotent at the per-email rate-limit ceiling per
|
|
119
|
-
* the
|
|
119
|
+
* the platform anti-abuse policy.
|
|
120
120
|
*/
|
|
121
121
|
type RequestOtpInput = {
|
|
122
122
|
email: string;
|
|
@@ -144,7 +144,7 @@ type RequestMagicLinkInput = {
|
|
|
144
144
|
email: string;
|
|
145
145
|
/**
|
|
146
146
|
* Post-redeem landing URL. When supplied it MUST exact-match an entry in
|
|
147
|
-
* the project's magic-link redirect allowlist (Gate config
|
|
147
|
+
* the project's magic-link redirect allowlist (Gate config); a
|
|
148
148
|
* non-allowlisted value is rejected with `GATE_REDIRECT_NOT_ALLOWED` (400).
|
|
149
149
|
* Omit to use the project's configured default redirect.
|
|
150
150
|
*/
|
|
@@ -171,7 +171,7 @@ type MagicLinkCallbackResult = {
|
|
|
171
171
|
error: string;
|
|
172
172
|
};
|
|
173
173
|
/**
|
|
174
|
-
* JWT claim shape that `verifyJwt` resolves. Mirrors
|
|
174
|
+
* JWT claim shape that `verifyJwt` resolves. Mirrors `subject.*`
|
|
175
175
|
* exposure for project-level JWTs plus the Gate-issued audience / issuer
|
|
176
176
|
* standard claims. Customer apps in Standalone mode consume this via the
|
|
177
177
|
* `verifyJwt` helper without needing the full SDK shape.
|
|
@@ -189,9 +189,9 @@ type GateJwtClaims = {
|
|
|
189
189
|
exp: number;
|
|
190
190
|
/** JWT id (for revocation tracking + idempotency). */
|
|
191
191
|
jti?: string;
|
|
192
|
-
/** Project-level role array
|
|
192
|
+
/** Project-level role array; floor is `PROJECT_END_USER`. */
|
|
193
193
|
roles?: ReadonlyArray<string>;
|
|
194
|
-
/** Project-level group memberships
|
|
194
|
+
/** Project-level group memberships. */
|
|
195
195
|
groups?: ReadonlyArray<string>;
|
|
196
196
|
/** Project-level scope strings — used by `requireScope`. */
|
|
197
197
|
scopes?: ReadonlyArray<string>;
|
package/package.json
CHANGED
package/src/client-factory.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `createGateClient(config)` — per-instance Gate SDK factory
|
|
2
|
+
* `createGateClient(config)` — per-instance Gate SDK factory.
|
|
3
3
|
*
|
|
4
4
|
* Returns a self-contained `GateClient` that does not depend on the
|
|
5
5
|
* module-level `configureGate()` singleton. Multiple clients can coexist
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* incoming request's resolved tenant) or for apps that maintain both a
|
|
9
9
|
* Standalone and Native binding against the same SDK instance.
|
|
10
10
|
*
|
|
11
|
-
* Per
|
|
11
|
+
* Per the URL grammar, supply `projectSlug` for
|
|
12
12
|
* canonical `/@<slug>/gate/...` routing. Slug is the only customer-facing
|
|
13
13
|
* project addressing form — project ids are internal-only
|
|
14
14
|
* (`feedback_slug_addressing_v2_5_68`); the retired `/v2/projects/...`
|
package/src/client.ts
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Centralises:
|
|
5
5
|
* - URL construction against the configured `baseUrl` + per-call path
|
|
6
|
-
* - the standard
|
|
7
|
-
* - the standard
|
|
6
|
+
* - the standard envelope unwrap on success
|
|
7
|
+
* - the standard `KError` rehydration on failure via `gateErrorFromWire`
|
|
8
8
|
* - mode-routing via the `X-Gate-Mode` header (so the gateway routes
|
|
9
9
|
* consumption to the right billing surface without per-function
|
|
10
10
|
* branching at the SDK)
|
|
@@ -47,7 +47,7 @@ export type RequestInit = {
|
|
|
47
47
|
* keeps the SDK portable across Bun + Node 18+ + browsers + test
|
|
48
48
|
* fixtures that supply a stub.
|
|
49
49
|
* - JSON parsing of non-JSON responses throws — gateway always returns
|
|
50
|
-
* JSON
|
|
50
|
+
* JSON +, so a parse failure is an upstream defect.
|
|
51
51
|
*/
|
|
52
52
|
export async function request<T>(init: RequestInit): Promise<Envelope<T>> {
|
|
53
53
|
return requestWith<T>(getGateConfig(), init);
|
|
@@ -130,7 +130,7 @@ export async function requestWith<T>(
|
|
|
130
130
|
return parsed;
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
-
// Non-2xx: the gateway returns a KError-shaped JSON payload
|
|
133
|
+
// Non-2xx: the gateway returns a KError-shaped JSON payload.
|
|
134
134
|
if (isKErrorWire(parsed)) {
|
|
135
135
|
throw gateErrorFromWire(parsed, response.status);
|
|
136
136
|
}
|
package/src/errors.ts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Gate error shapes. `GateError` is `KError`-compatible
|
|
2
|
+
* Gate error shapes. `GateError` is `KError`-compatible —
|
|
3
3
|
* downstream catch blocks can `instanceof GateError`-narrow without
|
|
4
4
|
* importing the gateway's `KError` class directly (the SDK is a customer-
|
|
5
5
|
* facing dependency; reaching across to the gateway's internal error
|
|
6
6
|
* type would be a layering violation).
|
|
7
7
|
*
|
|
8
|
-
* The taxonomy below is the
|
|
9
|
-
*
|
|
8
|
+
* The taxonomy below is the closed set; additions follow the
|
|
9
|
+
* error-catalogue freeze cycle.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* Closed-taxonomy error code
|
|
13
|
+
* Closed-taxonomy error code. Strings are the wire format —
|
|
14
14
|
* camelCase-cased KError families per the convention.
|
|
15
15
|
*/
|
|
16
16
|
export type GateErrorCode =
|
|
@@ -22,10 +22,8 @@ export type GateErrorCode =
|
|
|
22
22
|
| "REFRESH_TOKEN_INVALID"
|
|
23
23
|
| "TIER_FEATURE_GATED"
|
|
24
24
|
| "RBAC_DENY"
|
|
25
|
-
// FORBIDDEN + NOT_FOUND
|
|
26
|
-
//
|
|
27
|
-
// resource-existence checks per gateway v2.5.57 RBAC + NOT_FOUND
|
|
28
|
-
// paths).
|
|
25
|
+
// FORBIDDEN + NOT_FOUND are surfaced by the gate.idpProviders.*
|
|
26
|
+
// sub-namespaces (project-membership gate + resource-existence checks).
|
|
29
27
|
| "FORBIDDEN"
|
|
30
28
|
| "NOT_FOUND"
|
|
31
29
|
// GATE_REDIRECT_NOT_ALLOWED — magic-link `redirectUrl` not in the project's
|
|
@@ -38,7 +36,7 @@ export type GateErrorCode =
|
|
|
38
36
|
|
|
39
37
|
/**
|
|
40
38
|
* Surface error thrown by the SDK. Mirrors the gateway's `KError` shape
|
|
41
|
-
*
|
|
39
|
+
* — `code` (closed taxonomy), `message` (human-readable),
|
|
42
40
|
* `context` (structured per-code payload), `recommendation` (action the
|
|
43
41
|
* caller can take, or null when there's no canonical recommendation).
|
|
44
42
|
*/
|
|
@@ -100,7 +98,7 @@ export function gateErrorFromWire(wire: KErrorWire, status: number): GateError {
|
|
|
100
98
|
"UPSTREAM_UNAVAILABLE",
|
|
101
99
|
"INTERNAL_ERROR",
|
|
102
100
|
];
|
|
103
|
-
// Wire codes are platform-namespaced (`K9O_*`
|
|
101
|
+
// Wire codes are platform-namespaced (`K9O_*`);
|
|
104
102
|
// strip the prefix to match the SDK's bundled bare-code enum. The full wire
|
|
105
103
|
// code is always preserved in `context.originalCode` for telemetry.
|
|
106
104
|
const stripped = wire.code.replace(/^K9O_/, "");
|
package/src/gate.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Marquee `gate.*` namespace
|
|
2
|
+
* Marquee `gate.*` namespace.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* surfaces (canonical slug routing — `<orgSlug>.api.k9o.io/@<projectSlug>/...`):
|
|
5
5
|
* - `gate.signUp` — POST /@<projectSlug>/gate/signup
|
|
6
6
|
* - `gate.signIn` — POST /@<projectSlug>/gate/signin
|
|
7
7
|
* - `gate.signOut` — POST /@<projectSlug>/gate/signout
|
|
@@ -15,9 +15,9 @@
|
|
|
15
15
|
* cycles per the README catalogue.
|
|
16
16
|
*
|
|
17
17
|
* Wire shape: every function returns the standard envelope
|
|
18
|
-
* `{ data, meta }`
|
|
18
|
+
* `{ data, meta }` and throws a `GateError` on non-2xx
|
|
19
19
|
* gateway responses. Native vs Standalone mode does not affect SDK
|
|
20
|
-
* ergonomics
|
|
20
|
+
* ergonomics; the mode header is set internally by the
|
|
21
21
|
* client + does not surface in the function-call ergonomics.
|
|
22
22
|
*
|
|
23
23
|
* Endpoint paths are reconciled to the LIVE gateway routes (verified
|
|
@@ -61,10 +61,10 @@ export function makeGateNamespace(getConfig: () => GateConfig) {
|
|
|
61
61
|
return {
|
|
62
62
|
/**
|
|
63
63
|
* Create a new end-user identity for the configured project. Returns
|
|
64
|
-
* the new user record + an initial session
|
|
65
|
-
* `data.write.auth.signup` audit event
|
|
64
|
+
* the new user record + an initial session. Emits a
|
|
65
|
+
* `data.write.auth.signup` audit event.
|
|
66
66
|
*
|
|
67
|
-
* Errors (closed taxonomy
|
|
67
|
+
* Errors (closed taxonomy):
|
|
68
68
|
* - `EMAIL_ALREADY_REGISTERED` (409) when the email collides
|
|
69
69
|
* - `INVALID_FIELD_VALUE` (400) on schema violation (password policy, malformed email)
|
|
70
70
|
* - `TIER_FEATURE_GATED` (403) when the project's tier blocks email/password
|
|
@@ -254,7 +254,7 @@ export function makeGateNamespace(getConfig: () => GateConfig) {
|
|
|
254
254
|
},
|
|
255
255
|
|
|
256
256
|
/**
|
|
257
|
-
* Passwordless sub-namespace
|
|
257
|
+
* Passwordless sub-namespace — OTP + Magic Link flows
|
|
258
258
|
* for email-based authentication without a stored password.
|
|
259
259
|
*
|
|
260
260
|
* Wire endpoints (LIVE on the Gate end-user plane — verified against
|
|
@@ -263,13 +263,12 @@ export function makeGateNamespace(getConfig: () => GateConfig) {
|
|
|
263
263
|
* {send,redeem}` (routes/magic-link.ts). NOTE: these are the gateway's
|
|
264
264
|
* canonical paths; the SDK ergonomic method names (`requestMagicLink`/
|
|
265
265
|
* `verifyMagicLink`) do not mirror the path segments (`send`/`redeem`).
|
|
266
|
-
* (The
|
|
267
|
-
* that never matched the shipped gateway routes — reconciled here.)
|
|
266
|
+
* (The SDK paths match the shipped gateway routes.)
|
|
268
267
|
*/
|
|
269
268
|
passwordless: {
|
|
270
269
|
/**
|
|
271
270
|
* Request a one-time passcode delivered to the supplied email.
|
|
272
|
-
* The OTP is short-lived (typically 5 min
|
|
271
|
+
* The OTP is short-lived (typically 5 min) and
|
|
273
272
|
* single-use; redemption via `verifyOtp` mints a session.
|
|
274
273
|
*/
|
|
275
274
|
async requestOtp(input: RequestOtpInput): Promise<Envelope<{ requested: boolean }>> {
|
|
@@ -299,8 +298,8 @@ export function makeGateNamespace(getConfig: () => GateConfig) {
|
|
|
299
298
|
|
|
300
299
|
/**
|
|
301
300
|
* Request a magic-link emailed to the supplied address. The link
|
|
302
|
-
* carries an opaque short-lived token (typically 15 min
|
|
303
|
-
*
|
|
301
|
+
* carries an opaque short-lived token (typically 15 min
|
|
302
|
+
*); clicking the link lands at the customer's chosen
|
|
304
303
|
* redirect URL with the token in the query string, which the
|
|
305
304
|
* customer's frontend then exchanges via `verifyMagicLink`.
|
|
306
305
|
*/
|
|
@@ -357,7 +356,7 @@ export function makeGateNamespace(getConfig: () => GateConfig) {
|
|
|
357
356
|
},
|
|
358
357
|
|
|
359
358
|
/**
|
|
360
|
-
* Project-scoped end-user IdP provider-config management
|
|
359
|
+
* Project-scoped end-user IdP provider-config management.
|
|
361
360
|
* PROJECT_ADMIN+ required; end-user JWTs rejected at the route. Only
|
|
362
361
|
* `create()` is bound — the REST create the Gate Studio
|
|
363
362
|
* `FederationPresetsPanel` routes to when it drops the `gate_flows`
|
|
@@ -376,7 +375,7 @@ export function makeGateNamespace(getConfig: () => GateConfig) {
|
|
|
376
375
|
}
|
|
377
376
|
|
|
378
377
|
/** Singleton bound to the module-level `configureGate()` config.
|
|
379
|
-
*
|
|
378
|
+
* Per-instance clients: `createGateClient(config)`. */
|
|
380
379
|
export const gate = makeGateNamespace(getGateConfig);
|
|
381
380
|
|
|
382
381
|
/** Convenience type alias mirroring the `gate` runtime export.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `gate.identityProviders` namespace — project-scoped end-user IdP
|
|
3
|
-
* provider-config management
|
|
3
|
+
* provider-config management.
|
|
4
4
|
*
|
|
5
5
|
* Wraps the live gateway route family shipped in
|
|
6
6
|
* `services/gateway/src/routes/project-identity-providers.ts`, mounted on
|
|
@@ -37,7 +37,7 @@ import { requestWith } from "../client.ts";
|
|
|
37
37
|
import { resolveProjectPathRoot } from "../paths.ts";
|
|
38
38
|
import type { Envelope } from "../types.ts";
|
|
39
39
|
|
|
40
|
-
/** Closed end-user-class provider enum
|
|
40
|
+
/** Closed end-user-class provider enum — 11 values since v221 (the project-plane substrate
|
|
41
41
|
* `_sys.end_user_idp_provider_configs`); the org plane carries the same 11 since v222/v223. */
|
|
42
42
|
export type IdpProviderKind =
|
|
43
43
|
| "google" | "github" | "microsoft" | "oidc" | "saml" | "scim"
|
|
@@ -60,7 +60,7 @@ export type FederationTestProviderResult = {
|
|
|
60
60
|
| "kind_unsupported";
|
|
61
61
|
};
|
|
62
62
|
|
|
63
|
-
/** Per
|
|
63
|
+
/** Per the provider→tier pairing is structurally fixed:
|
|
64
64
|
* `free_tier_ok ∈ {google, github, microsoft, apple, facebook, twitter}`,
|
|
65
65
|
* `ridge_plus ∈ {oidc, saml, scim, ldap, active_directory}`. The gateway rejects a mismatched
|
|
66
66
|
* pairing (`K9O_INVALID_FIELD_VALUE`); the SDK forwards the caller value
|
|
@@ -74,7 +74,7 @@ export type IdpTierGating = "free_tier_ok" | "ridge_plus";
|
|
|
74
74
|
*
|
|
75
75
|
* Reads carry `clientSecretSet` (presence only), never the secret or a handle (see the module header).
|
|
76
76
|
* `metadataUrl`/`updatedAt` are `null` until set; `attributeMap` defaults to `{}`; `allowedRedirectUris`
|
|
77
|
-
* defaults to `[]`. The `directory*` fields are GS-F7 scheduled directory sync (Google only,
|
|
77
|
+
* defaults to `[]`. The `directory*` fields are GS-F7 scheduled directory sync (Google only,):
|
|
78
78
|
* settings plus the scheduler's last-run status; the service-account key itself is never returned.
|
|
79
79
|
*/
|
|
80
80
|
export type IdpConfig = {
|
|
@@ -147,7 +147,7 @@ export type CreateIdpInput = {
|
|
|
147
147
|
* `tierGating` are immutable after create. An empty patch returns the current config unchanged.
|
|
148
148
|
*
|
|
149
149
|
* 🔴 For `oidc`/`microsoft`, changing `metadataUrl` WITHOUT `clientSecretRef` in the same patch CLEARS the
|
|
150
|
-
* stored client secret (the gateway's secret-invalidate-on-host-change control,
|
|
150
|
+
* stored client secret (the gateway's secret-invalidate-on-host-change control,): re-supply the
|
|
151
151
|
* secret whenever the metadata URL changes.
|
|
152
152
|
*/
|
|
153
153
|
export type PatchIdpInput = {
|
|
@@ -176,8 +176,8 @@ export function makeIdentityProviders(getConfig: () => GateConfig) {
|
|
|
176
176
|
* client secret is encrypted-at-rest server-side; the returned config
|
|
177
177
|
* carries only the opaque secret handle.
|
|
178
178
|
*
|
|
179
|
-
* The gateway validates the `idpProvider`→`tierGating` pairing
|
|
180
|
-
*
|
|
179
|
+
* The gateway validates the `idpProvider`→`tierGating` pairing
|
|
180
|
+
* and rejects a mismatch with `K9O_INVALID_FIELD_VALUE`.
|
|
181
181
|
*/
|
|
182
182
|
async create(input: CreateIdpInput): Promise<Envelope<IdpConfig>> {
|
|
183
183
|
const config = getConfig();
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `@k9o/gate` — Gate (Identity-Aware Kernel) SDK entry point.
|
|
3
3
|
*
|
|
4
|
-
* Re-exports the canonical surface
|
|
4
|
+
* Re-exports the canonical surface +:
|
|
5
5
|
* - `gate` — marquee namespace + sub-namespaces
|
|
6
6
|
* - `configureGate` / `getGateConfig` / `resetGateConfig` — mode + config plumbing
|
|
7
7
|
* - `verifyJwt` / `extractClaims` / `requireScope` — standalone JWT primitives
|
package/src/jwt.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*
|
|
13
13
|
* Native-mode customers don't typically reach for this directly — the
|
|
14
14
|
* gateway verifies project-issued tokens on every request and rehydrates
|
|
15
|
-
* `subject.*` claims
|
|
15
|
+
* `subject.*` claims. But the same primitives are
|
|
16
16
|
* portable: Native customers running their own services downstream of
|
|
17
17
|
* the gateway can verify Gate-issued JWTs identically.
|
|
18
18
|
*/
|
package/src/mode.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Standalone vs Native mode wiring
|
|
2
|
+
* Standalone vs Native mode wiring.
|
|
3
3
|
*
|
|
4
4
|
* The SDK surface is identical across modes; mode determines gateway-
|
|
5
5
|
* side behavior (whether the end-user row scope applies on read/write paths),
|
|
6
6
|
* not SDK ergonomics. The mode boundary is a deployment-time decision
|
|
7
|
-
|
|
7
|
+
*; the SDK does not branch behavior at function-call time.
|
|
8
8
|
*
|
|
9
9
|
* What mode affects (today + forward):
|
|
10
10
|
*
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
* What mode does NOT affect:
|
|
25
25
|
*
|
|
26
26
|
* - Function names + signatures (identical across modes)
|
|
27
|
-
* - Wire-envelope shape (identical
|
|
28
|
-
* - Error taxonomy (identical
|
|
27
|
+
* - Wire-envelope shape (identical)
|
|
28
|
+
* - Error taxonomy (identical)
|
|
29
29
|
*/
|
|
30
30
|
|
|
31
31
|
/**
|
|
@@ -42,17 +42,17 @@ export type GateMode = "standalone" | "native";
|
|
|
42
42
|
*/
|
|
43
43
|
export type GateConfig = {
|
|
44
44
|
mode: GateMode;
|
|
45
|
-
/** Project slug per
|
|
45
|
+
/** Project slug per the URL grammar (e.g. `partner-console-staging`).
|
|
46
46
|
* The only customer-facing project addressing form; routes resolve to
|
|
47
47
|
* `/@<slug>/gate/...` (`feedback_slug_addressing_v2_5_68`). Required. */
|
|
48
48
|
projectSlug: string;
|
|
49
|
-
/** Gateway base URL — e.g. `https://<orgSlug>.api.k9o.io` per
|
|
49
|
+
/** Gateway base URL — e.g. `https://<orgSlug>.api.k9o.io` per the URL grammar */
|
|
50
50
|
baseUrl: string;
|
|
51
51
|
/**
|
|
52
52
|
* Optional partner-credentialled JWT for Standalone mode — used as the
|
|
53
53
|
* default Authorization header when no per-call bearer is supplied.
|
|
54
54
|
* Not required in Native mode; the gateway resolves credentials from
|
|
55
|
-
* the standard project context
|
|
55
|
+
* the standard project context.
|
|
56
56
|
*/
|
|
57
57
|
partnerToken?: string;
|
|
58
58
|
/**
|
|
@@ -88,7 +88,7 @@ export function validateGateConfig(config: GateConfig): void {
|
|
|
88
88
|
const hasSlug = typeof config.projectSlug === "string" && config.projectSlug.length > 0;
|
|
89
89
|
if (!hasSlug) {
|
|
90
90
|
throw new TypeError(
|
|
91
|
-
`Gate config missing projectSlug (required,
|
|
91
|
+
`Gate config missing projectSlug (required, slug grammar — project ids are internal-only and never customer-facing)`,
|
|
92
92
|
);
|
|
93
93
|
}
|
|
94
94
|
if (typeof config.baseUrl !== "string" || config.baseUrl.length === 0) {
|
package/src/paths.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared path-resolution helper for project-scoped routes.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* URL grammar: project-scoped resources address
|
|
5
5
|
* via `/@<projectSlug>/...` against the org subdomain. Slug addressing is
|
|
6
6
|
* the only customer-facing form — project ids are internal-only and never
|
|
7
7
|
* appear in customer paths (`feedback_slug_addressing_v2_5_68`); the
|
package/src/types.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@k9o/gate`
|
|
2
|
+
* `@k9o/gate` — public type surface.
|
|
3
3
|
*
|
|
4
|
-
* The shapes here track
|
|
5
|
-
* prefix
|
|
6
|
-
*
|
|
4
|
+
* The shapes here track verbatim. End-user IDs carry the `eu_`
|
|
5
|
+
* prefix; role and group identifiers compose against the
|
|
6
|
+
* role lattice (Trust-Zone-separate `PROJECT_END_USER` for project-
|
|
7
7
|
* level end-user identities). Sessions, passkeys, MFA factors, federation
|
|
8
8
|
* links, and the rest of the Gate-managed resources receive their per-
|
|
9
|
-
* resource prefixes as the
|
|
9
|
+
* resource prefixes as the end-user table family is specified.
|
|
10
10
|
*
|
|
11
|
-
* Envelope shape (`data` + `meta`) matches
|
|
11
|
+
* Envelope shape (`data` + `meta`) matches; failures land via
|
|
12
12
|
* the `GateError` family per `errors.ts`, which is `KError`-compatible
|
|
13
|
-
|
|
13
|
+
*.
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
|
-
* Standard
|
|
17
|
+
* Standard envelope. Generic over the `data` shape per function.
|
|
18
18
|
* Returned by every successful SDK call.
|
|
19
19
|
*/
|
|
20
20
|
export type Envelope<T> = {
|
|
@@ -23,21 +23,21 @@ export type Envelope<T> = {
|
|
|
23
23
|
};
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
|
-
* Project-level end-user identity (the customers OF the customer
|
|
27
|
-
*
|
|
28
|
-
* `eu_<base62>` prefix
|
|
26
|
+
* Project-level end-user identity (the customers OF the customer as
|
|
27
|
+
* the `PROJECT_END_USER` 7th canonical role). End-user IDs carry the
|
|
28
|
+
* `eu_<base62>` prefix.
|
|
29
29
|
*/
|
|
30
30
|
export type EndUser = {
|
|
31
|
-
/** `eu_<base62>` — see
|
|
31
|
+
/** `eu_<base62>` — see. */
|
|
32
32
|
id: string;
|
|
33
33
|
email: string;
|
|
34
34
|
status: "active" | "pending" | "disabled";
|
|
35
35
|
createdAt: string;
|
|
36
36
|
updatedAt: string | null;
|
|
37
37
|
lastSigninAt: string | null;
|
|
38
|
-
/** Project-level roles
|
|
38
|
+
/** Project-level roles; `PROJECT_END_USER` is the floor membership. */
|
|
39
39
|
roles: ReadonlyArray<string>;
|
|
40
|
-
/** Project-level group memberships
|
|
40
|
+
/** Project-level group memberships `_sys.end_user_groups`. */
|
|
41
41
|
groups: ReadonlyArray<string>;
|
|
42
42
|
};
|
|
43
43
|
|
|
@@ -56,7 +56,7 @@ export type Session = {
|
|
|
56
56
|
};
|
|
57
57
|
|
|
58
58
|
/**
|
|
59
|
-
* Marquee sign-up / sign-in shape
|
|
59
|
+
* Marquee sign-up / sign-in shape:
|
|
60
60
|
* `{ user, session }`
|
|
61
61
|
*/
|
|
62
62
|
export type AuthResult = {
|
|
@@ -65,7 +65,7 @@ export type AuthResult = {
|
|
|
65
65
|
};
|
|
66
66
|
|
|
67
67
|
/**
|
|
68
|
-
* `gate.whoami()` shape
|
|
68
|
+
* `gate.whoami()` shape:
|
|
69
69
|
* `{ user }` — no fresh session is minted by `whoami` (it reflects the
|
|
70
70
|
* caller's current session).
|
|
71
71
|
*/
|
|
@@ -122,7 +122,7 @@ export type OtpPurpose = "signin" | "magic_link" | "password_reset" | "mfa_chall
|
|
|
122
122
|
/**
|
|
123
123
|
* `gate.passwordless.requestOtp` input — emails an OTP code to the
|
|
124
124
|
* given address. Idempotent at the per-email rate-limit ceiling per
|
|
125
|
-
* the
|
|
125
|
+
* the platform anti-abuse policy.
|
|
126
126
|
*/
|
|
127
127
|
export type RequestOtpInput = {
|
|
128
128
|
email: string;
|
|
@@ -152,7 +152,7 @@ export type RequestMagicLinkInput = {
|
|
|
152
152
|
email: string;
|
|
153
153
|
/**
|
|
154
154
|
* Post-redeem landing URL. When supplied it MUST exact-match an entry in
|
|
155
|
-
* the project's magic-link redirect allowlist (Gate config
|
|
155
|
+
* the project's magic-link redirect allowlist (Gate config); a
|
|
156
156
|
* non-allowlisted value is rejected with `GATE_REDIRECT_NOT_ALLOWED` (400).
|
|
157
157
|
* Omit to use the project's configured default redirect.
|
|
158
158
|
*/
|
|
@@ -178,7 +178,7 @@ export type MagicLinkCallbackResult =
|
|
|
178
178
|
| { ok: false; error: string };
|
|
179
179
|
|
|
180
180
|
/**
|
|
181
|
-
* JWT claim shape that `verifyJwt` resolves. Mirrors
|
|
181
|
+
* JWT claim shape that `verifyJwt` resolves. Mirrors `subject.*`
|
|
182
182
|
* exposure for project-level JWTs plus the Gate-issued audience / issuer
|
|
183
183
|
* standard claims. Customer apps in Standalone mode consume this via the
|
|
184
184
|
* `verifyJwt` helper without needing the full SDK shape.
|
|
@@ -196,9 +196,9 @@ export type GateJwtClaims = {
|
|
|
196
196
|
exp: number;
|
|
197
197
|
/** JWT id (for revocation tracking + idempotency). */
|
|
198
198
|
jti?: string;
|
|
199
|
-
/** Project-level role array
|
|
199
|
+
/** Project-level role array; floor is `PROJECT_END_USER`. */
|
|
200
200
|
roles?: ReadonlyArray<string>;
|
|
201
|
-
/** Project-level group memberships
|
|
201
|
+
/** Project-level group memberships. */
|
|
202
202
|
groups?: ReadonlyArray<string>;
|
|
203
203
|
/** Project-level scope strings — used by `requireScope`. */
|
|
204
204
|
scopes?: ReadonlyArray<string>;
|
|
@@ -1 +0,0 @@
|
|
|
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":[]}
|
|
@@ -1 +0,0 @@
|
|
|
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":[]}
|
|
@@ -1 +0,0 @@
|
|
|
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":";;;;;AAmB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