@mayurajs/km-unkey 0.0.0-stage → 1.2.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/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +47 -2
- package/dist/index.d.ts +51 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +98 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
- package/src/index.ts +122 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Mayura
|
|
2
|
+
Copyright 2026 The Mayura Authors
|
|
3
|
+
|
|
4
|
+
This product includes software developed by the Mayura contributors.
|
|
5
|
+
|
|
6
|
+
Third-party dependencies retain their own copyright and license terms. Exact
|
|
7
|
+
resolved versions are recorded in pnpm-lock.yaml and reviewed by the release
|
|
8
|
+
artifact and dependency qualification procedures.
|
package/README.md
CHANGED
|
@@ -1,3 +1,48 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/km-unkey
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
API keys issued by [Unkey](https://www.unkey.com/docs/api-management/keys/verifying-keys) as Mayura server identities:
|
|
4
|
+
each key is verified with Unkey's API, on any runtime, with no dependency (no Unkey SDK).
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install mayura @mayurajs/km-unkey
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { mapCapabilities } from 'mayura/auth';
|
|
12
|
+
import { keyAuthenticator } from 'mayura/keys';
|
|
13
|
+
import { unkeyVerifier } from '@mayurajs/km-unkey';
|
|
14
|
+
|
|
15
|
+
const keys = unkeyVerifier({
|
|
16
|
+
rootKey: process.env.UNKEY_ROOT_KEY!, // allowed api.*.verify_key, or api.<id>.verify_key
|
|
17
|
+
prefix: 'sk',
|
|
18
|
+
keyspaces: ['ks_...'], // your API's keyspace
|
|
19
|
+
permissions: 'agents.use', // optional: checked by Unkey before rate limits and credits
|
|
20
|
+
identity: key => key.identity ? {
|
|
21
|
+
principalId: `unkey/${key.identity.externalId}`,
|
|
22
|
+
projectId: key.identity.externalId,
|
|
23
|
+
agentIds: ['support'],
|
|
24
|
+
capabilities: mapCapabilities(key.permissions, { 'agents.use': ['runs:submit', 'runs:read'] }),
|
|
25
|
+
} : null,
|
|
26
|
+
});
|
|
27
|
+
// createAgentServer({ ..., authenticate: keyAuthenticator(keys, { cost: 1 }) })
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- **Which keys.** Only tokens shaped like your keys (`<prefix>_...`) are sent to Unkey; anything else (a JWT, another
|
|
31
|
+
provider's key) is refused without a request. Unkey checks the key with `keys.verifyKey`, limited to `keyspaces`, so
|
|
32
|
+
keys of your other APIs are refused, and spends the request's cost in credits.
|
|
33
|
+
- **Refusals.** Unkey's outcomes become Mayura's: `NOT_FOUND` is `not_found`; `DISABLED` and `EXPIRED` keep their names;
|
|
34
|
+
`FORBIDDEN` and `INSUFFICIENT_PERMISSIONS` are `forbidden`; `RATE_LIMITED` is `rate_limited`, with the time until the
|
|
35
|
+
soonest exceeded limit resets; `USAGE_EXCEEDED` is `exhausted`. Any outcome Mayura does not know is refused.
|
|
36
|
+
- **Spending.** Unkey checks permissions before rate limits and credits, so with `permissions` a key without them
|
|
37
|
+
spends nothing. A key that `identity` refuses has already spent its cost.
|
|
38
|
+
- **No cache.** Every request asks Unkey, so a key revoked or disabled there is refused at once. When Unkey cannot be
|
|
39
|
+
reached or answers with an error (such as a root key it refuses), the server answers that authentication is
|
|
40
|
+
unavailable; neither the root key nor the caller's key is ever in an error.
|
|
41
|
+
- **What you get.** `identity` receives the key: `keyId`, `keyspaceId`, `name`, `meta`, `permissions`, `roles`,
|
|
42
|
+
`identity` (`id`, `externalId`, `meta`), `expiresAtMs` and `remaining` credits. Nothing is granted unless
|
|
43
|
+
`identity` grants it. The grant lasts no longer than the key.
|
|
44
|
+
- Options: `rootKey`, `prefix`, `keyspaces`, `identity`, `permissions`, `timeoutMs` (5 s), `baseUrl` (for a
|
|
45
|
+
self-hosted Unkey), `fetch`.
|
|
46
|
+
|
|
47
|
+
Mayura's own keys (`mayura/keys`) are stored as Unkey stores them (SHA-256), so they can move to Unkey later. See
|
|
48
|
+
[Authentication and API keys](https://mayurajs.com/docs/guides/authentication/). Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { IdentityGrant } from 'mayura/auth';
|
|
2
|
+
import type { KeyVerifier } from 'mayura/keys';
|
|
3
|
+
/** A key Unkey verified, as `identity` receives it. */
|
|
4
|
+
export interface UnkeyKey {
|
|
5
|
+
readonly keyId: string;
|
|
6
|
+
/** The keyspace (API) the key belongs to: one of `keyspaces`. */
|
|
7
|
+
readonly keyspaceId: string;
|
|
8
|
+
readonly name: string | null;
|
|
9
|
+
/** The key's metadata, when set. */
|
|
10
|
+
readonly meta: Readonly<Record<string, unknown>> | null;
|
|
11
|
+
/** Every permission the key holds, directly or through its roles. */
|
|
12
|
+
readonly permissions: readonly string[];
|
|
13
|
+
readonly roles: readonly string[];
|
|
14
|
+
/** The identity the key is linked to (its `externalId` is yours, such as a user or organization id). */
|
|
15
|
+
readonly identity: {
|
|
16
|
+
readonly id: string;
|
|
17
|
+
readonly externalId: string;
|
|
18
|
+
readonly meta: Readonly<Record<string, unknown>> | null;
|
|
19
|
+
} | null;
|
|
20
|
+
readonly expiresAtMs: number | null;
|
|
21
|
+
/** Credits left after this verification; null for keys without credits. */
|
|
22
|
+
readonly remaining: number | null;
|
|
23
|
+
}
|
|
24
|
+
export interface UnkeyVerifierOptions {
|
|
25
|
+
/** A root key allowed to verify keys (`api.*.verify_key`, or `api.<id>.verify_key`); never sent anywhere but Unkey. */
|
|
26
|
+
readonly rootKey: string;
|
|
27
|
+
/** Your keys' prefix, such as `sk` for `sk_...`: only tokens with it are sent to Unkey. */
|
|
28
|
+
readonly prefix: string;
|
|
29
|
+
/** The keyspaces (`ks_...`, your APIs') whose keys are accepted; keys of any other are refused by Unkey. */
|
|
30
|
+
readonly keyspaces: readonly string[];
|
|
31
|
+
/** What a verified key may do, or null to refuse; for example from `key.permissions` with `mapCapabilities`. */
|
|
32
|
+
readonly identity: (key: UnkeyKey) => IdentityGrant | null | Promise<IdentityGrant | null>;
|
|
33
|
+
/**
|
|
34
|
+
* A permission query every key must satisfy, such as `agents.use`. Unkey checks it before rate limits and credits,
|
|
35
|
+
* so a key without it spends nothing; a key `identity` refuses has already spent its cost.
|
|
36
|
+
*/
|
|
37
|
+
readonly permissions?: string;
|
|
38
|
+
/** How long Unkey may take to answer; 5 s by default (1 to 30 s). */
|
|
39
|
+
readonly timeoutMs?: number;
|
|
40
|
+
/** Unkey's API, for a self-hosted Unkey; `https://api.unkey.com` by default. */
|
|
41
|
+
readonly baseUrl?: string;
|
|
42
|
+
/** For tests and proxies: the fetch to use. */
|
|
43
|
+
readonly fetch?: typeof fetch;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* A key verifier (`KeyVerifier`, for `keyAuthenticator`) for keys issued by Unkey: each key with your prefix is checked
|
|
47
|
+
* with Unkey's `keys.verifyKey` (spending its cost in credits), limited to your keyspaces, and `identity` turns what
|
|
48
|
+
* Unkey knows about it into a grant. Unkey's own answers are never cached, so a key revoked there is refused at once.
|
|
49
|
+
*/
|
|
50
|
+
export declare function unkeyVerifier(options: UnkeyVerifierOptions): KeyVerifier;
|
|
51
|
+
//# sourceMappingURL=index.d.ts.map
|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AAS,MAAM,EAAE,CAAC;IACtC,gHAAgH;IAChH,QAAQ,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,QAAQ,KAAK,aAAa,GAAG,IAAI,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC;IAC3F;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,qEAAqE;IACrE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,gFAAgF;IAChF,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,+CAA+C;IAC/C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CAC/B;AAWD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,WAAW,CA+DxE"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
const refusals = {
|
|
3
|
+
NOT_FOUND: 'not_found', DISABLED: 'disabled', EXPIRED: 'expired', FORBIDDEN: 'forbidden',
|
|
4
|
+
INSUFFICIENT_PERMISSIONS: 'forbidden', RATE_LIMITED: 'rate_limited', USAGE_EXCEEDED: 'exhausted',
|
|
5
|
+
};
|
|
6
|
+
const text = (value) => typeof value === 'string' && value !== '' ? value : null;
|
|
7
|
+
const strings = (value) => Object.freeze(Array.isArray(value) ? value.filter((item) => typeof item === 'string') : []);
|
|
8
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
|
|
9
|
+
const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
10
|
+
/**
|
|
11
|
+
* A key verifier (`KeyVerifier`, for `keyAuthenticator`) for keys issued by Unkey: each key with your prefix is checked
|
|
12
|
+
* with Unkey's `keys.verifyKey` (spending its cost in credits), limited to your keyspaces, and `identity` turns what
|
|
13
|
+
* Unkey knows about it into a grant. Unkey's own answers are never cached, so a key revoked there is refused at once.
|
|
14
|
+
*/
|
|
15
|
+
export function unkeyVerifier(options) {
|
|
16
|
+
if (!options || typeof options.identity !== 'function')
|
|
17
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): identity decides what a key may do.');
|
|
18
|
+
if (typeof options.rootKey !== 'string' || !/^[\x21-\x7e]{16,512}$/u.test(options.rootKey))
|
|
19
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): rootKey is an Unkey root key allowed to verify keys.');
|
|
20
|
+
const prefix = options.prefix;
|
|
21
|
+
if (typeof prefix !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_]{0,15}$/u.test(prefix))
|
|
22
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): prefix is your keys\' prefix, such as sk, 1 to 16 letters, digits or underscores.');
|
|
23
|
+
const keyspaces = options.keyspaces;
|
|
24
|
+
if (!Array.isArray(keyspaces) || keyspaces.length === 0 || keyspaces.length > 5 || keyspaces.some(id => typeof id !== 'string' || !/^ks_[A-Za-z0-9]{1,97}$/u.test(id))) {
|
|
25
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): keyspaces are 1 to 5 keyspace ids (ks_...) whose keys are accepted.');
|
|
26
|
+
}
|
|
27
|
+
const permissions = options.permissions;
|
|
28
|
+
if (permissions !== undefined && (typeof permissions !== 'string' || permissions.length === 0 || permissions.length > 1_000))
|
|
29
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): permissions is a permission query of 1 to 1,000 characters.');
|
|
30
|
+
const timeoutMs = options.timeoutMs ?? 5_000;
|
|
31
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000 || timeoutMs > 30_000)
|
|
32
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): timeoutMs is 1,000 to 30,000.');
|
|
33
|
+
const base = (options.baseUrl ?? 'https://api.unkey.com').replace(/\/$/u, '');
|
|
34
|
+
if (typeof base !== 'string' || !/^(?:https:\/\/[^/?#\s]+|http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?)$/u.test(base))
|
|
35
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): baseUrl is an https URL (http only on this machine).');
|
|
36
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
37
|
+
const shape = new RegExp(`^${prefix}_[A-Za-z0-9]{8,500}$`, 'u');
|
|
38
|
+
const accepts = (key) => shape.test(key);
|
|
39
|
+
const verify = async (key, verifyOptions = {}) => {
|
|
40
|
+
if (!accepts(key))
|
|
41
|
+
return { ok: false, reason: 'malformed' };
|
|
42
|
+
const cost = verifyOptions.cost ?? 1;
|
|
43
|
+
if (!Number.isSafeInteger(cost) || cost < 0)
|
|
44
|
+
throw new MayuraError('INVALID_INPUT', 'unkeyVerifier(): cost is a whole number of credits.');
|
|
45
|
+
const signal = verifyOptions.signal ?? new AbortController().signal;
|
|
46
|
+
let response;
|
|
47
|
+
try {
|
|
48
|
+
response = await fetcher(`${base}/v2/keys.verifyKey`, {
|
|
49
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
|
50
|
+
headers: { authorization: `Bearer ${options.rootKey}`, 'content-type': 'application/json', accept: 'application/json' },
|
|
51
|
+
body: JSON.stringify({ key, keyspaces, credits: { cost }, ...(permissions !== undefined ? { permissions } : {}) }),
|
|
52
|
+
});
|
|
53
|
+
// Neither the root key nor the key may reach an error.
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw signal.aborted ? new MayuraError('CANCELLED', 'Key verification was cancelled.') : new MayuraError('TOOL_FAILED', 'Unkey could not be reached to verify the key.');
|
|
57
|
+
}
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
void response.body?.cancel().catch(() => undefined);
|
|
60
|
+
throw new MayuraError('TOOL_FAILED', `Unkey answered HTTP ${response.status} when verifying the key.`);
|
|
61
|
+
}
|
|
62
|
+
const body = await response.json().catch(() => undefined);
|
|
63
|
+
const data = object(body?.data);
|
|
64
|
+
if (!data || typeof data['valid'] !== 'boolean' || typeof data['code'] !== 'string')
|
|
65
|
+
throw new MayuraError('TOOL_FAILED', 'Unkey\'s answer about the key is not one Mayura knows.');
|
|
66
|
+
if (data['valid'] !== true || data['code'] !== 'VALID') {
|
|
67
|
+
const reason = refusals[data['code']] ?? 'forbidden';
|
|
68
|
+
if (reason !== 'rate_limited')
|
|
69
|
+
return { ok: false, reason };
|
|
70
|
+
// The soonest an exceeded limit resets, when Unkey says.
|
|
71
|
+
const resets = (Array.isArray(data['ratelimits']) ? data['ratelimits'] : []).map(object).filter(limit => limit?.['exceeded'] === true).map(limit => limit['reset']).filter((reset) => typeof reset === 'number');
|
|
72
|
+
const retryAfterMs = resets.length > 0 ? Math.max(0, Math.min(...resets) - Date.now()) : undefined;
|
|
73
|
+
return { ok: false, reason, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) };
|
|
74
|
+
}
|
|
75
|
+
const keyId = text(data['keyId']);
|
|
76
|
+
const keyspaceId = keyspaces.find(id => id === data['keyspaceId']);
|
|
77
|
+
// Unkey keeps to the keyspaces asked for; a key from any other is refused here too.
|
|
78
|
+
if (keyId === null || keyspaceId === undefined)
|
|
79
|
+
return { ok: false, reason: 'forbidden' };
|
|
80
|
+
const linked = object(data['identity']);
|
|
81
|
+
const identityId = text(linked?.['id']);
|
|
82
|
+
const externalId = text(linked?.['externalId']);
|
|
83
|
+
const expires = data['expires'];
|
|
84
|
+
const found = Object.freeze({
|
|
85
|
+
keyId, keyspaceId, name: text(data['name']), meta: object(data['meta']), permissions: strings(data['permissions']), roles: strings(data['roles']),
|
|
86
|
+
identity: identityId !== null && externalId !== null ? Object.freeze({ id: identityId, externalId, meta: object(linked['meta']) }) : null,
|
|
87
|
+
expiresAtMs: typeof expires === 'number' && Number.isSafeInteger(expires) ? expires : null, remaining: count(data['credits']),
|
|
88
|
+
});
|
|
89
|
+
const grant = await options.identity(found);
|
|
90
|
+
if (!grant)
|
|
91
|
+
return { ok: false, reason: 'forbidden' };
|
|
92
|
+
// The sooner of the key's expiry and the grant's.
|
|
93
|
+
const ends = [found.expiresAtMs, grant.expiresAtMs].filter((end) => typeof end === 'number');
|
|
94
|
+
return { ok: true, principalId: grant.principalId, projectId: grant.projectId, agentIds: grant.agentIds, capabilities: grant.capabilities, expiresAtMs: ends.length > 0 ? Math.min(...ends) : null, remaining: found.remaining };
|
|
95
|
+
};
|
|
96
|
+
return Object.freeze({ accepts, verify });
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AA4CrC,MAAM,QAAQ,GAAyC;IACrD,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW;IACxF,wBAAwB,EAAE,WAAW,EAAE,YAAY,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW;CACjG,CAAC;AACF,MAAM,IAAI,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1F,MAAM,OAAO,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAkB,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AAChJ,MAAM,MAAM,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,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AC,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,CAAC;IACnO,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\nimport type { IdentityGrant } from 'mayura/auth';\nimport type { KeyRefusal, KeyVerification, KeyVerifier } from 'mayura/keys';\n\n/** A key Unkey verified, as `identity` receives it. */\nexport interface UnkeyKey {\n readonly keyId: string;\n /** The keyspace (API) the key belongs to: one of `keyspaces`. */\n readonly keyspaceId: string;\n readonly name: string | null;\n /** The key's metadata, when set. */\n readonly meta: Readonly<Record<string, unknown>> | null;\n /** Every permission the key holds, directly or through its roles. */\n readonly permissions: readonly string[];\n readonly roles: readonly string[];\n /** The identity the key is linked to (its `externalId` is yours, such as a user or organization id). */\n readonly identity: { readonly id: string; readonly externalId: string; readonly meta: Readonly<Record<string, unknown>> | null } | null;\n readonly expiresAtMs: number | null;\n /** Credits left after this verification; null for keys without credits. */\n readonly remaining: number | null;\n}\n\nexport interface UnkeyVerifierOptions {\n /** A root key allowed to verify keys (`api.*.verify_key`, or `api.<id>.verify_key`); never sent anywhere but Unkey. */\n readonly rootKey: string;\n /** Your keys' prefix, such as `sk` for `sk_...`: only tokens with it are sent to Unkey. */\n readonly prefix: string;\n /** The keyspaces (`ks_...`, your APIs') whose keys are accepted; keys of any other are refused by Unkey. */\n readonly keyspaces: readonly string[];\n /** What a verified key may do, or null to refuse; for example from `key.permissions` with `mapCapabilities`. */\n readonly identity: (key: UnkeyKey) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /**\n * A permission query every key must satisfy, such as `agents.use`. Unkey checks it before rate limits and credits,\n * so a key without it spends nothing; a key `identity` refuses has already spent its cost.\n */\n readonly permissions?: string;\n /** How long Unkey may take to answer; 5 s by default (1 to 30 s). */\n readonly timeoutMs?: number;\n /** Unkey's API, for a self-hosted Unkey; `https://api.unkey.com` by default. */\n readonly baseUrl?: string;\n /** For tests and proxies: the fetch to use. */\n readonly fetch?: typeof fetch;\n}\n\nconst refusals: Readonly<Record<string, KeyRefusal>> = {\n NOT_FOUND: 'not_found', DISABLED: 'disabled', EXPIRED: 'expired', FORBIDDEN: 'forbidden',\n INSUFFICIENT_PERMISSIONS: 'forbidden', RATE_LIMITED: 'rate_limited', USAGE_EXCEEDED: 'exhausted',\n};\nconst text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;\nconst strings = (value: unknown) => Object.freeze(Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []);\nconst object = (value: unknown) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Readonly<Record<string, unknown>> : null;\nconst count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;\n\n/**\n * A key verifier (`KeyVerifier`, for `keyAuthenticator`) for keys issued by Unkey: each key with your prefix is checked\n * with Unkey's `keys.verifyKey` (spending its cost in credits), limited to your keyspaces, and `identity` turns what\n * Unkey knows about it into a grant. Unkey's own answers are never cached, so a key revoked there is refused at once.\n */\nexport function unkeyVerifier(options: UnkeyVerifierOptions): KeyVerifier {\n if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): identity decides what a key may do.');\n if (typeof options.rootKey !== 'string' || !/^[\\x21-\\x7e]{16,512}$/u.test(options.rootKey)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): rootKey is an Unkey root key allowed to verify keys.');\n const prefix = options.prefix;\n if (typeof prefix !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_]{0,15}$/u.test(prefix)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): prefix is your keys\\' prefix, such as sk, 1 to 16 letters, digits or underscores.');\n const keyspaces = options.keyspaces;\n if (!Array.isArray(keyspaces) || keyspaces.length === 0 || keyspaces.length > 5 || keyspaces.some(id => typeof id !== 'string' || !/^ks_[A-Za-z0-9]{1,97}$/u.test(id))) {\n throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): keyspaces are 1 to 5 keyspace ids (ks_...) whose keys are accepted.');\n }\n const permissions = options.permissions;\n if (permissions !== undefined && (typeof permissions !== 'string' || permissions.length === 0 || permissions.length > 1_000)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): permissions is a permission query of 1 to 1,000 characters.');\n const timeoutMs = options.timeoutMs ?? 5_000;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000 || timeoutMs > 30_000) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): timeoutMs is 1,000 to 30,000.');\n const base = (options.baseUrl ?? 'https://api.unkey.com').replace(/\\/$/u, '');\n if (typeof base !== 'string' || !/^(?:https:\\/\\/[^/?#\\s]+|http:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?)$/u.test(base)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): baseUrl is an https URL (http only on this machine).');\n const fetcher = options.fetch ?? globalThis.fetch;\n const shape = new RegExp(`^${prefix}_[A-Za-z0-9]{8,500}$`, 'u');\n const accepts = (key: string) => shape.test(key);\n\n const verify = async (key: string, verifyOptions: { readonly signal?: AbortSignal; readonly cost?: number } = {}): Promise<KeyVerification> => {\n if (!accepts(key)) return { ok: false, reason: 'malformed' };\n const cost = verifyOptions.cost ?? 1;\n if (!Number.isSafeInteger(cost) || cost < 0) throw new MayuraError('INVALID_INPUT', 'unkeyVerifier(): cost is a whole number of credits.');\n const signal = verifyOptions.signal ?? new AbortController().signal;\n let response: Response;\n try {\n response = await fetcher(`${base}/v2/keys.verifyKey`, {\n method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),\n headers: { authorization: `Bearer ${options.rootKey}`, 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ key, keyspaces, credits: { cost }, ...(permissions !== undefined ? { permissions } : {}) }),\n });\n // Neither the root key nor the key may reach an error.\n } catch { throw signal.aborted ? new MayuraError('CANCELLED', 'Key verification was cancelled.') : new MayuraError('TOOL_FAILED', 'Unkey could not be reached to verify the key.'); }\n if (!response.ok) { void response.body?.cancel().catch(() => undefined); throw new MayuraError('TOOL_FAILED', `Unkey answered HTTP ${response.status} when verifying the key.`); }\n const body = await response.json().catch(() => undefined) as { data?: unknown } | undefined;\n const data = object(body?.data);\n if (!data || typeof data['valid'] !== 'boolean' || typeof data['code'] !== 'string') throw new MayuraError('TOOL_FAILED', 'Unkey\\'s answer about the key is not one Mayura knows.');\n if (data['valid'] !== true || data['code'] !== 'VALID') {\n const reason = refusals[data['code']] ?? 'forbidden';\n if (reason !== 'rate_limited') return { ok: false, reason };\n // The soonest an exceeded limit resets, when Unkey says.\n const resets = (Array.isArray(data['ratelimits']) ? data['ratelimits'] : []).map(object).filter(limit => limit?.['exceeded'] === true).map(limit => limit!['reset']).filter((reset): reset is number => typeof reset === 'number');\n const retryAfterMs = resets.length > 0 ? Math.max(0, Math.min(...resets) - Date.now()) : undefined;\n return { ok: false, reason, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) };\n }\n const keyId = text(data['keyId']); const keyspaceId = keyspaces.find(id => id === data['keyspaceId']);\n // Unkey keeps to the keyspaces asked for; a key from any other is refused here too.\n if (keyId === null || keyspaceId === undefined) return { ok: false, reason: 'forbidden' };\n const linked = object(data['identity']);\n const identityId = text(linked?.['id']); const externalId = text(linked?.['externalId']);\n const expires = data['expires'];\n const found: UnkeyKey = Object.freeze({\n keyId, keyspaceId, name: text(data['name']), meta: object(data['meta']), permissions: strings(data['permissions']), roles: strings(data['roles']),\n identity: identityId !== null && externalId !== null ? Object.freeze({ id: identityId, externalId, meta: object(linked!['meta']) }) : null,\n expiresAtMs: typeof expires === 'number' && Number.isSafeInteger(expires) ? expires : null, remaining: count(data['credits']),\n });\n const grant = await options.identity(found);\n if (!grant) return { ok: false, reason: 'forbidden' };\n // The sooner of the key's expiry and the grant's.\n const ends = [found.expiresAtMs, grant.expiresAtMs].filter((end): end is number => typeof end === 'number');\n return { ok: true, principalId: grant.principalId, projectId: grant.projectId, agentIds: grant.agentIds, capabilities: grant.capabilities, expiresAtMs: ends.length > 0 ? Math.min(...ends) : null, remaining: found.remaining };\n };\n return Object.freeze({ accepts, verify });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mayurajs/km-unkey",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "API keys issued by Unkey as Mayura server identities, verified with Unkey's API.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Aryabh",
|
|
7
|
+
"email": "dev@rokad.co"
|
|
8
|
+
},
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/KartikeyAI/mayura.git",
|
|
13
|
+
"directory": "extensions/km-unkey"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/KartikeyAI/mayura#readme",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/KartikeyAI/mayura/issues"
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22.12.0 <23 || >=24.14.1 <25"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"src/**/*.ts",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"NOTICE"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"mayura": "^1.2.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"provenance": true
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import type { IdentityGrant } from 'mayura/auth';
|
|
3
|
+
import type { KeyRefusal, KeyVerification, KeyVerifier } from 'mayura/keys';
|
|
4
|
+
|
|
5
|
+
/** A key Unkey verified, as `identity` receives it. */
|
|
6
|
+
export interface UnkeyKey {
|
|
7
|
+
readonly keyId: string;
|
|
8
|
+
/** The keyspace (API) the key belongs to: one of `keyspaces`. */
|
|
9
|
+
readonly keyspaceId: string;
|
|
10
|
+
readonly name: string | null;
|
|
11
|
+
/** The key's metadata, when set. */
|
|
12
|
+
readonly meta: Readonly<Record<string, unknown>> | null;
|
|
13
|
+
/** Every permission the key holds, directly or through its roles. */
|
|
14
|
+
readonly permissions: readonly string[];
|
|
15
|
+
readonly roles: readonly string[];
|
|
16
|
+
/** The identity the key is linked to (its `externalId` is yours, such as a user or organization id). */
|
|
17
|
+
readonly identity: { readonly id: string; readonly externalId: string; readonly meta: Readonly<Record<string, unknown>> | null } | null;
|
|
18
|
+
readonly expiresAtMs: number | null;
|
|
19
|
+
/** Credits left after this verification; null for keys without credits. */
|
|
20
|
+
readonly remaining: number | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface UnkeyVerifierOptions {
|
|
24
|
+
/** A root key allowed to verify keys (`api.*.verify_key`, or `api.<id>.verify_key`); never sent anywhere but Unkey. */
|
|
25
|
+
readonly rootKey: string;
|
|
26
|
+
/** Your keys' prefix, such as `sk` for `sk_...`: only tokens with it are sent to Unkey. */
|
|
27
|
+
readonly prefix: string;
|
|
28
|
+
/** The keyspaces (`ks_...`, your APIs') whose keys are accepted; keys of any other are refused by Unkey. */
|
|
29
|
+
readonly keyspaces: readonly string[];
|
|
30
|
+
/** What a verified key may do, or null to refuse; for example from `key.permissions` with `mapCapabilities`. */
|
|
31
|
+
readonly identity: (key: UnkeyKey) => IdentityGrant | null | Promise<IdentityGrant | null>;
|
|
32
|
+
/**
|
|
33
|
+
* A permission query every key must satisfy, such as `agents.use`. Unkey checks it before rate limits and credits,
|
|
34
|
+
* so a key without it spends nothing; a key `identity` refuses has already spent its cost.
|
|
35
|
+
*/
|
|
36
|
+
readonly permissions?: string;
|
|
37
|
+
/** How long Unkey may take to answer; 5 s by default (1 to 30 s). */
|
|
38
|
+
readonly timeoutMs?: number;
|
|
39
|
+
/** Unkey's API, for a self-hosted Unkey; `https://api.unkey.com` by default. */
|
|
40
|
+
readonly baseUrl?: string;
|
|
41
|
+
/** For tests and proxies: the fetch to use. */
|
|
42
|
+
readonly fetch?: typeof fetch;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const refusals: Readonly<Record<string, KeyRefusal>> = {
|
|
46
|
+
NOT_FOUND: 'not_found', DISABLED: 'disabled', EXPIRED: 'expired', FORBIDDEN: 'forbidden',
|
|
47
|
+
INSUFFICIENT_PERMISSIONS: 'forbidden', RATE_LIMITED: 'rate_limited', USAGE_EXCEEDED: 'exhausted',
|
|
48
|
+
};
|
|
49
|
+
const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;
|
|
50
|
+
const strings = (value: unknown) => Object.freeze(Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []);
|
|
51
|
+
const object = (value: unknown) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Readonly<Record<string, unknown>> : null;
|
|
52
|
+
const count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A key verifier (`KeyVerifier`, for `keyAuthenticator`) for keys issued by Unkey: each key with your prefix is checked
|
|
56
|
+
* with Unkey's `keys.verifyKey` (spending its cost in credits), limited to your keyspaces, and `identity` turns what
|
|
57
|
+
* Unkey knows about it into a grant. Unkey's own answers are never cached, so a key revoked there is refused at once.
|
|
58
|
+
*/
|
|
59
|
+
export function unkeyVerifier(options: UnkeyVerifierOptions): KeyVerifier {
|
|
60
|
+
if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): identity decides what a key may do.');
|
|
61
|
+
if (typeof options.rootKey !== 'string' || !/^[\x21-\x7e]{16,512}$/u.test(options.rootKey)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): rootKey is an Unkey root key allowed to verify keys.');
|
|
62
|
+
const prefix = options.prefix;
|
|
63
|
+
if (typeof prefix !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_]{0,15}$/u.test(prefix)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): prefix is your keys\' prefix, such as sk, 1 to 16 letters, digits or underscores.');
|
|
64
|
+
const keyspaces = options.keyspaces;
|
|
65
|
+
if (!Array.isArray(keyspaces) || keyspaces.length === 0 || keyspaces.length > 5 || keyspaces.some(id => typeof id !== 'string' || !/^ks_[A-Za-z0-9]{1,97}$/u.test(id))) {
|
|
66
|
+
throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): keyspaces are 1 to 5 keyspace ids (ks_...) whose keys are accepted.');
|
|
67
|
+
}
|
|
68
|
+
const permissions = options.permissions;
|
|
69
|
+
if (permissions !== undefined && (typeof permissions !== 'string' || permissions.length === 0 || permissions.length > 1_000)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): permissions is a permission query of 1 to 1,000 characters.');
|
|
70
|
+
const timeoutMs = options.timeoutMs ?? 5_000;
|
|
71
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000 || timeoutMs > 30_000) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): timeoutMs is 1,000 to 30,000.');
|
|
72
|
+
const base = (options.baseUrl ?? 'https://api.unkey.com').replace(/\/$/u, '');
|
|
73
|
+
if (typeof base !== 'string' || !/^(?:https:\/\/[^/?#\s]+|http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?)$/u.test(base)) throw new MayuraError('INVALID_CONFIG', 'unkeyVerifier(): baseUrl is an https URL (http only on this machine).');
|
|
74
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
75
|
+
const shape = new RegExp(`^${prefix}_[A-Za-z0-9]{8,500}$`, 'u');
|
|
76
|
+
const accepts = (key: string) => shape.test(key);
|
|
77
|
+
|
|
78
|
+
const verify = async (key: string, verifyOptions: { readonly signal?: AbortSignal; readonly cost?: number } = {}): Promise<KeyVerification> => {
|
|
79
|
+
if (!accepts(key)) return { ok: false, reason: 'malformed' };
|
|
80
|
+
const cost = verifyOptions.cost ?? 1;
|
|
81
|
+
if (!Number.isSafeInteger(cost) || cost < 0) throw new MayuraError('INVALID_INPUT', 'unkeyVerifier(): cost is a whole number of credits.');
|
|
82
|
+
const signal = verifyOptions.signal ?? new AbortController().signal;
|
|
83
|
+
let response: Response;
|
|
84
|
+
try {
|
|
85
|
+
response = await fetcher(`${base}/v2/keys.verifyKey`, {
|
|
86
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
|
87
|
+
headers: { authorization: `Bearer ${options.rootKey}`, 'content-type': 'application/json', accept: 'application/json' },
|
|
88
|
+
body: JSON.stringify({ key, keyspaces, credits: { cost }, ...(permissions !== undefined ? { permissions } : {}) }),
|
|
89
|
+
});
|
|
90
|
+
// Neither the root key nor the key may reach an error.
|
|
91
|
+
} catch { throw signal.aborted ? new MayuraError('CANCELLED', 'Key verification was cancelled.') : new MayuraError('TOOL_FAILED', 'Unkey could not be reached to verify the key.'); }
|
|
92
|
+
if (!response.ok) { void response.body?.cancel().catch(() => undefined); throw new MayuraError('TOOL_FAILED', `Unkey answered HTTP ${response.status} when verifying the key.`); }
|
|
93
|
+
const body = await response.json().catch(() => undefined) as { data?: unknown } | undefined;
|
|
94
|
+
const data = object(body?.data);
|
|
95
|
+
if (!data || typeof data['valid'] !== 'boolean' || typeof data['code'] !== 'string') throw new MayuraError('TOOL_FAILED', 'Unkey\'s answer about the key is not one Mayura knows.');
|
|
96
|
+
if (data['valid'] !== true || data['code'] !== 'VALID') {
|
|
97
|
+
const reason = refusals[data['code']] ?? 'forbidden';
|
|
98
|
+
if (reason !== 'rate_limited') return { ok: false, reason };
|
|
99
|
+
// The soonest an exceeded limit resets, when Unkey says.
|
|
100
|
+
const resets = (Array.isArray(data['ratelimits']) ? data['ratelimits'] : []).map(object).filter(limit => limit?.['exceeded'] === true).map(limit => limit!['reset']).filter((reset): reset is number => typeof reset === 'number');
|
|
101
|
+
const retryAfterMs = resets.length > 0 ? Math.max(0, Math.min(...resets) - Date.now()) : undefined;
|
|
102
|
+
return { ok: false, reason, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) };
|
|
103
|
+
}
|
|
104
|
+
const keyId = text(data['keyId']); const keyspaceId = keyspaces.find(id => id === data['keyspaceId']);
|
|
105
|
+
// Unkey keeps to the keyspaces asked for; a key from any other is refused here too.
|
|
106
|
+
if (keyId === null || keyspaceId === undefined) return { ok: false, reason: 'forbidden' };
|
|
107
|
+
const linked = object(data['identity']);
|
|
108
|
+
const identityId = text(linked?.['id']); const externalId = text(linked?.['externalId']);
|
|
109
|
+
const expires = data['expires'];
|
|
110
|
+
const found: UnkeyKey = Object.freeze({
|
|
111
|
+
keyId, keyspaceId, name: text(data['name']), meta: object(data['meta']), permissions: strings(data['permissions']), roles: strings(data['roles']),
|
|
112
|
+
identity: identityId !== null && externalId !== null ? Object.freeze({ id: identityId, externalId, meta: object(linked!['meta']) }) : null,
|
|
113
|
+
expiresAtMs: typeof expires === 'number' && Number.isSafeInteger(expires) ? expires : null, remaining: count(data['credits']),
|
|
114
|
+
});
|
|
115
|
+
const grant = await options.identity(found);
|
|
116
|
+
if (!grant) return { ok: false, reason: 'forbidden' };
|
|
117
|
+
// The sooner of the key's expiry and the grant's.
|
|
118
|
+
const ends = [found.expiresAtMs, grant.expiresAtMs].filter((end): end is number => typeof end === 'number');
|
|
119
|
+
return { ok: true, principalId: grant.principalId, projectId: grant.projectId, agentIds: grant.agentIds, capabilities: grant.capabilities, expiresAtMs: ends.length > 0 ? Math.min(...ends) : null, remaining: found.remaining };
|
|
120
|
+
};
|
|
121
|
+
return Object.freeze({ accepts, verify });
|
|
122
|
+
}
|