@mayurajs/auth-entra 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,43 @@
1
- # Temporary Holding Version
1
+ # @mayurajs/auth-entra
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
+ [Microsoft Entra ID](https://learn.microsoft.com/entra/identity-platform/access-tokens) access tokens for your API as
4
+ Mayura server identities: verified with Microsoft's published keys, on any runtime, with no dependency (no MSAL).
5
+
6
+ ```bash
7
+ npm install mayura @mayurajs/auth-entra
8
+ ```
9
+
10
+ ```ts
11
+ import { mapCapabilities, principalId } from 'mayura/auth';
12
+ import { entraAuthenticator } from '@mayurajs/auth-entra';
13
+
14
+ const authenticate = entraAuthenticator({
15
+ tenants: ['11111111-1111-4111-8111-111111111111'], // or 'any' for a multi-tenant application
16
+ audience: ['aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'api://agents'], // your API's client id and app ID URI
17
+ identity: session => ({
18
+ principalId: principalId('entra', session.objectId),
19
+ projectId: session.tenantId,
20
+ agentIds: ['support'],
21
+ capabilities: mapCapabilities(session.roles, { 'Agents.Use': ['runs:submit', 'runs:read'] }),
22
+ }),
23
+ });
24
+ // createAgentServer({ ..., authenticate })
25
+ ```
26
+
27
+ - **Which tokens.** RS256 access tokens issued for your API (`aud`) by a tenant you list, with the issuer substituted
28
+ for that tenant (`https://login.microsoftonline.com/<tenant>/v2.0`), never matched by pattern. With `tenants: 'any'`
29
+ each token's issuer is still its own tenant's, and `identity` decides which tenants get anything.
30
+ - **Microsoft's keys.** v2.0 tokens are checked against `https://login.microsoftonline.com/common/discovery/v2.0/keys`.
31
+ A key that names its issuer verifies only that issuer's tokens, so a key bound to one tenant never verifies another's.
32
+ v1.0 tokens (`https://sts.windows.net/<tenant>/`, with `versions: ['1.0', '2.0']`) use the v1.0 key set. Tokens from
33
+ tenants not accepted never make it fetch.
34
+ - **Refused.** App-only tokens (client credentials, no `scp`) unless `allowApps`, tokens whose `tid` is not their
35
+ issuer's tenant, and tokens with no object id. It refuses to be configured for Microsoft Graph's audience: tokens for
36
+ Graph are Graph's to check.
37
+ - **What you get.** `identity` receives the session: `objectId` (the stable key, the same across your applications),
38
+ `tenantId`, `subject` (pairwise), `app`, `clientId`, `roles`, `scopes`, `name`, `username` (never a key), `version`
39
+ and the raw `claims`. Nothing is granted unless `identity` grants it.
40
+ - Options: `tenants`, `audience`, `identity`, `allowApps`, `versions` (`['2.0']`), `clockSkewMs` (5 s),
41
+ `maxIdentityMs` (60 s), `fetch`.
42
+
43
+ See [Authentication and API keys](https://mayurajs.com/docs/guides/authentication/). Apache-2.0.
@@ -0,0 +1,52 @@
1
+ import { type Authenticator, type IdentityGrant, type JwtClaims } from 'mayura/auth';
2
+ /** A verified Entra ID access token for your API. */
3
+ export interface EntraSession {
4
+ /** The user or service principal: its object id (`oid`), the same across your applications. */
5
+ readonly objectId: string;
6
+ /** The tenant the token was issued in (`tid`). */
7
+ readonly tenantId: string;
8
+ /** `sub`: pairwise, different for each application; prefer `objectId`. */
9
+ readonly subject: string;
10
+ /** Whether an application holds it on its own behalf (no delegated scopes), rather than a user. */
11
+ readonly app: boolean;
12
+ /** The client application the token was issued to (`azp` in v2.0 tokens, `appid` in v1.0). */
13
+ readonly clientId: string | null;
14
+ /** App roles: a user's assigned roles, or an application's granted permissions. */
15
+ readonly roles: readonly string[];
16
+ /** Delegated permissions granted to the client on the user's behalf (`scp`). */
17
+ readonly scopes: readonly string[];
18
+ readonly name: string | null;
19
+ /** The user's sign-in name (`preferred_username` in v2.0, `upn` or `unique_name` in v1.0); never a stable key. */
20
+ readonly username: string | null;
21
+ readonly version: '1.0' | '2.0';
22
+ /** The token's claims, as verified. */
23
+ readonly claims: JwtClaims;
24
+ }
25
+ export interface EntraAuthenticatorOptions {
26
+ /** The tenants (directory ids) accepted, or `any` for a multi-tenant application that accepts every tenant. */
27
+ readonly tenants: readonly string[] | 'any';
28
+ /** Your API's application (client) id, and its app ID URI if tokens name that instead. */
29
+ readonly audience: string | readonly string[];
30
+ /** What a token's holder may do, or null to refuse; for example from `session.roles` with `mapCapabilities`. */
31
+ readonly identity: (session: EntraSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
32
+ /** Accept app-only tokens (client credentials, no user); refused by default. */
33
+ readonly allowApps?: boolean;
34
+ /** The access token versions accepted: `['2.0']` by default (your API's `accessTokenAcceptedVersion`). */
35
+ readonly versions?: readonly ('1.0' | '2.0')[];
36
+ /** Clock difference allowed; 5 s by default. */
37
+ readonly clockSkewMs?: number;
38
+ /** The longest an identity lasts before the token is checked again; 60 s by default. */
39
+ readonly maxIdentityMs?: number;
40
+ /** For tests and proxies: the fetch to use for Microsoft's keys. */
41
+ readonly fetch?: typeof fetch;
42
+ }
43
+ /** An Entra session from verified claims; undefined without an object id and a tenant matching the issuer. */
44
+ export declare function entraSession(claims: JwtClaims): EntraSession | undefined;
45
+ /**
46
+ * A server `authenticate` for Microsoft Entra ID access tokens issued for your API: RS256 with Microsoft's keys (for
47
+ * the token's version; keys bound to a tenant verify only that tenant's tokens), from a tenant you accept, the issuer
48
+ * substituted for each tenant, never wildcarded. App-only tokens only with `allowApps`. `identity` decides what the
49
+ * holder may do; never accept tokens meant for Microsoft Graph, which this refuses to be configured for.
50
+ */
51
+ export declare function entraAuthenticator(options: EntraAuthenticatorOptions): Authenticator;
52
+ //# sourceMappingURL=index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GAAG,IAAI,CAAC,CAAC;IACnG,gFAAgF;IAChF,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B,0GAA0G;IAC1G,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,KAAK,GAAG,KAAK,CAAC,EAAE,CAAC;IAC/C,gDAAgD;IAChD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,wFAAwF;IACxF,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,oEAAoE;IACpE,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CAC/B;AAkBD,8GAA8G;AAC9G,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,YAAY,GAAG,SAAS,CAcxE;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,yBAAyB,GAAG,aAAa,CA6CpF"}
package/dist/index.js ADDED
@@ -0,0 +1,100 @@
1
+ import { MayuraError } from 'mayura';
2
+ import { jwtVerifier, peekIssuer, remoteJwks, serverIdentity, } from 'mayura/auth';
3
+ const guid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
4
+ /** Microsoft Graph: tokens for it are Graph's to check, never an API's. */
5
+ const graph = new Set(['00000003-0000-0000-c000-000000000000', 'https://graph.microsoft.com', 'https://graph.microsoft.com/']);
6
+ const issuerV2 = (tenant) => `https://login.microsoftonline.com/${tenant}/v2.0`;
7
+ const issuerV1 = (tenant) => `https://sts.windows.net/${tenant}/`;
8
+ const text = (value) => typeof value === 'string' && value !== '' ? value : null;
9
+ /** The tenant an issuer names, for either token version; undefined for any other issuer. */
10
+ function tenantOf(issuer) {
11
+ const v2 = issuer && /^https:\/\/login\.microsoftonline\.com\/([0-9a-f-]{36})\/v2\.0$/u.exec(issuer);
12
+ if (v2 && guid.test(v2[1]))
13
+ return { tenant: v2[1], version: '2.0' };
14
+ const v1 = issuer && /^https:\/\/sts\.windows\.net\/([0-9a-f-]{36})\/$/u.exec(issuer);
15
+ if (v1 && guid.test(v1[1]))
16
+ return { tenant: v1[1], version: '1.0' };
17
+ return undefined;
18
+ }
19
+ /** An Entra session from verified claims; undefined without an object id and a tenant matching the issuer. */
20
+ export function entraSession(claims) {
21
+ const issued = tenantOf(claims.iss);
22
+ const oid = claims['oid'];
23
+ const tid = claims['tid'];
24
+ if (!issued || typeof oid !== 'string' || !guid.test(oid) || tid !== issued.tenant || typeof claims.sub !== 'string' || claims.sub === '')
25
+ return undefined;
26
+ const scopes = typeof claims['scp'] === 'string' ? claims['scp'].split(' ').filter(Boolean) : [];
27
+ return Object.freeze({
28
+ objectId: oid, tenantId: tid, subject: claims.sub,
29
+ // Delegated tokens always carry scp; a token without it is an application's own.
30
+ app: typeof claims['scp'] !== 'string',
31
+ clientId: text(claims['azp']) ?? text(claims['appid']),
32
+ roles: Object.freeze(Array.isArray(claims['roles']) ? claims['roles'].filter((role) => typeof role === 'string') : []),
33
+ scopes: Object.freeze(scopes), name: text(claims['name']),
34
+ username: text(claims['preferred_username']) ?? text(claims['upn']) ?? text(claims['unique_name']), version: issued.version, claims,
35
+ });
36
+ }
37
+ /**
38
+ * A server `authenticate` for Microsoft Entra ID access tokens issued for your API: RS256 with Microsoft's keys (for
39
+ * the token's version; keys bound to a tenant verify only that tenant's tokens), from a tenant you accept, the issuer
40
+ * substituted for each tenant, never wildcarded. App-only tokens only with `allowApps`. `identity` decides what the
41
+ * holder may do; never accept tokens meant for Microsoft Graph, which this refuses to be configured for.
42
+ */
43
+ export function entraAuthenticator(options) {
44
+ if (!options || typeof options.identity !== 'function')
45
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): identity decides what a token\'s holder may do.');
46
+ const tenants = options.tenants;
47
+ if (tenants !== 'any' && (!Array.isArray(tenants) || tenants.length === 0 || tenants.some(tenant => typeof tenant !== 'string' || !guid.test(tenant)))) {
48
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): tenants are directory (tenant) ids, or any for a multi-tenant application.');
49
+ }
50
+ const audience = typeof options.audience === 'string' ? [options.audience] : options.audience;
51
+ if (!Array.isArray(audience) || audience.length === 0 || audience.some(item => typeof item !== 'string' || item === ''))
52
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): audience is your API\'s application id or app ID URI.');
53
+ if (audience.some(item => graph.has(item.toLowerCase())))
54
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): tokens for Microsoft Graph are Graph\'s to check: give your own API\'s audience.');
55
+ const versions = options.versions ?? ['2.0'];
56
+ if (!Array.isArray(versions) || versions.length === 0 || versions.some(version => version !== '1.0' && version !== '2.0'))
57
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): versions are 1.0 and/or 2.0.');
58
+ if (options.allowApps !== undefined && typeof options.allowApps !== 'boolean')
59
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): allowApps must be a boolean.');
60
+ const maxIdentityMs = options.maxIdentityMs ?? 60_000;
61
+ if (!Number.isSafeInteger(maxIdentityMs) || maxIdentityMs < 1_000 || maxIdentityMs > 3_600_000)
62
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): maxIdentityMs is 1,000 to 3,600,000.');
63
+ const fetchOption = options.fetch ? { fetch: options.fetch } : {};
64
+ // A key that names its issuer (a template with {tenantid}, or one tenant) verifies only tokens from that issuer.
65
+ const keyFilter = (key, claims) => typeof key['issuer'] !== 'string' || key['issuer'].replace('{tenantid}', String(claims['tid'])) === claims['iss'];
66
+ const v2Keys = remoteJwks({ url: 'https://login.microsoftonline.com/common/discovery/v2.0/keys', keyFilter, ...fetchOption });
67
+ const v1Keys = remoteJwks({ url: 'https://login.microsoftonline.com/common/discovery/keys', keyFilter, ...fetchOption });
68
+ // v1.0 and v2.0 tokens are signed with different key sets.
69
+ const keys = Object.freeze({
70
+ key: (header, keyOptions) => (typeof keyOptions.claims?.['iss'] === 'string' && keyOptions.claims['iss'].startsWith('https://sts.windows.net/') ? v1Keys : v2Keys).key(header, keyOptions),
71
+ });
72
+ // Either version's issuer for the tenant: tenantFor has already refused versions not accepted.
73
+ const verifierFor = (tenant) => jwtVerifier({
74
+ issuer: [issuerV2(tenant), issuerV1(tenant)], audience, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000, keys,
75
+ });
76
+ const verifiers = new Map();
77
+ if (tenants !== 'any')
78
+ for (const tenant of tenants)
79
+ verifiers.set(tenant, verifierFor(tenant));
80
+ const tenantFor = (token) => {
81
+ const issued = tenantOf(peekIssuer(token));
82
+ return issued && versions.includes(issued.version) && (tenants === 'any' || verifiers.has(issued.tenant)) ? issued.tenant : undefined;
83
+ };
84
+ const accepts = (token) => tenantFor(token) !== undefined;
85
+ const authenticate = async ({ token, signal }) => {
86
+ const tenant = tenantFor(token);
87
+ if (tenant === undefined)
88
+ return null;
89
+ // Any tenant: a verifier made for this token's tenant, its issuer substituted; nothing is kept for a tenant unseen.
90
+ const result = await (verifiers.get(tenant) ?? verifierFor(tenant)).verify(token, { signal });
91
+ if (!result.ok)
92
+ return null;
93
+ const session = entraSession(result.claims);
94
+ if (!session || (session.app && options.allowApps !== true))
95
+ return null;
96
+ return serverIdentity(await options.identity(session), { credentialExpiresAtMs: result.claims.exp * 1_000, maxIdentityMs });
97
+ };
98
+ return Object.assign(authenticate, { accepts });
99
+ }
100
+ //# 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,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,cAAc,GAEpD,MAAM,aAAa,CAAC;AA6CrB,MAAM,IAAI,GAAG,iEAAiE,CAAC;AAC/E,2EAA2E;AAC3E,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,sCAAsC,EAAE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dentityGrant, type JwtClaims, type JwtKeyFilter, type JwtKeySource, type JwtVerifier,\n} from 'mayura/auth';\n\n/** A verified Entra ID access token for your API. */\nexport interface EntraSession {\n /** The user or service principal: its object id (`oid`), the same across your applications. */\n readonly objectId: string;\n /** The tenant the token was issued in (`tid`). */\n readonly tenantId: string;\n /** `sub`: pairwise, different for each application; prefer `objectId`. */\n readonly subject: string;\n /** Whether an application holds it on its own behalf (no delegated scopes), rather than a user. */\n readonly app: boolean;\n /** The client application the token was issued to (`azp` in v2.0 tokens, `appid` in v1.0). */\n readonly clientId: string | null;\n /** App roles: a user's assigned roles, or an application's granted permissions. */\n readonly roles: readonly string[];\n /** Delegated permissions granted to the client on the user's behalf (`scp`). */\n readonly scopes: readonly string[];\n readonly name: string | null;\n /** The user's sign-in name (`preferred_username` in v2.0, `upn` or `unique_name` in v1.0); never a stable key. */\n readonly username: string | null;\n readonly version: '1.0' | '2.0';\n /** The token's claims, as verified. */\n readonly claims: JwtClaims;\n}\n\nexport interface EntraAuthenticatorOptions {\n /** The tenants (directory ids) accepted, or `any` for a multi-tenant application that accepts every tenant. */\n readonly tenants: readonly string[] | 'any';\n /** Your API's application (client) id, and its app ID URI if tokens name that instead. */\n readonly audience: string | readonly string[];\n /** What a token's holder may do, or null to refuse; for example from `session.roles` with `mapCapabilities`. */\n readonly identity: (session: EntraSession) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** Accept app-only tokens (client credentials, no user); refused by default. */\n readonly allowApps?: boolean;\n /** The access token versions accepted: `['2.0']` by default (your API's `accessTokenAcceptedVersion`). */\n readonly versions?: readonly ('1.0' | '2.0')[];\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 Microsoft's keys. */\n readonly fetch?: typeof fetch;\n}\n\nconst guid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;\n/** Microsoft Graph: tokens for it are Graph's to check, never an API's. */\nconst graph = new Set(['00000003-0000-0000-c000-000000000000', 'https://graph.microsoft.com', 'https://graph.microsoft.com/']);\nconst issuerV2 = (tenant: string) => `https://login.microsoftonline.com/${tenant}/v2.0`;\nconst issuerV1 = (tenant: string) => `https://sts.windows.net/${tenant}/`;\nconst text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;\n\n/** The tenant an issuer names, for either token version; undefined for any other issuer. */\nfunction tenantOf(issuer: string | undefined): { readonly tenant: string; readonly version: '1.0' | '2.0' } | undefined {\n const v2 = issuer && /^https:\\/\\/login\\.microsoftonline\\.com\\/([0-9a-f-]{36})\\/v2\\.0$/u.exec(issuer);\n if (v2 && guid.test(v2[1]!)) return { tenant: v2[1]!, version: '2.0' };\n const v1 = issuer && /^https:\\/\\/sts\\.windows\\.net\\/([0-9a-f-]{36})\\/$/u.exec(issuer);\n if (v1 && guid.test(v1[1]!)) return { tenant: v1[1]!, version: '1.0' };\n return undefined;\n}\n\n/** An Entra session from verified claims; undefined without an object id and a tenant matching the issuer. */\nexport function entraSession(claims: JwtClaims): EntraSession | undefined {\n const issued = tenantOf(claims.iss);\n const oid = claims['oid']; const tid = claims['tid'];\n if (!issued || typeof oid !== 'string' || !guid.test(oid) || tid !== issued.tenant || typeof claims.sub !== 'string' || claims.sub === '') return undefined;\n const scopes = typeof claims['scp'] === 'string' ? claims['scp'].split(' ').filter(Boolean) : [];\n return Object.freeze({\n objectId: oid, tenantId: tid, subject: claims.sub,\n // Delegated tokens always carry scp; a token without it is an application's own.\n app: typeof claims['scp'] !== 'string',\n clientId: text(claims['azp']) ?? text(claims['appid']),\n roles: Object.freeze(Array.isArray(claims['roles']) ? claims['roles'].filter((role): role is string => typeof role === 'string') : []),\n scopes: Object.freeze(scopes), name: text(claims['name']),\n username: text(claims['preferred_username']) ?? text(claims['upn']) ?? text(claims['unique_name']), version: issued.version, claims,\n });\n}\n\n/**\n * A server `authenticate` for Microsoft Entra ID access tokens issued for your API: RS256 with Microsoft's keys (for\n * the token's version; keys bound to a tenant verify only that tenant's tokens), from a tenant you accept, the issuer\n * substituted for each tenant, never wildcarded. App-only tokens only with `allowApps`. `identity` decides what the\n * holder may do; never accept tokens meant for Microsoft Graph, which this refuses to be configured for.\n */\nexport function entraAuthenticator(options: EntraAuthenticatorOptions): Authenticator {\n if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): identity decides what a token\\'s holder may do.');\n const tenants = options.tenants;\n if (tenants !== 'any' && (!Array.isArray(tenants) || tenants.length === 0 || tenants.some(tenant => typeof tenant !== 'string' || !guid.test(tenant)))) {\n throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): tenants are directory (tenant) ids, or any for a multi-tenant application.');\n }\n const audience = typeof options.audience === 'string' ? [options.audience] : options.audience;\n if (!Array.isArray(audience) || audience.length === 0 || audience.some(item => typeof item !== 'string' || item === '')) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): audience is your API\\'s application id or app ID URI.');\n if (audience.some(item => graph.has(item.toLowerCase()))) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): tokens for Microsoft Graph are Graph\\'s to check: give your own API\\'s audience.');\n const versions = options.versions ?? ['2.0'];\n if (!Array.isArray(versions) || versions.length === 0 || versions.some(version => version !== '1.0' && version !== '2.0')) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): versions are 1.0 and/or 2.0.');\n if (options.allowApps !== undefined && typeof options.allowApps !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): allowApps must be a boolean.');\n const maxIdentityMs = options.maxIdentityMs ?? 60_000;\n if (!Number.isSafeInteger(maxIdentityMs) || maxIdentityMs < 1_000 || maxIdentityMs > 3_600_000) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): maxIdentityMs is 1,000 to 3,600,000.');\n const fetchOption = options.fetch ? { fetch: options.fetch } : {};\n // A key that names its issuer (a template with {tenantid}, or one tenant) verifies only tokens from that issuer.\n const keyFilter: JwtKeyFilter = (key, claims) => typeof key['issuer'] !== 'string' || key['issuer'].replace('{tenantid}', String(claims['tid'])) === claims['iss'];\n const v2Keys = remoteJwks({ url: 'https://login.microsoftonline.com/common/discovery/v2.0/keys', keyFilter, ...fetchOption });\n const v1Keys = remoteJwks({ url: 'https://login.microsoftonline.com/common/discovery/keys', keyFilter, ...fetchOption });\n // v1.0 and v2.0 tokens are signed with different key sets.\n const keys: JwtKeySource = Object.freeze({\n key: (header: Parameters<JwtKeySource['key']>[0], keyOptions: Parameters<JwtKeySource['key']>[1]) => (typeof keyOptions.claims?.['iss'] === 'string' && keyOptions.claims['iss'].startsWith('https://sts.windows.net/') ? v1Keys : v2Keys).key(header, keyOptions),\n });\n // Either version's issuer for the tenant: tenantFor has already refused versions not accepted.\n const verifierFor = (tenant: string): JwtVerifier => jwtVerifier({\n issuer: [issuerV2(tenant), issuerV1(tenant)], audience, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000, keys,\n });\n const verifiers = new Map<string, JwtVerifier>();\n if (tenants !== 'any') for (const tenant of tenants) verifiers.set(tenant, verifierFor(tenant));\n const tenantFor = (token: string) => {\n const issued = tenantOf(peekIssuer(token));\n return issued && versions.includes(issued.version) && (tenants === 'any' || verifiers.has(issued.tenant)) ? issued.tenant : undefined;\n };\n const accepts = (token: string) => tenantFor(token) !== undefined;\n const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }) => {\n const tenant = tenantFor(token);\n if (tenant === undefined) return null;\n // Any tenant: a verifier made for this token's tenant, its issuer substituted; nothing is kept for a tenant unseen.\n const result = await (verifiers.get(tenant) ?? verifierFor(tenant)).verify(token, { signal });\n if (!result.ok) return null;\n const session = entraSession(result.claims);\n if (!session || (session.app && options.allowApps !== true)) return null;\n return serverIdentity(await options.identity(session), { credentialExpiresAtMs: result.claims.exp * 1_000, maxIdentityMs });\n };\n return Object.assign(authenticate, { accepts });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@mayurajs/auth-entra",
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": "Microsoft Entra ID access tokens for your API as Mayura server identities, single- or multi-tenant.",
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-entra"
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,134 @@
1
+ import { MayuraError } from 'mayura';
2
+ import {
3
+ jwtVerifier, peekIssuer, remoteJwks, serverIdentity,
4
+ type Authenticator, type IdentityGrant, type JwtClaims, type JwtKeyFilter, type JwtKeySource, type JwtVerifier,
5
+ } from 'mayura/auth';
6
+
7
+ /** A verified Entra ID access token for your API. */
8
+ export interface EntraSession {
9
+ /** The user or service principal: its object id (`oid`), the same across your applications. */
10
+ readonly objectId: string;
11
+ /** The tenant the token was issued in (`tid`). */
12
+ readonly tenantId: string;
13
+ /** `sub`: pairwise, different for each application; prefer `objectId`. */
14
+ readonly subject: string;
15
+ /** Whether an application holds it on its own behalf (no delegated scopes), rather than a user. */
16
+ readonly app: boolean;
17
+ /** The client application the token was issued to (`azp` in v2.0 tokens, `appid` in v1.0). */
18
+ readonly clientId: string | null;
19
+ /** App roles: a user's assigned roles, or an application's granted permissions. */
20
+ readonly roles: readonly string[];
21
+ /** Delegated permissions granted to the client on the user's behalf (`scp`). */
22
+ readonly scopes: readonly string[];
23
+ readonly name: string | null;
24
+ /** The user's sign-in name (`preferred_username` in v2.0, `upn` or `unique_name` in v1.0); never a stable key. */
25
+ readonly username: string | null;
26
+ readonly version: '1.0' | '2.0';
27
+ /** The token's claims, as verified. */
28
+ readonly claims: JwtClaims;
29
+ }
30
+
31
+ export interface EntraAuthenticatorOptions {
32
+ /** The tenants (directory ids) accepted, or `any` for a multi-tenant application that accepts every tenant. */
33
+ readonly tenants: readonly string[] | 'any';
34
+ /** Your API's application (client) id, and its app ID URI if tokens name that instead. */
35
+ readonly audience: string | readonly string[];
36
+ /** What a token's holder may do, or null to refuse; for example from `session.roles` with `mapCapabilities`. */
37
+ readonly identity: (session: EntraSession) => IdentityGrant | null | Promise<IdentityGrant | null>;
38
+ /** Accept app-only tokens (client credentials, no user); refused by default. */
39
+ readonly allowApps?: boolean;
40
+ /** The access token versions accepted: `['2.0']` by default (your API's `accessTokenAcceptedVersion`). */
41
+ readonly versions?: readonly ('1.0' | '2.0')[];
42
+ /** Clock difference allowed; 5 s by default. */
43
+ readonly clockSkewMs?: number;
44
+ /** The longest an identity lasts before the token is checked again; 60 s by default. */
45
+ readonly maxIdentityMs?: number;
46
+ /** For tests and proxies: the fetch to use for Microsoft's keys. */
47
+ readonly fetch?: typeof fetch;
48
+ }
49
+
50
+ const guid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
51
+ /** Microsoft Graph: tokens for it are Graph's to check, never an API's. */
52
+ const graph = new Set(['00000003-0000-0000-c000-000000000000', 'https://graph.microsoft.com', 'https://graph.microsoft.com/']);
53
+ const issuerV2 = (tenant: string) => `https://login.microsoftonline.com/${tenant}/v2.0`;
54
+ const issuerV1 = (tenant: string) => `https://sts.windows.net/${tenant}/`;
55
+ const text = (value: unknown) => typeof value === 'string' && value !== '' ? value : null;
56
+
57
+ /** The tenant an issuer names, for either token version; undefined for any other issuer. */
58
+ function tenantOf(issuer: string | undefined): { readonly tenant: string; readonly version: '1.0' | '2.0' } | undefined {
59
+ const v2 = issuer && /^https:\/\/login\.microsoftonline\.com\/([0-9a-f-]{36})\/v2\.0$/u.exec(issuer);
60
+ if (v2 && guid.test(v2[1]!)) return { tenant: v2[1]!, version: '2.0' };
61
+ const v1 = issuer && /^https:\/\/sts\.windows\.net\/([0-9a-f-]{36})\/$/u.exec(issuer);
62
+ if (v1 && guid.test(v1[1]!)) return { tenant: v1[1]!, version: '1.0' };
63
+ return undefined;
64
+ }
65
+
66
+ /** An Entra session from verified claims; undefined without an object id and a tenant matching the issuer. */
67
+ export function entraSession(claims: JwtClaims): EntraSession | undefined {
68
+ const issued = tenantOf(claims.iss);
69
+ const oid = claims['oid']; const tid = claims['tid'];
70
+ if (!issued || typeof oid !== 'string' || !guid.test(oid) || tid !== issued.tenant || typeof claims.sub !== 'string' || claims.sub === '') return undefined;
71
+ const scopes = typeof claims['scp'] === 'string' ? claims['scp'].split(' ').filter(Boolean) : [];
72
+ return Object.freeze({
73
+ objectId: oid, tenantId: tid, subject: claims.sub,
74
+ // Delegated tokens always carry scp; a token without it is an application's own.
75
+ app: typeof claims['scp'] !== 'string',
76
+ clientId: text(claims['azp']) ?? text(claims['appid']),
77
+ roles: Object.freeze(Array.isArray(claims['roles']) ? claims['roles'].filter((role): role is string => typeof role === 'string') : []),
78
+ scopes: Object.freeze(scopes), name: text(claims['name']),
79
+ username: text(claims['preferred_username']) ?? text(claims['upn']) ?? text(claims['unique_name']), version: issued.version, claims,
80
+ });
81
+ }
82
+
83
+ /**
84
+ * A server `authenticate` for Microsoft Entra ID access tokens issued for your API: RS256 with Microsoft's keys (for
85
+ * the token's version; keys bound to a tenant verify only that tenant's tokens), from a tenant you accept, the issuer
86
+ * substituted for each tenant, never wildcarded. App-only tokens only with `allowApps`. `identity` decides what the
87
+ * holder may do; never accept tokens meant for Microsoft Graph, which this refuses to be configured for.
88
+ */
89
+ export function entraAuthenticator(options: EntraAuthenticatorOptions): Authenticator {
90
+ if (!options || typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): identity decides what a token\'s holder may do.');
91
+ const tenants = options.tenants;
92
+ if (tenants !== 'any' && (!Array.isArray(tenants) || tenants.length === 0 || tenants.some(tenant => typeof tenant !== 'string' || !guid.test(tenant)))) {
93
+ throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): tenants are directory (tenant) ids, or any for a multi-tenant application.');
94
+ }
95
+ const audience = typeof options.audience === 'string' ? [options.audience] : options.audience;
96
+ if (!Array.isArray(audience) || audience.length === 0 || audience.some(item => typeof item !== 'string' || item === '')) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): audience is your API\'s application id or app ID URI.');
97
+ if (audience.some(item => graph.has(item.toLowerCase()))) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): tokens for Microsoft Graph are Graph\'s to check: give your own API\'s audience.');
98
+ const versions = options.versions ?? ['2.0'];
99
+ if (!Array.isArray(versions) || versions.length === 0 || versions.some(version => version !== '1.0' && version !== '2.0')) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): versions are 1.0 and/or 2.0.');
100
+ if (options.allowApps !== undefined && typeof options.allowApps !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): allowApps must be a boolean.');
101
+ const maxIdentityMs = options.maxIdentityMs ?? 60_000;
102
+ if (!Number.isSafeInteger(maxIdentityMs) || maxIdentityMs < 1_000 || maxIdentityMs > 3_600_000) throw new MayuraError('INVALID_CONFIG', 'entraAuthenticator(): maxIdentityMs is 1,000 to 3,600,000.');
103
+ const fetchOption = options.fetch ? { fetch: options.fetch } : {};
104
+ // A key that names its issuer (a template with {tenantid}, or one tenant) verifies only tokens from that issuer.
105
+ const keyFilter: JwtKeyFilter = (key, claims) => typeof key['issuer'] !== 'string' || key['issuer'].replace('{tenantid}', String(claims['tid'])) === claims['iss'];
106
+ const v2Keys = remoteJwks({ url: 'https://login.microsoftonline.com/common/discovery/v2.0/keys', keyFilter, ...fetchOption });
107
+ const v1Keys = remoteJwks({ url: 'https://login.microsoftonline.com/common/discovery/keys', keyFilter, ...fetchOption });
108
+ // v1.0 and v2.0 tokens are signed with different key sets.
109
+ const keys: JwtKeySource = Object.freeze({
110
+ key: (header: Parameters<JwtKeySource['key']>[0], keyOptions: Parameters<JwtKeySource['key']>[1]) => (typeof keyOptions.claims?.['iss'] === 'string' && keyOptions.claims['iss'].startsWith('https://sts.windows.net/') ? v1Keys : v2Keys).key(header, keyOptions),
111
+ });
112
+ // Either version's issuer for the tenant: tenantFor has already refused versions not accepted.
113
+ const verifierFor = (tenant: string): JwtVerifier => jwtVerifier({
114
+ issuer: [issuerV2(tenant), issuerV1(tenant)], audience, algorithms: ['RS256'], clockSkewMs: options.clockSkewMs ?? 5_000, keys,
115
+ });
116
+ const verifiers = new Map<string, JwtVerifier>();
117
+ if (tenants !== 'any') for (const tenant of tenants) verifiers.set(tenant, verifierFor(tenant));
118
+ const tenantFor = (token: string) => {
119
+ const issued = tenantOf(peekIssuer(token));
120
+ return issued && versions.includes(issued.version) && (tenants === 'any' || verifiers.has(issued.tenant)) ? issued.tenant : undefined;
121
+ };
122
+ const accepts = (token: string) => tenantFor(token) !== undefined;
123
+ const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }) => {
124
+ const tenant = tenantFor(token);
125
+ if (tenant === undefined) return null;
126
+ // Any tenant: a verifier made for this token's tenant, its issuer substituted; nothing is kept for a tenant unseen.
127
+ const result = await (verifiers.get(tenant) ?? verifierFor(tenant)).verify(token, { signal });
128
+ if (!result.ok) return null;
129
+ const session = entraSession(result.claims);
130
+ if (!session || (session.app && options.allowApps !== true)) return null;
131
+ return serverIdentity(await options.identity(session), { credentialExpiresAtMs: result.claims.exp * 1_000, maxIdentityMs });
132
+ };
133
+ return Object.assign(authenticate, { accepts });
134
+ }