@kana-ai/edgar-ext-iap 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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 2026 Kana.ai
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.
202
+
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # @kana-ai/edgar-ext-iap
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Identity-Aware Proxy extension of EDGAR. Google Cloud's [Identity-Aware Proxy](https://cloud.google.com/iap/docs/concepts-overview) (IAP) signs each person in before a request reaches EDGAR, and adds the header `x-goog-iap-jwt-assertion`, a JWT that Google signs. This extension verifies that header and gives EDGAR the person's email, so people open the console from their own browser and their moves are recorded with their name. How EDGAR uses the answer is in [Open the console through a sign-in proxy](/docs/guides/operating.md#open-the-console-through-a-sign-in-proxy).
4
+
5
+ ## Configuration
6
+
7
+ ```toml
8
+ [api]
9
+ public_url = "https://edgar.example.com"
10
+ identity = { extension = "iap" }
11
+
12
+ [extensions]
13
+ enabled = ["iap"]
14
+
15
+ [extensions.iap]
16
+ audience = "/projects/123456789012/global/backendServices/4567890123456789012"
17
+
18
+ [people.ada]
19
+ email = "ada@example.com"
20
+ ```
21
+
22
+ `audience` names the backend service that IAP protects, by the project's number and the backend service's id. Read them with:
23
+
24
+ ```sh
25
+ gcloud projects describe <project> --format='value(projectNumber)'
26
+ gcloud compute backend-services describe <backend-service> --global --format='value(id)'
27
+ ```
28
+
29
+ The extension has no secret. It reads Google's public keys from `https://www.gstatic.com/iap/verify/public_key-jwk`, its only host.
30
+
31
+ ## Set up Google Cloud
32
+
33
+ 1. Run EDGAR on a VM, with `[console] bind` on `127.0.0.1:7401`.
34
+ 2. Run a reverse proxy on the VM that sends every path to the console and keeps the `Host` header. The load balancer ends TLS, so the proxy listens on plain HTTP. With Caddy:
35
+
36
+ ```text
37
+ :80 {
38
+ reverse_proxy 127.0.0.1:7401
39
+ }
40
+ ```
41
+
42
+ 3. Make a global external HTTPS load balancer for `edgar.example.com`, with a managed certificate, and a backend service whose backend is an instance group that holds the VM, on port 80.
43
+ 4. Give the backend service a health check of `HTTP` on port 80 and the path `/healthz`. EDGAR answers it on any host with no sign-in.
44
+ 5. Turn IAP on for the backend service, and give each person the role `IAP-secured Web App User`.
45
+ 6. Let only Google reach the VM: a firewall rule that allows port 80 from `130.211.0.0/22` and `35.191.0.0/16`, the ranges of Google's load balancers and health checks, and no other rule that opens the port.
46
+ 7. Point `edgar.example.com` at the load balancer's address, and add each person to `[people]` with the email they sign in with.
47
+
48
+ ## What the extension checks
49
+
50
+ For each request, EDGAR hands the extension only the `x-goog-iap-jwt-assertion` header. The extension answers the email when every check holds, and refuses the request with the first that fails:
51
+
52
+ | Check | Refused with |
53
+ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
54
+ | The header is there. | `the request has no x-goog-iap-jwt-assertion header` |
55
+ | It is a JWT of three base64url parts with JSON. | `the IAP assertion is not a JWT` |
56
+ | `alg` is `ES256`. Any other algorithm, `none` included, is refused. | `the IAP assertion is not signed with ES256` |
57
+ | `kid` names a key of Google's set. | `the IAP assertion names no key`, or `names a key that Google does not publish` |
58
+ | The P-256 signature verifies. | `the IAP assertion's signature does not verify` |
59
+ | `iss` is `https://cloud.google.com/iap`. | `the IAP assertion is not issued by Google's Identity-Aware Proxy` |
60
+ | `aud` is `audience`. | `the IAP assertion is for another backend service` |
61
+ | `exp` is not past, and `iat` is not ahead, with 60 seconds of clock skew. | `the IAP assertion has expired`, or `is issued in the future` |
62
+ | `email` is not empty. | `the IAP assertion names no email` |
63
+
64
+ The email is answered in lower case, with Google's `accounts.google.com:` prefix removed. EDGAR keeps the answer until the assertion expires or for five minutes, whichever is first, so a person removed from IAP loses access within five minutes.
65
+
66
+ The key set is fetched on the first request, again when it is six hours old, and for a `kid` it does not hold, at most once in five minutes. One fetch runs at a time. A fetch that fails keeps the keys held. With no key ever read, each request is refused with `Google's IAP keys could not be read` and the reason.
67
+
68
+ ## Validation
69
+
70
+ Run from the repository root. The tests sign assertions with a P-256 key pair made in the test, and answer the key set from a fake fetch; no call reaches Google.
71
+
72
+ | Command | Exit code |
73
+ | ------------------------------------------------------- | --------------- |
74
+ | `pnpm --filter @kana-ai/edgar-ext-iap run check-types` | 0 |
75
+ | `pnpm --filter @kana-ai/edgar-ext-iap run lint` | 0 |
76
+ | `pnpm --filter @kana-ai/edgar-ext-iap run format:check` | 0 |
77
+ | `pnpm --filter @kana-ai/edgar-ext-iap run test` | 0, 6 tests pass |
78
+
79
+ ## Shortcuts
80
+
81
+ - shortcut: the key set is held per extension process, so a process that the engine starts again fetches it again. Upgrade if the fetches show in Google's quota.
@@ -0,0 +1,3 @@
1
+ /** The Identity-Aware Proxy extension: it verifies the proxy's signed header and answers the person's email. */
2
+ declare const _default: import("@kana-ai/edgar-sdk").Extension;
3
+ export default _default;
@@ -0,0 +1,30 @@
1
+ import { defineExtension, defineIdentity, err, permanentFailure, temporaryFailure, } from "@kana-ai/edgar-sdk";
2
+ import { config } from "#schemas/config";
3
+ import { HEADER, identify } from "#verify/assertion";
4
+ import { KEYS_URL, keys } from "#verify/keys";
5
+ const capabilities = [`network:${new URL(KEYS_URL).host}`];
6
+ /** Google's keys, held for as long as the extension's process runs. */
7
+ const held = keys({ fetch: async (url, init) => await fetch(url, init), now: Date.now });
8
+ /** The Identity-Aware Proxy extension: it verifies the proxy's signed header and answers the person's email. */
9
+ export default defineExtension({
10
+ name: "iap",
11
+ config,
12
+ capabilities,
13
+ identity: defineIdentity({
14
+ headers: [HEADER],
15
+ capabilities,
16
+ identify: async (ctx, headers) => {
17
+ const table = config.safeParse(ctx.config);
18
+ if (!table.success) {
19
+ return err(permanentFailure("invalid", "`[extensions.iap] audience` is not set"));
20
+ }
21
+ const found = await identify(headers, table.data.audience, held, Date.now());
22
+ if (found.ok)
23
+ return found;
24
+ const { reason, message } = found.error;
25
+ return err(reason === "keys_unavailable"
26
+ ? temporaryFailure("provider_unavailable", message)
27
+ : permanentFailure("unauthenticated", message));
28
+ },
29
+ }),
30
+ });
@@ -0,0 +1,5 @@
1
+ import { z } from "zod";
2
+ /** The `[extensions.iap]` table. */
3
+ export declare const config: z.ZodObject<{
4
+ audience: z.ZodString;
5
+ }, z.core.$strict>;
@@ -0,0 +1,8 @@
1
+ import { z } from "zod";
2
+ /** The `[extensions.iap]` table. */
3
+ export const config = z.strictObject({
4
+ audience: z
5
+ .string()
6
+ .regex(/^\/projects\/\d{1,20}\/global\/backendServices\/\d{1,20}$/)
7
+ .describe("the backend service each assertion must name, as /projects/<number>/global/backendServices/<id>"),
8
+ });
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+ /** The part of an assertion's header that is read. */
3
+ export declare const header: z.ZodObject<{
4
+ alg: z.ZodString;
5
+ kid: z.ZodOptional<z.ZodString>;
6
+ }, z.core.$strip>;
7
+ /** The claims of an assertion that are checked, in Unix seconds. */
8
+ export declare const claims: z.ZodObject<{
9
+ iss: z.ZodString;
10
+ aud: z.ZodString;
11
+ exp: z.ZodNumber;
12
+ iat: z.ZodNumber;
13
+ email: z.ZodOptional<z.ZodString>;
14
+ }, z.core.$strip>;
15
+ /** A JWK set as Google publishes it; a key on another curve is left out when it is read. */
16
+ export declare const keySet: z.ZodObject<{
17
+ keys: z.ZodArray<z.ZodObject<{
18
+ kid: z.ZodString;
19
+ kty: z.ZodString;
20
+ crv: z.ZodString;
21
+ x: z.ZodString;
22
+ y: z.ZodString;
23
+ }, z.core.$strip>>;
24
+ }, z.core.$strip>;
@@ -0,0 +1,21 @@
1
+ import { z } from "zod";
2
+ /** The part of an assertion's header that is read. */
3
+ export const header = z.object({ alg: z.string(), kid: z.string().min(1).optional() });
4
+ /** The claims of an assertion that are checked, in Unix seconds. */
5
+ export const claims = z.object({
6
+ iss: z.string(),
7
+ aud: z.string(),
8
+ exp: z.number().int().nonnegative(),
9
+ iat: z.number().int().nonnegative(),
10
+ email: z.string().optional(),
11
+ });
12
+ /** A JWK set as Google publishes it; a key on another curve is left out when it is read. */
13
+ export const keySet = z.object({
14
+ keys: z.array(z.object({
15
+ kid: z.string().min(1),
16
+ kty: z.string(),
17
+ crv: z.string(),
18
+ x: z.string(),
19
+ y: z.string(),
20
+ })),
21
+ });
@@ -0,0 +1,13 @@
1
+ import { type Identified, type Result } from "@kana-ai/edgar-sdk";
2
+ import type { Keys } from "#verify/keys";
3
+ /** The header the proxy signs each request with. */
4
+ export declare const HEADER = "x-goog-iap-jwt-assertion";
5
+ /** Why an assertion names no one. */
6
+ export type Reason = "missing" | "malformed" | "algorithm" | "no_key" | "unknown_key" | "keys_unavailable" | "signature" | "issuer" | "audience" | "expired" | "early" | "no_email";
7
+ /** A refusal with the line the person sees. */
8
+ export interface Refusal {
9
+ readonly reason: Reason;
10
+ readonly message: string;
11
+ }
12
+ /** The person of the assertion in `headers`, once its signature and claims hold for `audience` at `nowMs`: the email in lower case, kept until the assertion expires or five minutes pass. */
13
+ export declare function identify(headers: Readonly<Record<string, string>>, audience: string, keys: Keys, nowMs: number): Promise<Result<Identified, Refusal>>;
@@ -0,0 +1,81 @@
1
+ import { verify } from "node:crypto";
2
+ import { attempt, err, ok } from "@kana-ai/edgar-sdk";
3
+ import { claims, header } from "#schemas/jwt";
4
+ /** The header the proxy signs each request with. */
5
+ export const HEADER = "x-goog-iap-jwt-assertion";
6
+ /** The issuer of every assertion. */
7
+ const ISSUER = "https://cloud.google.com/iap";
8
+ /** How far the proxy's clock may be from this one, in seconds. */
9
+ const SKEW = 60;
10
+ /** The longest EDGAR keeps an answer, so a person removed from the proxy loses access soon. */
11
+ const KEEP_MS = 5 * 60 * 1000;
12
+ const lines = {
13
+ missing: `the request has no \`${HEADER}\` header of Google's Identity-Aware Proxy`,
14
+ malformed: "the IAP assertion is not a JWT",
15
+ algorithm: "the IAP assertion is not signed with ES256",
16
+ no_key: "the IAP assertion names no key",
17
+ unknown_key: "the IAP assertion names a key that Google does not publish",
18
+ keys_unavailable: "Google's IAP keys could not be read",
19
+ signature: "the IAP assertion's signature does not verify",
20
+ issuer: "the IAP assertion is not issued by Google's Identity-Aware Proxy",
21
+ audience: "the IAP assertion is for another backend service",
22
+ expired: "the IAP assertion has expired",
23
+ early: "the IAP assertion is issued in the future",
24
+ no_email: "the IAP assertion names no email",
25
+ };
26
+ const refuse = (reason, detail) => err({ reason, message: detail === undefined ? lines[reason] : `${lines[reason]}: ${detail}` });
27
+ /** One part of a JWT, base64url with no padding, read as JSON with `schema`. */
28
+ function decode(part, schema) {
29
+ if (!/^[A-Za-z0-9_-]+$/.test(part))
30
+ return refuse("malformed");
31
+ const json = attempt(() => JSON.parse(Buffer.from(part, "base64url").toString("utf8")), () => undefined);
32
+ const parsed = json.ok ? schema.safeParse(json.value) : undefined;
33
+ return parsed?.success === true ? ok(parsed.data) : refuse("malformed");
34
+ }
35
+ /** The person of the assertion in `headers`, once its signature and claims hold for `audience` at `nowMs`: the email in lower case, kept until the assertion expires or five minutes pass. */
36
+ export async function identify(headers, audience, keys, nowMs) {
37
+ const assertion = headers[HEADER];
38
+ if (assertion === undefined || assertion === "")
39
+ return refuse("missing");
40
+ const parts = assertion.split(".");
41
+ const [head, body, signature] = parts;
42
+ if (parts.length !== 3 || head === undefined || body === undefined || signature === undefined) {
43
+ return refuse("malformed");
44
+ }
45
+ const read = decode(head, header);
46
+ if (!read.ok)
47
+ return read;
48
+ if (read.value.alg !== "ES256")
49
+ return refuse("algorithm");
50
+ const kid = read.value.kid;
51
+ if (kid === undefined)
52
+ return refuse("no_key");
53
+ const key = await keys.key(kid);
54
+ if (!key.ok) {
55
+ return key.error.reason === "unknown_key"
56
+ ? refuse("unknown_key")
57
+ : refuse("keys_unavailable", key.error.message);
58
+ }
59
+ if (!/^[A-Za-z0-9_-]+$/.test(signature))
60
+ return refuse("malformed");
61
+ const verified = attempt(() => verify("sha256", Buffer.from(`${head}.${body}`), { key: key.value, dsaEncoding: "ieee-p1363" }, Buffer.from(signature, "base64url")), () => false);
62
+ if (!verified.ok || !verified.value)
63
+ return refuse("signature");
64
+ const said = decode(body, claims);
65
+ if (!said.ok)
66
+ return said;
67
+ const { iss, aud, exp, iat, email } = said.value;
68
+ const now = Math.floor(nowMs / 1000);
69
+ if (iss !== ISSUER)
70
+ return refuse("issuer");
71
+ if (aud !== audience)
72
+ return refuse("audience");
73
+ if (exp + SKEW <= now)
74
+ return refuse("expired");
75
+ if (iat >= now + SKEW)
76
+ return refuse("early");
77
+ const address = email?.replace(/^accounts\.google\.com:/, "").toLowerCase() ?? "";
78
+ if (address === "")
79
+ return refuse("no_email");
80
+ return ok({ email: address, expires_at_ms: Math.min(exp * 1000, nowMs + KEEP_MS) });
81
+ }
@@ -0,0 +1,24 @@
1
+ import { type KeyObject } from "node:crypto";
2
+ import { type Result } from "@kana-ai/edgar-sdk";
3
+ /** Google's public keys for the proxy's assertions. */
4
+ export declare const KEYS_URL = "https://www.gstatic.com/iap/verify/public_key-jwk";
5
+ /** Where the key set comes from, and the wall clock in Unix milliseconds; a test passes its own. */
6
+ export interface KeySource {
7
+ readonly fetch: (url: string, init: {
8
+ readonly signal: AbortSignal;
9
+ }) => Promise<Response>;
10
+ readonly now: () => number;
11
+ }
12
+ /** Why no key verifies an assertion: the set has no such `kid`, or no set was ever read. */
13
+ export type KeyMiss = {
14
+ readonly reason: "unknown_key";
15
+ } | {
16
+ readonly reason: "keys_unavailable";
17
+ readonly message: string;
18
+ };
19
+ /** The key of each `kid`, fetched when the set is six hours old or lacks a `kid`, at most once in five minutes. */
20
+ export interface Keys {
21
+ key(kid: string): Promise<Result<KeyObject, KeyMiss>>;
22
+ }
23
+ /** The keys of `source`. A fetch that fails keeps the keys held, and one fetch runs at a time: a lookup that comes during it reads its keys. */
24
+ export declare function keys(source: KeySource): Keys;
@@ -0,0 +1,73 @@
1
+ import { createPublicKey } from "node:crypto";
2
+ import { attempt, attemptAsync, err, ok } from "@kana-ai/edgar-sdk";
3
+ import { keySet } from "#schemas/jwt";
4
+ /** Google's public keys for the proxy's assertions. */
5
+ export const KEYS_URL = "https://www.gstatic.com/iap/verify/public_key-jwk";
6
+ /** How old a held key set may be before it is fetched again. */
7
+ const REFRESH_MS = 6 * 3600 * 1000;
8
+ /** The least time between two fetches of the key set. */
9
+ const RETRY_MS = 5 * 60 * 1000;
10
+ /** How long one fetch of the key set may take. */
11
+ const FETCH_MS = 10_000;
12
+ /** The keys of `source`. A fetch that fails keeps the keys held, and one fetch runs at a time: a lookup that comes during it reads its keys. */
13
+ export function keys(source) {
14
+ let held = new Map();
15
+ let fetchedAt;
16
+ let triedAt;
17
+ let failed = "the key set was never fetched";
18
+ let fetching;
19
+ const refresh = async (now) => {
20
+ triedAt = now;
21
+ const read = await load(source);
22
+ if (read.ok) {
23
+ held = read.value;
24
+ fetchedAt = now;
25
+ }
26
+ else {
27
+ failed = read.error;
28
+ }
29
+ };
30
+ return {
31
+ key: async (kid) => {
32
+ const now = source.now();
33
+ const stale = fetchedAt === undefined || now >= fetchedAt + REFRESH_MS;
34
+ const due = triedAt === undefined || now >= triedAt + RETRY_MS;
35
+ if (fetching === undefined && due && (stale || !held.has(kid))) {
36
+ fetching = refresh(now).finally(() => {
37
+ fetching = undefined;
38
+ });
39
+ }
40
+ if (fetching !== undefined)
41
+ await fetching;
42
+ const found = held.get(kid);
43
+ if (found !== undefined)
44
+ return ok(found);
45
+ if (held.size === 0)
46
+ return err({ reason: "keys_unavailable", message: failed });
47
+ return err({ reason: "unknown_key" });
48
+ },
49
+ };
50
+ }
51
+ /** The P-256 keys of the set at `KEYS_URL`, by `kid`, or why it could not be read. */
52
+ async function load(source) {
53
+ const fetched = await attemptAsync(async () => await source.fetch(KEYS_URL, { signal: AbortSignal.timeout(FETCH_MS) }), (caught) => `Google's key set could not be fetched: ${String(caught)}`);
54
+ if (!fetched.ok)
55
+ return fetched;
56
+ if (!fetched.value.ok)
57
+ return err(`Google's key set answered ${fetched.value.status}`);
58
+ const body = await attemptAsync(async () => await fetched.value.json(), () => "Google's key set is not JSON");
59
+ if (!body.ok)
60
+ return body;
61
+ const set = keySet.safeParse(body.value);
62
+ if (!set.success)
63
+ return err("Google's key set is not a JWK set");
64
+ const found = new Map();
65
+ for (const { kid, kty, crv, x, y } of set.data.keys) {
66
+ if (kty !== "EC" || crv !== "P-256")
67
+ continue;
68
+ const key = attempt(() => createPublicKey({ key: { kty, crv, x, y }, format: "jwk" }), () => undefined);
69
+ if (key.ok)
70
+ found.set(kid, key.value);
71
+ }
72
+ return ok(found);
73
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "contract": 1,
3
+ "name": "iap",
4
+ "version": "0.1.4",
5
+ "config_schema": "schemas/config.json",
6
+ "secrets": [],
7
+ "capabilities": ["network:www.gstatic.com"],
8
+ "tools": [],
9
+ "webhooks": [],
10
+ "workflows": [],
11
+ "roles": [],
12
+ "skills": [],
13
+ "tracker": null,
14
+ "environments": [],
15
+ "hooks": [],
16
+ "identity": {
17
+ "headers": ["x-goog-iap-jwt-assertion"],
18
+ "secrets": [],
19
+ "capabilities": ["network:www.gstatic.com"]
20
+ }
21
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@kana-ai/edgar-ext-iap",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.4",
4
+ "description": "EDGAR extension for Google Cloud's Identity-Aware Proxy: it verifies the proxy's signed header and gives EDGAR the email of the person who opens the console.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/kana-ai/edgar",
9
+ "directory": "packages/extensions/ext-iap"
10
+ },
11
+ "files": [
12
+ "dist/src",
13
+ "edgar-extension.json",
14
+ "schemas"
15
+ ],
16
+ "type": "module",
17
+ "imports": {
18
+ "#*": "./dist/src/*.js"
19
+ },
20
+ "exports": {
21
+ ".": "./dist/src/index.js"
22
+ },
23
+ "dependencies": {
24
+ "@kana-ai/edgar-sdk": "0.1.4",
25
+ "zod": "4.6.7"
26
+ },
27
+ "devDependencies": {
28
+ "@kana-ai/edgar-contracts": "0.1.4",
29
+ "@types/node": "24.19.2",
30
+ "oxfmt": "0.76.0",
31
+ "oxlint": "1.91.0",
32
+ "oxlint-tsgolint": "7.0.2005",
33
+ "typescript": "7.0.2"
34
+ },
35
+ "scripts": {
36
+ "build": "edgar-extension-build src/index.ts",
37
+ "check-types": "tsc --noEmit",
38
+ "lint": "oxlint --type-aware --deny-warnings",
39
+ "format:check": "oxfmt --check",
40
+ "test": "node --test"
41
+ }
6
42
  }
@@ -0,0 +1,13 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "audience": {
6
+ "type": "string",
7
+ "pattern": "^\\/projects\\/\\d{1,20}\\/global\\/backendServices\\/\\d{1,20}$",
8
+ "description": "the backend service each assertion must name, as /projects/<number>/global/backendServices/<id>"
9
+ }
10
+ },
11
+ "required": ["audience"],
12
+ "additionalProperties": false
13
+ }