@mayurajs/auth-clerk 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +44 -2
- package/dist/index.d.ts +71 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +136 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
- package/src/index.ts +160 -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,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/auth-clerk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Clerk](https://clerk.com) session tokens as Mayura server identities: verified with your instance's published keys
|
|
4
|
+
(or its PEM key, with no network), on any runtime, with no dependency.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install mayura @mayurajs/auth-clerk
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { mapCapabilities, principalId } from 'mayura/auth';
|
|
12
|
+
import { clerkAuthenticator } from '@mayurajs/auth-clerk';
|
|
13
|
+
|
|
14
|
+
const authenticate = clerkAuthenticator({
|
|
15
|
+
publishableKey: 'pk_live_...', // or frontendApi: 'https://clerk.example.com'
|
|
16
|
+
authorizedParties: ['https://app.example.com'], // the origins your users sign in from
|
|
17
|
+
identity: session => session.orgId ? {
|
|
18
|
+
principalId: principalId('clerk', session.userId),
|
|
19
|
+
projectId: session.orgId,
|
|
20
|
+
agentIds: ['support'],
|
|
21
|
+
capabilities: mapCapabilities(session.orgPermissions, {
|
|
22
|
+
'org:agents:use': ['runs:submit', 'runs:read'],
|
|
23
|
+
'org:agents:operate': ['workflows:read', 'workflows:control'],
|
|
24
|
+
}),
|
|
25
|
+
} : null,
|
|
26
|
+
});
|
|
27
|
+
// createAgentServer({ ..., authenticate })
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- **What is checked.** RS256 tokens issued by your Frontend API (read from the publishable key), signed with its keys
|
|
31
|
+
from `/.well-known/jwks.json` (or `jwtKey`, your PEM public key, with no network), within their 60-second lifetime
|
|
32
|
+
(5 s of clock skew, as Clerk's SDK). Their `azp` must be one of `authorizedParties` (Clerk tokens carry no audience;
|
|
33
|
+
this is what stands for it, against CSRF); `false` turns that off only where no browser is involved. Sessions Clerk
|
|
34
|
+
marks `pending` are refused unless `allowPending`.
|
|
35
|
+
- **What you get.** `identity` receives the session: `userId`, `sessionId`, `status`, the active organization
|
|
36
|
+
(`orgId`, `orgSlug`, `orgRole` as `org:admin`) and the user's `orgPermissions` there (`org:<feature>:<permission>`),
|
|
37
|
+
decoded from version 2 tokens' feature bitmasks exactly as Clerk's SDK decodes them, or read from version 1 tokens;
|
|
38
|
+
`actor` when someone is impersonating the user; and the raw `claims`. Nothing is granted unless `identity` grants it.
|
|
39
|
+
- `clerkFrontendApi(publishableKey)`, `clerkSession(claims)` and `clerkPermissions(claims)` are exported for your own
|
|
40
|
+
checks.
|
|
41
|
+
- Clerk API keys are verified by `@mayurajs/km-clerk`.
|
|
42
|
+
- Options: `publishableKey` or `frontendApi`, `jwtKey`, `authorizedParties`, `identity`, `allowPending`, `clockSkewMs`,
|
|
43
|
+
`maxIdentityMs` (60 s), `fetch`.
|
|
44
|
+
|
|
45
|
+
See [Authentication and API keys](https://mayurajs.com/docs/guides/authentication/). Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type Authenticator, type IdentityGrant, type JwtClaims } from 'mayura/auth';
|
|
2
|
+
/** A verified Clerk session, from its token's claims (version 2, or the older version 1). */
|
|
3
|
+
export interface ClerkSession {
|
|
4
|
+
/** The user (`sub`). */
|
|
5
|
+
readonly userId: string;
|
|
6
|
+
/** The session (`sid`). */
|
|
7
|
+
readonly sessionId: string;
|
|
8
|
+
/** The session's status (`sts`), such as `active` or `pending`. */
|
|
9
|
+
readonly status: string | null;
|
|
10
|
+
/** The active organization, when there is one. */
|
|
11
|
+
readonly orgId: string | null;
|
|
12
|
+
readonly orgSlug: string | null;
|
|
13
|
+
/** The user's role in it, as Clerk names roles: `org:admin`. */
|
|
14
|
+
readonly orgRole: string | null;
|
|
15
|
+
/** The user's permissions in it, as Clerk names them: `org:invoices:read`. */
|
|
16
|
+
readonly orgPermissions: readonly string[];
|
|
17
|
+
/** Someone acting as the user (impersonation), from the `act` claim. */
|
|
18
|
+
readonly actor: {
|
|
19
|
+
readonly sub?: string;
|
|
20
|
+
readonly sid?: string;
|
|
21
|
+
readonly iss?: string;
|
|
22
|
+
} | null;
|
|
23
|
+
/** The token's claims, as verified. */
|
|
24
|
+
readonly claims: JwtClaims;
|
|
25
|
+
}
|
|
26
|
+
export interface ClerkAuthenticatorOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Your Clerk publishable key (`pk_live_...` or `pk_test_...`), from which your Frontend API URL (the tokens' issuer
|
|
29
|
+
* and where its keys are published) is read. Or give `frontendApi`.
|
|
30
|
+
*/
|
|
31
|
+
readonly publishableKey?: string;
|
|
32
|
+
/** Your Clerk Frontend API URL, such as `https://clerk.example.com`. */
|
|
33
|
+
readonly frontendApi?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Your instance's JWKS public key (PEM, from the API keys page), to verify with no network at all. Without it, the
|
|
36
|
+
* keys are fetched from your Frontend API.
|
|
37
|
+
*/
|
|
38
|
+
readonly jwtKey?: string;
|
|
39
|
+
/**
|
|
40
|
+
* The origins your users sign in from, which a token's `azp` must be one of, as Clerk advises against CSRF. `false`
|
|
41
|
+
* only where no browser is involved.
|
|
42
|
+
*/
|
|
43
|
+
readonly authorizedParties: readonly string[] | false;
|
|
44
|
+
/** What a signed-in user may do, or null to refuse; for example from `session.orgPermissions` with `mapCapabilities`. */
|
|
45
|
+
readonly identity: (session: ClerkSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
|
|
46
|
+
/** Accept sessions Clerk marks `pending` (tasks such as choosing an organization not done yet); refused by default. */
|
|
47
|
+
readonly allowPending?: boolean;
|
|
48
|
+
/** Clock difference allowed; 5 s by default, as Clerk's own SDK. */
|
|
49
|
+
readonly clockSkewMs?: number;
|
|
50
|
+
/** The longest an identity lasts before the token is checked again; 60 s by default (Clerk tokens last 60 s). */
|
|
51
|
+
readonly maxIdentityMs?: number;
|
|
52
|
+
/** For tests and proxies: the fetch to use for the JWKS. */
|
|
53
|
+
readonly fetch?: typeof fetch;
|
|
54
|
+
}
|
|
55
|
+
/** The Frontend API URL in a publishable key: `pk_<live|test>_` and the base64 of `<host>$`. */
|
|
56
|
+
export declare function clerkFrontendApi(publishableKey: string): string;
|
|
57
|
+
/** Clerk's organization permissions from a version 2 token: features (`fea`), names (`o.per`) and bitmasks (`o.fpm`). */
|
|
58
|
+
export declare function clerkPermissions(claims: {
|
|
59
|
+
readonly fea?: unknown;
|
|
60
|
+
readonly o?: unknown;
|
|
61
|
+
readonly [claim: string]: unknown;
|
|
62
|
+
}): string[];
|
|
63
|
+
/** A Clerk session from verified claims, either token version. */
|
|
64
|
+
export declare function clerkSession(claims: JwtClaims): ClerkSession | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* A server `authenticate` for Clerk session tokens: RS256 tokens issued by your Frontend API, verified with its
|
|
67
|
+
* published keys (or your PEM key, with no network), from your own origins (`azp`), active (not `pending`), and
|
|
68
|
+
* no older than Clerk's 60-second lifetime allows. `identity` decides what the user may do.
|
|
69
|
+
*/
|
|
70
|
+
export declare function clerkAuthenticator(options: ClerkAuthenticatorOptions): Authenticator;
|
|
71
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,aAAa,EAAE,KAAK,aAAa,EAAE,KAAK,SAAS,EACvD,MAAM,aAAa,CAAC;AAErB,6FAA6F;AAC7F,MAAM,WAAW,YAAY;IAC3B,wBAAwB;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,2BAA2B;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,mEAAmE;IACnE,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,kDAAkD;IAClD,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,gEAAgE;IAChE,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,8EAA8E;IAC9E,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,wEAAwE;IACxE,QAAQ,CAAC,KAAK,EAAE;QAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAC/F,uCAAuC;I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B,GAAG,aAAa,CA4BpF"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import { jwtAuthenticator, jwtVerifier, remoteJwks, } from 'mayura/auth';
|
|
3
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
4
|
+
/** The Frontend API URL in a publishable key: `pk_<live|test>_` and the base64 of `<host>$`. */
|
|
5
|
+
export function clerkFrontendApi(publishableKey) {
|
|
6
|
+
const match = typeof publishableKey === 'string' ? /^pk_(?:live|test)_([A-Za-z0-9+/=_-]+)$/u.exec(publishableKey) : null;
|
|
7
|
+
let host;
|
|
8
|
+
try {
|
|
9
|
+
host = match ? decoder.decode(Uint8Array.from(atob(match[1].replace(/-/gu, '+').replace(/_/gu, '/')), char => char.charCodeAt(0))) : undefined;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
host = undefined;
|
|
13
|
+
}
|
|
14
|
+
if (!host || !host.endsWith('$') || !/^[a-z0-9.-]+(?::\d{1,5})?$/iu.test(host.slice(0, -1)))
|
|
15
|
+
throw new MayuraError('INVALID_CONFIG', 'publishableKey is a Clerk publishable key, pk_live_... or pk_test_....');
|
|
16
|
+
return `https://${host.slice(0, -1)}`;
|
|
17
|
+
}
|
|
18
|
+
/** A key source for one PEM public key (SPKI), RS256, as Clerk publishes it for networkless verification. */
|
|
19
|
+
function pemKey(pem) {
|
|
20
|
+
const body = typeof pem === 'string' ? /-----BEGIN PUBLIC KEY-----([A-Za-z0-9+/=\s]+)-----END PUBLIC KEY-----/u.exec(pem)?.[1]?.replace(/\s+/gu, '') : undefined;
|
|
21
|
+
let der;
|
|
22
|
+
try {
|
|
23
|
+
der = Uint8Array.from(atob(body ?? '!'), char => char.charCodeAt(0));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new MayuraError('INVALID_CONFIG', 'jwtKey is your instance\'s PEM public key (-----BEGIN PUBLIC KEY-----...).');
|
|
27
|
+
}
|
|
28
|
+
const key = crypto.subtle.importKey('spki', der, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']).catch(() => undefined);
|
|
29
|
+
return Object.freeze({
|
|
30
|
+
key: async () => {
|
|
31
|
+
const imported = await key;
|
|
32
|
+
if (!imported)
|
|
33
|
+
throw new MayuraError('INVALID_CONFIG', 'jwtKey is not an RSA public key Mayura can use.');
|
|
34
|
+
// The verifier accepts RS256 alone.
|
|
35
|
+
return imported;
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/** Clerk's organization permissions from a version 2 token: features (`fea`), names (`o.per`) and bitmasks (`o.fpm`). */
|
|
40
|
+
export function clerkPermissions(claims) {
|
|
41
|
+
const org = claims.o;
|
|
42
|
+
if (typeof claims.fea !== 'string' || typeof org?.per !== 'string' || typeof org.fpm !== 'string')
|
|
43
|
+
return [];
|
|
44
|
+
// Features scoped to organizations: `o:<feature>`, or both (`ou`, `uo`); as Clerk's own SDK reads them.
|
|
45
|
+
const features = [];
|
|
46
|
+
for (const part of claims.fea.split(',')) {
|
|
47
|
+
const item = part.trim();
|
|
48
|
+
const colon = item.indexOf(':');
|
|
49
|
+
if (colon === -1)
|
|
50
|
+
return [];
|
|
51
|
+
if (['o', 'ou', 'uo'].includes(item.slice(0, colon)))
|
|
52
|
+
features.push(item.slice(colon + 1));
|
|
53
|
+
}
|
|
54
|
+
const names = org.per.split(',').map(name => name.trim());
|
|
55
|
+
const masks = org.fpm.split(',').map(mask => mask.trim());
|
|
56
|
+
const permissions = [];
|
|
57
|
+
for (const [index, feature] of features.entries()) {
|
|
58
|
+
const mask = masks[index];
|
|
59
|
+
if (mask === undefined || !/^\d{1,300}$/u.test(mask))
|
|
60
|
+
continue;
|
|
61
|
+
// Bit 0 (the rightmost) is the first permission name.
|
|
62
|
+
const bits = BigInt(mask);
|
|
63
|
+
for (const [bit, name] of names.entries())
|
|
64
|
+
if ((bits >> BigInt(bit)) & 1n)
|
|
65
|
+
permissions.push(`org:${feature}:${name}`);
|
|
66
|
+
}
|
|
67
|
+
return permissions;
|
|
68
|
+
}
|
|
69
|
+
/** A Clerk session from verified claims, either token version. */
|
|
70
|
+
export function clerkSession(claims) {
|
|
71
|
+
if (typeof claims.sub !== 'string' || claims.sub === '' || typeof claims['sid'] !== 'string')
|
|
72
|
+
return undefined;
|
|
73
|
+
const text = (value) => typeof value === 'string' && value !== '' ? value : null;
|
|
74
|
+
const actor = claims['act'] && typeof claims['act'] === 'object' ? claims['act'] : null;
|
|
75
|
+
const base = { userId: claims.sub, sessionId: claims['sid'], status: text(claims['sts']), actor, claims };
|
|
76
|
+
if (claims['v'] === 2) {
|
|
77
|
+
const org = claims['o'];
|
|
78
|
+
const orgId = text(org?.id);
|
|
79
|
+
return Object.freeze({ ...base, orgId, orgSlug: orgId ? text(org?.slg) : null, orgRole: orgId && text(org?.rol) ? `org:${org.rol}` : null,
|
|
80
|
+
orgPermissions: Object.freeze(orgId ? clerkPermissions(claims) : []) });
|
|
81
|
+
}
|
|
82
|
+
// Version 1 (Clerk stopped issuing these in April 2025).
|
|
83
|
+
const orgId = text(claims['org_id']);
|
|
84
|
+
const permissions = claims['org_permissions'];
|
|
85
|
+
return Object.freeze({ ...base, orgId, orgSlug: orgId ? text(claims['org_slug']) : null, orgRole: orgId ? text(claims['org_role']) : null,
|
|
86
|
+
orgPermissions: Object.freeze(orgId && Array.isArray(permissions) ? permissions.filter((item) => typeof item === 'string') : []) });
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A server `authenticate` for Clerk session tokens: RS256 tokens issued by your Frontend API, verified with its
|
|
90
|
+
* published keys (or your PEM key, with no network), from your own origins (`azp`), active (not `pending`), and
|
|
91
|
+
* no older than Clerk's 60-second lifetime allows. `identity` decides what the user may do.
|
|
92
|
+
*/
|
|
93
|
+
export function clerkAuthenticator(options) {
|
|
94
|
+
if (!options || typeof options.identity !== 'function')
|
|
95
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): identity decides what a signed-in user may do.');
|
|
96
|
+
let frontendApi;
|
|
97
|
+
if (options.frontendApi !== undefined) {
|
|
98
|
+
let url;
|
|
99
|
+
try {
|
|
100
|
+
url = new URL(options.frontendApi);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): frontendApi is your Clerk Frontend API URL.');
|
|
104
|
+
}
|
|
105
|
+
if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password)
|
|
106
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): frontendApi is an https origin, such as https://clerk.example.com.');
|
|
107
|
+
frontendApi = url.origin;
|
|
108
|
+
if (options.publishableKey !== undefined && clerkFrontendApi(options.publishableKey) !== frontendApi)
|
|
109
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): publishableKey and frontendApi name different instances.');
|
|
110
|
+
}
|
|
111
|
+
else if (options.publishableKey !== undefined)
|
|
112
|
+
frontendApi = clerkFrontendApi(options.publishableKey);
|
|
113
|
+
else
|
|
114
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): give publishableKey (or frontendApi): tokens are checked against your instance.');
|
|
115
|
+
const parties = options.authorizedParties;
|
|
116
|
+
if (parties !== false && (!Array.isArray(parties) || parties.length === 0 || parties.some(party => typeof party !== 'string' || !/^https?:\/\/[^/\s]+$/u.test(party)))) {
|
|
117
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): authorizedParties are the origins your users sign in from, such as https://app.example.com, or false where no browser is involved.');
|
|
118
|
+
}
|
|
119
|
+
if (options.allowPending !== undefined && typeof options.allowPending !== 'boolean')
|
|
120
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): allowPending must be a boolean.');
|
|
121
|
+
const keys = options.jwtKey !== undefined ? pemKey(options.jwtKey) : remoteJwks({ url: `${frontendApi}/.well-known/jwks.json`, ...(options.fetch ? { fetch: options.fetch } : {}) });
|
|
122
|
+
const verifier = jwtVerifier({ issuer: frontendApi, audience: false, algorithms: ['RS256'], keys, clockSkewMs: options.clockSkewMs ?? 5_000 });
|
|
123
|
+
return jwtAuthenticator({
|
|
124
|
+
verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),
|
|
125
|
+
identity: claims => {
|
|
126
|
+
// Clerk tokens carry no audience: the origin a token was made for (azp) stands for it.
|
|
127
|
+
if (parties !== false && (typeof claims['azp'] !== 'string' || !parties.includes(claims['azp'])))
|
|
128
|
+
return null;
|
|
129
|
+
const session = clerkSession(claims);
|
|
130
|
+
if (!session || (session.status === 'pending' && options.allowPending !== true))
|
|
131
|
+
return null;
|
|
132
|
+
return options.identity(session);
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
//# 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;AACrC,OAAO,EACL,gBAAgB,EAAE,WAAW,EAAE,UAAU,GAE1C,MAAM,aAAa,CAAC;AAqDrB,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAE1D,gGAAgG;AAChG,MAAM,UAAU,gBAAgB,CAAC,cAAsB;IACrD,MAAM,KAAK,GAAG,OAAO,cAAc,KAAK,QAAQ,CAAC,CAAC,CAAC,yCAAyC,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzH,IAAI,IAAwB,CAAC;IAC7B,IAAI,CAAC;QAAC,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,C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AC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACrL,MAAM,QAAQ,GAAG,WAAW,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,KAAK,EAAE,CAAC,CAAC;IAC/I,OAAO,gBAAgB,CAAC;QACtB,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClG,QAAQ,EAAE,MAAM,CAAC,EAAE;YACjB,uFAAuF;YACvF,IAAI,OAAO,KAAK,KAAK,IAAI,CAAC,OAAO,MAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;gBAAE,OAAO,IAAI,CAAC;YAC9G,MAAM,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;YACrC,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,OAAO,CAAC,YAAY,KAAK,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YAC7F,OAAO,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\nimport {\n jwtAuthenticator, jwtVerifier, remoteJwks,\n type Authenticator, type IdentityGrant, type JwtClaims, type JwtKeySource,\n} from 'mayura/auth';\n\n/** A verified Clerk session, from its token's claims (version 2, or the older version 1). */\nexport interface ClerkSession {\n /** The user (`sub`). */\n readonly userId: string;\n /** The session (`sid`). */\n readonly sessionId: string;\n /** The session's status (`sts`), such as `active` or `pending`. */\n readonly status: string | null;\n /** The active organization, when there is one. */\n readonly orgId: string | null;\n readonly orgSlug: string | null;\n /** The user's role in it, as Clerk names roles: `org:admin`. */\n readonly orgRole: string | null;\n /** The user's permissions in it, as Clerk names them: `org:invoices:read`. */\n readonly orgPermissions: readonly string[];\n /** Someone acting as the user (impersonation), from the `act` claim. */\n readonly actor: { readonly sub?: string; readonly sid?: string; readonly iss?: string } | null;\n /** The token's claims, as verified. */\n readonly claims: JwtClaims;\n}\n\nexport interface ClerkAuthenticatorOptions {\n /**\n * Your Clerk publishable key (`pk_live_...` or `pk_test_...`), from which your Frontend API URL (the tokens' issuer\n * and where its keys are published) is read. Or give `frontendApi`.\n */\n readonly publishableKey?: string;\n /** Your Clerk Frontend API URL, such as `https://clerk.example.com`. */\n readonly frontendApi?: string;\n /**\n * Your instance's JWKS public key (PEM, from the API keys page), to verify with no network at all. Without it, the\n * keys are fetched from your Frontend API.\n */\n readonly jwtKey?: string;\n /**\n * The origins your users sign in from, which a token's `azp` must be one of, as Clerk advises against CSRF. `false`\n * only where no browser is involved.\n */\n readonly authorizedParties: readonly string[] | false;\n /** What a signed-in user may do, or null to refuse; for example from `session.orgPermissions` with `mapCapabilities`. */\n readonly identity: (session: ClerkSession) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** Accept sessions Clerk marks `pending` (tasks such as choosing an organization not done yet); refused by default. */\n readonly allowPending?: boolean;\n /** Clock difference allowed; 5 s by default, as Clerk's own SDK. */\n readonly clockSkewMs?: number;\n /** The longest an identity lasts before the token is checked again; 60 s by default (Clerk tokens last 60 s). */\n readonly maxIdentityMs?: number;\n /** For tests and proxies: the fetch to use for the JWKS. */\n readonly fetch?: typeof fetch;\n}\n\nconst decoder = new TextDecoder('utf-8', { fatal: true });\n\n/** The Frontend API URL in a publishable key: `pk_<live|test>_` and the base64 of `<host>$`. */\nexport function clerkFrontendApi(publishableKey: string): string {\n const match = typeof publishableKey === 'string' ? /^pk_(?:live|test)_([A-Za-z0-9+/=_-]+)$/u.exec(publishableKey) : null;\n let host: string | undefined;\n try { host = match ? decoder.decode(Uint8Array.from(atob(match[1]!.replace(/-/gu, '+').replace(/_/gu, '/')), char => char.charCodeAt(0))) : undefined; } catch { host = undefined; }\n if (!host || !host.endsWith('$') || !/^[a-z0-9.-]+(?::\\d{1,5})?$/iu.test(host.slice(0, -1))) throw new MayuraError('INVALID_CONFIG', 'publishableKey is a Clerk publishable key, pk_live_... or pk_test_....');\n return `https://${host.slice(0, -1)}`;\n}\n\n/** A key source for one PEM public key (SPKI), RS256, as Clerk publishes it for networkless verification. */\nfunction pemKey(pem: string): JwtKeySource {\n const body = typeof pem === 'string' ? /-----BEGIN PUBLIC KEY-----([A-Za-z0-9+/=\\s]+)-----END PUBLIC KEY-----/u.exec(pem)?.[1]?.replace(/\\s+/gu, '') : undefined;\n let der: Uint8Array;\n try { der = Uint8Array.from(atob(body ?? '!'), char => char.charCodeAt(0)); } catch { throw new MayuraError('INVALID_CONFIG', 'jwtKey is your instance\\'s PEM public key (-----BEGIN PUBLIC KEY-----...).'); }\n const key = crypto.subtle.importKey('spki', der as Uint8Array<ArrayBuffer>, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']).catch(() => undefined);\n return Object.freeze({\n key: async () => {\n const imported = await key;\n if (!imported) throw new MayuraError('INVALID_CONFIG', 'jwtKey is not an RSA public key Mayura can use.');\n // The verifier accepts RS256 alone.\n return imported;\n },\n });\n}\n\n/** Clerk's organization permissions from a version 2 token: features (`fea`), names (`o.per`) and bitmasks (`o.fpm`). */\nexport function clerkPermissions(claims: { readonly fea?: unknown; readonly o?: unknown; readonly [claim: string]: unknown }): string[] {\n const org = claims.o as { per?: unknown; fpm?: unknown } | undefined;\n if (typeof claims.fea !== 'string' || typeof org?.per !== 'string' || typeof org.fpm !== 'string') return [];\n // Features scoped to organizations: `o:<feature>`, or both (`ou`, `uo`); as Clerk's own SDK reads them.\n const features: string[] = [];\n for (const part of claims.fea.split(',')) {\n const item = part.trim(); const colon = item.indexOf(':');\n if (colon === -1) return [];\n if (['o', 'ou', 'uo'].includes(item.slice(0, colon))) features.push(item.slice(colon + 1));\n }\n const names = org.per.split(',').map(name => name.trim());\n const masks = org.fpm.split(',').map(mask => mask.trim());\n const permissions: string[] = [];\n for (const [index, feature] of features.entries()) {\n const mask = masks[index];\n if (mask === undefined || !/^\\d{1,300}$/u.test(mask)) continue;\n // Bit 0 (the rightmost) is the first permission name.\n const bits = BigInt(mask);\n for (const [bit, name] of names.entries()) if ((bits >> BigInt(bit)) & 1n) permissions.push(`org:${feature}:${name}`);\n }\n return permissions;\n}\n\n/** A Clerk session from verified claims, either token version. */\nexport function clerkSession(claims: JwtClaims): ClerkSession | undefined {\n if (typeof claims.sub !== 'string' || claims.sub === '' || typeof claims['sid'] !== 'string') return undefined;\n const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;\n const actor = claims['act'] && typeof claims['act'] === 'object' ? claims['act'] as ClerkSession['actor'] : null;\n const base = { userId: claims.sub, sessionId: claims['sid'], status: text(claims['sts']), actor, claims };\n if (claims['v'] === 2) {\n const org = claims['o'] as { id?: unknown; slg?: unknown; rol?: unknown } | undefined;\n const orgId = text(org?.id);\n return Object.freeze({ ...base, orgId, orgSlug: orgId ? text(org?.slg) : null, orgRole: orgId && text(org?.rol) ? `org:${org!.rol as string}` : null,\n orgPermissions: Object.freeze(orgId ? clerkPermissions(claims) : []) });\n }\n // Version 1 (Clerk stopped issuing these in April 2025).\n const orgId = text(claims['org_id']); const permissions = claims['org_permissions'];\n return Object.freeze({ ...base, orgId, orgSlug: orgId ? text(claims['org_slug']) : null, orgRole: orgId ? text(claims['org_role']) : null,\n orgPermissions: Object.freeze(orgId && Array.isArray(permissions) ? permissions.filter((item): item is string => typeof item === 'string') : []) });\n}\n\n/**\n * A server `authenticate` for Clerk session tokens: RS256 tokens issued by your Frontend API, verified with its\n * published keys (or your PEM key, with no network), from your own origins (`azp`), active (not `pending`), and\n * no older than Clerk's 60-second lifetime allows. `identity` decides what the user may do.\n */\nexport function clerkAuthenticator(options: ClerkAuthenticatorOptions): Authenticator {\n if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): identity decides what a signed-in user may do.');\n let frontendApi: string;\n if (options.frontendApi !== undefined) {\n let url: URL;\n try { url = new URL(options.frontendApi); } catch { throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): frontendApi is your Clerk Frontend API URL.'); }\n if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password) throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): frontendApi is an https origin, such as https://clerk.example.com.');\n frontendApi = url.origin;\n if (options.publishableKey !== undefined && clerkFrontendApi(options.publishableKey) !== frontendApi) throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): publishableKey and frontendApi name different instances.');\n } else if (options.publishableKey !== undefined) frontendApi = clerkFrontendApi(options.publishableKey);\n else throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): give publishableKey (or frontendApi): tokens are checked against your instance.');\n const parties = options.authorizedParties;\n if (parties !== false && (!Array.isArray(parties) || parties.length === 0 || parties.some(party => typeof party !== 'string' || !/^https?:\\/\\/[^/\\s]+$/u.test(party)))) {\n throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): authorizedParties are the origins your users sign in from, such as https://app.example.com, or false where no browser is involved.');\n }\n if (options.allowPending !== undefined && typeof options.allowPending !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): allowPending must be a boolean.');\n const keys = options.jwtKey !== undefined ? pemKey(options.jwtKey) : remoteJwks({ url: `${frontendApi}/.well-known/jwks.json`, ...(options.fetch ? { fetch: options.fetch } : {}) });\n const verifier = jwtVerifier({ issuer: frontendApi, audience: false, algorithms: ['RS256'], keys, clockSkewMs: options.clockSkewMs ?? 5_000 });\n return jwtAuthenticator({\n verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),\n identity: claims => {\n // Clerk tokens carry no audience: the origin a token was made for (azp) stands for it.\n if (parties !== false && (typeof claims['azp'] !== 'string' || !parties.includes(claims['azp']))) return null;\n const session = clerkSession(claims);\n if (!session || (session.status === 'pending' && options.allowPending !== true)) return null;\n return options.identity(session);\n },\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mayurajs/auth-clerk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Clerk session tokens as Mayura server identities, verified with Clerk's published keys or its PEM key.",
|
|
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/auth-clerk"
|
|
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.1.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"provenance": true
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import {
|
|
3
|
+
jwtAuthenticator, jwtVerifier, remoteJwks,
|
|
4
|
+
type Authenticator, type IdentityGrant, type JwtClaims, type JwtKeySource,
|
|
5
|
+
} from 'mayura/auth';
|
|
6
|
+
|
|
7
|
+
/** A verified Clerk session, from its token's claims (version 2, or the older version 1). */
|
|
8
|
+
export interface ClerkSession {
|
|
9
|
+
/** The user (`sub`). */
|
|
10
|
+
readonly userId: string;
|
|
11
|
+
/** The session (`sid`). */
|
|
12
|
+
readonly sessionId: string;
|
|
13
|
+
/** The session's status (`sts`), such as `active` or `pending`. */
|
|
14
|
+
readonly status: string | null;
|
|
15
|
+
/** The active organization, when there is one. */
|
|
16
|
+
readonly orgId: string | null;
|
|
17
|
+
readonly orgSlug: string | null;
|
|
18
|
+
/** The user's role in it, as Clerk names roles: `org:admin`. */
|
|
19
|
+
readonly orgRole: string | null;
|
|
20
|
+
/** The user's permissions in it, as Clerk names them: `org:invoices:read`. */
|
|
21
|
+
readonly orgPermissions: readonly string[];
|
|
22
|
+
/** Someone acting as the user (impersonation), from the `act` claim. */
|
|
23
|
+
readonly actor: { readonly sub?: string; readonly sid?: string; readonly iss?: string } | null;
|
|
24
|
+
/** The token's claims, as verified. */
|
|
25
|
+
readonly claims: JwtClaims;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ClerkAuthenticatorOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Your Clerk publishable key (`pk_live_...` or `pk_test_...`), from which your Frontend API URL (the tokens' issuer
|
|
31
|
+
* and where its keys are published) is read. Or give `frontendApi`.
|
|
32
|
+
*/
|
|
33
|
+
readonly publishableKey?: string;
|
|
34
|
+
/** Your Clerk Frontend API URL, such as `https://clerk.example.com`. */
|
|
35
|
+
readonly frontendApi?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Your instance's JWKS public key (PEM, from the API keys page), to verify with no network at all. Without it, the
|
|
38
|
+
* keys are fetched from your Frontend API.
|
|
39
|
+
*/
|
|
40
|
+
readonly jwtKey?: string;
|
|
41
|
+
/**
|
|
42
|
+
* The origins your users sign in from, which a token's `azp` must be one of, as Clerk advises against CSRF. `false`
|
|
43
|
+
* only where no browser is involved.
|
|
44
|
+
*/
|
|
45
|
+
readonly authorizedParties: readonly string[] | false;
|
|
46
|
+
/** What a signed-in user may do, or null to refuse; for example from `session.orgPermissions` with `mapCapabilities`. */
|
|
47
|
+
readonly identity: (session: ClerkSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
|
|
48
|
+
/** Accept sessions Clerk marks `pending` (tasks such as choosing an organization not done yet); refused by default. */
|
|
49
|
+
readonly allowPending?: boolean;
|
|
50
|
+
/** Clock difference allowed; 5 s by default, as Clerk's own SDK. */
|
|
51
|
+
readonly clockSkewMs?: number;
|
|
52
|
+
/** The longest an identity lasts before the token is checked again; 60 s by default (Clerk tokens last 60 s). */
|
|
53
|
+
readonly maxIdentityMs?: number;
|
|
54
|
+
/** For tests and proxies: the fetch to use for the JWKS. */
|
|
55
|
+
readonly fetch?: typeof fetch;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
59
|
+
|
|
60
|
+
/** The Frontend API URL in a publishable key: `pk_<live|test>_` and the base64 of `<host>$`. */
|
|
61
|
+
export function clerkFrontendApi(publishableKey: string): string {
|
|
62
|
+
const match = typeof publishableKey === 'string' ? /^pk_(?:live|test)_([A-Za-z0-9+/=_-]+)$/u.exec(publishableKey) : null;
|
|
63
|
+
let host: string | undefined;
|
|
64
|
+
try { host = match ? decoder.decode(Uint8Array.from(atob(match[1]!.replace(/-/gu, '+').replace(/_/gu, '/')), char => char.charCodeAt(0))) : undefined; } catch { host = undefined; }
|
|
65
|
+
if (!host || !host.endsWith('$') || !/^[a-z0-9.-]+(?::\d{1,5})?$/iu.test(host.slice(0, -1))) throw new MayuraError('INVALID_CONFIG', 'publishableKey is a Clerk publishable key, pk_live_... or pk_test_....');
|
|
66
|
+
return `https://${host.slice(0, -1)}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A key source for one PEM public key (SPKI), RS256, as Clerk publishes it for networkless verification. */
|
|
70
|
+
function pemKey(pem: string): JwtKeySource {
|
|
71
|
+
const body = typeof pem === 'string' ? /-----BEGIN PUBLIC KEY-----([A-Za-z0-9+/=\s]+)-----END PUBLIC KEY-----/u.exec(pem)?.[1]?.replace(/\s+/gu, '') : undefined;
|
|
72
|
+
let der: Uint8Array;
|
|
73
|
+
try { der = Uint8Array.from(atob(body ?? '!'), char => char.charCodeAt(0)); } catch { throw new MayuraError('INVALID_CONFIG', 'jwtKey is your instance\'s PEM public key (-----BEGIN PUBLIC KEY-----...).'); }
|
|
74
|
+
const key = crypto.subtle.importKey('spki', der as Uint8Array<ArrayBuffer>, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']).catch(() => undefined);
|
|
75
|
+
return Object.freeze({
|
|
76
|
+
key: async () => {
|
|
77
|
+
const imported = await key;
|
|
78
|
+
if (!imported) throw new MayuraError('INVALID_CONFIG', 'jwtKey is not an RSA public key Mayura can use.');
|
|
79
|
+
// The verifier accepts RS256 alone.
|
|
80
|
+
return imported;
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Clerk's organization permissions from a version 2 token: features (`fea`), names (`o.per`) and bitmasks (`o.fpm`). */
|
|
86
|
+
export function clerkPermissions(claims: { readonly fea?: unknown; readonly o?: unknown; readonly [claim: string]: unknown }): string[] {
|
|
87
|
+
const org = claims.o as { per?: unknown; fpm?: unknown } | undefined;
|
|
88
|
+
if (typeof claims.fea !== 'string' || typeof org?.per !== 'string' || typeof org.fpm !== 'string') return [];
|
|
89
|
+
// Features scoped to organizations: `o:<feature>`, or both (`ou`, `uo`); as Clerk's own SDK reads them.
|
|
90
|
+
const features: string[] = [];
|
|
91
|
+
for (const part of claims.fea.split(',')) {
|
|
92
|
+
const item = part.trim(); const colon = item.indexOf(':');
|
|
93
|
+
if (colon === -1) return [];
|
|
94
|
+
if (['o', 'ou', 'uo'].includes(item.slice(0, colon))) features.push(item.slice(colon + 1));
|
|
95
|
+
}
|
|
96
|
+
const names = org.per.split(',').map(name => name.trim());
|
|
97
|
+
const masks = org.fpm.split(',').map(mask => mask.trim());
|
|
98
|
+
const permissions: string[] = [];
|
|
99
|
+
for (const [index, feature] of features.entries()) {
|
|
100
|
+
const mask = masks[index];
|
|
101
|
+
if (mask === undefined || !/^\d{1,300}$/u.test(mask)) continue;
|
|
102
|
+
// Bit 0 (the rightmost) is the first permission name.
|
|
103
|
+
const bits = BigInt(mask);
|
|
104
|
+
for (const [bit, name] of names.entries()) if ((bits >> BigInt(bit)) & 1n) permissions.push(`org:${feature}:${name}`);
|
|
105
|
+
}
|
|
106
|
+
return permissions;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** A Clerk session from verified claims, either token version. */
|
|
110
|
+
export function clerkSession(claims: JwtClaims): ClerkSession | undefined {
|
|
111
|
+
if (typeof claims.sub !== 'string' || claims.sub === '' || typeof claims['sid'] !== 'string') return undefined;
|
|
112
|
+
const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;
|
|
113
|
+
const actor = claims['act'] && typeof claims['act'] === 'object' ? claims['act'] as ClerkSession['actor'] : null;
|
|
114
|
+
const base = { userId: claims.sub, sessionId: claims['sid'], status: text(claims['sts']), actor, claims };
|
|
115
|
+
if (claims['v'] === 2) {
|
|
116
|
+
const org = claims['o'] as { id?: unknown; slg?: unknown; rol?: unknown } | undefined;
|
|
117
|
+
const orgId = text(org?.id);
|
|
118
|
+
return Object.freeze({ ...base, orgId, orgSlug: orgId ? text(org?.slg) : null, orgRole: orgId && text(org?.rol) ? `org:${org!.rol as string}` : null,
|
|
119
|
+
orgPermissions: Object.freeze(orgId ? clerkPermissions(claims) : []) });
|
|
120
|
+
}
|
|
121
|
+
// Version 1 (Clerk stopped issuing these in April 2025).
|
|
122
|
+
const orgId = text(claims['org_id']); const permissions = claims['org_permissions'];
|
|
123
|
+
return Object.freeze({ ...base, orgId, orgSlug: orgId ? text(claims['org_slug']) : null, orgRole: orgId ? text(claims['org_role']) : null,
|
|
124
|
+
orgPermissions: Object.freeze(orgId && Array.isArray(permissions) ? permissions.filter((item): item is string => typeof item === 'string') : []) });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A server `authenticate` for Clerk session tokens: RS256 tokens issued by your Frontend API, verified with its
|
|
129
|
+
* published keys (or your PEM key, with no network), from your own origins (`azp`), active (not `pending`), and
|
|
130
|
+
* no older than Clerk's 60-second lifetime allows. `identity` decides what the user may do.
|
|
131
|
+
*/
|
|
132
|
+
export function clerkAuthenticator(options: ClerkAuthenticatorOptions): Authenticator {
|
|
133
|
+
if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): identity decides what a signed-in user may do.');
|
|
134
|
+
let frontendApi: string;
|
|
135
|
+
if (options.frontendApi !== undefined) {
|
|
136
|
+
let url: URL;
|
|
137
|
+
try { url = new URL(options.frontendApi); } catch { throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): frontendApi is your Clerk Frontend API URL.'); }
|
|
138
|
+
if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password) throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): frontendApi is an https origin, such as https://clerk.example.com.');
|
|
139
|
+
frontendApi = url.origin;
|
|
140
|
+
if (options.publishableKey !== undefined && clerkFrontendApi(options.publishableKey) !== frontendApi) throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): publishableKey and frontendApi name different instances.');
|
|
141
|
+
} else if (options.publishableKey !== undefined) frontendApi = clerkFrontendApi(options.publishableKey);
|
|
142
|
+
else throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): give publishableKey (or frontendApi): tokens are checked against your instance.');
|
|
143
|
+
const parties = options.authorizedParties;
|
|
144
|
+
if (parties !== false && (!Array.isArray(parties) || parties.length === 0 || parties.some(party => typeof party !== 'string' || !/^https?:\/\/[^/\s]+$/u.test(party)))) {
|
|
145
|
+
throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): authorizedParties are the origins your users sign in from, such as https://app.example.com, or false where no browser is involved.');
|
|
146
|
+
}
|
|
147
|
+
if (options.allowPending !== undefined && typeof options.allowPending !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'clerkAuthenticator(): allowPending must be a boolean.');
|
|
148
|
+
const keys = options.jwtKey !== undefined ? pemKey(options.jwtKey) : remoteJwks({ url: `${frontendApi}/.well-known/jwks.json`, ...(options.fetch ? { fetch: options.fetch } : {}) });
|
|
149
|
+
const verifier = jwtVerifier({ issuer: frontendApi, audience: false, algorithms: ['RS256'], keys, clockSkewMs: options.clockSkewMs ?? 5_000 });
|
|
150
|
+
return jwtAuthenticator({
|
|
151
|
+
verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),
|
|
152
|
+
identity: claims => {
|
|
153
|
+
// Clerk tokens carry no audience: the origin a token was made for (azp) stands for it.
|
|
154
|
+
if (parties !== false && (typeof claims['azp'] !== 'string' || !parties.includes(claims['azp']))) return null;
|
|
155
|
+
const session = clerkSession(claims);
|
|
156
|
+
if (!session || (session.status === 'pending' && options.allowPending !== true)) return null;
|
|
157
|
+
return options.identity(session);
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
}
|