@mayurajs/auth-cognito 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 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,41 @@
1
- # Temporary Holding Version
1
+ # @mayurajs/auth-cognito
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html)
4
+ user pool tokens as Mayura server identities: verified with the pool's published keys, on any runtime, with no
5
+ dependency (no AWS SDK).
6
+
7
+ ```bash
8
+ npm install mayura @mayurajs/auth-cognito
9
+ ```
10
+
11
+ ```ts
12
+ import { mapCapabilities, principalId } from 'mayura/auth';
13
+ import { cognitoAuthenticator } from '@mayurajs/auth-cognito';
14
+
15
+ const authenticate = cognitoAuthenticator({
16
+ userPoolId: 'us-east-1_AbCdEf123',
17
+ clientIds: ['1example23456789abcdefghij'],
18
+ identity: session => ({
19
+ principalId: principalId('cognito', session.subject),
20
+ projectId: 'acme',
21
+ agentIds: ['support'],
22
+ capabilities: mapCapabilities(session.groups, { agents: ['runs:submit', 'runs:read'] }),
23
+ }),
24
+ });
25
+ // createAgentServer({ ..., authenticate })
26
+ ```
27
+
28
+ - **Which tokens.** RS256 tokens issued by the pool (`https://cognito-idp.<region>.amazonaws.com/<userPoolId>`, the
29
+ region read from the pool id), checked against its `/.well-known/jwks.json`, for one of your app clients. Access
30
+ tokens by default (`token_use` `access`, the client in `client_id`); with `tokenUse: 'id'`, ID tokens instead (the
31
+ client in `aud`). One is never accepted for the other.
32
+ - **Refused.** Machine tokens (client credentials: no user name, the client as subject) unless `allowMachines`.
33
+ Cognito can revoke tokens (sign-out, revoked refresh tokens) that still verify until they expire: keep access tokens
34
+ short-lived.
35
+ - **What you get.** `identity` receives the session: `tokenUse`, `subject` (`sub`, the stable key), `username`,
36
+ `clientId`, `machine`, `groups` (`cognito:groups`), `scopes` (access tokens), `email` and `emailVerified` (ID
37
+ tokens), and the raw `claims`. Nothing is granted unless `identity` grants it.
38
+ - Options: `userPoolId`, `clientIds`, `identity`, `tokenUse` (`access`), `allowMachines`, `clockSkewMs` (5 s),
39
+ `maxIdentityMs` (60 s), `fetch`.
40
+
41
+ See [Authentication and API keys](https://mayurajs.com/docs/guides/authentication/). Apache-2.0.
@@ -0,0 +1,50 @@
1
+ import { type Authenticator, type IdentityGrant, type JwtClaims } from 'mayura/auth';
2
+ /** A verified Amazon Cognito user pool token: an access token, or with `tokenUse: 'id'` an ID token. */
3
+ export interface CognitoSession {
4
+ readonly tokenUse: 'access' | 'id';
5
+ /** The user's id in the pool (`sub`), the stable key; or for a machine its app client id. */
6
+ readonly subject: string;
7
+ /** The user name (`username`, or `cognito:username` in ID tokens); null for a machine. */
8
+ readonly username: string | null;
9
+ /** The app client the token was issued to (`client_id`, or `aud` in ID tokens). */
10
+ readonly clientId: string;
11
+ /** Whether a machine holds it (client credentials: no user, its own client as subject). */
12
+ readonly machine: boolean;
13
+ /** The user pool groups the user is in (`cognito:groups`). */
14
+ readonly groups: readonly string[];
15
+ /** The scopes granted (`scope`, access tokens only). */
16
+ readonly scopes: readonly string[];
17
+ /** The email and whether it is verified (ID tokens only). */
18
+ readonly email: string | null;
19
+ readonly emailVerified: boolean;
20
+ /** The token's claims, as verified. */
21
+ readonly claims: JwtClaims;
22
+ }
23
+ export interface CognitoAuthenticatorOptions {
24
+ /** The user pool's id, such as `us-east-1_AbCdEf123`; its region is read from it. */
25
+ readonly userPoolId: string;
26
+ /** The app clients whose tokens are accepted. */
27
+ readonly clientIds: readonly string[];
28
+ /** What a token's holder may do, or null to refuse; for example from `session.groups` with `mapCapabilities`. */
29
+ readonly identity: (session: CognitoSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
30
+ /** Which tokens are accepted: `access` (the default, as APIs should), or `id`; never both. */
31
+ readonly tokenUse?: 'access' | 'id';
32
+ /** Accept machine (client credentials) access tokens; refused by default. */
33
+ readonly allowMachines?: boolean;
34
+ /** Clock difference allowed; 5 s by default. */
35
+ readonly clockSkewMs?: number;
36
+ /** The longest an identity lasts before the token is checked again; 60 s by default. */
37
+ readonly maxIdentityMs?: number;
38
+ /** For tests and proxies: the fetch to use for the JWKS. */
39
+ readonly fetch?: typeof fetch;
40
+ }
41
+ /** A Cognito session from verified claims; undefined when they are not a Cognito access or ID token's. */
42
+ export declare function cognitoSession(claims: JwtClaims): CognitoSession | undefined;
43
+ /**
44
+ * A server `authenticate` for Amazon Cognito user pool tokens: RS256 with the pool's published keys, issued by the pool
45
+ * (`https://cognito-idp.<region>.amazonaws.com/<pool>`) to one of your app clients. Access tokens by default, ID tokens
46
+ * only with `tokenUse: 'id'`, never one for the other. Machine tokens only with `allowMachines`. Cognito can revoke
47
+ * tokens that stay valid until they expire; keep them short-lived. `identity` decides what the holder may do.
48
+ */
49
+ export declare function cognitoAuthenticator(options: CognitoAuthenticatorOptions): Authenticator;
50
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAA6C,KAAK,aAAa,EAAE,KAAK,aAAa,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAEhI,wGAAwG;AACxG,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IACnC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AAC1G,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,GAAG,cAAc,GAAG,SAAS,CAc5E;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,aAAa,CAuBxF"}
package/dist/index.js ADDED
@@ -0,0 +1,59 @@
1
+ import { MayuraError } from 'mayura';
2
+ import { jwtAuthenticator, jwtVerifier, remoteJwks } from 'mayura/auth';
3
+ const text = (value) => typeof value === 'string' && value !== '' ? value : null;
4
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
5
+ /** A Cognito session from verified claims; undefined when they are not a Cognito access or ID token's. */
6
+ export function cognitoSession(claims) {
7
+ const tokenUse = claims['token_use'];
8
+ if (tokenUse !== 'access' && tokenUse !== 'id')
9
+ return undefined;
10
+ const clientId = tokenUse === 'access' ? text(claims['client_id']) : text(claims.aud);
11
+ if (clientId === null || typeof claims.sub !== 'string' || claims.sub === '')
12
+ return undefined;
13
+ const username = text(claims[tokenUse === 'access' ? 'username' : 'cognito:username']);
14
+ return Object.freeze({
15
+ tokenUse, subject: claims.sub, username, clientId,
16
+ // A client credentials token names no user, and its subject is its own client.
17
+ machine: tokenUse === 'access' && username === null && claims.sub === clientId,
18
+ groups: Object.freeze(strings(claims['cognito:groups'])),
19
+ scopes: Object.freeze(tokenUse === 'access' && typeof claims['scope'] === 'string' ? claims['scope'].split(' ').filter(Boolean) : []),
20
+ email: text(claims['email']), emailVerified: claims['email_verified'] === true, claims,
21
+ });
22
+ }
23
+ /**
24
+ * A server `authenticate` for Amazon Cognito user pool tokens: RS256 with the pool's published keys, issued by the pool
25
+ * (`https://cognito-idp.<region>.amazonaws.com/<pool>`) to one of your app clients. Access tokens by default, ID tokens
26
+ * only with `tokenUse: 'id'`, never one for the other. Machine tokens only with `allowMachines`. Cognito can revoke
27
+ * tokens that stay valid until they expire; keep them short-lived. `identity` decides what the holder may do.
28
+ */
29
+ export function cognitoAuthenticator(options) {
30
+ if (!options || typeof options.identity !== 'function')
31
+ throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): identity decides what a token\'s holder may do.');
32
+ const pool = typeof options.userPoolId === 'string' ? /^([a-z]{2}(?:-[a-z]+)+-\d{1,2})_[0-9A-Za-z]{1,64}$/u.exec(options.userPoolId) : null;
33
+ if (!pool)
34
+ throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): userPoolId is the user pool\'s id, such as us-east-1_AbCdEf123.');
35
+ const clientIds = options.clientIds;
36
+ if (!Array.isArray(clientIds) || clientIds.length === 0 || clientIds.some(id => typeof id !== 'string' || !/^[0-9a-z]{1,128}$/u.test(id)))
37
+ throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): clientIds are the user pool\'s app client ids.');
38
+ const tokenUse = options.tokenUse ?? 'access';
39
+ if (tokenUse !== 'access' && tokenUse !== 'id')
40
+ throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): tokenUse is access or id.');
41
+ if (options.allowMachines !== undefined && typeof options.allowMachines !== 'boolean')
42
+ throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): allowMachines must be a boolean.');
43
+ const issuer = `https://cognito-idp.${pool[1]}.amazonaws.com/${options.userPoolId}`;
44
+ const verifier = jwtVerifier({
45
+ // Access tokens carry no audience: the client (client_id, or an ID token's aud) is checked against clientIds below.
46
+ issuer, audience: false, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000,
47
+ keys: remoteJwks({ url: `${issuer}/.well-known/jwks.json`, ...(options.fetch ? { fetch: options.fetch } : {}) }),
48
+ });
49
+ return jwtAuthenticator({
50
+ verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),
51
+ identity: claims => {
52
+ const session = cognitoSession(claims);
53
+ if (!session || session.tokenUse !== tokenUse || !clientIds.includes(session.clientId) || (session.machine && options.allowMachines !== true))
54
+ return null;
55
+ return options.identity(session);
56
+ },
57
+ });
58
+ }
59
+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,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClG,QAAQ,EAAE,MAAM,CAAC,EAAE;YACjB,MAAM,OAAO,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;YACvC,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YAC3J,OAAO,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\nimport { jwtAuthenticator, jwtVerifier, remoteJwks, type Authenticator, type IdentityGrant, type JwtClaims } from 'mayura/auth';\n\n/** A verified Amazon Cognito user pool token: an access token, or with `tokenUse: 'id'` an ID token. */\nexport interface CognitoSession {\n readonly tokenUse: 'access' | 'id';\n /** The user's id in the pool (`sub`), the stable key; or for a machine its app client id. */\n readonly subject: string;\n /** The user name (`username`, or `cognito:username` in ID tokens); null for a machine. */\n readonly username: string | null;\n /** The app client the token was issued to (`client_id`, or `aud` in ID tokens). */\n readonly clientId: string;\n /** Whether a machine holds it (client credentials: no user, its own client as subject). */\n readonly machine: boolean;\n /** The user pool groups the user is in (`cognito:groups`). */\n readonly groups: readonly string[];\n /** The scopes granted (`scope`, access tokens only). */\n readonly scopes: readonly string[];\n /** The email and whether it is verified (ID tokens only). */\n readonly email: string | null;\n readonly emailVerified: boolean;\n /** The token's claims, as verified. */\n readonly claims: JwtClaims;\n}\n\nexport interface CognitoAuthenticatorOptions {\n /** The user pool's id, such as `us-east-1_AbCdEf123`; its region is read from it. */\n readonly userPoolId: string;\n /** The app clients whose tokens are accepted. */\n readonly clientIds: readonly string[];\n /** What a token's holder may do, or null to refuse; for example from `session.groups` with `mapCapabilities`. */\n readonly identity: (session: CognitoSession) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** Which tokens are accepted: `access` (the default, as APIs should), or `id`; never both. */\n readonly tokenUse?: 'access' | 'id';\n /** Accept machine (client credentials) access tokens; refused by default. */\n readonly allowMachines?: boolean;\n /** Clock difference allowed; 5 s by default. */\n readonly clockSkewMs?: number;\n /** The longest an identity lasts before the token is checked again; 60 s by default. */\n readonly maxIdentityMs?: number;\n /** For tests and proxies: the fetch to use for the JWKS. */\n readonly fetch?: typeof fetch;\n}\n\nconst text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;\nconst strings = (value: unknown): string[] => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];\n\n/** A Cognito session from verified claims; undefined when they are not a Cognito access or ID token's. */\nexport function cognitoSession(claims: JwtClaims): CognitoSession | undefined {\n const tokenUse = claims['token_use'];\n if (tokenUse !== 'access' && tokenUse !== 'id') return undefined;\n const clientId = tokenUse === 'access' ? text(claims['client_id']) : text(claims.aud);\n if (clientId === null || typeof claims.sub !== 'string' || claims.sub === '') return undefined;\n const username = text(claims[tokenUse === 'access' ? 'username' : 'cognito:username']);\n return Object.freeze({\n tokenUse, subject: claims.sub, username, clientId,\n // A client credentials token names no user, and its subject is its own client.\n machine: tokenUse === 'access' && username === null && claims.sub === clientId,\n groups: Object.freeze(strings(claims['cognito:groups'])),\n scopes: Object.freeze(tokenUse === 'access' && typeof claims['scope'] === 'string' ? claims['scope'].split(' ').filter(Boolean) : []),\n email: text(claims['email']), emailVerified: claims['email_verified'] === true, claims,\n });\n}\n\n/**\n * A server `authenticate` for Amazon Cognito user pool tokens: RS256 with the pool's published keys, issued by the pool\n * (`https://cognito-idp.<region>.amazonaws.com/<pool>`) to one of your app clients. Access tokens by default, ID tokens\n * only with `tokenUse: 'id'`, never one for the other. Machine tokens only with `allowMachines`. Cognito can revoke\n * tokens that stay valid until they expire; keep them short-lived. `identity` decides what the holder may do.\n */\nexport function cognitoAuthenticator(options: CognitoAuthenticatorOptions): Authenticator {\n if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): identity decides what a token\\'s holder may do.');\n const pool = typeof options.userPoolId === 'string' ? /^([a-z]{2}(?:-[a-z]+)+-\\d{1,2})_[0-9A-Za-z]{1,64}$/u.exec(options.userPoolId) : null;\n if (!pool) throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): userPoolId is the user pool\\'s id, such as us-east-1_AbCdEf123.');\n const clientIds = options.clientIds;\n if (!Array.isArray(clientIds) || clientIds.length === 0 || clientIds.some(id => typeof id !== 'string' || !/^[0-9a-z]{1,128}$/u.test(id))) throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): clientIds are the user pool\\'s app client ids.');\n const tokenUse = options.tokenUse ?? 'access';\n if (tokenUse !== 'access' && tokenUse !== 'id') throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): tokenUse is access or id.');\n if (options.allowMachines !== undefined && typeof options.allowMachines !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): allowMachines must be a boolean.');\n const issuer = `https://cognito-idp.${pool[1]}.amazonaws.com/${options.userPoolId}`;\n const verifier = jwtVerifier({\n // Access tokens carry no audience: the client (client_id, or an ID token's aud) is checked against clientIds below.\n issuer, audience: false, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000,\n keys: remoteJwks({ url: `${issuer}/.well-known/jwks.json`, ...(options.fetch ? { fetch: options.fetch } : {}) }),\n });\n return jwtAuthenticator({\n verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),\n identity: claims => {\n const session = cognitoSession(claims);\n if (!session || session.tokenUse !== tokenUse || !clientIds.includes(session.clientId) || (session.machine && options.allowMachines !== 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-cognito",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0",
4
+ "description": "Amazon Cognito user pool tokens as Mayura server identities, verified with the pool's published keys.",
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-cognito"
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,94 @@
1
+ import { MayuraError } from 'mayura';
2
+ import { jwtAuthenticator, jwtVerifier, remoteJwks, type Authenticator, type IdentityGrant, type JwtClaims } from 'mayura/auth';
3
+
4
+ /** A verified Amazon Cognito user pool token: an access token, or with `tokenUse: 'id'` an ID token. */
5
+ export interface CognitoSession {
6
+ readonly tokenUse: 'access' | 'id';
7
+ /** The user's id in the pool (`sub`), the stable key; or for a machine its app client id. */
8
+ readonly subject: string;
9
+ /** The user name (`username`, or `cognito:username` in ID tokens); null for a machine. */
10
+ readonly username: string | null;
11
+ /** The app client the token was issued to (`client_id`, or `aud` in ID tokens). */
12
+ readonly clientId: string;
13
+ /** Whether a machine holds it (client credentials: no user, its own client as subject). */
14
+ readonly machine: boolean;
15
+ /** The user pool groups the user is in (`cognito:groups`). */
16
+ readonly groups: readonly string[];
17
+ /** The scopes granted (`scope`, access tokens only). */
18
+ readonly scopes: readonly string[];
19
+ /** The email and whether it is verified (ID tokens only). */
20
+ readonly email: string | null;
21
+ readonly emailVerified: boolean;
22
+ /** The token's claims, as verified. */
23
+ readonly claims: JwtClaims;
24
+ }
25
+
26
+ export interface CognitoAuthenticatorOptions {
27
+ /** The user pool's id, such as `us-east-1_AbCdEf123`; its region is read from it. */
28
+ readonly userPoolId: string;
29
+ /** The app clients whose tokens are accepted. */
30
+ readonly clientIds: readonly string[];
31
+ /** What a token's holder may do, or null to refuse; for example from `session.groups` with `mapCapabilities`. */
32
+ readonly identity: (session: CognitoSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
33
+ /** Which tokens are accepted: `access` (the default, as APIs should), or `id`; never both. */
34
+ readonly tokenUse?: 'access' | 'id';
35
+ /** Accept machine (client credentials) access tokens; refused by default. */
36
+ readonly allowMachines?: boolean;
37
+ /** Clock difference allowed; 5 s by default. */
38
+ readonly clockSkewMs?: number;
39
+ /** The longest an identity lasts before the token is checked again; 60 s by default. */
40
+ readonly maxIdentityMs?: number;
41
+ /** For tests and proxies: the fetch to use for the JWKS. */
42
+ readonly fetch?: typeof fetch;
43
+ }
44
+
45
+ const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;
46
+ const strings = (value: unknown): string[] => Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
47
+
48
+ /** A Cognito session from verified claims; undefined when they are not a Cognito access or ID token's. */
49
+ export function cognitoSession(claims: JwtClaims): CognitoSession | undefined {
50
+ const tokenUse = claims['token_use'];
51
+ if (tokenUse !== 'access' && tokenUse !== 'id') return undefined;
52
+ const clientId = tokenUse === 'access' ? text(claims['client_id']) : text(claims.aud);
53
+ if (clientId === null || typeof claims.sub !== 'string' || claims.sub === '') return undefined;
54
+ const username = text(claims[tokenUse === 'access' ? 'username' : 'cognito:username']);
55
+ return Object.freeze({
56
+ tokenUse, subject: claims.sub, username, clientId,
57
+ // A client credentials token names no user, and its subject is its own client.
58
+ machine: tokenUse === 'access' && username === null && claims.sub === clientId,
59
+ groups: Object.freeze(strings(claims['cognito:groups'])),
60
+ scopes: Object.freeze(tokenUse === 'access' && typeof claims['scope'] === 'string' ? claims['scope'].split(' ').filter(Boolean) : []),
61
+ email: text(claims['email']), emailVerified: claims['email_verified'] === true, claims,
62
+ });
63
+ }
64
+
65
+ /**
66
+ * A server `authenticate` for Amazon Cognito user pool tokens: RS256 with the pool's published keys, issued by the pool
67
+ * (`https://cognito-idp.<region>.amazonaws.com/<pool>`) to one of your app clients. Access tokens by default, ID tokens
68
+ * only with `tokenUse: 'id'`, never one for the other. Machine tokens only with `allowMachines`. Cognito can revoke
69
+ * tokens that stay valid until they expire; keep them short-lived. `identity` decides what the holder may do.
70
+ */
71
+ export function cognitoAuthenticator(options: CognitoAuthenticatorOptions): Authenticator {
72
+ if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): identity decides what a token\'s holder may do.');
73
+ const pool = typeof options.userPoolId === 'string' ? /^([a-z]{2}(?:-[a-z]+)+-\d{1,2})_[0-9A-Za-z]{1,64}$/u.exec(options.userPoolId) : null;
74
+ if (!pool) throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): userPoolId is the user pool\'s id, such as us-east-1_AbCdEf123.');
75
+ const clientIds = options.clientIds;
76
+ if (!Array.isArray(clientIds) || clientIds.length === 0 || clientIds.some(id => typeof id !== 'string' || !/^[0-9a-z]{1,128}$/u.test(id))) throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): clientIds are the user pool\'s app client ids.');
77
+ const tokenUse = options.tokenUse ?? 'access';
78
+ if (tokenUse !== 'access' && tokenUse !== 'id') throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): tokenUse is access or id.');
79
+ if (options.allowMachines !== undefined && typeof options.allowMachines !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'cognitoAuthenticator(): allowMachines must be a boolean.');
80
+ const issuer = `https://cognito-idp.${pool[1]}.amazonaws.com/${options.userPoolId}`;
81
+ const verifier = jwtVerifier({
82
+ // Access tokens carry no audience: the client (client_id, or an ID token's aud) is checked against clientIds below.
83
+ issuer, audience: false, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000,
84
+ keys: remoteJwks({ url: `${issuer}/.well-known/jwks.json`, ...(options.fetch ? { fetch: options.fetch } : {}) }),
85
+ });
86
+ return jwtAuthenticator({
87
+ verifier, ...(options.maxIdentityMs !== undefined ? { maxIdentityMs: options.maxIdentityMs } : {}),
88
+ identity: claims => {
89
+ const session = cognitoSession(claims);
90
+ if (!session || session.tokenUse !== tokenUse || !clientIds.includes(session.clientId) || (session.machine && options.allowMachines !== true)) return null;
91
+ return options.identity(session);
92
+ },
93
+ });
94
+ }