@owf/openid-federation 0.0.0 → 0.6.0-alpha-20261025205149
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/dist/index.d.mts +16 -0
- package/dist/index.mjs +21 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +19 -20
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/dist/index.d.mts
CHANGED
|
@@ -173,6 +173,22 @@ export declare const fetcher: {
|
|
|
173
173
|
*
|
|
174
174
|
*/
|
|
175
175
|
export declare const addPaths: (baseUrl: string, ...paths: Array<string>) => string;
|
|
176
|
+
/**
|
|
177
|
+
*
|
|
178
|
+
* Add search params to a url, keeping the query component it already has (Section 5.1.1 allows one for the
|
|
179
|
+
* endpoints)
|
|
180
|
+
*
|
|
181
|
+
* ## example
|
|
182
|
+
*
|
|
183
|
+
* ```typescript
|
|
184
|
+
* const url = addSearchParams('https://example.org', { one: 'two' })
|
|
185
|
+
* assert(url, "https://example.org?one=two")
|
|
186
|
+
*
|
|
187
|
+
* const url = addSearchParams('https://example.org?tenant=a', { one: 'two' })
|
|
188
|
+
* assert(url, "https://example.org?tenant=a&one=two")
|
|
189
|
+
* ```
|
|
190
|
+
*
|
|
191
|
+
*/
|
|
176
192
|
export declare const addSearchParams: (baseUrl: string, searchParams: URLSearchParams | Record<string, string>) => string;
|
|
177
193
|
/**
|
|
178
194
|
*
|
package/dist/index.mjs
CHANGED
|
@@ -612,7 +612,27 @@ const addPaths = (baseUrl, ...paths) => {
|
|
|
612
612
|
if (!rest) throw new OpenIdFederationError("validation", "not a valid URL");
|
|
613
613
|
return `${scheme}://${rest.split("/").concat(...paths.map((p) => p.split("/"))).filter((s) => s.length > 0).join("/")}`;
|
|
614
614
|
};
|
|
615
|
-
|
|
615
|
+
/**
|
|
616
|
+
*
|
|
617
|
+
* Add search params to a url, keeping the query component it already has (Section 5.1.1 allows one for the
|
|
618
|
+
* endpoints)
|
|
619
|
+
*
|
|
620
|
+
* ## example
|
|
621
|
+
*
|
|
622
|
+
* ```typescript
|
|
623
|
+
* const url = addSearchParams('https://example.org', { one: 'two' })
|
|
624
|
+
* assert(url, "https://example.org?one=two")
|
|
625
|
+
*
|
|
626
|
+
* const url = addSearchParams('https://example.org?tenant=a', { one: 'two' })
|
|
627
|
+
* assert(url, "https://example.org?tenant=a&one=two")
|
|
628
|
+
* ```
|
|
629
|
+
*
|
|
630
|
+
*/
|
|
631
|
+
const addSearchParams = (baseUrl, searchParams) => {
|
|
632
|
+
const query = searchParams instanceof URLSearchParams ? searchParams : new URLSearchParams(searchParams);
|
|
633
|
+
if (!baseUrl.includes("?")) return `${baseUrl}?${query}`;
|
|
634
|
+
return baseUrl.endsWith("?") || baseUrl.endsWith("&") ? `${baseUrl}${query}` : `${baseUrl}&${query}`;
|
|
635
|
+
};
|
|
616
636
|
/**
|
|
617
637
|
*
|
|
618
638
|
* Compares two entity identifiers as Section 16 requires: code point by code point. A trailing slash is only removed
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/constraints.ts","../src/jsonWeb/createJsonWebToken.ts","../src/jsonWeb/createJsonWebTokenSignableInput.ts","../src/error/PolicyErrorStage.ts","../src/error/OpenIdFederationError.ts","../src/utils/validate.ts","../src/jsonWeb/jsonWebKey.ts","../src/jsonWeb/jsonWebKeySet.ts","../src/jsonWeb/getUsedJsonWebKey.ts","../src/jsonWeb/jsonWebToken.ts","../src/metadata/common.ts","../src/metadata/operator/MetadataMergeStrategy.ts","../src/metadata/operator/MetadataOrderOfApplication.ts","../src/metadata/operator/utils/createPolicyOperatorSchema.ts","../src/metadata/operator/utils/swapValidators.ts","../src/metadata/operator/standard/add.ts","../src/metadata/operator/standard/default.ts","../src/metadata/operator/standard/essential.ts","../src/metadata/operator/standard/oneOf.ts","../src/metadata/operator/standard/subsetOf.ts","../src/metadata/operator/standard/supersetOf.ts","../src/metadata/operator/standard/value.ts","../src/metadata/policy.ts","../src/metadata/entity/utils/createEntity.ts","../src/metadata/entity/federationEntity.ts","../src/metadata/entity/oauthAuthorizationServer.ts","../src/metadata/entity/oauthClient.ts","../src/metadata/entity/oauthResource.ts","../src/metadata/entity/openIdCredentialIssuer.ts","../src/metadata/entity/openIdCredentialVerifier.ts","../src/metadata/entity/openIdProvider.ts","../src/metadata/entity/openIdRelyingParty.ts","../src/metadata/metadata.ts","../src/utils/dateSchema.ts","../src/utils/url.ts","../src/utils/fetch.ts","../src/trustMark/trustMark.ts","../src/trustMark/trustMarkIssuer.ts","../src/trustMark/trustMarkOwner.ts","../src/entityStatement/entityStatementClaims.ts","../src/entityStatement/entityStatementHeader.ts","../src/entityStatement/createEntityStatement.ts","../src/jsonWeb/parseJsonWebToken.ts","../src/jsonWeb/verifyJsonWebToken.ts","../src/entityStatement/entityStatementJwt.ts","../src/entityStatement/fetchEntityStatement.ts","../src/entityConfiguration/entityConfigurationClaims.ts","../src/entityConfiguration/entityConfigurationHeader.ts","../src/entityConfiguration/createEntityConfiguration.ts","../src/entityConfiguration/entityConfigurationJwt.ts","../src/entityConfiguration/fetchEntityConfiguration.ts","../src/utils/data.ts","../src/resolveTrustChains/policies/errors/PolicyValidationError.ts","../src/resolveTrustChains/policies/MetadataHelper.ts","../src/resolveTrustChains/policies/utils.ts","../src/resolveTrustChains/policies/applyMetadataPolicyToMetadata.ts","../src/resolveTrustChains/policies/errors/PolicyMergeError.ts","../src/resolveTrustChains/policies/combineExistingMetadataPolicyOperators.ts","../src/resolveTrustChains/policies/combineMetadataPolicies.ts","../src/resolveTrustChains/resolveTrustChains.ts"],"sourcesContent":["import { z } from 'zod'\n\nexport const constraintSchema = z.object({\n max_path_length: z.number().optional(),\n naming_constraints: z\n .object({\n permitted: z.array(z.string()).optional(),\n excluded: z.array(z.string()).optional(),\n })\n .optional(),\n allowed_entity_types: z\n .array(\n z.string().refine((s) => s !== 'federation_entity', {\n message: `Value cannot be \"federation_entity\"`,\n })\n )\n .optional(),\n})\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#name-constraints | Constraints}\n *\n * Trust Anchors and Intermediate Entities MAY define constraining criteria that apply to their Subordinates. They are expressed in the constraints claim of a Subordinate Statement, as described in {@link https://openid.net/specs/openid-federation-1_0.html#entity-statement | Section 3}.\n *\n */\nexport type Constraint = z.input<typeof constraintSchema>\n","import { base64url, base64urlEncode } from '@owf/identity-common'\n\n/**\n *\n * Create a json web token according to {@link https://datatracker.ietf.org/doc/html/rfc7519 | RFC7519 }\n *\n */\nexport const createJsonWebToken = (\n header: Record<string, unknown>,\n payload: Record<string, unknown>,\n signature: Uint8Array\n) => {\n const encodedHeader = base64urlEncode(JSON.stringify(header))\n const encodedPayload = base64urlEncode(JSON.stringify(payload))\n\n const encodedSignature = base64url.encode(signature)\n\n return `${encodedHeader}.${encodedPayload}.${encodedSignature}`\n}\n","import { base64urlEncode, stringToBytes } from '@owf/identity-common'\n\n/**\n *\n * Converts a JSON header and payload into a byte array which can be used to verify and sign a JWT\n *\n */\nexport const createJwtSignableInput = (header: Record<string, unknown>, payload: Record<string, unknown>) => {\n if (Object.keys(header).length === 0) {\n throw new Error('Can not create JWT with an empty header')\n }\n\n if (Object.keys(payload).length === 0) {\n throw new Error('Can not create JWT with an empty payload')\n }\n\n const encodedHeader = base64urlEncode(JSON.stringify(header))\n const encodedPayload = base64urlEncode(JSON.stringify(payload))\n\n const toBeSignedString = `${encodedHeader}.${encodedPayload}`\n\n return stringToBytes(toBeSignedString)\n}\n","export enum PolicyErrorStage {\n Generic = 'generic',\n Validation = 'validation',\n MetadataPolicyCrit = 'metadataPolicyCrit',\n PolicyMerge = 'policyMerge',\n PolicyApply = 'policyApply',\n}\n","import type { ZodError } from 'zod'\nimport { PolicyErrorStage } from './PolicyErrorStage'\n\nexport class OpenIdFederationError extends Error {\n public constructor(\n public readonly errorCode: PolicyErrorStage,\n message?: string,\n public readonly cause?: unknown\n ) {\n super(message)\n }\n\n public static fromZodError(zodError: ZodError) {\n return new OpenIdFederationError(PolicyErrorStage.Validation, undefined, zodError)\n }\n\n public static isMetadataPolicyCritError(error: unknown) {\n return error instanceof OpenIdFederationError && error.errorCode === PolicyErrorStage.MetadataPolicyCrit\n }\n}\n","import type { z } from 'zod'\nimport { OpenIdFederationError } from '../error/OpenIdFederationError'\n\ntype ValidateOptions<Schema extends z.ZodType> = {\n data: z.input<Schema> | unknown\n schema: Schema\n errorMessage?: string\n}\n\nexport const validate = <Schema extends z.ZodType>({\n schema,\n data,\n errorMessage,\n}: ValidateOptions<Schema>): z.output<Schema> => {\n try {\n return schema.parse(data)\n } catch (e) {\n const error = OpenIdFederationError.fromZodError(e as z.ZodError)\n error.message = errorMessage ?? error.message\n throw error\n }\n}\n","import { z } from 'zod'\n\nexport const jsonWebKeySchema = z\n .object({\n kty: z.string(),\n // TODO: spec mentions kid may be undefined, but we always need a key id for open id federation\n kid: z.string(),\n use: z.string().optional(),\n key_ops: z.array(z.string()).optional(),\n alg: z.string().optional(),\n x5u: z.string().optional(),\n x5c: z.array(z.string()).optional(),\n x5t: z.string().optional(),\n 'x5t#S256': z.string().optional(),\n })\n .loose()\n\nexport type JsonWebKey = z.input<typeof jsonWebKeySchema>\n","import { z } from 'zod'\nimport { jsonWebKeySchema } from './jsonWebKey'\n\nexport const jsonWebKeySetSchema = z.object({\n keys: z.array(jsonWebKeySchema),\n})\n\nexport type JsonWebKeySetOptions = z.input<typeof jsonWebKeySetSchema>\n\nexport type JsonWebKeySet = z.output<typeof jsonWebKeySetSchema>\n","import { z } from 'zod'\nimport { validate } from '../utils/validate'\nimport { jsonWebKeySetSchema } from './jsonWebKeySet'\n\nexport const getUsedJsonWebKey = (header: Record<string, unknown>, claims: Record<string, unknown>) => {\n const validatedHeader = validate({\n schema: z\n .object({\n kid: z.string(),\n })\n .loose(),\n data: header,\n errorMessage: 'invalid header claims. Should contain a key id',\n })\n const validatedClaims = validate({\n schema: z.object({ jwks: jsonWebKeySetSchema }).loose(),\n data: claims,\n errorMessage: 'Invalid payload claims. Should contain a json web key set',\n })\n\n // Get the key from the `claims.jwks` by the `header.kid`\n const key = validatedClaims.jwks?.keys.find((key) => key.kid === validatedHeader.kid)\n\n if (!key) {\n throw new Error(`key with id: '${header.kid}' could not be found in the claims`)\n }\n\n return key\n}\n","import { base64url, base64urlDecodeJson } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { validate } from '../utils/validate'\n\nconst defaultSchema = z.record(z.string(), z.unknown())\n\n/**\n *\n * @todo better jwt validation\n *\n */\nexport const jsonWebTokenSchema = <\n CS extends z.ZodType = typeof defaultSchema,\n HS extends z.ZodType = typeof defaultSchema,\n>(\n {\n claimsSchema = defaultSchema as unknown as CS,\n headerSchema = defaultSchema as unknown as HS,\n }: {\n claimsSchema?: CS\n headerSchema?: HS\n } = {\n claimsSchema: defaultSchema as unknown as CS,\n headerSchema: defaultSchema as unknown as HS,\n }\n) =>\n z.string().transform((s, ctx) => {\n const [header, claims, signature] = s.split('.')\n\n if (!header) {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT does not contain a header parameter',\n })\n return z.NEVER\n }\n\n if (!claims) {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT does not contain a payload',\n })\n return z.NEVER\n }\n\n if (!signature) {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT does not contain a signature',\n })\n\n return z.NEVER\n }\n\n let decodedHeader: unknown\n let decodedClaims: unknown\n let decodedSignature: Uint8Array\n try {\n decodedHeader = base64urlDecodeJson(header)\n decodedClaims = base64urlDecodeJson(claims)\n decodedSignature = base64url.decode(signature)\n } catch {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT is not a valid compact JWS',\n })\n return z.NEVER\n }\n\n const validatedHeader = validate({\n schema: headerSchema,\n data: decodedHeader,\n errorMessage: 'invalid header claims provided',\n })\n const validatedClaims = validate({\n schema: claimsSchema,\n data: decodedClaims,\n errorMessage: 'invalid payload claims provided',\n })\n\n return {\n jwt: s,\n header: validatedHeader,\n claims: validatedClaims,\n signature: decodedSignature,\n }\n })\n","import { z } from 'zod'\nimport { jsonWebKeySetSchema } from '../jsonWeb'\n\nexport const commonMetadataSchema = z.object({\n // -- 5.2.1 Extensions for JWK Sets in Entity Metadata\n signed_jwks_uri: z.url().optional(),\n jwks_uri: z.url().optional(),\n jwks: jsonWebKeySetSchema.optional(),\n\n // -- 5.2.2 informational Metadata Extensions --\n organization_name: z.string().optional(),\n contacts: z.array(z.string()).min(1).optional(),\n logo_uri: z.url().optional(),\n policy_uri: z.url().optional(),\n homepage_uri: z.url().optional(),\n})\n","export enum MetadataMergeStrategy {\n /**\n *\n * Allowed only when the operator values are equal. If not, this MUST result in a policy error.\n *\n */\n OperatorValuesEqual = 0,\n /**\n *\n * The result of merging the values of two these operators is the union of the operator values.\n *\n */\n Union = 1,\n /**\n *\n * The result of merging the values of two these operators is the intersection of the operator values. If the intersection is empty, this MUST result in a policy error.\n *\n */\n Intersection = 2,\n /**\n *\n * The result of merging the values of two these operators is the logical disjunction (OR) of the operator values.\n *\n */\n LogicalOr = 3,\n /**\n *\n * The result of merging the values of two these operators is the intersection of the operator values. The intersection may be an empty array.\n *\n */\n IntersectionMayBeEmpty = 4,\n}\n","export enum MetadataOrderOfApplication {\n First = 0,\n AfterValue = 1,\n AfterAdd = 2,\n AfterDefault = 3,\n AfterOneOf = 4,\n AfterSubsetOf = 5,\n Last = 6,\n}\n","import type { MetadataOperator } from '../MetadataOperator'\n\nexport const createPolicyOperatorSchema = <TKey extends string>(operator: MetadataOperator<TKey>) =>\n ({\n /**\n * The key of the operator which is used to identify the operator\n */\n key: operator.key,\n /**\n * The merge strategy of the operator\n */\n mergeStrategy: operator.mergeStrategy,\n /**\n * The order of application of the operator\n */\n orderOfApplication: operator.orderOfApplication,\n /**\n * The operator itself\n */\n operator: operator,\n /**\n * The schema for the operator itself so for essential it is only a boolean\n */\n operatorSchema: operator.operatorJsonValues.reduce((acc, schema) => acc.or(schema)).optional(),\n /**\n * The schema for the parameter the operator can be applied to so when the policy is targeting federation_entity we can check if the policy can handle that property\n */\n parameterSchema: operator.parameterJsonValues.reduce((acc, schema) => acc.or(schema)).optional(),\n }) as const\n","import { z } from 'zod'\n\nexport const swapValidators = <T extends z.ZodRawShape, V extends z.ZodType>(\n schema: z.ZodObject<T>,\n newValidator: V\n): z.ZodObject<{ [K in keyof T]: V }> => {\n return z.object(\n Object.keys(schema.shape).reduce(\n (acc, key) => {\n acc[key as keyof typeof acc] = newValidator\n return acc\n },\n {} as { [K in keyof T]: V }\n )\n )\n}\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const addOperator = createPolicyOperatorSchema({\n key: 'add',\n parameterJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'default', 'subset_of', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterValue,\n mergeStrategy: MetadataMergeStrategy.Union,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const defaultOperator = createPolicyOperatorSchema({\n key: 'default',\n parameterJsonValues: [z.string(), z.number(), z.boolean(), z.record(z.string(), z.unknown()), z.array(z.unknown())],\n operatorJsonValues: [z.string(), z.number(), z.boolean(), z.record(z.string(), z.unknown()), z.array(z.unknown())],\n canBeCombinedWith: ['value', 'add', 'one_of', 'subset_of', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterAdd,\n mergeStrategy: MetadataMergeStrategy.OperatorValuesEqual,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const essentialOperator = createPolicyOperatorSchema({\n key: 'essential',\n parameterJsonValues: [\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), z.string().or(z.number())),\n z.unknown(),\n z.array(z.unknown()),\n ],\n operatorJsonValues: [z.boolean()],\n canBeCombinedWith: ['add', 'default', 'one_of', 'subset_of', 'superset_of', 'value'],\n orderOfApplication: MetadataOrderOfApplication.Last,\n mergeStrategy: MetadataMergeStrategy.LogicalOr,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const oneOfOperator = createPolicyOperatorSchema({\n key: 'one_of',\n parameterJsonValues: [\n z.string(),\n // TODO: See how we want to we handle the comparison of objects\n // z.record(z.string(), z.unknown()),\n z.number(),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'default', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterDefault,\n mergeStrategy: MetadataMergeStrategy.Intersection,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const subsetOfOperator = createPolicyOperatorSchema({\n key: 'subset_of',\n parameterJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'add', 'default', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterOneOf,\n mergeStrategy: MetadataMergeStrategy.IntersectionMayBeEmpty,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const supersetOfOperator = createPolicyOperatorSchema({\n key: 'superset_of',\n parameterJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'add', 'default', 'subset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterSubsetOf,\n mergeStrategy: MetadataMergeStrategy.Union,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const valueOperator = createPolicyOperatorSchema({\n key: 'value',\n parameterJsonValues: [z.string(), z.number(), z.boolean(), z.record(z.string(), z.unknown()), z.array(z.unknown())],\n operatorJsonValues: [\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), z.unknown()),\n z.array(z.unknown()),\n z.null(),\n ],\n canBeCombinedWith: ['add', 'default', 'one_of', 'subset_of', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.First,\n mergeStrategy: MetadataMergeStrategy.OperatorValuesEqual,\n})\n","import { z } from 'zod'\nimport {\n addOperator,\n defaultOperator,\n essentialOperator,\n oneOfOperator,\n subsetOfOperator,\n supersetOfOperator,\n valueOperator,\n} from './operator'\n\nexport const allSupportedPolicies = {\n [addOperator.key]: addOperator,\n [defaultOperator.key]: defaultOperator,\n [essentialOperator.key]: essentialOperator,\n [oneOfOperator.key]: oneOfOperator,\n [subsetOfOperator.key]: subsetOfOperator,\n [supersetOfOperator.key]: supersetOfOperator,\n [valueOperator.key]: valueOperator,\n} as const\n\nexport type SupportedPolicyKey = keyof typeof allSupportedPolicies\n\nexport const isExistingPolicyKey = (key: string): key is SupportedPolicyKey => key in allSupportedPolicies\n\nconst isSubset = (values: unknown, of: unknown) =>\n Array.isArray(values) && Array.isArray(of) && values.every((value) => of.includes(value))\n\n/**\n * The conditions that Section 6.1.3.1 sets on combinations of the standard operators.\n */\nconst conditionalCombinationErrors = (policy: Record<string, unknown>): Array<string> => {\n const errors: Array<string> = []\n const has = (key: SupportedPolicyKey) => policy[key] !== undefined\n const { value, add, one_of, subset_of, superset_of, essential } = policy\n\n if (has('value')) {\n // A null value removes the metadata parameter, so it has no values for add, subset_of and superset_of\n const values = value === null ? [] : value\n if (value === null && has('default')) errors.push(\"'value' null can not be combined with 'default'\")\n if (value === null && essential === true) errors.push(\"'value' null can not be combined with 'essential' true\")\n if (has('add') && !isSubset(add, values))\n errors.push(\"the values of 'add' must be a subset of the values of 'value'\")\n if (has('one_of') && !(Array.isArray(one_of) && value !== null && one_of.includes(value)))\n errors.push(\"the value of 'value' must be among the 'one_of' values\")\n if (has('subset_of') && !isSubset(values, subset_of))\n errors.push(\"the values of 'value' must be a subset of the values of 'subset_of'\")\n if (has('superset_of') && !isSubset(superset_of, values))\n errors.push(\"the values of 'value' must be a superset of the values of 'superset_of'\")\n }\n if (has('add') && has('subset_of') && !isSubset(add, subset_of))\n errors.push(\"the values of 'add' must be a subset of the values of 'subset_of'\")\n if (has('subset_of') && has('superset_of') && !isSubset(superset_of, subset_of))\n errors.push(\"the values of 'subset_of' must be a superset of the values of 'superset_of'\")\n\n return errors\n}\n\nexport const metadataPolicySchema = z\n .object(\n Object.entries(allSupportedPolicies).reduce(\n // biome-ignore lint/performance/noAccumulatingSpread: In this case we want to use the spread operator\n (acc, [key, policy]) => ({ ...acc, [key]: policy.operatorSchema }),\n {} as {\n [key in keyof typeof allSupportedPolicies]: (typeof allSupportedPolicies)[key]['operatorSchema']\n }\n )\n )\n .and(z.record(z.string(), z.any()))\n .superRefine((data, ctx) => {\n const dataKeys = Object.keys(data)\n\n for (const dataKey of dataKeys) {\n if (!isExistingPolicyKey(dataKey)) continue\n const { operator } = allSupportedPolicies[dataKey]\n\n // Additional operators that are not understood are ignored (Section 6.1.3.2), so they do not restrict combinations\n if (\n dataKeys.some(\n (key) => key !== operator.key && isExistingPolicyKey(key) && !operator.canBeCombinedWith.includes(key)\n )\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `policy operator '${\n operator.key\n }' can only be combined with one of: [${operator.canBeCombinedWith.join(\n ', '\n )}]. keys: [${Object.keys(data).join(',')}]`,\n })\n }\n }\n\n for (const message of conditionalCombinationErrors(data)) {\n ctx.addIssue({ code: 'custom', message })\n }\n })\n\nexport type MetadataPolicyOperator = z.input<typeof metadataPolicySchema>\n","import type { z } from 'zod'\nimport { commonMetadataSchema } from '../../common'\nimport { swapValidators } from '../../operator'\nimport { metadataPolicySchema } from '../../policy'\n\nexport const createEntity = <T extends string, S extends z.ZodRawShape>({\n identifier,\n additionalValidation = {} as S,\n}: {\n identifier: T\n additionalValidation?: S\n}) => {\n const schema = commonMetadataSchema.extend(additionalValidation)\n return {\n identifier,\n // Metadata parameters the schema does not define are kept, for example the protocol specific parameters of\n // `oauth_authorization_server`. Dropping them would remove them from the resolved metadata.\n schema: schema.loose(),\n policySchema: swapValidators(schema, metadataPolicySchema.optional()),\n }\n}\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.1-1 | Federation Entity}\n *\n */\nexport const federationEntityMetadata = createEntity({\n identifier: 'federation_entity',\n additionalValidation: {\n federation_fetch_endpoint: z.url().optional(),\n federation_list_endpoint: z.url().optional(),\n federation_resolve_endpoint: z.url().optional(),\n federation_trust_mark_status_endpoint: z.url().optional(),\n federation_trust_mark_list_endpoint: z.url().optional(),\n federation_trust_mark_endpoint: z.url().optional(),\n federation_historical_keys_endpoint: z.url().optional(),\n },\n})\n\nexport type FederationEntityMetadata = z.input<(typeof federationEntityMetadata)['schema']>\n","import type { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * https://openid.net/specs/openid-federation-1_0.html#section-5.1.4-1\n *\n */\nexport const oauthAuthorizationServerEntityMetadata = createEntity({\n identifier: 'oauth_authorization_server',\n})\n\nexport type OauthAuthorizationServerMetadata = z.input<(typeof oauthAuthorizationServerEntityMetadata)['schema']>\n","import type { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.5-1 | oauth Client}\n *\n */\nexport const oauthClientEntityMetadata = createEntity({ identifier: 'oauth_client' })\n\nexport type OauthClientMetadata = z.input<(typeof oauthClientEntityMetadata)['schema']>\n","import type { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * https://openid.net/specs/openid-federation-1_0.html#section-5.1.6\n *\n */\nexport const oauthResourceEntityMetadata = createEntity({\n identifier: 'oauth_resource',\n})\n\nexport type OauthResourceMetadata = z.input<(typeof oauthResourceEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.github.io/federation-wallet/main.html#name-wallet-architecture-entity- | OpenID Credential Issuer}\n *\n */\nexport const openIdCredentialIssuerEntityMetadata = createEntity({\n identifier: 'openid_credential_issuer',\n additionalValidation: {\n client_registration_types_supported: z.array(z.string()).optional(),\n federation_registration_endpoint: z.url().optional(),\n request_authentication_methods_supported: z\n .object({\n authorization_endpoint: z.array(z.string()).optional(),\n pushed_authorization_request_endpoint: z.array(z.string()).optional(),\n })\n .optional(),\n request_authentication_signing_alg_values_supported: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdCredentialIssuerMetadata = z.input<(typeof openIdCredentialIssuerEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.github.io/federation-wallet/main.html#name-wallet-architecture-entity- | OpenID Credential Verifier }\n *\n */\nexport const openidCredentialVerifierEntityMetadata = createEntity({\n identifier: 'openid_credential_verifier',\n additionalValidation: {\n client_registration_types: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdCredentialVerifierMetadata = z.input<(typeof openidCredentialVerifierEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.3-1 | openID Provider}\n *\n */\nexport const openIdProviderEntityMetadata = createEntity({\n identifier: 'openid_provider',\n additionalValidation: {\n client_registration_types_supported: z.array(z.string()).optional(),\n federation_registration_endpoint: z.url().optional(),\n request_authentication_methods_supported: z\n .object({\n authorization_endpoint: z.array(z.string()).optional(),\n pushed_authorization_request_endpoint: z.array(z.string()).optional(),\n })\n .optional(),\n request_authentication_signing_alg_values_supported: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdProviderMetadata = z.input<(typeof openIdProviderEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.2-1 | openID Relying Party }\n *\n */\nexport const openidRelyingPartyEntityMetadata = createEntity({\n identifier: 'openid_relying_party',\n additionalValidation: {\n client_registration_types: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdRelyingPartyMetadata = z.input<(typeof openidRelyingPartyEntityMetadata)['schema']>\n","import { z } from 'zod'\n\nimport {\n federationEntityMetadata,\n oauthAuthorizationServerEntityMetadata,\n oauthClientEntityMetadata,\n oauthResourceEntityMetadata,\n openIdCredentialIssuerEntityMetadata,\n openIdProviderEntityMetadata,\n openidCredentialVerifierEntityMetadata,\n openidRelyingPartyEntityMetadata,\n} from './entity'\n\nexport const metadataSchema = z\n .object({\n [federationEntityMetadata.identifier]: federationEntityMetadata.schema.optional(),\n [openidRelyingPartyEntityMetadata.identifier]: openidRelyingPartyEntityMetadata.schema.optional(),\n [openidCredentialVerifierEntityMetadata.identifier]: openidCredentialVerifierEntityMetadata.schema.optional(),\n [openIdCredentialIssuerEntityMetadata.identifier]: openIdCredentialIssuerEntityMetadata.schema.optional(),\n [openIdProviderEntityMetadata.identifier]: openIdProviderEntityMetadata.schema.optional(),\n [oauthAuthorizationServerEntityMetadata.identifier]: oauthAuthorizationServerEntityMetadata.schema.optional(),\n [oauthClientEntityMetadata.identifier]: oauthClientEntityMetadata.schema.optional(),\n [oauthResourceEntityMetadata.identifier]: oauthResourceEntityMetadata.schema.optional(),\n })\n // Entity types not defined here are kept unvalidated, as OpenID Federation allows further entity types.\n .loose()\n\nexport type Metadata = z.input<typeof metadataSchema>\n","import { z } from 'zod'\n\n/**\n *\n * NumericDate (RFC 7519 Section 2): seconds since the epoch, parsed to a js date object\n *\n */\nexport const dateSchema = z.number().transform((seconds) => new Date(seconds * 1000))\n","import { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\n\n/**\n *\n * Add paths to a url\n *\n * ## example\n *\n * ```typescript\n * const url = addPaths('https://example.org','path', 'two')\n * assert(url, \"https://example.org/path/two\")\n *\n * const url = addPaths('https://example.org/','path', 'two')\n * assert(url, \"https://example.org/path/two\")\n *\n * const url = addPaths('https://example.org/','path/', '/two/')\n * assert(url, \"https://example.org/path/two\")\n * ```\n *\n */\nexport const addPaths = (baseUrl: string, ...paths: Array<string>) => {\n const [scheme, rest] = baseUrl.split('://')\n if (!rest) {\n throw new OpenIdFederationError(PolicyErrorStage.Validation, 'not a valid URL')\n }\n\n const urlWithoutScheme = rest\n // Get all base the parts\n .split('/')\n // Add the paths\n .concat(...paths.map((p) => p.split('/')))\n // Filter out empty paths (i.e. '///path///' to 'path')\n .filter((s) => s.length > 0)\n // Create the full url\n .join('/')\n\n return `${scheme}://${urlWithoutScheme}`\n}\n\nexport const addSearchParams = (baseUrl: string, searchParams: URLSearchParams | Record<string, string>) =>\n baseUrl.endsWith('?')\n ? `${baseUrl}${searchParams instanceof URLSearchParams ? searchParams : new URLSearchParams(searchParams)}`\n : `${baseUrl}?${searchParams instanceof URLSearchParams ? searchParams : new URLSearchParams(searchParams)}`\n\n/**\n *\n * Compares two entity identifiers as Section 16 requires: code point by code point. A trailing slash is only removed\n * when building the well-known URL.\n *\n */\nexport const isSameEntityId = (a: string, b: string) => a === b\n","import { isMediaType } from '@owf/identity-common'\nimport type { z } from 'zod'\nimport type { FetchCallback } from './types'\nimport { addSearchParams } from './url'\nimport { validate } from './validate'\n\n// Resolved on every call, so a fetch that is set or replaced after this module is loaded is used\nconst defaultFetch: FetchCallback = (input, init) => globalThis.fetch(input, init)\n\ntype GetOptions = {\n url: string\n searchParams?: Record<string, string>\n requiredContentType?: string\n fetchCallback?: FetchCallback\n}\n\n/**\n *\n * Fetch the url and return the JSON response validated against the schema, or the text response without a schema\n *\n */\nasync function get<T extends z.ZodType>(options: GetOptions & { responseValidationSchema: T }): Promise<z.output<T>>\nasync function get(options: GetOptions & { responseValidationSchema?: undefined }): Promise<string>\nasync function get({\n url,\n searchParams,\n responseValidationSchema,\n requiredContentType,\n fetchCallback = defaultFetch,\n}: GetOptions & { responseValidationSchema?: z.ZodType }): Promise<unknown> {\n // Fetch the url with the search params\n const urlSearchParams = new URLSearchParams(searchParams)\n const urlWithSearchParams = urlSearchParams.toString() ? addSearchParams(url, urlSearchParams) : url\n const response = await fetchCallback(urlWithSearchParams, {\n method: 'GET',\n })\n\n if (!response.ok) {\n throw new Error(`request to '${urlWithSearchParams}' failed with status ${response.status}`)\n }\n\n // validate the expected content-type, ignoring parameters such as `charset` and case (RFC 9110 8.3.1)\n if (requiredContentType && !isMediaType(response.headers.get('content-type'), requiredContentType)) {\n throw new Error(\n `received content-type '${response.headers.get(\n 'content-type'\n )}' does not equal expected content-type '${requiredContentType}'`\n )\n }\n\n // If we pass in a validation schema, we expect JSON output\n if (responseValidationSchema) {\n const json = await response.json()\n return validate({\n data: json,\n schema: responseValidationSchema,\n errorMessage: 'invalid response from the GET call',\n })\n }\n\n // If no validation schema is passed in, we expect a string as response\n const text = await response.text()\n return text\n}\n\n/**\n *\n * @todo make get/post use the same method private internally as changes with apply to both\n *\n */\nconst post = async ({\n url,\n body,\n responseValidationSchema,\n fetchCallback = defaultFetch,\n}: {\n url: string\n body?: Record<string, unknown>\n responseValidationSchema?: z.ZodType\n fetchCallback?: FetchCallback\n}) => {\n const response = await fetchCallback(url, {\n method: 'POST',\n body: body ? JSON.stringify(body) : undefined,\n headers: { 'Content-Type': 'application/json' },\n })\n\n if (responseValidationSchema) {\n const json = await response.json()\n return validate({\n data: json,\n schema: responseValidationSchema,\n errorMessage: 'invalid response from a POST call',\n })\n }\n\n const text = await response.text()\n\n return text\n}\n\nexport const fetcher = {\n get,\n post,\n} as const\n","import { z } from 'zod'\nimport { jsonWebTokenSchema } from '../jsonWeb'\nimport { dateSchema } from '../utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-7.1 | Trust Mark Claims}\n *\n */\nexport const trustMarkClaimsSchema = z\n .object({\n iss: z.string(),\n sub: z.string(),\n trust_mark_type: z.string(),\n iat: dateSchema,\n exp: dateSchema.optional(),\n logo_uri: z.url().optional(),\n ref: z.url().optional(),\n delegation: z.string().optional(),\n })\n .loose()\n\n/**\n *\n * An entry of the `trust_marks` claim of an entity configuration\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-3.1.1 | trust_marks}\n *\n */\nexport const trustMarkSchema = z\n .object({\n trust_mark_type: z.string(),\n trust_mark: jsonWebTokenSchema({\n claimsSchema: trustMarkClaimsSchema,\n }),\n })\n .refine((entry) => entry.trust_mark_type === entry.trust_mark.claims.trust_mark_type, {\n message: 'trust_mark_type must be the trust_mark_type of the trust mark JWT',\n path: ['trust_mark_type'],\n })\n\nexport type TrustMark = z.output<typeof trustMarkSchema>\n","import { z } from 'zod'\n\nexport const trustMarkIssuerSchema = z.record(z.string(), z.array(z.string()))\n\nexport type TrustMarkIssuer = z.input<typeof trustMarkIssuerSchema>\n","import { z } from 'zod'\nimport { jsonWebKeySetSchema } from '../jsonWeb'\n\nexport const trustMarkOwnerSchema = z.record(\n z.string(),\n z.object({\n sub: z.string(),\n jwks: jsonWebKeySetSchema,\n })\n)\n\nexport type TrustMarkOwner = z.input<typeof trustMarkOwnerSchema>\n","import { z } from 'zod'\nimport { constraintSchema } from '../constraints'\nimport { jsonWebKeySetSchema } from '../jsonWeb'\nimport { metadataPolicySchema, metadataSchema } from '../metadata'\nimport { trustMarkIssuerSchema, trustMarkOwnerSchema, trustMarkSchema } from '../trustMark'\nimport { dateSchema } from '../utils'\n\nexport const entityStatementClaimsSchema = z\n .object({\n iss: z.string(),\n sub: z.string(),\n iat: dateSchema,\n exp: dateSchema,\n jwks: jsonWebKeySetSchema,\n authority_hints: z.array(z.url()).optional(),\n metadata: metadataSchema.optional(),\n metadata_policy: z.record(z.string(), z.record(z.string(), metadataPolicySchema.optional())).optional(),\n constraints: constraintSchema.optional(),\n crit: z.array(z.string()).optional(),\n metadata_policy_crit: z.array(z.string()).optional(),\n trust_marks: z.array(trustMarkSchema).optional(),\n trust_mark_issuers: trustMarkIssuerSchema.optional(),\n trust_mark_owners: trustMarkOwnerSchema.optional(),\n source_endpoint: z.url().optional(),\n })\n .superRefine((data, ctx) => {\n const keyIds = data.jwks.keys.map((key) => key.kid)\n if (keyIds.some((key, i) => keyIds.indexOf(key) !== i)) {\n ctx.addIssue({\n code: 'custom',\n message: 'keys include duplicate key ids',\n path: ['jwks', 'keys'],\n })\n }\n })\n\nexport type EntityStatementClaimsOptions = z.input<typeof entityStatementClaimsSchema>\n\nexport type EntityStatementClaims = z.output<typeof entityStatementClaimsSchema>\n\nexport type EntityStatementChain = Array<EntityStatementClaims>\n","import { z } from 'zod'\n\n/**\n *\n * @todo define extact scheme\n *\n */\nexport const entityStatementHeaderSchema = z\n .object({\n kid: z.string(),\n typ: z.literal('entity-statement+jwt'),\n })\n .loose()\n\nexport type EntityStatementHeaderOptions = z.input<typeof entityStatementHeaderSchema>\n\nexport type EntityStatementHeader = z.output<typeof entityStatementHeaderSchema>\n","import { createJsonWebToken, createJwtSignableInput, type JsonWebKey } from '../jsonWeb'\nimport type { SignCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { type EntityStatementClaimsOptions, entityStatementClaimsSchema } from './entityStatementClaims'\nimport { type EntityStatementHeaderOptions, entityStatementHeaderSchema } from './entityStatementHeader'\n\nexport type CreateEntityStatementOptions = {\n claims: EntityStatementClaimsOptions\n header?: EntityStatementHeaderOptions\n signJwtCallback: SignCallback\n /**\n *\n * The Json Web Key of the issuer used for signing the statement about the subject\n *\n */\n jwk: JsonWebKey\n}\n\n/**\n *\n * Create an entity statement\n *\n * The signing callback will be called with the `header.kid` value in the `claims.jwks.keys` and a signed JWT will be returned\n *\n */\nexport const createEntityStatement = async ({\n signJwtCallback,\n claims,\n jwk,\n header = {\n typ: 'entity-statement+jwt',\n kid: jwk.kid,\n },\n}: CreateEntityStatementOptions) => {\n if (header.kid !== jwk.kid) {\n throw new Error(`key id in the header: '${header.kid}' does not match the key id in the JWK: '${jwk.kid}'`)\n }\n\n // Validate the input\n validate({\n schema: entityStatementHeaderSchema,\n data: header,\n errorMessage: 'invalid header claims provided',\n })\n validate({\n schema: entityStatementClaimsSchema,\n data: claims,\n errorMessage: 'invalid payload claims provided',\n })\n\n // Create a signable input based on the header and payload\n const toBeSigned = createJwtSignableInput(header, claims)\n\n // Call the signing callback so the user has to handle the crypto part\n const signature = await signJwtCallback({ toBeSigned, jwk })\n\n // return a json web token based on the header, claims and associated signature\n return createJsonWebToken(header, claims, signature)\n}\n","import { base64url, base64urlDecodeJson, stringToBytes } from '@owf/identity-common'\n\ntype JsonWebTokenParts = {\n header: Record<string, unknown>\n claims: Record<string, unknown>\n signature: Uint8Array\n signableInput: Uint8Array\n}\n\nexport const parseJsonWebToken = (jwt: string): JsonWebTokenParts => {\n const [encodedHeader, encodedClaims, encodedSignature] = jwt.split('.')\n\n if (!encodedHeader) {\n throw new Error('could not find the header in the JWT')\n }\n\n if (!encodedClaims) {\n throw new Error('could not find the claims in the JWT')\n }\n\n if (!encodedSignature) {\n throw new Error('could not find the signature in the JWT')\n }\n\n const header = base64urlDecodeJson<Record<string, unknown>>(encodedHeader)\n const claims = base64urlDecodeJson<Record<string, unknown>>(encodedClaims)\n const signature = base64url.decode(encodedSignature)\n\n return {\n header,\n claims,\n signature,\n signableInput: stringToBytes(`${encodedHeader}.${encodedClaims}`),\n }\n}\n","import type { VerifyCallback } from '../utils'\nimport { getUsedJsonWebKey } from './getUsedJsonWebKey'\nimport type { JsonWebKeySet } from './jsonWebKeySet'\nimport { parseJsonWebToken } from './parseJsonWebToken'\n\ntype VerifyJsonWebTokenOptions = {\n verifyJwtCallback: VerifyCallback\n jwks?: JsonWebKeySet\n jwt: string\n}\n\nexport const verifyJwtSignature = async ({ jwt, jwks, verifyJwtCallback }: VerifyJsonWebTokenOptions) => {\n const { header, signature, claims, signableInput } = parseJsonWebToken(jwt)\n\n const jsonWebKeySetClaims = jwks ? { jwks } : claims\n\n const jwk = getUsedJsonWebKey(header, jsonWebKeySetClaims)\n\n try {\n const isValid = await verifyJwtCallback({\n jwt,\n header,\n claims,\n signature,\n jwk,\n data: signableInput,\n })\n\n // TODO: better error message\n if (!isValid) {\n throw new Error('Signature in the JWT is invalid')\n }\n } catch (e: unknown) {\n if (typeof e === 'string') {\n throw new Error(e)\n }\n\n throw e\n }\n}\n","import { jsonWebTokenSchema } from '../jsonWeb'\nimport { entityStatementClaimsSchema } from './entityStatementClaims'\nimport { entityStatementHeaderSchema } from './entityStatementHeader'\n\nexport const entityStatementJwtSchema = jsonWebTokenSchema({\n headerSchema: entityStatementHeaderSchema,\n claimsSchema: entityStatementClaimsSchema,\n})\n","import { type EntityConfigurationClaims, fetchEntityConfiguration } from '../entityConfiguration'\nimport { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\nimport { verifyJwtSignature } from '../jsonWeb/verifyJsonWebToken'\nimport { type FetchCallback, fetcher, isSameEntityId, type VerifyCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { entityStatementJwtSchema } from './entityStatementJwt'\n\nexport type FetchEntityStatementOptions = {\n iss: string\n sub: string\n verifyJwtCallback: VerifyCallback\n fetchCallback?: FetchCallback\n /**\n *\n * The issuers entity configuration\n *\n * If this is not passed in, it will be fetched from the provided `iss` argument.\n *\n */\n issEntityConfiguration?: EntityConfigurationClaims\n /**\n *\n * Fetch endpoint to get the statements from.\n *\n * If this is not passed in, it will be fetched from the `entityConfiguration.source_endpoint`\n *\n */\n endpoint?: string\n}\n\nexport const fetchEntityStatement = async ({\n sub,\n verifyJwtCallback,\n iss,\n endpoint,\n issEntityConfiguration,\n fetchCallback,\n}: FetchEntityStatementOptions) => {\n const issEntityConfigurationClaims =\n issEntityConfiguration ?? (await fetchEntityConfiguration({ entityId: iss, verifyJwtCallback, fetchCallback }))\n\n const fetchEndpoint = endpoint ?? issEntityConfigurationClaims.metadata?.federation_entity?.federation_fetch_endpoint\n\n if (!fetchEndpoint) {\n throw new Error('No fetch endpoint provided or in the issuer configuration')\n }\n\n const entityStatementJwt = await fetcher.get({\n url: fetchEndpoint,\n searchParams: { sub },\n requiredContentType: 'application/entity-statement+jwt',\n fetchCallback,\n })\n\n // Parse the JWT into its claims and header claims\n const { claims } = validate({\n schema: entityStatementJwtSchema,\n data: entityStatementJwt,\n errorMessage: 'fetched entity statement JWT is invalid',\n })\n\n if (!isSameEntityId(claims.iss, iss) || !isSameEntityId(claims.sub, sub)) {\n throw new OpenIdFederationError(\n PolicyErrorStage.Validation,\n `entity statement fetched for issuer '${iss}' and subject '${sub}' has issuer '${claims.iss}' and subject '${claims.sub}'`\n )\n }\n\n await verifyJwtSignature({\n verifyJwtCallback,\n jwt: entityStatementJwt,\n jwks: issEntityConfigurationClaims.jwks,\n })\n\n return claims\n}\n","import type { z } from 'zod'\nimport { entityStatementClaimsSchema } from '../entityStatement'\n\nexport const entityConfigurationClaimsSchema = entityStatementClaimsSchema.refine((data) => data.iss === data.sub, {\n message: 'iss and sub must be equal',\n path: ['iss', 'sub'],\n})\n\nexport type EntityConfigurationClaimsOptions = z.input<typeof entityConfigurationClaimsSchema>\n\nexport type EntityConfigurationClaims = z.output<typeof entityConfigurationClaimsSchema>\n","import { z } from 'zod'\n\n/**\n *\n * @todo define exact scheme\n *\n */\nexport const entityConfigurationHeaderSchema = z\n .object({\n kid: z.string(),\n typ: z.literal('entity-statement+jwt'),\n })\n .loose()\n\nexport type EntityConfigurationHeaderOptions = z.input<typeof entityConfigurationHeaderSchema>\n\nexport type EntityConfigurationHeader = z.output<typeof entityConfigurationHeaderSchema>\n","import { createJsonWebToken, createJwtSignableInput, getUsedJsonWebKey } from '../jsonWeb'\nimport type { SignCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { type EntityConfigurationClaimsOptions, entityConfigurationClaimsSchema } from './entityConfigurationClaims'\nimport { type EntityConfigurationHeaderOptions, entityConfigurationHeaderSchema } from './entityConfigurationHeader'\n\nexport type CreateEntityConfigurationOptions = {\n claims: EntityConfigurationClaimsOptions\n header: EntityConfigurationHeaderOptions\n signJwtCallback: SignCallback\n}\n\n/**\n *\n * Create an entity configuration\n *\n * The signing callback will be called with the `header.kid` value in the `claims.jwks.keys` and a signed JWT will be returned\n *\n */\nexport const createEntityConfiguration = async ({\n header,\n signJwtCallback,\n claims,\n}: CreateEntityConfigurationOptions) => {\n // Validate the input\n const validatedHeader = validate({\n schema: entityConfigurationHeaderSchema,\n data: header,\n errorMessage: 'invalid header claims provided',\n })\n\n const validatedClaims = validate({\n data: claims,\n schema: entityConfigurationClaimsSchema,\n errorMessage: 'invalid payload claims provided',\n })\n\n // Create a signable input based on the header and payload\n const toBeSigned = createJwtSignableInput(header, claims)\n\n // Fetch the key that will be used for signing\n const jwk = getUsedJsonWebKey(validatedHeader, validatedClaims)\n\n // Call the signing callback so the user has to handle the crypto part\n const signature = await signJwtCallback({ toBeSigned, jwk })\n\n // return a json web token based on the header, claims and associated signature\n return createJsonWebToken(header, claims, signature)\n}\n","import { jsonWebTokenSchema } from '../jsonWeb'\nimport { entityConfigurationClaimsSchema } from './entityConfigurationClaims'\nimport { entityConfigurationHeaderSchema } from './entityConfigurationHeader'\n\nexport const entityConfigurationJwtSchema = jsonWebTokenSchema({\n headerSchema: entityConfigurationHeaderSchema,\n claimsSchema: entityConfigurationClaimsSchema,\n})\n","import { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\nimport { verifyJwtSignature } from '../jsonWeb/verifyJsonWebToken'\nimport { addPaths, type FetchCallback, fetcher, isSameEntityId, type VerifyCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { entityConfigurationJwtSchema } from './entityConfigurationJwt'\n\nexport type FetchEntityConfigurationOptions = {\n entityId: string\n verifyJwtCallback: VerifyCallback\n fetchCallback?: FetchCallback\n}\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-9.1 | Federation Entity Request}\n *\n */\nexport const fetchEntityConfiguration = async ({\n entityId,\n verifyJwtCallback,\n fetchCallback,\n}: FetchEntityConfigurationOptions) => {\n // Create the entity URL\n const federationUrl = addPaths(entityId, '.well-known', 'openid-federation')\n\n // Fetch the JWT entity configuration\n const entityConfigurationJwt = await fetcher.get({\n url: federationUrl,\n requiredContentType: 'application/entity-statement+jwt',\n fetchCallback,\n })\n\n // Parse the JWT into its claims\n const { claims } = validate({\n schema: entityConfigurationJwtSchema,\n data: entityConfigurationJwt,\n errorMessage: 'fetched entity configuration JWT is invalid',\n })\n\n // The entity configuration must be about the requested entity, otherwise any URL could claim to be another entity\n if (!isSameEntityId(claims.sub, entityId)) {\n throw new OpenIdFederationError(\n PolicyErrorStage.Validation,\n `entity configuration fetched for '${entityId}' has subject '${claims.sub}'`\n )\n }\n\n await verifyJwtSignature({ jwt: entityConfigurationJwt, verifyJwtCallback })\n\n return claims\n}\n","/**\n * Converts an object to an array of entries with better typing for the key\n */\nexport function objectToEntries<\n TObject extends {\n [Tkey in keyof TObject]: TObject[Tkey]\n },\n>(obj: TObject) {\n return Object.entries(obj) as [keyof TObject, TObject[keyof TObject]][]\n}\n\nexport const isNullOrUndefined = (value: unknown): value is null | undefined => value === null || value === undefined\n\nexport const immutable = <T extends object>(obj: T): T =>\n new Proxy(obj, {\n get(target: T, prop: string | symbol) {\n const value = target[prop as keyof T]\n return typeof value === 'object' && value !== null\n ? Array.isArray(value)\n ? Object.freeze(\n [...value].map((item) => (typeof item === 'object' && item !== null ? immutable(item) : item))\n )\n : immutable(value)\n : value\n },\n set() {\n throw new Error('This object is immutable.')\n },\n deleteProperty() {\n throw new Error('This object is immutable.')\n },\n })\n","export type PolicyValidationErrorDetails = {\n path: string\n policyValue: unknown\n targetValue: unknown\n}\n\nexport class PolicyValidationError extends Error {\n public readonly details: PolicyValidationErrorDetails\n\n public constructor(message: string, details: PolicyValidationErrorDetails) {\n super(message)\n this.name = 'PolicyValidationError'\n this.details = details\n }\n}\n","import type { Metadata } from '../../metadata'\nimport type { MetadataPolicy } from '../../metadata/metadataPolicy'\n\nexport class MetadataHelper {\n private leafMetadata: Record<string, Record<string, unknown>>\n\n public constructor(leafMetadata: Metadata) {\n this.leafMetadata = leafMetadata as Record<string, Record<string, unknown>>\n }\n\n public hasEntityType(service: string) {\n return this.leafMetadata[service] !== undefined\n }\n\n public hasProperty(service: string, property: string) {\n return this.leafMetadata[service]?.[property] !== undefined\n }\n\n public getPropertyValue<T = unknown>(service: string, property: string): T | undefined {\n const serviceBlock = this.leafMetadata[service]\n if (serviceBlock === undefined) return undefined\n const propertyValue = serviceBlock[property]\n if (propertyValue === undefined) return undefined\n return propertyValue as T\n }\n\n public setPropertyValue(service: string, property: string, value: unknown) {\n this.leafMetadata = {\n ...this.leafMetadata,\n [service]: {\n ...this.leafMetadata[service], // optionally add a helper method to get a value or an empty object otherwise\n [property]: value,\n },\n }\n }\n\n public deleteProperty(service: string, property: string) {\n const serviceBlock = this.leafMetadata[service]\n if (serviceBlock === undefined) return\n\n this.leafMetadata = {\n ...this.leafMetadata,\n [service]: {\n ...this.leafMetadata[service],\n },\n }\n\n // The entity type stays, also when it has no metadata parameters left\n delete this.leafMetadata[service][property]\n }\n\n public asMetadata(): Metadata {\n return this.leafMetadata\n }\n\n public asMetadataPolicy(): MetadataPolicy {\n return this.leafMetadata\n }\n}\n","import type { Metadata } from '../../metadata'\nimport { immutable, objectToEntries } from '../../utils/data'\nimport { MetadataHelper } from './MetadataHelper'\n\nexport type PolicyValue = boolean | string | number\n\nexport type PolicyValueArray = PolicyValue[]\n\nexport function intersect(operator1: PolicyValueArray, operator2: PolicyValueArray) {\n const set1 = new Set(operator1)\n const set2 = new Set(operator2)\n const intersection = [...set1].filter((value) => set2.has(value))\n return intersection\n}\n\nexport function union(operator1: PolicyValueArray, operator2: PolicyValueArray) {\n return [...new Set([...operator1, ...operator2])]\n}\n\n/**\n * Merges the metadata of the leaf entity with the metadata of the superior entity statement\n * The superior always has the highest priority\n */\nexport function mergeMetadata(leafConfigMetadata: Metadata, superiorEntityStatement: Metadata): Metadata {\n const mergedLeafMetadata = new MetadataHelper(immutable(leafConfigMetadata))\n\n for (const [entityType, entityConfigMetadata] of objectToEntries(superiorEntityStatement)) {\n // Section 3.1.1: it applies only to the entity types present in the subject's entity configuration\n if (!mergedLeafMetadata.hasEntityType(String(entityType))) continue\n for (const [key, value] of objectToEntries((entityConfigMetadata ?? {}) as Record<string, unknown>)) {\n mergedLeafMetadata.setPropertyValue(String(entityType), String(key), value)\n }\n }\n\n return mergedLeafMetadata.asMetadata()\n}\n","import {\n allSupportedPolicies,\n isExistingPolicyKey,\n type Metadata,\n type MetadataPolicyOperator,\n type SupportedPolicyKey,\n} from '../../metadata'\nimport { immutable, isNullOrUndefined, objectToEntries } from '../../utils/data'\nimport { PolicyValidationError } from './errors/PolicyValidationError'\nimport { MetadataHelper } from './MetadataHelper'\nimport { type PolicyValue, union } from './utils'\n\nexport function applyMetadataPolicyToMetadata({\n leafMetadata,\n policyMetadata,\n}: {\n leafMetadata: Metadata\n policyMetadata: Record<string, Record<string, MetadataPolicyOperator | undefined> | undefined>\n}) {\n const resolvedLeafMetadata = new MetadataHelper(immutable(leafMetadata))\n\n for (const [serviceKey, service] of objectToEntries(policyMetadata)) {\n // Section 6.1.4.2: policies apply to the entity types the metadata has, operators do not add an entity type\n if (!service || !resolvedLeafMetadata.hasEntityType(serviceKey)) continue\n\n for (const [servicePropertyKey, policyValue] of objectToEntries(service)) {\n if (!policyValue) continue\n\n const policies = objectToEntries(policyValue)\n .filter(([key]) => isExistingPolicyKey(key))\n .sort(\n ([policyKeyA], [policyKeyB]) =>\n allSupportedPolicies[policyKeyA as SupportedPolicyKey].orderOfApplication -\n allSupportedPolicies[policyKeyB as SupportedPolicyKey].orderOfApplication\n )\n\n const path = `${serviceKey}.${servicePropertyKey}`\n\n // Section 6.1.3.1.8: scope, a string of space-separated values, is processed as a string array\n const isScope = servicePropertyKey === 'scope'\n const scope = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey)\n if (isScope && typeof scope === 'string') {\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, splitScope(scope))\n }\n\n for (const [policyPropertyKey, rawValueFromPolicy] of policies) {\n const valueFromPolicy =\n isScope && typeof rawValueFromPolicy === 'string' ? splitScope(rawValueFromPolicy) : rawValueFromPolicy\n\n switch (policyPropertyKey) {\n case 'value':\n if (valueFromPolicy === null) {\n // When the policy value is null, we delete the property\n resolvedLeafMetadata.deleteProperty(serviceKey, servicePropertyKey)\n break\n }\n\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, valueFromPolicy)\n break\n case 'add': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey) ?? []\n if (!Array.isArray(targetValue))\n throw new PolicyValidationError('Cannot apply add policy because the target is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n const newValue = union(targetValue, valueFromPolicy)\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, newValue)\n break\n }\n case 'one_of': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n // With one_of it's allowed to not have a value and can be enforced with essential\n if (isNullOrUndefined(targetValue)) break\n\n if (!Array.isArray(valueFromPolicy))\n throw new PolicyValidationError('Cannot apply one_of policy because the value is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n if (!valueFromPolicy.some((value) => value === targetValue))\n throw new PolicyValidationError('Cannot apply one_of policy because the intersection is empty', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n break\n }\n case 'default':\n if (resolvedLeafMetadata.hasProperty(serviceKey, servicePropertyKey)) continue\n\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, valueFromPolicy)\n break\n case 'subset_of': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n // Only applies when the metadata parameter is present, essential enforces its presence\n if (isNullOrUndefined(targetValue)) break\n if (!Array.isArray(targetValue))\n throw new PolicyValidationError('Cannot apply subset_of policy because the target is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n if (!Array.isArray(valueFromPolicy))\n throw new PolicyValidationError('Cannot apply subset_of policy because the value is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n // The intersection may be an empty array, which stays the value of the metadata parameter\n const newValue = targetValue.filter((value) => valueFromPolicy.includes(value))\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, newValue)\n break\n }\n case 'superset_of': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n // Only applies when the metadata parameter is present, essential enforces its presence\n if (isNullOrUndefined(targetValue)) break\n if (!Array.isArray(targetValue))\n throw new PolicyValidationError('Cannot apply superset_of policy because the target is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n if (!Array.isArray(valueFromPolicy))\n throw new PolicyValidationError('Cannot apply superset_of policy because the value is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n if (!valueFromPolicy.every((value) => targetValue.includes(value)))\n throw new PolicyValidationError('The target does not contain all the values from the policy superset', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n break\n }\n case 'essential': {\n if (!valueFromPolicy) break\n\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n if (isNullOrUndefined(targetValue))\n throw new PolicyValidationError('The policy is required to have a value', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n // An empty array, for example after subset_of, is present (Section 6.1.3.1.8, Table 1)\n break\n }\n }\n }\n\n const resolvedScope = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey)\n if (isScope && Array.isArray(resolvedScope)) {\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, resolvedScope.join(' '))\n }\n }\n }\n\n return {\n resolvedLeafMetadata: resolvedLeafMetadata.asMetadata(),\n }\n}\n\nconst splitScope = (scope: string) => scope.split(' ').filter((value) => value !== '')\n","import type { MetadataPolicyOperator } from '../../../metadata'\n\nexport type PolicyOperatorMergeErrorDetails = {\n path: string\n operatorA: MetadataPolicyOperator\n operatorB: MetadataPolicyOperator\n}\n\nexport class PolicyOperatorMergeError extends Error {\n public readonly details: PolicyOperatorMergeErrorDetails\n\n constructor(message: string, details: PolicyOperatorMergeErrorDetails) {\n super(message)\n this.name = 'PolicyOperatorMergeError'\n this.details = details\n }\n}\n","import { allSupportedPolicies, isExistingPolicyKey, type MetadataPolicyOperator } from '../../metadata'\nimport { MetadataMergeStrategy } from '../../metadata/operator/MetadataMergeStrategy'\nimport { objectToEntries } from '../../utils/data'\nimport { PolicyOperatorMergeError } from './errors'\nimport { intersect, union } from './utils'\n\n// TODO: Add support for objects (they are optional in the spec)\n\nexport function combineExistingMetadataPolicyOperators({\n contextPath,\n existingPolicyRules,\n newPolicyRules,\n}: {\n contextPath: string\n existingPolicyRules: MetadataPolicyOperator\n newPolicyRules: MetadataPolicyOperator\n}) {\n const combinedPolicyRules = { ...existingPolicyRules }\n\n for (const [policyPropertyKey, policyRuleValue] of objectToEntries(newPolicyRules)) {\n // When we don't know the policy key we can skip it because we already know it's not critical\n if (!isExistingPolicyKey(policyPropertyKey)) continue\n\n if (combinedPolicyRules[policyPropertyKey] === undefined) {\n combinedPolicyRules[policyPropertyKey] = policyRuleValue\n continue\n }\n\n const existingPolicyRuleValue = combinedPolicyRules[policyPropertyKey]\n const operator = allSupportedPolicies[policyPropertyKey]\n\n // Check if the new policy rule value is correctly used\n const operatorInputResult = operator.operatorSchema.safeParse(policyRuleValue)\n if (!operatorInputResult.success) throw operatorInputResult.error\n const newPolicyRuleValue = operatorInputResult.data\n\n switch (operator.mergeStrategy) {\n case MetadataMergeStrategy.OperatorValuesEqual:\n if (Array.isArray(existingPolicyRuleValue) && Array.isArray(newPolicyRuleValue)) {\n if (existingPolicyRuleValue.length !== newPolicyRuleValue.length)\n throw new PolicyOperatorMergeError('Policy rule values are not equal', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n\n if (existingPolicyRuleValue.some((value, i) => value !== newPolicyRuleValue[i]))\n throw new PolicyOperatorMergeError('Policy rule values are not equal', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n } else if (existingPolicyRuleValue !== newPolicyRuleValue) {\n throw new PolicyOperatorMergeError('Policy rule values are not equal', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n\n // Don't have to do anything because it is already there by the existing policy rule\n break\n case MetadataMergeStrategy.Union:\n if (!Array.isArray(existingPolicyRuleValue) || !Array.isArray(newPolicyRuleValue)) {\n throw new PolicyOperatorMergeError('Operator values are not an array', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n\n combinedPolicyRules[policyPropertyKey] = union(existingPolicyRuleValue, newPolicyRuleValue)\n break\n case MetadataMergeStrategy.Intersection:\n case MetadataMergeStrategy.IntersectionMayBeEmpty: {\n if (!Array.isArray(existingPolicyRuleValue) || !Array.isArray(newPolicyRuleValue)) {\n throw new PolicyOperatorMergeError('Existing policy rule value is not an array', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n const intersection = intersect(existingPolicyRuleValue, newPolicyRuleValue)\n if (intersection.length === 0 && operator.mergeStrategy === MetadataMergeStrategy.Intersection) {\n throw new PolicyOperatorMergeError('Intersection is empty', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n\n combinedPolicyRules[policyPropertyKey] = intersection\n\n break\n }\n case MetadataMergeStrategy.LogicalOr:\n if (typeof existingPolicyRuleValue !== 'boolean' || typeof newPolicyRuleValue !== 'boolean') {\n throw new PolicyOperatorMergeError('Existing policy rule value is not a boolean', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n combinedPolicyRules[policyPropertyKey] = existingPolicyRuleValue || newPolicyRuleValue\n break\n\n default:\n throw new PolicyOperatorMergeError(`Unknown merge strategy: ${operator.mergeStrategy}`, {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n }\n\n return combinedPolicyRules\n}\n","import type { EntityStatementClaims } from '../../entityStatement'\nimport { OpenIdFederationError } from '../../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../../error/PolicyErrorStage'\nimport { isExistingPolicyKey, metadataPolicySchema } from '../../metadata'\nimport type { MetadataPolicy } from '../../metadata/metadataPolicy'\nimport { objectToEntries } from '../../utils/data'\nimport { combineExistingMetadataPolicyOperators } from './combineExistingMetadataPolicyOperators'\nimport { MetadataHelper } from './MetadataHelper'\n\nexport function combineMetadataPolicies({\n statements,\n}: {\n /**\n * The entity statements of the chain without the leaf entity\n */\n statements: Array<EntityStatementClaims>\n}): {\n mergedPolicy: MetadataPolicy\n} {\n if (statements.length === 0) throw new OpenIdFederationError(PolicyErrorStage.Generic, 'Chain is empty')\n const mergedPolicyMap = new MetadataHelper({})\n\n // We start from the TA and go down to the intermediate\n for (let i = statements.length - 1; i >= 0; i--) {\n const entityStatement = statements[i]\n if (!entityStatement) continue\n // When the current entity doesn't have a metadata policy we can skip it\n if (!entityStatement.metadata_policy) continue\n\n const metadataPolicyCrit = entityStatement.metadata_policy_crit\n\n for (const [serviceKey, serviceProperties] of objectToEntries(entityStatement.metadata_policy)) {\n for (const [servicePropertyKey, newPolicyRules] of objectToEntries(serviceProperties)) {\n if (newPolicyRules === undefined) continue\n\n const contextPath = `${serviceKey}.${servicePropertyKey}`\n\n // When the metadata_policy_crit is not empty we need to check if it contains a policy method that is not supported and is used by the new policy rule\n if (metadataPolicyCrit) {\n const methodsToCheck = Object.keys(newPolicyRules)\n const unsupportedMethodsAndRequired = methodsToCheck.filter(\n (method) => !isExistingPolicyKey(method) && metadataPolicyCrit.includes(method)\n )\n if (unsupportedMethodsAndRequired.length > 0) {\n throw new OpenIdFederationError(\n PolicyErrorStage.MetadataPolicyCrit,\n `Unsupported policy method and is required by the metadata_policy_crit: ${unsupportedMethodsAndRequired.join(', ')}`\n )\n }\n }\n\n const existingPolicyRule = mergedPolicyMap.getPropertyValue(serviceKey, servicePropertyKey)\n if (!existingPolicyRule) {\n // When there is no existing policy rule yet we can set the new policy rule\n mergedPolicyMap.setPropertyValue(serviceKey, servicePropertyKey, newPolicyRules)\n continue\n }\n\n // So we found a new property which we already have in the map yet so this can be a federation_entity property for example\n // We need to combine the existing policy rule together with the new one\n const combinedPolicyRulesRaw = combineExistingMetadataPolicyOperators({\n contextPath: contextPath,\n existingPolicyRules: existingPolicyRule,\n newPolicyRules: newPolicyRules,\n })\n\n // Check if the the new properties are able to be combined\n const combinedPolicyRules = metadataPolicySchema.safeParse(combinedPolicyRulesRaw)\n if (!combinedPolicyRules.success) throw combinedPolicyRules.error\n\n mergedPolicyMap.setPropertyValue(serviceKey, servicePropertyKey, combinedPolicyRules.data)\n }\n }\n }\n\n return {\n mergedPolicy: mergedPolicyMap.asMetadataPolicy(),\n }\n}\n","import type { EntityConfigurationClaims } from '../entityConfiguration'\nimport { entityConfigurationJwtSchema } from '../entityConfiguration/entityConfigurationJwt'\nimport type { EntityStatementChain, EntityStatementClaims } from '../entityStatement'\nimport { entityStatementJwtSchema } from '../entityStatement/entityStatementJwt'\nimport { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\nimport type { JsonWebKeySetOptions } from '../jsonWeb'\nimport { verifyJwtSignature } from '../jsonWeb/verifyJsonWebToken'\nimport type { Metadata } from '../metadata'\nimport { addPaths, type FetchCallback, fetcher, isSameEntityId, type VerifyCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { applyMetadataPolicyToMetadata, combineMetadataPolicies } from './policies'\nimport { mergeMetadata } from './policies/utils'\n\nexport type TrustAnchor = {\n entityId: string\n /**\n * The federation keys of the trust anchor, obtained out of band. When given, the trust anchor's entity\n * configuration must be signed with one of them. Without them, the entity configuration fetched from the\n * trust anchor's well-known URL is trusted on its own signature.\n */\n jwks?: JsonWebKeySetOptions\n}\n\nexport type ResolveTrustChainsOptions = {\n verifyJwtCallback: VerifyCallback\n entityId: string\n trustAnchors: Array<TrustAnchor>\n /**\n * Used for every request. Pass one that applies your outbound request policy (allowed hosts, timeouts,\n * response size), as entity configurations name the URLs that are fetched.\n *\n * @default globalThis.fetch\n */\n fetchCallback?: FetchCallback\n /**\n * @default new Date()\n */\n currentDate?: Date\n /**\n * Allowed clock difference for `iat` and `exp`.\n *\n * @default 0\n */\n clockSkewSeconds?: number\n /**\n * Maximum number of superiors followed from the leaf, including the trust anchor.\n *\n * @default 8\n */\n maxDepth?: number\n /**\n * Maximum number of requests (entity configurations and subordinate statements) for one resolution. It also bounds\n * the number of entities visited while following authority hints, as an entity reached on several paths is\n * visited once per path.\n *\n * @default 64\n */\n maxRequests?: number\n /**\n * Maximum number of `authority_hints` followed per entity. Duplicates are ignored.\n *\n * @default 10\n */\n maxAuthorityHints?: number\n /**\n * Claims listed in `crit` that the caller understands. A statement whose `crit` lists another claim is rejected.\n *\n * @default []\n */\n understoodCriticalClaims?: Array<string>\n}\n\nexport type TrustChain = {\n valid: true\n\n /**\n * The subordinate statements, leaf side first, followed by the trust anchor's entity configuration.\n * When the leaf is a trust anchor, only its entity configuration.\n */\n chain: EntityStatementChain\n /**\n * The trust chain as defined in {@link https://openid.net/specs/openid-federation-1_0.html#section-4 | Section 4}:\n * the leaf's entity configuration, the subordinate statements and the trust anchor's entity configuration, as compact JWTs.\n * When the leaf is a trust anchor, only its entity configuration.\n */\n jwtChain: Array<string>\n /**\n * The raw leaf entity configuration before the policy is applied.\n * So the metadata is not valid yet.\n */\n rawLeafEntityConfiguration: EntityConfigurationClaims\n /**\n * The resolved leaf metadata after the policy is applied and the metadata is merged with the superior entity's metadata.\n */\n resolvedLeafMetadata: EntityConfigurationClaims['metadata']\n trustAnchorEntityConfiguration: EntityConfigurationClaims\n /**\n * The earliest `exp` of all statements in the chain. The chain must not be used after it.\n */\n expiresAt: Date\n}\n\nexport type TrustChainFailure = {\n /**\n * The entities of the failed path, leaf first.\n */\n entityIds: Array<string>\n reason: string\n cause?: unknown\n}\n\nexport type TrustChainResolution = {\n trustChains: Array<TrustChain>\n failures: Array<TrustChainFailure>\n}\n\ntype FetchedEntityConfiguration = { jwt: string; claims: EntityConfigurationClaims }\n\nconst ENTITY_STATEMENT_CONTENT_TYPE = 'application/entity-statement+jwt'\n\nconst fail = (message: string) => new OpenIdFederationError(PolicyErrorStage.Validation, message)\n\nconst reasonOf = (error: unknown) => (error instanceof Error && error.message ? error.message : String(error))\n\n/**\n * Resolves the trust chains from the given entity to the given trust anchors and validates them as described in\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-10 | Section 10}.\n *\n * Every entity configuration and subordinate statement is checked for its signature, `iat`, `exp` and `crit`. An\n * entity configuration must be about the requested entity and signed with a key its superior's subordinate statement\n * lists. A subordinate statement must be issued by the superior about the subject. Each statement may only contain the\n * claims Section 3.2 allows for its kind. `max_path_length` and\n * `allowed_entity_types` constraints are applied, then the metadata policies. Chains with `naming_constraints` are\n * rejected, as they are not evaluated. Trust marks are not verified.\n *\n * Paths that fail are returned in `failures` with the reason.\n */\nexport const resolveTrustChainsWithFailures = async (\n options: ResolveTrustChainsOptions\n): Promise<TrustChainResolution> => {\n const {\n entityId,\n verifyJwtCallback,\n fetchCallback,\n clockSkewSeconds = 0,\n maxDepth = 8,\n maxRequests = 64,\n maxAuthorityHints = 10,\n understoodCriticalClaims = [],\n } = options\n const now = options.currentDate ?? new Date()\n\n const { trustAnchors } = options\n if (trustAnchors.length === 0) {\n throw fail('Cannot resolve a trust chain for zero trust anchors')\n }\n const findTrustAnchor = (id: string) => trustAnchors.find((anchor) => isSameEntityId(anchor.entityId, id))\n\n const failures: Array<TrustChainFailure> = []\n let requests = 0\n let visits = 0\n const get = async (url: string, searchParams?: Record<string, string>) => {\n requests++\n if (requests > maxRequests) {\n throw fail(`trust chain resolution exceeded ${maxRequests} requests`)\n }\n return fetcher.get({ url, searchParams, requiredContentType: ENTITY_STATEMENT_CONTENT_TYPE, fetchCallback })\n }\n\n const assertCurrent = (statement: EntityStatementClaims) => {\n const skewMs = clockSkewSeconds * 1000\n if (!Number.isFinite(statement.iat.getTime()) || !Number.isFinite(statement.exp.getTime())) {\n throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has an invalid iat or exp`)\n }\n if (statement.iat.getTime() > now.getTime() + skewMs) {\n throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has an iat in the future`)\n }\n if (statement.exp.getTime() <= now.getTime() - skewMs) {\n throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has expired`)\n }\n const notUnderstood = (statement.crit ?? []).filter((claim) => !understoodCriticalClaims.includes(claim))\n if (notUnderstood.length > 0) {\n throw fail(\n `statement about '${statement.sub}' issued by '${statement.iss}' has critical claims that are not understood: ${notUnderstood.join(', ')}`\n )\n }\n }\n\n // An entity reached through several superiors is fetched once per resolution\n const entityConfigurations = new Map<string, Promise<FetchedEntityConfiguration>>()\n const fetchEntityConfiguration = (id: string) => {\n let pending = entityConfigurations.get(id)\n if (!pending) {\n pending = (async () => {\n const jwt = await get(addPaths(id, '.well-known', 'openid-federation'))\n const { claims } = validate({\n schema: entityConfigurationJwtSchema,\n data: jwt,\n errorMessage: `entity configuration of '${id}' is invalid`,\n })\n if (!isSameEntityId(claims.sub, id)) {\n throw fail(`entity configuration fetched for '${id}' has subject '${claims.sub}'`)\n }\n await verifyJwtSignature({ jwt, verifyJwtCallback })\n assertCurrent(claims)\n assertEntityConfigurationClaims(claims)\n return { jwt, claims }\n })()\n entityConfigurations.set(id, pending)\n }\n return pending\n }\n\n /**\n * Follows the authority hints up to the trust anchors and returns every path of entity configurations,\n * leaf first, that ends at a trust anchor.\n */\n const discover = async (\n id: string,\n path: Array<FetchedEntityConfiguration>\n ): Promise<Array<Array<FetchedEntityConfiguration>>> => {\n // Without this bound, repeated or converging authority hints would enumerate exponentially many paths\n visits++\n if (visits > maxRequests) {\n throw fail(`trust chain resolution exceeded ${maxRequests} entity visits`)\n }\n const configuration = await fetchEntityConfiguration(id)\n const localPath = [...path, configuration]\n const paths: Array<Array<FetchedEntityConfiguration>> = []\n\n if (findTrustAnchor(configuration.claims.sub)) {\n paths.push(localPath)\n }\n\n // The path holds the leaf and its superiors\n if (localPath.length > maxDepth) return paths\n\n const superiors: Array<string> = []\n for (const superior of configuration.claims.authority_hints ?? []) {\n if (superiors.length === maxAuthorityHints) break\n if (localPath.some((entry) => isSameEntityId(entry.claims.sub, superior))) continue\n if (superiors.some((entry) => isSameEntityId(entry, superior))) continue\n superiors.push(superior)\n }\n const results = await Promise.allSettled(superiors.map((superior) => discover(superior, localPath)))\n results.forEach((result, index) => {\n if (result.status === 'fulfilled') {\n paths.push(...result.value)\n } else {\n failures.push({\n entityIds: [...localPath.map((entry) => entry.claims.sub), superiors[index] as string],\n reason: reasonOf(result.reason),\n cause: result.reason,\n })\n }\n })\n\n return paths\n }\n\n const validatePath = async (path: Array<FetchedEntityConfiguration>): Promise<TrustChain> => {\n const leaf = path[0] as FetchedEntityConfiguration\n const trustAnchorConfiguration = path[path.length - 1] as FetchedEntityConfiguration\n const trustAnchor = findTrustAnchor(trustAnchorConfiguration.claims.sub) as TrustAnchor\n\n if (trustAnchor.jwks) {\n await verifyJwtSignature({\n jwt: trustAnchorConfiguration.jwt,\n jwks: trustAnchor.jwks,\n verifyJwtCallback,\n }).catch((error: unknown) => {\n throw fail(\n `entity configuration of trust anchor '${trustAnchor.entityId}' is not signed with a configured key: ${reasonOf(error)}`\n )\n })\n }\n\n const statements: Array<{ jwt: string; claims: EntityStatementClaims }> = []\n for (let index = 0; index < path.length - 1; index++) {\n const subject = path[index] as FetchedEntityConfiguration\n const superior = path[index + 1] as FetchedEntityConfiguration\n\n const fetchEndpoint = superior.claims.metadata?.federation_entity?.federation_fetch_endpoint\n if (!fetchEndpoint) {\n throw fail(`'${superior.claims.sub}' has no federation_fetch_endpoint`)\n }\n\n const jwt = await get(fetchEndpoint, { sub: subject.claims.sub })\n const { claims } = validate({\n schema: entityStatementJwtSchema,\n data: jwt,\n errorMessage: `subordinate statement about '${subject.claims.sub}' issued by '${superior.claims.sub}' is invalid`,\n })\n if (!isSameEntityId(claims.iss, superior.claims.sub) || !isSameEntityId(claims.sub, subject.claims.sub)) {\n throw fail(\n `subordinate statement requested from '${superior.claims.sub}' about '${subject.claims.sub}' has issuer '${claims.iss}' and subject '${claims.sub}'`\n )\n }\n assertCurrent(claims)\n assertSubordinateStatementClaims(claims)\n\n // Naming constraints are not evaluated, so a chain that sets them is rejected instead of ignoring them\n if (claims.constraints?.naming_constraints) {\n throw fail(`'${superior.claims.sub}' sets naming_constraints, which are not supported`)\n }\n\n // The statement at this index is issued `index + 1` levels above the leaf, so `index` intermediates are between them\n const maxPathLength = claims.constraints?.max_path_length\n if (maxPathLength !== undefined && index > maxPathLength) {\n throw fail(`'${superior.claims.sub}' allows ${maxPathLength} intermediates, the chain has ${index}`)\n }\n\n statements.push({ jwt, claims })\n }\n\n // Section 10.2: each statement validates with a key the next one lists. The leaf's entity configuration with the keys\n // of the statement about it, each subordinate statement with the keys its superior's statement lists for the\n // superior, and the last one with the trust anchor's keys.\n const signers = statements.length > 0 ? [leaf, ...statements] : []\n for (let index = 0; index < signers.length; index++) {\n const signed = signers[index] as { jwt: string; claims: EntityStatementClaims }\n const next = statements[index]\n const jwks = next ? next.claims.jwks : trustAnchorConfiguration.claims.jwks\n await verifyJwtSignature({ jwt: signed.jwt, jwks, verifyJwtCallback }).catch((error: unknown) => {\n throw fail(\n `statement about '${signed.claims.sub}' issued by '${signed.claims.iss}' is not signed with a key listed by '${next ? next.claims.iss : trustAnchorConfiguration.claims.sub}': ${reasonOf(error)}`\n )\n })\n }\n\n const expiresAt = new Date(Math.min(...[...path, ...statements].map((statement) => statement.claims.exp.getTime())))\n\n if (statements.length === 0) {\n return {\n valid: true,\n chain: [leaf.claims],\n jwtChain: [leaf.jwt],\n rawLeafEntityConfiguration: leaf.claims,\n resolvedLeafMetadata: leaf.claims.metadata,\n trustAnchorEntityConfiguration: leaf.claims,\n expiresAt,\n }\n }\n\n const statementClaims = statements.map((statement) => statement.claims)\n const { mergedPolicy } = combineMetadataPolicies({ statements: statementClaims })\n\n // Section 6: the superior's metadata is applied first, then entity types the constraints do not allow are removed,\n // then the metadata policies are applied\n const mergedLeafMetadata = restrictEntityTypes(\n mergeMetadata(leaf.claims.metadata ?? {}, statementClaims[0]?.metadata ?? {}),\n statementClaims\n )\n const { resolvedLeafMetadata } = applyMetadataPolicyToMetadata({\n leafMetadata: mergedLeafMetadata,\n policyMetadata: mergedPolicy,\n })\n\n return {\n valid: true,\n chain: [...statementClaims, trustAnchorConfiguration.claims],\n jwtChain: [leaf.jwt, ...statements.map((statement) => statement.jwt), trustAnchorConfiguration.jwt],\n rawLeafEntityConfiguration: leaf.claims,\n // The policies do not add entity types, so a removed one stays removed\n resolvedLeafMetadata,\n trustAnchorEntityConfiguration: trustAnchorConfiguration.claims,\n expiresAt,\n }\n }\n\n let paths: Array<Array<FetchedEntityConfiguration>>\n try {\n paths = await discover(entityId, [])\n } catch (error) {\n // The leaf's own entity configuration could not be used\n return { trustChains: [], failures: [{ entityIds: [entityId], reason: reasonOf(error), cause: error }] }\n }\n\n const trustChains: Array<TrustChain> = []\n for (const path of paths) {\n try {\n trustChains.push(await validatePath(path))\n } catch (error) {\n failures.push({ entityIds: path.map((entry) => entry.claims.sub), reason: reasonOf(error), cause: error })\n }\n }\n\n return { trustChains, failures }\n}\n\n/**\n * Section 3.2: claims that only a subordinate statement may contain are rejected in an entity configuration.\n */\nconst assertEntityConfigurationClaims = (claims: EntityConfigurationClaims) => {\n const present = (['metadata_policy', 'metadata_policy_crit', 'constraints', 'source_endpoint'] as const).filter(\n (claim) => claims[claim] !== undefined\n )\n if (present.length > 0) {\n throw fail(\n `entity configuration of '${claims.sub}' contains ${present.join(', ')}, which only subordinate statements may contain`\n )\n }\n if (claims.authority_hints?.length === 0) {\n throw fail(`entity configuration of '${claims.sub}' has an empty authority_hints array`)\n }\n}\n\n/**\n * Section 3.2: claims that only an entity configuration may contain are rejected in a subordinate statement.\n */\nconst assertSubordinateStatementClaims = (claims: EntityStatementClaims) => {\n const present = (['authority_hints', 'trust_marks', 'trust_mark_issuers', 'trust_mark_owners'] as const).filter(\n (claim) => claims[claim] !== undefined\n )\n if (present.length > 0) {\n throw fail(\n `subordinate statement about '${claims.sub}' issued by '${claims.iss}' contains ${present.join(', ')}, which only entity configurations may contain`\n )\n }\n if (claims.metadata_policy_crit?.length === 0) {\n throw fail(\n `subordinate statement about '${claims.sub}' issued by '${claims.iss}' has an empty metadata_policy_crit array`\n )\n }\n // Section 3.1.3: listed operators that are not understood make the statement invalid. No additional operators are\n // supported, and the standard ones must not be listed.\n if (claims.metadata_policy_crit !== undefined) {\n throw fail(\n `subordinate statement about '${claims.sub}' issued by '${claims.iss}' requires policy operators that are not supported: ${claims.metadata_policy_crit.join(', ')}`\n )\n }\n}\n\n/**\n * Removes the entity types that `allowed_entity_types` constraints of the chain do not allow. `federation_entity` is always allowed.\n */\nconst restrictEntityTypes = (metadata: Metadata, statements: Array<EntityStatementClaims>): Metadata => {\n const allowed = statements\n .map((statement) => statement.constraints?.allowed_entity_types)\n .filter((types): types is Array<string> => types !== undefined)\n if (allowed.length === 0) return metadata\n\n return Object.fromEntries(\n Object.entries(metadata).filter(\n ([entityType]) => entityType === 'federation_entity' || allowed.every((types) => types.includes(entityType))\n )\n ) as Metadata\n}\n\n/**\n * Resolves the trust chains for the given entityId and trust anchors. See {@link resolveTrustChainsWithFailures},\n * which also returns why paths failed.\n *\n * @returns the valid trust chains\n */\nexport const resolveTrustChains = async (options: ResolveTrustChainsOptions): Promise<Array<TrustChain>> =>\n (await resolveTrustChainsWithFailures(options)).trustChains\n"],"mappings":";;;AAEA,MAAa,mBAAmB,EAAE,OAAO;CACvC,iBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS;CACrC,oBAAoB,EACjB,OAAO;EACN,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;EACxC,UAAU,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AC;EAAmB;EAAe;EAAsB;CAAmB,CAAC,CAAW,QACtG,UAAU,OAAO,WAAW,KAAA,CAC/B;CACA,IAAI,QAAQ,SAAS,GACnB,MAAM,KACJ,gCAAgC,OAAO,IAAI,eAAe,OAAO,IAAI,aAAa,QAAQ,KAAK,IAAI,EAAE,+CACvG;CAEF,IAAI,OAAO,sBAAsB,WAAW,GAC1C,MAAM,KACJ,gCAAgC,OAAO,IAAI,eAAe,OAAO,IAAI,0CACvE;CAIF,IAAI,OAAO,yBAAyB,KAAA,GAClC,MAAM,KACJ,gCAAgC,OAAO,IAAI,eAAe,OAAO,IAAI,sDAAsD,OAAO,qBAAqB,KAAK,IAAI,GAClK;AAEJ;;;;AAKA,MAAM,uBAAuB,UAAoB,eAAuD;CACtG,MAAM,UAAU,WACb,KAAK,cAAc,UAAU,aAAa,oBAAoB,CAAC,CAC/D,QAAQ,UAAkC,UAAU,KAAA,CAAS;CAChE,IAAI,QAAQ,WAAW,GAAG,OAAO;CAEjC,OAAO,OAAO,YACZ,OAAO,QAAQ,QAAQ,CAAC,CAAC,QACtB,CAAC,gBAAgB,eAAe,uBAAuB,QAAQ,OAAO,UAAU,MAAM,SAAS,UAAU,CAAC,CAC7G,CACF;AACF;;;;;;;AAQA,MAAa,qBAAqB,OAAO,aACtC,MAAM,+BAA+B,OAAO,EAAA,CAAG"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/constraints.ts","../src/jsonWeb/createJsonWebToken.ts","../src/jsonWeb/createJsonWebTokenSignableInput.ts","../src/error/PolicyErrorStage.ts","../src/error/OpenIdFederationError.ts","../src/utils/validate.ts","../src/jsonWeb/jsonWebKey.ts","../src/jsonWeb/jsonWebKeySet.ts","../src/jsonWeb/getUsedJsonWebKey.ts","../src/jsonWeb/jsonWebToken.ts","../src/metadata/common.ts","../src/metadata/operator/MetadataMergeStrategy.ts","../src/metadata/operator/MetadataOrderOfApplication.ts","../src/metadata/operator/utils/createPolicyOperatorSchema.ts","../src/metadata/operator/utils/swapValidators.ts","../src/metadata/operator/standard/add.ts","../src/metadata/operator/standard/default.ts","../src/metadata/operator/standard/essential.ts","../src/metadata/operator/standard/oneOf.ts","../src/metadata/operator/standard/subsetOf.ts","../src/metadata/operator/standard/supersetOf.ts","../src/metadata/operator/standard/value.ts","../src/metadata/policy.ts","../src/metadata/entity/utils/createEntity.ts","../src/metadata/entity/federationEntity.ts","../src/metadata/entity/oauthAuthorizationServer.ts","../src/metadata/entity/oauthClient.ts","../src/metadata/entity/oauthResource.ts","../src/metadata/entity/openIdCredentialIssuer.ts","../src/metadata/entity/openIdCredentialVerifier.ts","../src/metadata/entity/openIdProvider.ts","../src/metadata/entity/openIdRelyingParty.ts","../src/metadata/metadata.ts","../src/utils/dateSchema.ts","../src/utils/url.ts","../src/utils/fetch.ts","../src/trustMark/trustMark.ts","../src/trustMark/trustMarkIssuer.ts","../src/trustMark/trustMarkOwner.ts","../src/entityStatement/entityStatementClaims.ts","../src/entityStatement/entityStatementHeader.ts","../src/entityStatement/createEntityStatement.ts","../src/jsonWeb/parseJsonWebToken.ts","../src/jsonWeb/verifyJsonWebToken.ts","../src/entityStatement/entityStatementJwt.ts","../src/entityStatement/fetchEntityStatement.ts","../src/entityConfiguration/entityConfigurationClaims.ts","../src/entityConfiguration/entityConfigurationHeader.ts","../src/entityConfiguration/createEntityConfiguration.ts","../src/entityConfiguration/entityConfigurationJwt.ts","../src/entityConfiguration/fetchEntityConfiguration.ts","../src/utils/data.ts","../src/resolveTrustChains/policies/errors/PolicyValidationError.ts","../src/resolveTrustChains/policies/MetadataHelper.ts","../src/resolveTrustChains/policies/utils.ts","../src/resolveTrustChains/policies/applyMetadataPolicyToMetadata.ts","../src/resolveTrustChains/policies/errors/PolicyMergeError.ts","../src/resolveTrustChains/policies/combineExistingMetadataPolicyOperators.ts","../src/resolveTrustChains/policies/combineMetadataPolicies.ts","../src/resolveTrustChains/resolveTrustChains.ts"],"sourcesContent":["import { z } from 'zod'\n\nexport const constraintSchema = z.object({\n max_path_length: z.number().optional(),\n naming_constraints: z\n .object({\n permitted: z.array(z.string()).optional(),\n excluded: z.array(z.string()).optional(),\n })\n .optional(),\n allowed_entity_types: z\n .array(\n z.string().refine((s) => s !== 'federation_entity', {\n message: `Value cannot be \"federation_entity\"`,\n })\n )\n .optional(),\n})\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#name-constraints | Constraints}\n *\n * Trust Anchors and Intermediate Entities MAY define constraining criteria that apply to their Subordinates. They are expressed in the constraints claim of a Subordinate Statement, as described in {@link https://openid.net/specs/openid-federation-1_0.html#entity-statement | Section 3}.\n *\n */\nexport type Constraint = z.input<typeof constraintSchema>\n","import { base64url, base64urlEncode } from '@owf/identity-common'\n\n/**\n *\n * Create a json web token according to {@link https://datatracker.ietf.org/doc/html/rfc7519 | RFC7519 }\n *\n */\nexport const createJsonWebToken = (\n header: Record<string, unknown>,\n payload: Record<string, unknown>,\n signature: Uint8Array\n) => {\n const encodedHeader = base64urlEncode(JSON.stringify(header))\n const encodedPayload = base64urlEncode(JSON.stringify(payload))\n\n const encodedSignature = base64url.encode(signature)\n\n return `${encodedHeader}.${encodedPayload}.${encodedSignature}`\n}\n","import { base64urlEncode, stringToBytes } from '@owf/identity-common'\n\n/**\n *\n * Converts a JSON header and payload into a byte array which can be used to verify and sign a JWT\n *\n */\nexport const createJwtSignableInput = (header: Record<string, unknown>, payload: Record<string, unknown>) => {\n if (Object.keys(header).length === 0) {\n throw new Error('Can not create JWT with an empty header')\n }\n\n if (Object.keys(payload).length === 0) {\n throw new Error('Can not create JWT with an empty payload')\n }\n\n const encodedHeader = base64urlEncode(JSON.stringify(header))\n const encodedPayload = base64urlEncode(JSON.stringify(payload))\n\n const toBeSignedString = `${encodedHeader}.${encodedPayload}`\n\n return stringToBytes(toBeSignedString)\n}\n","export enum PolicyErrorStage {\n Generic = 'generic',\n Validation = 'validation',\n MetadataPolicyCrit = 'metadataPolicyCrit',\n PolicyMerge = 'policyMerge',\n PolicyApply = 'policyApply',\n}\n","import type { ZodError } from 'zod'\nimport { PolicyErrorStage } from './PolicyErrorStage'\n\nexport class OpenIdFederationError extends Error {\n public constructor(\n public readonly errorCode: PolicyErrorStage,\n message?: string,\n public readonly cause?: unknown\n ) {\n super(message)\n }\n\n public static fromZodError(zodError: ZodError) {\n return new OpenIdFederationError(PolicyErrorStage.Validation, undefined, zodError)\n }\n\n public static isMetadataPolicyCritError(error: unknown) {\n return error instanceof OpenIdFederationError && error.errorCode === PolicyErrorStage.MetadataPolicyCrit\n }\n}\n","import type { z } from 'zod'\nimport { OpenIdFederationError } from '../error/OpenIdFederationError'\n\ntype ValidateOptions<Schema extends z.ZodType> = {\n data: z.input<Schema> | unknown\n schema: Schema\n errorMessage?: string\n}\n\nexport const validate = <Schema extends z.ZodType>({\n schema,\n data,\n errorMessage,\n}: ValidateOptions<Schema>): z.output<Schema> => {\n try {\n return schema.parse(data)\n } catch (e) {\n const error = OpenIdFederationError.fromZodError(e as z.ZodError)\n error.message = errorMessage ?? error.message\n throw error\n }\n}\n","import { z } from 'zod'\n\nexport const jsonWebKeySchema = z\n .object({\n kty: z.string(),\n // TODO: spec mentions kid may be undefined, but we always need a key id for open id federation\n kid: z.string(),\n use: z.string().optional(),\n key_ops: z.array(z.string()).optional(),\n alg: z.string().optional(),\n x5u: z.string().optional(),\n x5c: z.array(z.string()).optional(),\n x5t: z.string().optional(),\n 'x5t#S256': z.string().optional(),\n })\n .loose()\n\nexport type JsonWebKey = z.input<typeof jsonWebKeySchema>\n","import { z } from 'zod'\nimport { jsonWebKeySchema } from './jsonWebKey'\n\nexport const jsonWebKeySetSchema = z.object({\n keys: z.array(jsonWebKeySchema),\n})\n\nexport type JsonWebKeySetOptions = z.input<typeof jsonWebKeySetSchema>\n\nexport type JsonWebKeySet = z.output<typeof jsonWebKeySetSchema>\n","import { z } from 'zod'\nimport { validate } from '../utils/validate'\nimport { jsonWebKeySetSchema } from './jsonWebKeySet'\n\nexport const getUsedJsonWebKey = (header: Record<string, unknown>, claims: Record<string, unknown>) => {\n const validatedHeader = validate({\n schema: z\n .object({\n kid: z.string(),\n })\n .loose(),\n data: header,\n errorMessage: 'invalid header claims. Should contain a key id',\n })\n const validatedClaims = validate({\n schema: z.object({ jwks: jsonWebKeySetSchema }).loose(),\n data: claims,\n errorMessage: 'Invalid payload claims. Should contain a json web key set',\n })\n\n // Get the key from the `claims.jwks` by the `header.kid`\n const key = validatedClaims.jwks?.keys.find((key) => key.kid === validatedHeader.kid)\n\n if (!key) {\n throw new Error(`key with id: '${header.kid}' could not be found in the claims`)\n }\n\n return key\n}\n","import { base64url, base64urlDecodeJson } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { validate } from '../utils/validate'\n\nconst defaultSchema = z.record(z.string(), z.unknown())\n\n/**\n *\n * @todo better jwt validation\n *\n */\nexport const jsonWebTokenSchema = <\n CS extends z.ZodType = typeof defaultSchema,\n HS extends z.ZodType = typeof defaultSchema,\n>(\n {\n claimsSchema = defaultSchema as unknown as CS,\n headerSchema = defaultSchema as unknown as HS,\n }: {\n claimsSchema?: CS\n headerSchema?: HS\n } = {\n claimsSchema: defaultSchema as unknown as CS,\n headerSchema: defaultSchema as unknown as HS,\n }\n) =>\n z.string().transform((s, ctx) => {\n const [header, claims, signature] = s.split('.')\n\n if (!header) {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT does not contain a header parameter',\n })\n return z.NEVER\n }\n\n if (!claims) {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT does not contain a payload',\n })\n return z.NEVER\n }\n\n if (!signature) {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT does not contain a signature',\n })\n\n return z.NEVER\n }\n\n let decodedHeader: unknown\n let decodedClaims: unknown\n let decodedSignature: Uint8Array\n try {\n decodedHeader = base64urlDecodeJson(header)\n decodedClaims = base64urlDecodeJson(claims)\n decodedSignature = base64url.decode(signature)\n } catch {\n ctx.addIssue({\n code: 'custom',\n message: 'JWT is not a valid compact JWS',\n })\n return z.NEVER\n }\n\n const validatedHeader = validate({\n schema: headerSchema,\n data: decodedHeader,\n errorMessage: 'invalid header claims provided',\n })\n const validatedClaims = validate({\n schema: claimsSchema,\n data: decodedClaims,\n errorMessage: 'invalid payload claims provided',\n })\n\n return {\n jwt: s,\n header: validatedHeader,\n claims: validatedClaims,\n signature: decodedSignature,\n }\n })\n","import { z } from 'zod'\nimport { jsonWebKeySetSchema } from '../jsonWeb'\n\nexport const commonMetadataSchema = z.object({\n // -- 5.2.1 Extensions for JWK Sets in Entity Metadata\n signed_jwks_uri: z.url().optional(),\n jwks_uri: z.url().optional(),\n jwks: jsonWebKeySetSchema.optional(),\n\n // -- 5.2.2 informational Metadata Extensions --\n organization_name: z.string().optional(),\n contacts: z.array(z.string()).min(1).optional(),\n logo_uri: z.url().optional(),\n policy_uri: z.url().optional(),\n homepage_uri: z.url().optional(),\n})\n","export enum MetadataMergeStrategy {\n /**\n *\n * Allowed only when the operator values are equal. If not, this MUST result in a policy error.\n *\n */\n OperatorValuesEqual = 0,\n /**\n *\n * The result of merging the values of two these operators is the union of the operator values.\n *\n */\n Union = 1,\n /**\n *\n * The result of merging the values of two these operators is the intersection of the operator values. If the intersection is empty, this MUST result in a policy error.\n *\n */\n Intersection = 2,\n /**\n *\n * The result of merging the values of two these operators is the logical disjunction (OR) of the operator values.\n *\n */\n LogicalOr = 3,\n /**\n *\n * The result of merging the values of two these operators is the intersection of the operator values. The intersection may be an empty array.\n *\n */\n IntersectionMayBeEmpty = 4,\n}\n","export enum MetadataOrderOfApplication {\n First = 0,\n AfterValue = 1,\n AfterAdd = 2,\n AfterDefault = 3,\n AfterOneOf = 4,\n AfterSubsetOf = 5,\n Last = 6,\n}\n","import type { MetadataOperator } from '../MetadataOperator'\n\nexport const createPolicyOperatorSchema = <TKey extends string>(operator: MetadataOperator<TKey>) =>\n ({\n /**\n * The key of the operator which is used to identify the operator\n */\n key: operator.key,\n /**\n * The merge strategy of the operator\n */\n mergeStrategy: operator.mergeStrategy,\n /**\n * The order of application of the operator\n */\n orderOfApplication: operator.orderOfApplication,\n /**\n * The operator itself\n */\n operator: operator,\n /**\n * The schema for the operator itself so for essential it is only a boolean\n */\n operatorSchema: operator.operatorJsonValues.reduce((acc, schema) => acc.or(schema)).optional(),\n /**\n * The schema for the parameter the operator can be applied to so when the policy is targeting federation_entity we can check if the policy can handle that property\n */\n parameterSchema: operator.parameterJsonValues.reduce((acc, schema) => acc.or(schema)).optional(),\n }) as const\n","import { z } from 'zod'\n\nexport const swapValidators = <T extends z.ZodRawShape, V extends z.ZodType>(\n schema: z.ZodObject<T>,\n newValidator: V\n): z.ZodObject<{ [K in keyof T]: V }> => {\n return z.object(\n Object.keys(schema.shape).reduce(\n (acc, key) => {\n acc[key as keyof typeof acc] = newValidator\n return acc\n },\n {} as { [K in keyof T]: V }\n )\n )\n}\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const addOperator = createPolicyOperatorSchema({\n key: 'add',\n parameterJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'default', 'subset_of', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterValue,\n mergeStrategy: MetadataMergeStrategy.Union,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const defaultOperator = createPolicyOperatorSchema({\n key: 'default',\n parameterJsonValues: [z.string(), z.number(), z.boolean(), z.record(z.string(), z.unknown()), z.array(z.unknown())],\n operatorJsonValues: [z.string(), z.number(), z.boolean(), z.record(z.string(), z.unknown()), z.array(z.unknown())],\n canBeCombinedWith: ['value', 'add', 'one_of', 'subset_of', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterAdd,\n mergeStrategy: MetadataMergeStrategy.OperatorValuesEqual,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const essentialOperator = createPolicyOperatorSchema({\n key: 'essential',\n parameterJsonValues: [\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), z.string().or(z.number())),\n z.unknown(),\n z.array(z.unknown()),\n ],\n operatorJsonValues: [z.boolean()],\n canBeCombinedWith: ['add', 'default', 'one_of', 'subset_of', 'superset_of', 'value'],\n orderOfApplication: MetadataOrderOfApplication.Last,\n mergeStrategy: MetadataMergeStrategy.LogicalOr,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const oneOfOperator = createPolicyOperatorSchema({\n key: 'one_of',\n parameterJsonValues: [\n z.string(),\n // TODO: See how we want to we handle the comparison of objects\n // z.record(z.string(), z.unknown()),\n z.number(),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'default', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterDefault,\n mergeStrategy: MetadataMergeStrategy.Intersection,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const subsetOfOperator = createPolicyOperatorSchema({\n key: 'subset_of',\n parameterJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'add', 'default', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterOneOf,\n mergeStrategy: MetadataMergeStrategy.IntersectionMayBeEmpty,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const supersetOfOperator = createPolicyOperatorSchema({\n key: 'superset_of',\n parameterJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n operatorJsonValues: [\n z.array(z.string()),\n // TODO: See how we want to we handle the comparison of objects\n // z.array(z.record(z.string(), z.unknown())),\n z.array(z.number()),\n ],\n canBeCombinedWith: ['value', 'add', 'default', 'subset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.AfterSubsetOf,\n mergeStrategy: MetadataMergeStrategy.Union,\n})\n","import { z } from 'zod'\nimport { MetadataMergeStrategy } from '../MetadataMergeStrategy'\nimport { MetadataOrderOfApplication } from '../MetadataOrderOfApplication'\nimport { createPolicyOperatorSchema } from '../utils'\n\nexport const valueOperator = createPolicyOperatorSchema({\n key: 'value',\n parameterJsonValues: [z.string(), z.number(), z.boolean(), z.record(z.string(), z.unknown()), z.array(z.unknown())],\n operatorJsonValues: [\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), z.unknown()),\n z.array(z.unknown()),\n z.null(),\n ],\n canBeCombinedWith: ['add', 'default', 'one_of', 'subset_of', 'superset_of', 'essential'],\n orderOfApplication: MetadataOrderOfApplication.First,\n mergeStrategy: MetadataMergeStrategy.OperatorValuesEqual,\n})\n","import { z } from 'zod'\nimport {\n addOperator,\n defaultOperator,\n essentialOperator,\n oneOfOperator,\n subsetOfOperator,\n supersetOfOperator,\n valueOperator,\n} from './operator'\n\nexport const allSupportedPolicies = {\n [addOperator.key]: addOperator,\n [defaultOperator.key]: defaultOperator,\n [essentialOperator.key]: essentialOperator,\n [oneOfOperator.key]: oneOfOperator,\n [subsetOfOperator.key]: subsetOfOperator,\n [supersetOfOperator.key]: supersetOfOperator,\n [valueOperator.key]: valueOperator,\n} as const\n\nexport type SupportedPolicyKey = keyof typeof allSupportedPolicies\n\nexport const isExistingPolicyKey = (key: string): key is SupportedPolicyKey => key in allSupportedPolicies\n\nconst isSubset = (values: unknown, of: unknown) =>\n Array.isArray(values) && Array.isArray(of) && values.every((value) => of.includes(value))\n\n/**\n * The conditions that Section 6.1.3.1 sets on combinations of the standard operators.\n */\nconst conditionalCombinationErrors = (policy: Record<string, unknown>): Array<string> => {\n const errors: Array<string> = []\n const has = (key: SupportedPolicyKey) => policy[key] !== undefined\n const { value, add, one_of, subset_of, superset_of, essential } = policy\n\n if (has('value')) {\n // A null value removes the metadata parameter, so it has no values for add, subset_of and superset_of\n const values = value === null ? [] : value\n if (value === null && has('default')) errors.push(\"'value' null can not be combined with 'default'\")\n if (value === null && essential === true) errors.push(\"'value' null can not be combined with 'essential' true\")\n if (has('add') && !isSubset(add, values))\n errors.push(\"the values of 'add' must be a subset of the values of 'value'\")\n if (has('one_of') && !(Array.isArray(one_of) && value !== null && one_of.includes(value)))\n errors.push(\"the value of 'value' must be among the 'one_of' values\")\n if (has('subset_of') && !isSubset(values, subset_of))\n errors.push(\"the values of 'value' must be a subset of the values of 'subset_of'\")\n if (has('superset_of') && !isSubset(superset_of, values))\n errors.push(\"the values of 'value' must be a superset of the values of 'superset_of'\")\n }\n if (has('add') && has('subset_of') && !isSubset(add, subset_of))\n errors.push(\"the values of 'add' must be a subset of the values of 'subset_of'\")\n if (has('subset_of') && has('superset_of') && !isSubset(superset_of, subset_of))\n errors.push(\"the values of 'subset_of' must be a superset of the values of 'superset_of'\")\n\n return errors\n}\n\nexport const metadataPolicySchema = z\n .object(\n Object.entries(allSupportedPolicies).reduce(\n // biome-ignore lint/performance/noAccumulatingSpread: In this case we want to use the spread operator\n (acc, [key, policy]) => ({ ...acc, [key]: policy.operatorSchema }),\n {} as {\n [key in keyof typeof allSupportedPolicies]: (typeof allSupportedPolicies)[key]['operatorSchema']\n }\n )\n )\n .and(z.record(z.string(), z.any()))\n .superRefine((data, ctx) => {\n const dataKeys = Object.keys(data)\n\n for (const dataKey of dataKeys) {\n if (!isExistingPolicyKey(dataKey)) continue\n const { operator } = allSupportedPolicies[dataKey]\n\n // Additional operators that are not understood are ignored (Section 6.1.3.2), so they do not restrict combinations\n if (\n dataKeys.some(\n (key) => key !== operator.key && isExistingPolicyKey(key) && !operator.canBeCombinedWith.includes(key)\n )\n ) {\n ctx.addIssue({\n code: 'custom',\n message: `policy operator '${\n operator.key\n }' can only be combined with one of: [${operator.canBeCombinedWith.join(\n ', '\n )}]. keys: [${Object.keys(data).join(',')}]`,\n })\n }\n }\n\n for (const message of conditionalCombinationErrors(data)) {\n ctx.addIssue({ code: 'custom', message })\n }\n })\n\nexport type MetadataPolicyOperator = z.input<typeof metadataPolicySchema>\n","import type { z } from 'zod'\nimport { commonMetadataSchema } from '../../common'\nimport { swapValidators } from '../../operator'\nimport { metadataPolicySchema } from '../../policy'\n\nexport const createEntity = <T extends string, S extends z.ZodRawShape>({\n identifier,\n additionalValidation = {} as S,\n}: {\n identifier: T\n additionalValidation?: S\n}) => {\n const schema = commonMetadataSchema.extend(additionalValidation)\n return {\n identifier,\n // Metadata parameters the schema does not define are kept, for example the protocol specific parameters of\n // `oauth_authorization_server`. Dropping them would remove them from the resolved metadata.\n schema: schema.loose(),\n policySchema: swapValidators(schema, metadataPolicySchema.optional()),\n }\n}\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.1-1 | Federation Entity}\n *\n */\nexport const federationEntityMetadata = createEntity({\n identifier: 'federation_entity',\n additionalValidation: {\n federation_fetch_endpoint: z.url().optional(),\n federation_list_endpoint: z.url().optional(),\n federation_resolve_endpoint: z.url().optional(),\n federation_trust_mark_status_endpoint: z.url().optional(),\n federation_trust_mark_list_endpoint: z.url().optional(),\n federation_trust_mark_endpoint: z.url().optional(),\n federation_historical_keys_endpoint: z.url().optional(),\n },\n})\n\nexport type FederationEntityMetadata = z.input<(typeof federationEntityMetadata)['schema']>\n","import type { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * https://openid.net/specs/openid-federation-1_0.html#section-5.1.4-1\n *\n */\nexport const oauthAuthorizationServerEntityMetadata = createEntity({\n identifier: 'oauth_authorization_server',\n})\n\nexport type OauthAuthorizationServerMetadata = z.input<(typeof oauthAuthorizationServerEntityMetadata)['schema']>\n","import type { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.5-1 | oauth Client}\n *\n */\nexport const oauthClientEntityMetadata = createEntity({ identifier: 'oauth_client' })\n\nexport type OauthClientMetadata = z.input<(typeof oauthClientEntityMetadata)['schema']>\n","import type { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * https://openid.net/specs/openid-federation-1_0.html#section-5.1.6\n *\n */\nexport const oauthResourceEntityMetadata = createEntity({\n identifier: 'oauth_resource',\n})\n\nexport type OauthResourceMetadata = z.input<(typeof oauthResourceEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.github.io/federation-wallet/main.html#name-wallet-architecture-entity- | OpenID Credential Issuer}\n *\n */\nexport const openIdCredentialIssuerEntityMetadata = createEntity({\n identifier: 'openid_credential_issuer',\n additionalValidation: {\n client_registration_types_supported: z.array(z.string()).optional(),\n federation_registration_endpoint: z.url().optional(),\n request_authentication_methods_supported: z\n .object({\n authorization_endpoint: z.array(z.string()).optional(),\n pushed_authorization_request_endpoint: z.array(z.string()).optional(),\n })\n .optional(),\n request_authentication_signing_alg_values_supported: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdCredentialIssuerMetadata = z.input<(typeof openIdCredentialIssuerEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.github.io/federation-wallet/main.html#name-wallet-architecture-entity- | OpenID Credential Verifier }\n *\n */\nexport const openidCredentialVerifierEntityMetadata = createEntity({\n identifier: 'openid_credential_verifier',\n additionalValidation: {\n client_registration_types: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdCredentialVerifierMetadata = z.input<(typeof openidCredentialVerifierEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.3-1 | openID Provider}\n *\n */\nexport const openIdProviderEntityMetadata = createEntity({\n identifier: 'openid_provider',\n additionalValidation: {\n client_registration_types_supported: z.array(z.string()).optional(),\n federation_registration_endpoint: z.url().optional(),\n request_authentication_methods_supported: z\n .object({\n authorization_endpoint: z.array(z.string()).optional(),\n pushed_authorization_request_endpoint: z.array(z.string()).optional(),\n })\n .optional(),\n request_authentication_signing_alg_values_supported: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdProviderMetadata = z.input<(typeof openIdProviderEntityMetadata)['schema']>\n","import { z } from 'zod'\nimport { createEntity } from './utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.2-1 | openID Relying Party }\n *\n */\nexport const openidRelyingPartyEntityMetadata = createEntity({\n identifier: 'openid_relying_party',\n additionalValidation: {\n client_registration_types: z.array(z.string()).optional(),\n },\n})\n\nexport type OpenIdRelyingPartyMetadata = z.input<(typeof openidRelyingPartyEntityMetadata)['schema']>\n","import { z } from 'zod'\n\nimport {\n federationEntityMetadata,\n oauthAuthorizationServerEntityMetadata,\n oauthClientEntityMetadata,\n oauthResourceEntityMetadata,\n openIdCredentialIssuerEntityMetadata,\n openIdProviderEntityMetadata,\n openidCredentialVerifierEntityMetadata,\n openidRelyingPartyEntityMetadata,\n} from './entity'\n\nexport const metadataSchema = z\n .object({\n [federationEntityMetadata.identifier]: federationEntityMetadata.schema.optional(),\n [openidRelyingPartyEntityMetadata.identifier]: openidRelyingPartyEntityMetadata.schema.optional(),\n [openidCredentialVerifierEntityMetadata.identifier]: openidCredentialVerifierEntityMetadata.schema.optional(),\n [openIdCredentialIssuerEntityMetadata.identifier]: openIdCredentialIssuerEntityMetadata.schema.optional(),\n [openIdProviderEntityMetadata.identifier]: openIdProviderEntityMetadata.schema.optional(),\n [oauthAuthorizationServerEntityMetadata.identifier]: oauthAuthorizationServerEntityMetadata.schema.optional(),\n [oauthClientEntityMetadata.identifier]: oauthClientEntityMetadata.schema.optional(),\n [oauthResourceEntityMetadata.identifier]: oauthResourceEntityMetadata.schema.optional(),\n })\n // Entity types not defined here are kept unvalidated, as OpenID Federation allows further entity types.\n .loose()\n\nexport type Metadata = z.input<typeof metadataSchema>\n","import { z } from 'zod'\n\n/**\n *\n * NumericDate (RFC 7519 Section 2): seconds since the epoch, parsed to a js date object\n *\n */\nexport const dateSchema = z.number().transform((seconds) => new Date(seconds * 1000))\n","import { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\n\n/**\n *\n * Add paths to a url\n *\n * ## example\n *\n * ```typescript\n * const url = addPaths('https://example.org','path', 'two')\n * assert(url, \"https://example.org/path/two\")\n *\n * const url = addPaths('https://example.org/','path', 'two')\n * assert(url, \"https://example.org/path/two\")\n *\n * const url = addPaths('https://example.org/','path/', '/two/')\n * assert(url, \"https://example.org/path/two\")\n * ```\n *\n */\nexport const addPaths = (baseUrl: string, ...paths: Array<string>) => {\n const [scheme, rest] = baseUrl.split('://')\n if (!rest) {\n throw new OpenIdFederationError(PolicyErrorStage.Validation, 'not a valid URL')\n }\n\n const urlWithoutScheme = rest\n // Get all base the parts\n .split('/')\n // Add the paths\n .concat(...paths.map((p) => p.split('/')))\n // Filter out empty paths (i.e. '///path///' to 'path')\n .filter((s) => s.length > 0)\n // Create the full url\n .join('/')\n\n return `${scheme}://${urlWithoutScheme}`\n}\n\n/**\n *\n * Add search params to a url, keeping the query component it already has (Section 5.1.1 allows one for the\n * endpoints)\n *\n * ## example\n *\n * ```typescript\n * const url = addSearchParams('https://example.org', { one: 'two' })\n * assert(url, \"https://example.org?one=two\")\n *\n * const url = addSearchParams('https://example.org?tenant=a', { one: 'two' })\n * assert(url, \"https://example.org?tenant=a&one=two\")\n * ```\n *\n */\nexport const addSearchParams = (baseUrl: string, searchParams: URLSearchParams | Record<string, string>) => {\n const query = searchParams instanceof URLSearchParams ? searchParams : new URLSearchParams(searchParams)\n\n if (!baseUrl.includes('?')) {\n return `${baseUrl}?${query}`\n }\n\n // Do not add a separator when the query component is empty or already ends with one\n return baseUrl.endsWith('?') || baseUrl.endsWith('&') ? `${baseUrl}${query}` : `${baseUrl}&${query}`\n}\n\n/**\n *\n * Compares two entity identifiers as Section 16 requires: code point by code point. A trailing slash is only removed\n * when building the well-known URL.\n *\n */\nexport const isSameEntityId = (a: string, b: string) => a === b\n","import { isMediaType } from '@owf/identity-common'\nimport type { z } from 'zod'\nimport type { FetchCallback } from './types'\nimport { addSearchParams } from './url'\nimport { validate } from './validate'\n\n// Resolved on every call, so a fetch that is set or replaced after this module is loaded is used\nconst defaultFetch: FetchCallback = (input, init) => globalThis.fetch(input, init)\n\ntype GetOptions = {\n url: string\n searchParams?: Record<string, string>\n requiredContentType?: string\n fetchCallback?: FetchCallback\n}\n\n/**\n *\n * Fetch the url and return the JSON response validated against the schema, or the text response without a schema\n *\n */\nasync function get<T extends z.ZodType>(options: GetOptions & { responseValidationSchema: T }): Promise<z.output<T>>\nasync function get(options: GetOptions & { responseValidationSchema?: undefined }): Promise<string>\nasync function get({\n url,\n searchParams,\n responseValidationSchema,\n requiredContentType,\n fetchCallback = defaultFetch,\n}: GetOptions & { responseValidationSchema?: z.ZodType }): Promise<unknown> {\n // Fetch the url with the search params\n const urlSearchParams = new URLSearchParams(searchParams)\n const urlWithSearchParams = urlSearchParams.toString() ? addSearchParams(url, urlSearchParams) : url\n const response = await fetchCallback(urlWithSearchParams, {\n method: 'GET',\n })\n\n if (!response.ok) {\n throw new Error(`request to '${urlWithSearchParams}' failed with status ${response.status}`)\n }\n\n // validate the expected content-type, ignoring parameters such as `charset` and case (RFC 9110 8.3.1)\n if (requiredContentType && !isMediaType(response.headers.get('content-type'), requiredContentType)) {\n throw new Error(\n `received content-type '${response.headers.get(\n 'content-type'\n )}' does not equal expected content-type '${requiredContentType}'`\n )\n }\n\n // If we pass in a validation schema, we expect JSON output\n if (responseValidationSchema) {\n const json = await response.json()\n return validate({\n data: json,\n schema: responseValidationSchema,\n errorMessage: 'invalid response from the GET call',\n })\n }\n\n // If no validation schema is passed in, we expect a string as response\n const text = await response.text()\n return text\n}\n\n/**\n *\n * @todo make get/post use the same method private internally as changes with apply to both\n *\n */\nconst post = async ({\n url,\n body,\n responseValidationSchema,\n fetchCallback = defaultFetch,\n}: {\n url: string\n body?: Record<string, unknown>\n responseValidationSchema?: z.ZodType\n fetchCallback?: FetchCallback\n}) => {\n const response = await fetchCallback(url, {\n method: 'POST',\n body: body ? JSON.stringify(body) : undefined,\n headers: { 'Content-Type': 'application/json' },\n })\n\n if (responseValidationSchema) {\n const json = await response.json()\n return validate({\n data: json,\n schema: responseValidationSchema,\n errorMessage: 'invalid response from a POST call',\n })\n }\n\n const text = await response.text()\n\n return text\n}\n\nexport const fetcher = {\n get,\n post,\n} as const\n","import { z } from 'zod'\nimport { jsonWebTokenSchema } from '../jsonWeb'\nimport { dateSchema } from '../utils'\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-7.1 | Trust Mark Claims}\n *\n */\nexport const trustMarkClaimsSchema = z\n .object({\n iss: z.string(),\n sub: z.string(),\n trust_mark_type: z.string(),\n iat: dateSchema,\n exp: dateSchema.optional(),\n logo_uri: z.url().optional(),\n ref: z.url().optional(),\n delegation: z.string().optional(),\n })\n .loose()\n\n/**\n *\n * An entry of the `trust_marks` claim of an entity configuration\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-3.1.1 | trust_marks}\n *\n */\nexport const trustMarkSchema = z\n .object({\n trust_mark_type: z.string(),\n trust_mark: jsonWebTokenSchema({\n claimsSchema: trustMarkClaimsSchema,\n }),\n })\n .refine((entry) => entry.trust_mark_type === entry.trust_mark.claims.trust_mark_type, {\n message: 'trust_mark_type must be the trust_mark_type of the trust mark JWT',\n path: ['trust_mark_type'],\n })\n\nexport type TrustMark = z.output<typeof trustMarkSchema>\n","import { z } from 'zod'\n\nexport const trustMarkIssuerSchema = z.record(z.string(), z.array(z.string()))\n\nexport type TrustMarkIssuer = z.input<typeof trustMarkIssuerSchema>\n","import { z } from 'zod'\nimport { jsonWebKeySetSchema } from '../jsonWeb'\n\nexport const trustMarkOwnerSchema = z.record(\n z.string(),\n z.object({\n sub: z.string(),\n jwks: jsonWebKeySetSchema,\n })\n)\n\nexport type TrustMarkOwner = z.input<typeof trustMarkOwnerSchema>\n","import { z } from 'zod'\nimport { constraintSchema } from '../constraints'\nimport { jsonWebKeySetSchema } from '../jsonWeb'\nimport { metadataPolicySchema, metadataSchema } from '../metadata'\nimport { trustMarkIssuerSchema, trustMarkOwnerSchema, trustMarkSchema } from '../trustMark'\nimport { dateSchema } from '../utils'\n\nexport const entityStatementClaimsSchema = z\n .object({\n iss: z.string(),\n sub: z.string(),\n iat: dateSchema,\n exp: dateSchema,\n jwks: jsonWebKeySetSchema,\n authority_hints: z.array(z.url()).optional(),\n metadata: metadataSchema.optional(),\n metadata_policy: z.record(z.string(), z.record(z.string(), metadataPolicySchema.optional())).optional(),\n constraints: constraintSchema.optional(),\n crit: z.array(z.string()).optional(),\n metadata_policy_crit: z.array(z.string()).optional(),\n trust_marks: z.array(trustMarkSchema).optional(),\n trust_mark_issuers: trustMarkIssuerSchema.optional(),\n trust_mark_owners: trustMarkOwnerSchema.optional(),\n source_endpoint: z.url().optional(),\n })\n .superRefine((data, ctx) => {\n const keyIds = data.jwks.keys.map((key) => key.kid)\n if (keyIds.some((key, i) => keyIds.indexOf(key) !== i)) {\n ctx.addIssue({\n code: 'custom',\n message: 'keys include duplicate key ids',\n path: ['jwks', 'keys'],\n })\n }\n })\n\nexport type EntityStatementClaimsOptions = z.input<typeof entityStatementClaimsSchema>\n\nexport type EntityStatementClaims = z.output<typeof entityStatementClaimsSchema>\n\nexport type EntityStatementChain = Array<EntityStatementClaims>\n","import { z } from 'zod'\n\n/**\n *\n * @todo define extact scheme\n *\n */\nexport const entityStatementHeaderSchema = z\n .object({\n kid: z.string(),\n typ: z.literal('entity-statement+jwt'),\n })\n .loose()\n\nexport type EntityStatementHeaderOptions = z.input<typeof entityStatementHeaderSchema>\n\nexport type EntityStatementHeader = z.output<typeof entityStatementHeaderSchema>\n","import { createJsonWebToken, createJwtSignableInput, type JsonWebKey } from '../jsonWeb'\nimport type { SignCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { type EntityStatementClaimsOptions, entityStatementClaimsSchema } from './entityStatementClaims'\nimport { type EntityStatementHeaderOptions, entityStatementHeaderSchema } from './entityStatementHeader'\n\nexport type CreateEntityStatementOptions = {\n claims: EntityStatementClaimsOptions\n header?: EntityStatementHeaderOptions\n signJwtCallback: SignCallback\n /**\n *\n * The Json Web Key of the issuer used for signing the statement about the subject\n *\n */\n jwk: JsonWebKey\n}\n\n/**\n *\n * Create an entity statement\n *\n * The signing callback will be called with the `header.kid` value in the `claims.jwks.keys` and a signed JWT will be returned\n *\n */\nexport const createEntityStatement = async ({\n signJwtCallback,\n claims,\n jwk,\n header = {\n typ: 'entity-statement+jwt',\n kid: jwk.kid,\n },\n}: CreateEntityStatementOptions) => {\n if (header.kid !== jwk.kid) {\n throw new Error(`key id in the header: '${header.kid}' does not match the key id in the JWK: '${jwk.kid}'`)\n }\n\n // Validate the input\n validate({\n schema: entityStatementHeaderSchema,\n data: header,\n errorMessage: 'invalid header claims provided',\n })\n validate({\n schema: entityStatementClaimsSchema,\n data: claims,\n errorMessage: 'invalid payload claims provided',\n })\n\n // Create a signable input based on the header and payload\n const toBeSigned = createJwtSignableInput(header, claims)\n\n // Call the signing callback so the user has to handle the crypto part\n const signature = await signJwtCallback({ toBeSigned, jwk })\n\n // return a json web token based on the header, claims and associated signature\n return createJsonWebToken(header, claims, signature)\n}\n","import { base64url, base64urlDecodeJson, stringToBytes } from '@owf/identity-common'\n\ntype JsonWebTokenParts = {\n header: Record<string, unknown>\n claims: Record<string, unknown>\n signature: Uint8Array\n signableInput: Uint8Array\n}\n\nexport const parseJsonWebToken = (jwt: string): JsonWebTokenParts => {\n const [encodedHeader, encodedClaims, encodedSignature] = jwt.split('.')\n\n if (!encodedHeader) {\n throw new Error('could not find the header in the JWT')\n }\n\n if (!encodedClaims) {\n throw new Error('could not find the claims in the JWT')\n }\n\n if (!encodedSignature) {\n throw new Error('could not find the signature in the JWT')\n }\n\n const header = base64urlDecodeJson<Record<string, unknown>>(encodedHeader)\n const claims = base64urlDecodeJson<Record<string, unknown>>(encodedClaims)\n const signature = base64url.decode(encodedSignature)\n\n return {\n header,\n claims,\n signature,\n signableInput: stringToBytes(`${encodedHeader}.${encodedClaims}`),\n }\n}\n","import type { VerifyCallback } from '../utils'\nimport { getUsedJsonWebKey } from './getUsedJsonWebKey'\nimport type { JsonWebKeySet } from './jsonWebKeySet'\nimport { parseJsonWebToken } from './parseJsonWebToken'\n\ntype VerifyJsonWebTokenOptions = {\n verifyJwtCallback: VerifyCallback\n jwks?: JsonWebKeySet\n jwt: string\n}\n\nexport const verifyJwtSignature = async ({ jwt, jwks, verifyJwtCallback }: VerifyJsonWebTokenOptions) => {\n const { header, signature, claims, signableInput } = parseJsonWebToken(jwt)\n\n const jsonWebKeySetClaims = jwks ? { jwks } : claims\n\n const jwk = getUsedJsonWebKey(header, jsonWebKeySetClaims)\n\n try {\n const isValid = await verifyJwtCallback({\n jwt,\n header,\n claims,\n signature,\n jwk,\n data: signableInput,\n })\n\n // TODO: better error message\n if (!isValid) {\n throw new Error('Signature in the JWT is invalid')\n }\n } catch (e: unknown) {\n if (typeof e === 'string') {\n throw new Error(e)\n }\n\n throw e\n }\n}\n","import { jsonWebTokenSchema } from '../jsonWeb'\nimport { entityStatementClaimsSchema } from './entityStatementClaims'\nimport { entityStatementHeaderSchema } from './entityStatementHeader'\n\nexport const entityStatementJwtSchema = jsonWebTokenSchema({\n headerSchema: entityStatementHeaderSchema,\n claimsSchema: entityStatementClaimsSchema,\n})\n","import { type EntityConfigurationClaims, fetchEntityConfiguration } from '../entityConfiguration'\nimport { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\nimport { verifyJwtSignature } from '../jsonWeb/verifyJsonWebToken'\nimport { type FetchCallback, fetcher, isSameEntityId, type VerifyCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { entityStatementJwtSchema } from './entityStatementJwt'\n\nexport type FetchEntityStatementOptions = {\n iss: string\n sub: string\n verifyJwtCallback: VerifyCallback\n fetchCallback?: FetchCallback\n /**\n *\n * The issuers entity configuration\n *\n * If this is not passed in, it will be fetched from the provided `iss` argument.\n *\n */\n issEntityConfiguration?: EntityConfigurationClaims\n /**\n *\n * Fetch endpoint to get the statements from.\n *\n * If this is not passed in, it will be fetched from the `entityConfiguration.source_endpoint`\n *\n */\n endpoint?: string\n}\n\nexport const fetchEntityStatement = async ({\n sub,\n verifyJwtCallback,\n iss,\n endpoint,\n issEntityConfiguration,\n fetchCallback,\n}: FetchEntityStatementOptions) => {\n const issEntityConfigurationClaims =\n issEntityConfiguration ?? (await fetchEntityConfiguration({ entityId: iss, verifyJwtCallback, fetchCallback }))\n\n const fetchEndpoint = endpoint ?? issEntityConfigurationClaims.metadata?.federation_entity?.federation_fetch_endpoint\n\n if (!fetchEndpoint) {\n throw new Error('No fetch endpoint provided or in the issuer configuration')\n }\n\n const entityStatementJwt = await fetcher.get({\n url: fetchEndpoint,\n searchParams: { sub },\n requiredContentType: 'application/entity-statement+jwt',\n fetchCallback,\n })\n\n // Parse the JWT into its claims and header claims\n const { claims } = validate({\n schema: entityStatementJwtSchema,\n data: entityStatementJwt,\n errorMessage: 'fetched entity statement JWT is invalid',\n })\n\n if (!isSameEntityId(claims.iss, iss) || !isSameEntityId(claims.sub, sub)) {\n throw new OpenIdFederationError(\n PolicyErrorStage.Validation,\n `entity statement fetched for issuer '${iss}' and subject '${sub}' has issuer '${claims.iss}' and subject '${claims.sub}'`\n )\n }\n\n await verifyJwtSignature({\n verifyJwtCallback,\n jwt: entityStatementJwt,\n jwks: issEntityConfigurationClaims.jwks,\n })\n\n return claims\n}\n","import type { z } from 'zod'\nimport { entityStatementClaimsSchema } from '../entityStatement'\n\nexport const entityConfigurationClaimsSchema = entityStatementClaimsSchema.refine((data) => data.iss === data.sub, {\n message: 'iss and sub must be equal',\n path: ['iss', 'sub'],\n})\n\nexport type EntityConfigurationClaimsOptions = z.input<typeof entityConfigurationClaimsSchema>\n\nexport type EntityConfigurationClaims = z.output<typeof entityConfigurationClaimsSchema>\n","import { z } from 'zod'\n\n/**\n *\n * @todo define exact scheme\n *\n */\nexport const entityConfigurationHeaderSchema = z\n .object({\n kid: z.string(),\n typ: z.literal('entity-statement+jwt'),\n })\n .loose()\n\nexport type EntityConfigurationHeaderOptions = z.input<typeof entityConfigurationHeaderSchema>\n\nexport type EntityConfigurationHeader = z.output<typeof entityConfigurationHeaderSchema>\n","import { createJsonWebToken, createJwtSignableInput, getUsedJsonWebKey } from '../jsonWeb'\nimport type { SignCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { type EntityConfigurationClaimsOptions, entityConfigurationClaimsSchema } from './entityConfigurationClaims'\nimport { type EntityConfigurationHeaderOptions, entityConfigurationHeaderSchema } from './entityConfigurationHeader'\n\nexport type CreateEntityConfigurationOptions = {\n claims: EntityConfigurationClaimsOptions\n header: EntityConfigurationHeaderOptions\n signJwtCallback: SignCallback\n}\n\n/**\n *\n * Create an entity configuration\n *\n * The signing callback will be called with the `header.kid` value in the `claims.jwks.keys` and a signed JWT will be returned\n *\n */\nexport const createEntityConfiguration = async ({\n header,\n signJwtCallback,\n claims,\n}: CreateEntityConfigurationOptions) => {\n // Validate the input\n const validatedHeader = validate({\n schema: entityConfigurationHeaderSchema,\n data: header,\n errorMessage: 'invalid header claims provided',\n })\n\n const validatedClaims = validate({\n data: claims,\n schema: entityConfigurationClaimsSchema,\n errorMessage: 'invalid payload claims provided',\n })\n\n // Create a signable input based on the header and payload\n const toBeSigned = createJwtSignableInput(header, claims)\n\n // Fetch the key that will be used for signing\n const jwk = getUsedJsonWebKey(validatedHeader, validatedClaims)\n\n // Call the signing callback so the user has to handle the crypto part\n const signature = await signJwtCallback({ toBeSigned, jwk })\n\n // return a json web token based on the header, claims and associated signature\n return createJsonWebToken(header, claims, signature)\n}\n","import { jsonWebTokenSchema } from '../jsonWeb'\nimport { entityConfigurationClaimsSchema } from './entityConfigurationClaims'\nimport { entityConfigurationHeaderSchema } from './entityConfigurationHeader'\n\nexport const entityConfigurationJwtSchema = jsonWebTokenSchema({\n headerSchema: entityConfigurationHeaderSchema,\n claimsSchema: entityConfigurationClaimsSchema,\n})\n","import { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\nimport { verifyJwtSignature } from '../jsonWeb/verifyJsonWebToken'\nimport { addPaths, type FetchCallback, fetcher, isSameEntityId, type VerifyCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { entityConfigurationJwtSchema } from './entityConfigurationJwt'\n\nexport type FetchEntityConfigurationOptions = {\n entityId: string\n verifyJwtCallback: VerifyCallback\n fetchCallback?: FetchCallback\n}\n\n/**\n *\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-9.1 | Federation Entity Request}\n *\n */\nexport const fetchEntityConfiguration = async ({\n entityId,\n verifyJwtCallback,\n fetchCallback,\n}: FetchEntityConfigurationOptions) => {\n // Create the entity URL\n const federationUrl = addPaths(entityId, '.well-known', 'openid-federation')\n\n // Fetch the JWT entity configuration\n const entityConfigurationJwt = await fetcher.get({\n url: federationUrl,\n requiredContentType: 'application/entity-statement+jwt',\n fetchCallback,\n })\n\n // Parse the JWT into its claims\n const { claims } = validate({\n schema: entityConfigurationJwtSchema,\n data: entityConfigurationJwt,\n errorMessage: 'fetched entity configuration JWT is invalid',\n })\n\n // The entity configuration must be about the requested entity, otherwise any URL could claim to be another entity\n if (!isSameEntityId(claims.sub, entityId)) {\n throw new OpenIdFederationError(\n PolicyErrorStage.Validation,\n `entity configuration fetched for '${entityId}' has subject '${claims.sub}'`\n )\n }\n\n await verifyJwtSignature({ jwt: entityConfigurationJwt, verifyJwtCallback })\n\n return claims\n}\n","/**\n * Converts an object to an array of entries with better typing for the key\n */\nexport function objectToEntries<\n TObject extends {\n [Tkey in keyof TObject]: TObject[Tkey]\n },\n>(obj: TObject) {\n return Object.entries(obj) as [keyof TObject, TObject[keyof TObject]][]\n}\n\nexport const isNullOrUndefined = (value: unknown): value is null | undefined => value === null || value === undefined\n\nexport const immutable = <T extends object>(obj: T): T =>\n new Proxy(obj, {\n get(target: T, prop: string | symbol) {\n const value = target[prop as keyof T]\n return typeof value === 'object' && value !== null\n ? Array.isArray(value)\n ? Object.freeze(\n [...value].map((item) => (typeof item === 'object' && item !== null ? immutable(item) : item))\n )\n : immutable(value)\n : value\n },\n set() {\n throw new Error('This object is immutable.')\n },\n deleteProperty() {\n throw new Error('This object is immutable.')\n },\n })\n","export type PolicyValidationErrorDetails = {\n path: string\n policyValue: unknown\n targetValue: unknown\n}\n\nexport class PolicyValidationError extends Error {\n public readonly details: PolicyValidationErrorDetails\n\n public constructor(message: string, details: PolicyValidationErrorDetails) {\n super(message)\n this.name = 'PolicyValidationError'\n this.details = details\n }\n}\n","import type { Metadata } from '../../metadata'\nimport type { MetadataPolicy } from '../../metadata/metadataPolicy'\n\nexport class MetadataHelper {\n private leafMetadata: Record<string, Record<string, unknown>>\n\n public constructor(leafMetadata: Metadata) {\n this.leafMetadata = leafMetadata as Record<string, Record<string, unknown>>\n }\n\n public hasEntityType(service: string) {\n return this.leafMetadata[service] !== undefined\n }\n\n public hasProperty(service: string, property: string) {\n return this.leafMetadata[service]?.[property] !== undefined\n }\n\n public getPropertyValue<T = unknown>(service: string, property: string): T | undefined {\n const serviceBlock = this.leafMetadata[service]\n if (serviceBlock === undefined) return undefined\n const propertyValue = serviceBlock[property]\n if (propertyValue === undefined) return undefined\n return propertyValue as T\n }\n\n public setPropertyValue(service: string, property: string, value: unknown) {\n this.leafMetadata = {\n ...this.leafMetadata,\n [service]: {\n ...this.leafMetadata[service], // optionally add a helper method to get a value or an empty object otherwise\n [property]: value,\n },\n }\n }\n\n public deleteProperty(service: string, property: string) {\n const serviceBlock = this.leafMetadata[service]\n if (serviceBlock === undefined) return\n\n this.leafMetadata = {\n ...this.leafMetadata,\n [service]: {\n ...this.leafMetadata[service],\n },\n }\n\n // The entity type stays, also when it has no metadata parameters left\n delete this.leafMetadata[service][property]\n }\n\n public asMetadata(): Metadata {\n return this.leafMetadata\n }\n\n public asMetadataPolicy(): MetadataPolicy {\n return this.leafMetadata\n }\n}\n","import type { Metadata } from '../../metadata'\nimport { immutable, objectToEntries } from '../../utils/data'\nimport { MetadataHelper } from './MetadataHelper'\n\nexport type PolicyValue = boolean | string | number\n\nexport type PolicyValueArray = PolicyValue[]\n\nexport function intersect(operator1: PolicyValueArray, operator2: PolicyValueArray) {\n const set1 = new Set(operator1)\n const set2 = new Set(operator2)\n const intersection = [...set1].filter((value) => set2.has(value))\n return intersection\n}\n\nexport function union(operator1: PolicyValueArray, operator2: PolicyValueArray) {\n return [...new Set([...operator1, ...operator2])]\n}\n\n/**\n * Merges the metadata of the leaf entity with the metadata of the superior entity statement\n * The superior always has the highest priority\n */\nexport function mergeMetadata(leafConfigMetadata: Metadata, superiorEntityStatement: Metadata): Metadata {\n const mergedLeafMetadata = new MetadataHelper(immutable(leafConfigMetadata))\n\n for (const [entityType, entityConfigMetadata] of objectToEntries(superiorEntityStatement)) {\n // Section 3.1.1: it applies only to the entity types present in the subject's entity configuration\n if (!mergedLeafMetadata.hasEntityType(String(entityType))) continue\n for (const [key, value] of objectToEntries((entityConfigMetadata ?? {}) as Record<string, unknown>)) {\n mergedLeafMetadata.setPropertyValue(String(entityType), String(key), value)\n }\n }\n\n return mergedLeafMetadata.asMetadata()\n}\n","import {\n allSupportedPolicies,\n isExistingPolicyKey,\n type Metadata,\n type MetadataPolicyOperator,\n type SupportedPolicyKey,\n} from '../../metadata'\nimport { immutable, isNullOrUndefined, objectToEntries } from '../../utils/data'\nimport { PolicyValidationError } from './errors/PolicyValidationError'\nimport { MetadataHelper } from './MetadataHelper'\nimport { type PolicyValue, union } from './utils'\n\nexport function applyMetadataPolicyToMetadata({\n leafMetadata,\n policyMetadata,\n}: {\n leafMetadata: Metadata\n policyMetadata: Record<string, Record<string, MetadataPolicyOperator | undefined> | undefined>\n}) {\n const resolvedLeafMetadata = new MetadataHelper(immutable(leafMetadata))\n\n for (const [serviceKey, service] of objectToEntries(policyMetadata)) {\n // Section 6.1.4.2: policies apply to the entity types the metadata has, operators do not add an entity type\n if (!service || !resolvedLeafMetadata.hasEntityType(serviceKey)) continue\n\n for (const [servicePropertyKey, policyValue] of objectToEntries(service)) {\n if (!policyValue) continue\n\n const policies = objectToEntries(policyValue)\n .filter(([key]) => isExistingPolicyKey(key))\n .sort(\n ([policyKeyA], [policyKeyB]) =>\n allSupportedPolicies[policyKeyA as SupportedPolicyKey].orderOfApplication -\n allSupportedPolicies[policyKeyB as SupportedPolicyKey].orderOfApplication\n )\n\n const path = `${serviceKey}.${servicePropertyKey}`\n\n // Section 6.1.3.1.8: scope, a string of space-separated values, is processed as a string array\n const isScope = servicePropertyKey === 'scope'\n const scope = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey)\n if (isScope && typeof scope === 'string') {\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, splitScope(scope))\n }\n\n for (const [policyPropertyKey, rawValueFromPolicy] of policies) {\n const valueFromPolicy =\n isScope && typeof rawValueFromPolicy === 'string' ? splitScope(rawValueFromPolicy) : rawValueFromPolicy\n\n switch (policyPropertyKey) {\n case 'value':\n if (valueFromPolicy === null) {\n // When the policy value is null, we delete the property\n resolvedLeafMetadata.deleteProperty(serviceKey, servicePropertyKey)\n break\n }\n\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, valueFromPolicy)\n break\n case 'add': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey) ?? []\n if (!Array.isArray(targetValue))\n throw new PolicyValidationError('Cannot apply add policy because the target is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n const newValue = union(targetValue, valueFromPolicy)\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, newValue)\n break\n }\n case 'one_of': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n // With one_of it's allowed to not have a value and can be enforced with essential\n if (isNullOrUndefined(targetValue)) break\n\n if (!Array.isArray(valueFromPolicy))\n throw new PolicyValidationError('Cannot apply one_of policy because the value is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n if (!valueFromPolicy.some((value) => value === targetValue))\n throw new PolicyValidationError('Cannot apply one_of policy because the intersection is empty', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n break\n }\n case 'default':\n if (resolvedLeafMetadata.hasProperty(serviceKey, servicePropertyKey)) continue\n\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, valueFromPolicy)\n break\n case 'subset_of': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n // Only applies when the metadata parameter is present, essential enforces its presence\n if (isNullOrUndefined(targetValue)) break\n if (!Array.isArray(targetValue))\n throw new PolicyValidationError('Cannot apply subset_of policy because the target is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n if (!Array.isArray(valueFromPolicy))\n throw new PolicyValidationError('Cannot apply subset_of policy because the value is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n // The intersection may be an empty array, which stays the value of the metadata parameter\n const newValue = targetValue.filter((value) => valueFromPolicy.includes(value))\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, newValue)\n break\n }\n case 'superset_of': {\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n // Only applies when the metadata parameter is present, essential enforces its presence\n if (isNullOrUndefined(targetValue)) break\n if (!Array.isArray(targetValue))\n throw new PolicyValidationError('Cannot apply superset_of policy because the target is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n if (!Array.isArray(valueFromPolicy))\n throw new PolicyValidationError('Cannot apply superset_of policy because the value is not an array', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n\n if (!valueFromPolicy.every((value) => targetValue.includes(value)))\n throw new PolicyValidationError('The target does not contain all the values from the policy superset', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n break\n }\n case 'essential': {\n if (!valueFromPolicy) break\n\n const targetValue = resolvedLeafMetadata.getPropertyValue<PolicyValue>(serviceKey, servicePropertyKey)\n if (isNullOrUndefined(targetValue))\n throw new PolicyValidationError('The policy is required to have a value', {\n path,\n policyValue: valueFromPolicy,\n targetValue,\n })\n // An empty array, for example after subset_of, is present (Section 6.1.3.1.8, Table 1)\n break\n }\n }\n }\n\n const resolvedScope = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey)\n if (isScope && Array.isArray(resolvedScope)) {\n resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, resolvedScope.join(' '))\n }\n }\n }\n\n return {\n resolvedLeafMetadata: resolvedLeafMetadata.asMetadata(),\n }\n}\n\nconst splitScope = (scope: string) => scope.split(' ').filter((value) => value !== '')\n","import type { MetadataPolicyOperator } from '../../../metadata'\n\nexport type PolicyOperatorMergeErrorDetails = {\n path: string\n operatorA: MetadataPolicyOperator\n operatorB: MetadataPolicyOperator\n}\n\nexport class PolicyOperatorMergeError extends Error {\n public readonly details: PolicyOperatorMergeErrorDetails\n\n constructor(message: string, details: PolicyOperatorMergeErrorDetails) {\n super(message)\n this.name = 'PolicyOperatorMergeError'\n this.details = details\n }\n}\n","import { allSupportedPolicies, isExistingPolicyKey, type MetadataPolicyOperator } from '../../metadata'\nimport { MetadataMergeStrategy } from '../../metadata/operator/MetadataMergeStrategy'\nimport { objectToEntries } from '../../utils/data'\nimport { PolicyOperatorMergeError } from './errors'\nimport { intersect, union } from './utils'\n\n// TODO: Add support for objects (they are optional in the spec)\n\nexport function combineExistingMetadataPolicyOperators({\n contextPath,\n existingPolicyRules,\n newPolicyRules,\n}: {\n contextPath: string\n existingPolicyRules: MetadataPolicyOperator\n newPolicyRules: MetadataPolicyOperator\n}) {\n const combinedPolicyRules = { ...existingPolicyRules }\n\n for (const [policyPropertyKey, policyRuleValue] of objectToEntries(newPolicyRules)) {\n // When we don't know the policy key we can skip it because we already know it's not critical\n if (!isExistingPolicyKey(policyPropertyKey)) continue\n\n if (combinedPolicyRules[policyPropertyKey] === undefined) {\n combinedPolicyRules[policyPropertyKey] = policyRuleValue\n continue\n }\n\n const existingPolicyRuleValue = combinedPolicyRules[policyPropertyKey]\n const operator = allSupportedPolicies[policyPropertyKey]\n\n // Check if the new policy rule value is correctly used\n const operatorInputResult = operator.operatorSchema.safeParse(policyRuleValue)\n if (!operatorInputResult.success) throw operatorInputResult.error\n const newPolicyRuleValue = operatorInputResult.data\n\n switch (operator.mergeStrategy) {\n case MetadataMergeStrategy.OperatorValuesEqual:\n if (Array.isArray(existingPolicyRuleValue) && Array.isArray(newPolicyRuleValue)) {\n if (existingPolicyRuleValue.length !== newPolicyRuleValue.length)\n throw new PolicyOperatorMergeError('Policy rule values are not equal', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n\n if (existingPolicyRuleValue.some((value, i) => value !== newPolicyRuleValue[i]))\n throw new PolicyOperatorMergeError('Policy rule values are not equal', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n } else if (existingPolicyRuleValue !== newPolicyRuleValue) {\n throw new PolicyOperatorMergeError('Policy rule values are not equal', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n\n // Don't have to do anything because it is already there by the existing policy rule\n break\n case MetadataMergeStrategy.Union:\n if (!Array.isArray(existingPolicyRuleValue) || !Array.isArray(newPolicyRuleValue)) {\n throw new PolicyOperatorMergeError('Operator values are not an array', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n\n combinedPolicyRules[policyPropertyKey] = union(existingPolicyRuleValue, newPolicyRuleValue)\n break\n case MetadataMergeStrategy.Intersection:\n case MetadataMergeStrategy.IntersectionMayBeEmpty: {\n if (!Array.isArray(existingPolicyRuleValue) || !Array.isArray(newPolicyRuleValue)) {\n throw new PolicyOperatorMergeError('Existing policy rule value is not an array', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n const intersection = intersect(existingPolicyRuleValue, newPolicyRuleValue)\n if (intersection.length === 0 && operator.mergeStrategy === MetadataMergeStrategy.Intersection) {\n throw new PolicyOperatorMergeError('Intersection is empty', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n\n combinedPolicyRules[policyPropertyKey] = intersection\n\n break\n }\n case MetadataMergeStrategy.LogicalOr:\n if (typeof existingPolicyRuleValue !== 'boolean' || typeof newPolicyRuleValue !== 'boolean') {\n throw new PolicyOperatorMergeError('Existing policy rule value is not a boolean', {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n combinedPolicyRules[policyPropertyKey] = existingPolicyRuleValue || newPolicyRuleValue\n break\n\n default:\n throw new PolicyOperatorMergeError(`Unknown merge strategy: ${operator.mergeStrategy}`, {\n path: contextPath,\n operatorA: existingPolicyRules,\n operatorB: newPolicyRules,\n })\n }\n }\n\n return combinedPolicyRules\n}\n","import type { EntityStatementClaims } from '../../entityStatement'\nimport { OpenIdFederationError } from '../../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../../error/PolicyErrorStage'\nimport { isExistingPolicyKey, metadataPolicySchema } from '../../metadata'\nimport type { MetadataPolicy } from '../../metadata/metadataPolicy'\nimport { objectToEntries } from '../../utils/data'\nimport { combineExistingMetadataPolicyOperators } from './combineExistingMetadataPolicyOperators'\nimport { MetadataHelper } from './MetadataHelper'\n\nexport function combineMetadataPolicies({\n statements,\n}: {\n /**\n * The entity statements of the chain without the leaf entity\n */\n statements: Array<EntityStatementClaims>\n}): {\n mergedPolicy: MetadataPolicy\n} {\n if (statements.length === 0) throw new OpenIdFederationError(PolicyErrorStage.Generic, 'Chain is empty')\n const mergedPolicyMap = new MetadataHelper({})\n\n // We start from the TA and go down to the intermediate\n for (let i = statements.length - 1; i >= 0; i--) {\n const entityStatement = statements[i]\n if (!entityStatement) continue\n // When the current entity doesn't have a metadata policy we can skip it\n if (!entityStatement.metadata_policy) continue\n\n const metadataPolicyCrit = entityStatement.metadata_policy_crit\n\n for (const [serviceKey, serviceProperties] of objectToEntries(entityStatement.metadata_policy)) {\n for (const [servicePropertyKey, newPolicyRules] of objectToEntries(serviceProperties)) {\n if (newPolicyRules === undefined) continue\n\n const contextPath = `${serviceKey}.${servicePropertyKey}`\n\n // When the metadata_policy_crit is not empty we need to check if it contains a policy method that is not supported and is used by the new policy rule\n if (metadataPolicyCrit) {\n const methodsToCheck = Object.keys(newPolicyRules)\n const unsupportedMethodsAndRequired = methodsToCheck.filter(\n (method) => !isExistingPolicyKey(method) && metadataPolicyCrit.includes(method)\n )\n if (unsupportedMethodsAndRequired.length > 0) {\n throw new OpenIdFederationError(\n PolicyErrorStage.MetadataPolicyCrit,\n `Unsupported policy method and is required by the metadata_policy_crit: ${unsupportedMethodsAndRequired.join(', ')}`\n )\n }\n }\n\n const existingPolicyRule = mergedPolicyMap.getPropertyValue(serviceKey, servicePropertyKey)\n if (!existingPolicyRule) {\n // When there is no existing policy rule yet we can set the new policy rule\n mergedPolicyMap.setPropertyValue(serviceKey, servicePropertyKey, newPolicyRules)\n continue\n }\n\n // So we found a new property which we already have in the map yet so this can be a federation_entity property for example\n // We need to combine the existing policy rule together with the new one\n const combinedPolicyRulesRaw = combineExistingMetadataPolicyOperators({\n contextPath: contextPath,\n existingPolicyRules: existingPolicyRule,\n newPolicyRules: newPolicyRules,\n })\n\n // Check if the the new properties are able to be combined\n const combinedPolicyRules = metadataPolicySchema.safeParse(combinedPolicyRulesRaw)\n if (!combinedPolicyRules.success) throw combinedPolicyRules.error\n\n mergedPolicyMap.setPropertyValue(serviceKey, servicePropertyKey, combinedPolicyRules.data)\n }\n }\n }\n\n return {\n mergedPolicy: mergedPolicyMap.asMetadataPolicy(),\n }\n}\n","import type { EntityConfigurationClaims } from '../entityConfiguration'\nimport { entityConfigurationJwtSchema } from '../entityConfiguration/entityConfigurationJwt'\nimport type { EntityStatementChain, EntityStatementClaims } from '../entityStatement'\nimport { entityStatementJwtSchema } from '../entityStatement/entityStatementJwt'\nimport { OpenIdFederationError } from '../error/OpenIdFederationError'\nimport { PolicyErrorStage } from '../error/PolicyErrorStage'\nimport type { JsonWebKeySetOptions } from '../jsonWeb'\nimport { verifyJwtSignature } from '../jsonWeb/verifyJsonWebToken'\nimport type { Metadata } from '../metadata'\nimport { addPaths, type FetchCallback, fetcher, isSameEntityId, type VerifyCallback } from '../utils'\nimport { validate } from '../utils/validate'\nimport { applyMetadataPolicyToMetadata, combineMetadataPolicies } from './policies'\nimport { mergeMetadata } from './policies/utils'\n\nexport type TrustAnchor = {\n entityId: string\n /**\n * The federation keys of the trust anchor, obtained out of band. When given, the trust anchor's entity\n * configuration must be signed with one of them. Without them, the entity configuration fetched from the\n * trust anchor's well-known URL is trusted on its own signature.\n */\n jwks?: JsonWebKeySetOptions\n}\n\nexport type ResolveTrustChainsOptions = {\n verifyJwtCallback: VerifyCallback\n entityId: string\n trustAnchors: Array<TrustAnchor>\n /**\n * Used for every request. Pass one that applies your outbound request policy (allowed hosts, timeouts,\n * response size), as entity configurations name the URLs that are fetched.\n *\n * @default globalThis.fetch\n */\n fetchCallback?: FetchCallback\n /**\n * @default new Date()\n */\n currentDate?: Date\n /**\n * Allowed clock difference for `iat` and `exp`.\n *\n * @default 0\n */\n clockSkewSeconds?: number\n /**\n * Maximum number of superiors followed from the leaf, including the trust anchor.\n *\n * @default 8\n */\n maxDepth?: number\n /**\n * Maximum number of requests (entity configurations and subordinate statements) for one resolution. It also bounds\n * the number of entities visited while following authority hints, as an entity reached on several paths is\n * visited once per path.\n *\n * @default 64\n */\n maxRequests?: number\n /**\n * Maximum number of `authority_hints` followed per entity. Duplicates are ignored.\n *\n * @default 10\n */\n maxAuthorityHints?: number\n /**\n * Claims listed in `crit` that the caller understands. A statement whose `crit` lists another claim is rejected.\n *\n * @default []\n */\n understoodCriticalClaims?: Array<string>\n}\n\nexport type TrustChain = {\n valid: true\n\n /**\n * The subordinate statements, leaf side first, followed by the trust anchor's entity configuration.\n * When the leaf is a trust anchor, only its entity configuration.\n */\n chain: EntityStatementChain\n /**\n * The trust chain as defined in {@link https://openid.net/specs/openid-federation-1_0.html#section-4 | Section 4}:\n * the leaf's entity configuration, the subordinate statements and the trust anchor's entity configuration, as compact JWTs.\n * When the leaf is a trust anchor, only its entity configuration.\n */\n jwtChain: Array<string>\n /**\n * The raw leaf entity configuration before the policy is applied.\n * So the metadata is not valid yet.\n */\n rawLeafEntityConfiguration: EntityConfigurationClaims\n /**\n * The resolved leaf metadata after the policy is applied and the metadata is merged with the superior entity's metadata.\n */\n resolvedLeafMetadata: EntityConfigurationClaims['metadata']\n trustAnchorEntityConfiguration: EntityConfigurationClaims\n /**\n * The earliest `exp` of all statements in the chain. The chain must not be used after it.\n */\n expiresAt: Date\n}\n\nexport type TrustChainFailure = {\n /**\n * The entities of the failed path, leaf first.\n */\n entityIds: Array<string>\n reason: string\n cause?: unknown\n}\n\nexport type TrustChainResolution = {\n trustChains: Array<TrustChain>\n failures: Array<TrustChainFailure>\n}\n\ntype FetchedEntityConfiguration = { jwt: string; claims: EntityConfigurationClaims }\n\nconst ENTITY_STATEMENT_CONTENT_TYPE = 'application/entity-statement+jwt'\n\nconst fail = (message: string) => new OpenIdFederationError(PolicyErrorStage.Validation, message)\n\nconst reasonOf = (error: unknown) => (error instanceof Error && error.message ? error.message : String(error))\n\n/**\n * Resolves the trust chains from the given entity to the given trust anchors and validates them as described in\n * {@link https://openid.net/specs/openid-federation-1_0.html#section-10 | Section 10}.\n *\n * Every entity configuration and subordinate statement is checked for its signature, `iat`, `exp` and `crit`. An\n * entity configuration must be about the requested entity and signed with a key its superior's subordinate statement\n * lists. A subordinate statement must be issued by the superior about the subject. Each statement may only contain the\n * claims Section 3.2 allows for its kind. `max_path_length` and\n * `allowed_entity_types` constraints are applied, then the metadata policies. Chains with `naming_constraints` are\n * rejected, as they are not evaluated. Trust marks are not verified.\n *\n * Paths that fail are returned in `failures` with the reason.\n */\nexport const resolveTrustChainsWithFailures = async (\n options: ResolveTrustChainsOptions\n): Promise<TrustChainResolution> => {\n const {\n entityId,\n verifyJwtCallback,\n fetchCallback,\n clockSkewSeconds = 0,\n maxDepth = 8,\n maxRequests = 64,\n maxAuthorityHints = 10,\n understoodCriticalClaims = [],\n } = options\n const now = options.currentDate ?? new Date()\n\n const { trustAnchors } = options\n if (trustAnchors.length === 0) {\n throw fail('Cannot resolve a trust chain for zero trust anchors')\n }\n const findTrustAnchor = (id: string) => trustAnchors.find((anchor) => isSameEntityId(anchor.entityId, id))\n\n const failures: Array<TrustChainFailure> = []\n let requests = 0\n let visits = 0\n const get = async (url: string, searchParams?: Record<string, string>) => {\n requests++\n if (requests > maxRequests) {\n throw fail(`trust chain resolution exceeded ${maxRequests} requests`)\n }\n return fetcher.get({ url, searchParams, requiredContentType: ENTITY_STATEMENT_CONTENT_TYPE, fetchCallback })\n }\n\n const assertCurrent = (statement: EntityStatementClaims) => {\n const skewMs = clockSkewSeconds * 1000\n if (!Number.isFinite(statement.iat.getTime()) || !Number.isFinite(statement.exp.getTime())) {\n throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has an invalid iat or exp`)\n }\n if (statement.iat.getTime() > now.getTime() + skewMs) {\n throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has an iat in the future`)\n }\n if (statement.exp.getTime() <= now.getTime() - skewMs) {\n throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has expired`)\n }\n const notUnderstood = (statement.crit ?? []).filter((claim) => !understoodCriticalClaims.includes(claim))\n if (notUnderstood.length > 0) {\n throw fail(\n `statement about '${statement.sub}' issued by '${statement.iss}' has critical claims that are not understood: ${notUnderstood.join(', ')}`\n )\n }\n }\n\n // An entity reached through several superiors is fetched once per resolution\n const entityConfigurations = new Map<string, Promise<FetchedEntityConfiguration>>()\n const fetchEntityConfiguration = (id: string) => {\n let pending = entityConfigurations.get(id)\n if (!pending) {\n pending = (async () => {\n const jwt = await get(addPaths(id, '.well-known', 'openid-federation'))\n const { claims } = validate({\n schema: entityConfigurationJwtSchema,\n data: jwt,\n errorMessage: `entity configuration of '${id}' is invalid`,\n })\n if (!isSameEntityId(claims.sub, id)) {\n throw fail(`entity configuration fetched for '${id}' has subject '${claims.sub}'`)\n }\n await verifyJwtSignature({ jwt, verifyJwtCallback })\n assertCurrent(claims)\n assertEntityConfigurationClaims(claims)\n return { jwt, claims }\n })()\n entityConfigurations.set(id, pending)\n }\n return pending\n }\n\n /**\n * Follows the authority hints up to the trust anchors and returns every path of entity configurations,\n * leaf first, that ends at a trust anchor.\n */\n const discover = async (\n id: string,\n path: Array<FetchedEntityConfiguration>\n ): Promise<Array<Array<FetchedEntityConfiguration>>> => {\n // Without this bound, repeated or converging authority hints would enumerate exponentially many paths\n visits++\n if (visits > maxRequests) {\n throw fail(`trust chain resolution exceeded ${maxRequests} entity visits`)\n }\n const configuration = await fetchEntityConfiguration(id)\n const localPath = [...path, configuration]\n const paths: Array<Array<FetchedEntityConfiguration>> = []\n\n if (findTrustAnchor(configuration.claims.sub)) {\n paths.push(localPath)\n }\n\n // The path holds the leaf and its superiors\n if (localPath.length > maxDepth) return paths\n\n const superiors: Array<string> = []\n for (const superior of configuration.claims.authority_hints ?? []) {\n if (superiors.length === maxAuthorityHints) break\n if (localPath.some((entry) => isSameEntityId(entry.claims.sub, superior))) continue\n if (superiors.some((entry) => isSameEntityId(entry, superior))) continue\n superiors.push(superior)\n }\n const results = await Promise.allSettled(superiors.map((superior) => discover(superior, localPath)))\n results.forEach((result, index) => {\n if (result.status === 'fulfilled') {\n paths.push(...result.value)\n } else {\n failures.push({\n entityIds: [...localPath.map((entry) => entry.claims.sub), superiors[index] as string],\n reason: reasonOf(result.reason),\n cause: result.reason,\n })\n }\n })\n\n return paths\n }\n\n const validatePath = async (path: Array<FetchedEntityConfiguration>): Promise<TrustChain> => {\n const leaf = path[0] as FetchedEntityConfiguration\n const trustAnchorConfiguration = path[path.length - 1] as FetchedEntityConfiguration\n const trustAnchor = findTrustAnchor(trustAnchorConfiguration.claims.sub) as TrustAnchor\n\n if (trustAnchor.jwks) {\n await verifyJwtSignature({\n jwt: trustAnchorConfiguration.jwt,\n jwks: trustAnchor.jwks,\n verifyJwtCallback,\n }).catch((error: unknown) => {\n throw fail(\n `entity configuration of trust anchor '${trustAnchor.entityId}' is not signed with a configured key: ${reasonOf(error)}`\n )\n })\n }\n\n const statements: Array<{ jwt: string; claims: EntityStatementClaims }> = []\n for (let index = 0; index < path.length - 1; index++) {\n const subject = path[index] as FetchedEntityConfiguration\n const superior = path[index + 1] as FetchedEntityConfiguration\n\n const fetchEndpoint = superior.claims.metadata?.federation_entity?.federation_fetch_endpoint\n if (!fetchEndpoint) {\n throw fail(`'${superior.claims.sub}' has no federation_fetch_endpoint`)\n }\n\n const jwt = await get(fetchEndpoint, { sub: subject.claims.sub })\n const { claims } = validate({\n schema: entityStatementJwtSchema,\n data: jwt,\n errorMessage: `subordinate statement about '${subject.claims.sub}' issued by '${superior.claims.sub}' is invalid`,\n })\n if (!isSameEntityId(claims.iss, superior.claims.sub) || !isSameEntityId(claims.sub, subject.claims.sub)) {\n throw fail(\n `subordinate statement requested from '${superior.claims.sub}' about '${subject.claims.sub}' has issuer '${claims.iss}' and subject '${claims.sub}'`\n )\n }\n assertCurrent(claims)\n assertSubordinateStatementClaims(claims)\n\n // Naming constraints are not evaluated, so a chain that sets them is rejected instead of ignoring them\n if (claims.constraints?.naming_constraints) {\n throw fail(`'${superior.claims.sub}' sets naming_constraints, which are not supported`)\n }\n\n // The statement at this index is issued `index + 1` levels above the leaf, so `index` intermediates are between them\n const maxPathLength = claims.constraints?.max_path_length\n if (maxPathLength !== undefined && index > maxPathLength) {\n throw fail(`'${superior.claims.sub}' allows ${maxPathLength} intermediates, the chain has ${index}`)\n }\n\n statements.push({ jwt, claims })\n }\n\n // Section 10.2: each statement validates with a key the next one lists. The leaf's entity configuration with the keys\n // of the statement about it, each subordinate statement with the keys its superior's statement lists for the\n // superior, and the last one with the trust anchor's keys.\n const signers = statements.length > 0 ? [leaf, ...statements] : []\n for (let index = 0; index < signers.length; index++) {\n const signed = signers[index] as { jwt: string; claims: EntityStatementClaims }\n const next = statements[index]\n const jwks = next ? next.claims.jwks : trustAnchorConfiguration.claims.jwks\n await verifyJwtSignature({ jwt: signed.jwt, jwks, verifyJwtCallback }).catch((error: unknown) => {\n throw fail(\n `statement about '${signed.claims.sub}' issued by '${signed.claims.iss}' is not signed with a key listed by '${next ? next.claims.iss : trustAnchorConfiguration.claims.sub}': ${reasonOf(error)}`\n )\n })\n }\n\n const expiresAt = new Date(Math.min(...[...path, ...statements].map((statement) => statement.claims.exp.getTime())))\n\n if (statements.length === 0) {\n return {\n valid: true,\n chain: [leaf.claims],\n jwtChain: [leaf.jwt],\n rawLeafEntityConfiguration: leaf.claims,\n resolvedLeafMetadata: leaf.claims.metadata,\n trustAnchorEntityConfiguration: leaf.claims,\n expiresAt,\n }\n }\n\n const statementClaims = statements.map((statement) => statement.claims)\n const { mergedPolicy } = combineMetadataPolicies({ statements: statementClaims })\n\n // Section 6: the superior's metadata is applied first, then entity types the constraints do not allow are removed,\n // then the metadata policies are applied\n const mergedLeafMetadata = restrictEntityTypes(\n mergeMetadata(leaf.claims.metadata ?? {}, statementClaims[0]?.metadata ?? {}),\n statementClaims\n )\n const { resolvedLeafMetadata } = applyMetadataPolicyToMetadata({\n leafMetadata: mergedLeafMetadata,\n policyMetadata: mergedPolicy,\n })\n\n return {\n valid: true,\n chain: [...statementClaims, trustAnchorConfiguration.claims],\n jwtChain: [leaf.jwt, ...statements.map((statement) => statement.jwt), trustAnchorConfiguration.jwt],\n rawLeafEntityConfiguration: leaf.claims,\n // The policies do not add entity types, so a removed one stays removed\n resolvedLeafMetadata,\n trustAnchorEntityConfiguration: trustAnchorConfiguration.claims,\n expiresAt,\n }\n }\n\n let paths: Array<Array<FetchedEntityConfiguration>>\n try {\n paths = await discover(entityId, [])\n } catch (error) {\n // The leaf's own entity configuration could not be used\n return { trustChains: [], failures: [{ entityIds: [entityId], reason: reasonOf(error), cause: error }] }\n }\n\n const trustChains: Array<TrustChain> = []\n for (const path of paths) {\n try {\n trustChains.push(await validatePath(path))\n } catch (error) {\n failures.push({ entityIds: path.map((entry) => entry.claims.sub), reason: reasonOf(error), cause: error })\n }\n }\n\n return { trustChains, failures }\n}\n\n/**\n * Section 3.2: claims that only a subordinate statement may contain are rejected in an entity configuration.\n */\nconst assertEntityConfigurationClaims = (claims: EntityConfigurationClaims) => {\n const present = (['metadata_policy', 'metadata_policy_crit', 'constraints', 'source_endpoint'] as const).filter(\n (claim) => claims[claim] !== undefined\n )\n if (present.length > 0) {\n throw fail(\n `entity configuration of '${claims.sub}' contains ${present.join(', ')}, which only subordinate statements may contain`\n )\n }\n if (claims.authority_hints?.length === 0) {\n throw fail(`entity configuration of '${claims.sub}' has an empty authority_hints array`)\n }\n}\n\n/**\n * Section 3.2: claims that only an entity configuration may contain are rejected in a subordinate statement.\n */\nconst assertSubordinateStatementClaims = (claims: EntityStatementClaims) => {\n const present = (['authority_hints', 'trust_marks', 'trust_mark_issuers', 'trust_mark_owners'] as const).filter(\n (claim) => claims[claim] !== undefined\n )\n if (present.length > 0) {\n throw fail(\n `subordinate statement about '${claims.sub}' issued by '${claims.iss}' contains ${present.join(', ')}, which only entity configurations may contain`\n )\n }\n if (claims.metadata_policy_crit?.length === 0) {\n throw fail(\n `subordinate statement about '${claims.sub}' issued by '${claims.iss}' has an empty metadata_policy_crit array`\n )\n }\n // Section 3.1.3: listed operators that are not understood make the statement invalid. No additional operators are\n // supported, and the standard ones must not be listed.\n if (claims.metadata_policy_crit !== undefined) {\n throw fail(\n `subordinate statement about '${claims.sub}' issued by '${claims.iss}' requires policy operators that are not supported: ${claims.metadata_policy_crit.join(', ')}`\n )\n }\n}\n\n/**\n * Removes the entity types that `allowed_entity_types` constraints of the chain do not allow. `federation_entity` is always allowed.\n */\nconst restrictEntityTypes = (metadata: Metadata, statements: Array<EntityStatementClaims>): Metadata => {\n const allowed = statements\n .map((statement) => statement.constraints?.allowed_entity_types)\n .filter((types): types is Array<string> => types !== undefined)\n if (allowed.length === 0) return metadata\n\n return Object.fromEntries(\n Object.entries(metadata).filter(\n ([entityType]) => entityType === 'federation_entity' || allowed.every((types) => types.includes(entityType))\n )\n ) as Metadata\n}\n\n/**\n * Resolves the trust chains for the given entityId and trust anchors. See {@link resolveTrustChainsWithFailures},\n * which also returns why paths failed.\n *\n * @returns the valid trust chains\n */\nexport const resolveTrustChains = async (options: ResolveTrustChainsOptions): Promise<Array<TrustChain>> =>\n (await resolveTrustChainsWithFailures(options)).trustChains\n"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version": "0.
|
|
3
|
+
"version": "0.6.0-alpha-20261025205149",
|
|
4
4
|
"description": "OpenID Federation 1.0: create, fetch and validate entity statements, and resolve trust chains with metadata policies",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
7
7
|
],
|
|
8
8
|
"license": "Apache-2.0",
|
|
9
|
-
"exports":
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"default": "./dist/index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
10
16
|
"homepage": "https://github.com/openwallet-foundation-labs/identity-common-ts/tree/main/packages/openid-federation",
|
|
11
17
|
"repository": {
|
|
12
18
|
"type": "git",
|
|
@@ -14,24 +20,11 @@
|
|
|
14
20
|
"directory": "packages/openid-federation"
|
|
15
21
|
},
|
|
16
22
|
"publishConfig": {
|
|
17
|
-
"access": "public"
|
|
18
|
-
"main": "./dist/index.mjs",
|
|
19
|
-
"module": "./dist/index.mjs",
|
|
20
|
-
"types": "./dist/index.d.mts",
|
|
21
|
-
"exports": {
|
|
22
|
-
".": {
|
|
23
|
-
"types": "./dist/index.d.mts",
|
|
24
|
-
"default": "./dist/index.mjs"
|
|
25
|
-
},
|
|
26
|
-
"./package.json": "./package.json"
|
|
27
|
-
}
|
|
28
|
-
},
|
|
29
|
-
"scripts": {
|
|
30
|
-
"build": "tsdown src/index.ts --format esm --dts --sourcemap"
|
|
23
|
+
"access": "public"
|
|
31
24
|
},
|
|
32
25
|
"dependencies": {
|
|
33
|
-
"
|
|
34
|
-
"
|
|
26
|
+
"zod": "^4.6.7",
|
|
27
|
+
"@owf/identity-common": "0.6.0-alpha-20261025205149"
|
|
35
28
|
},
|
|
36
29
|
"keywords": [
|
|
37
30
|
"openid",
|
|
@@ -42,5 +35,11 @@
|
|
|
42
35
|
"metadata-policy",
|
|
43
36
|
"trust-mark",
|
|
44
37
|
"react-native"
|
|
45
|
-
]
|
|
46
|
-
|
|
38
|
+
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsdown src/index.ts --format esm --dts --sourcemap"
|
|
41
|
+
},
|
|
42
|
+
"main": "./dist/index.mjs",
|
|
43
|
+
"module": "./dist/index.mjs",
|
|
44
|
+
"types": "./dist/index.d.mts"
|
|
45
|
+
}
|