@agentproto/auth 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 agentproto contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/dist/index.d.ts CHANGED
@@ -540,6 +540,150 @@ declare class CredentialBroker {
540
540
  }): Promise<Record<string, string>>;
541
541
  }
542
542
 
543
+ /**
544
+ * Named auth-profile types (SPEC §1c/§3.1 — `agentproto-session-config-axes`).
545
+ *
546
+ * A profile is a named credential `{ vendor, method, credentialRef }` that
547
+ * lives independently of any adapter, generalizing `providers-store`'s
548
+ * `ProviderEntry` (one api-key per provider, `packages/providers-store/src/
549
+ * index.ts:68-80`) to N named profiles per vendor. `subscription|api-key` is
550
+ * not a session property — it demotes to the `method` facet of a profile.
551
+ *
552
+ * The secret itself is NEVER inlined here — `credentialRef` is an opaque
553
+ * handle into this package's own credential storage (`store/types.ts`'s
554
+ * `CredentialStore` / `token-store.ts`), matching how the rest of
555
+ * `@agentproto/auth` already fingerprints rather than echoes secrets
556
+ * (`broker.ts`, `KeychainStore`).
557
+ */
558
+ /** How a profile authenticates — the narrow eligibility gate (not adapter
559
+ * identity). Mirrors `@agentproto/auth`'s `FlowResult.tokenKind`
560
+ * (`types.ts:151`): `pat` → `api-key`, `oat` → `oauth-bearer`. Extensible —
561
+ * new methods are additive. */
562
+ type AuthMethod = "oauth-bearer" | "api-key";
563
+ /** A named, vendor-scoped credential reference. */
564
+ interface AuthProfile {
565
+ /** Stable id, unique across all profiles (the `profileRef` a session
566
+ * attaches). */
567
+ id: string;
568
+ /** Which vendor this credential bills against (`anthropic`, `moonshot`, …) —
569
+ * a `CatalogProvider` id, kept as `string` here to stay decoupled from
570
+ * `@agentproto/model-catalog`, same rationale as the driver's
571
+ * `AgentCliDefinition.provider`. */
572
+ vendor: string;
573
+ /** How this profile authenticates. */
574
+ method: AuthMethod;
575
+ /** Opaque handle into this package's credential storage — NEVER the secret
576
+ * itself. Resolved through `CredentialStore` / `token-store.ts` at use
577
+ * time, not stored inline. */
578
+ credentialRef: string;
579
+ /** Optional human-readable name ("Jeremy Max", "work OpenRouter"). */
580
+ label?: string;
581
+ }
582
+
583
+ /**
584
+ * Named auth-profile store — CRUD over `~/.agentproto/auth-profiles.json`
585
+ * (mode 0600), generalizing `providers-store`'s single-key-per-provider file
586
+ * (`packages/providers-store/src/index.ts:68-90`, `ProviderEntry`/
587
+ * `ProvidersFile`) to N named `AuthProfile`s per vendor, keyed by `id`.
588
+ *
589
+ * This is the profile-metadata store, not the credential store: entries hold
590
+ * `credentialRef` (a pointer), never a secret, so — unlike `FileStore`
591
+ * (`store/file-store.ts`) — this file needs no encryption. Reuses the exact
592
+ * persistence primitives `providers-store` already established (a versioned
593
+ * JSON file under `~/.agentproto/`, `node:fs/promises`, mode 0600) rather
594
+ * than inventing a new format, just relocated to `@agentproto/auth` — the
595
+ * correct home for named profiles per SPEC §1c (`providers.json` is the
596
+ * degenerate one-key-per-provider case this generalizes).
597
+ */
598
+
599
+ declare const authProfilesFileSchema: z.ZodObject<{
600
+ version: z.ZodLiteral<1>;
601
+ profiles: z.ZodRecord<z.ZodString, z.ZodObject<{
602
+ id: z.ZodString;
603
+ vendor: z.ZodString;
604
+ method: z.ZodEnum<{
605
+ "oauth-bearer": "oauth-bearer";
606
+ "api-key": "api-key";
607
+ }>;
608
+ credentialRef: z.ZodString;
609
+ label: z.ZodOptional<z.ZodString>;
610
+ }, z.core.$strip>>;
611
+ }, z.core.$strip>;
612
+ type AuthProfilesFile = z.infer<typeof authProfilesFileSchema>;
613
+ declare function authProfilesPath(): string;
614
+ declare function loadAuthProfiles(): Promise<AuthProfilesFile>;
615
+ /** List all profiles, optionally filtered to one vendor. */
616
+ declare function listAuthProfiles(vendor?: string): Promise<AuthProfile[]>;
617
+ /** Look up a single profile by id, or undefined if none exists. */
618
+ declare function getAuthProfile(id: string): Promise<AuthProfile | undefined>;
619
+ /** Add (or replace) a profile, keyed by its `id`. */
620
+ declare function addAuthProfile(profile: AuthProfile): Promise<void>;
621
+ /** Remove a profile by id. Returns true if it existed. */
622
+ declare function removeAuthProfile(id: string): Promise<boolean>;
623
+
624
+ /**
625
+ * (adapter × route) → vendor resolution + the profile eligibility predicate
626
+ * (SPEC §1c, `agentproto-session-config-axes/SPEC.md:102-125`).
627
+ *
628
+ * profile eligible for (adapter, route) iff
629
+ * profile.vendor == resolveEndpoint(adapter, route).vendor
630
+ * AND profile.method ∈ methodsPresentable(adapter, route)
631
+ *
632
+ * `route` is the endpoint selector (SPEC axis #4 — direct vs a gateway mode
633
+ * like `moonshot`/`openrouter`), so access is deliberately downstream of it:
634
+ * which vendor (and thus which profiles) are eligible changes when route
635
+ * changes. `AdapterAuthManifest` is a narrow, package-local projection of
636
+ * exactly what this predicate needs from an adapter's real AIP-45 manifest
637
+ * (`packages/driver/agent-cli/src/types.ts`'s `AgentCliDefinition`) — this
638
+ * package intentionally does not depend on `@agentproto/driver-agent-cli`
639
+ * (wrong dependency direction; drivers consume auth, not vice versa), so the
640
+ * runtime is the one that will later project a real manifest into this
641
+ * shape (out of scope here — foundation only, no live spawn-path wiring).
642
+ *
643
+ * `methodsByRoute` is the static per-vendor method table ADR'd in SPEC §3.4:
644
+ * "which auth methods this adapter can present for a resolved route." It is
645
+ * the derivable replacement for two hand-maintained artifacts SPEC §1c calls
646
+ * out for eventual removal — the per-adapter `authSubscription` boolean
647
+ * (`adapters/claude-code/src/index.ts:90-95`) and curatorial vendor deny
648
+ * lists (`adapters/hermes/HERMES.md:40-42`) — neither of which this PR
649
+ * touches; `authSubscription` stays exactly as-is (see the comment on it in
650
+ * `spawn-defaults.ts:345` — this module is additive, not a replacement).
651
+ *
652
+ * ACP `authenticate` is NOT a live discovery source for this table (the
653
+ * server handler is a stub, `packages/acp/src/server/index.ts:69`) — method
654
+ * discovery is this static table, not runtime negotiation (SPEC §3.7).
655
+ */
656
+
657
+ /** A narrow, package-local projection of an adapter's declared auth
658
+ * capability — enough to resolve (adapter, route) → vendor and the auth
659
+ * methods presentable on that route. Not the real AIP-45 manifest type. */
660
+ interface AdapterAuthManifest {
661
+ /** Adapter id (e.g. "claude-code", "hermes"), for error messages only. */
662
+ id: string;
663
+ /** route id (e.g. "direct", or a gateway mode id like "moonshot") →
664
+ * the vendor billed when spawned on that route. */
665
+ vendorByRoute: Readonly<Record<string, string>>;
666
+ /** route id → the auth methods this adapter can present when spawned on
667
+ * that route — the method-side of the eligibility predicate. */
668
+ methodsByRoute: Readonly<Record<string, readonly AuthMethod[]>>;
669
+ }
670
+ /** Resolve which vendor a given (adapter, route) pair bills against. Throws
671
+ * when the manifest declares no vendor for `route` — an unresolvable route
672
+ * is a caller bug (a bad/unknown route id), not a "no profiles eligible"
673
+ * case, so this fails loud rather than returning an empty vendor. */
674
+ declare function resolveEndpoint(manifest: AdapterAuthManifest, route: string): {
675
+ vendor: string;
676
+ };
677
+ /** Which auth methods `manifest`'s adapter can present on `route`. Empty
678
+ * (never throws) when the route is declared for vendor resolution but has
679
+ * no methods table entry — that's "no eligible profiles", a legitimate
680
+ * eligibility outcome, not an error. */
681
+ declare function methodsPresentable(manifest: AdapterAuthManifest, route: string): AuthMethod[];
682
+ /** The eligibility predicate: profiles whose vendor matches the route's
683
+ * resolved endpoint AND whose method the adapter can present on that
684
+ * route. */
685
+ declare function eligibleProfiles(profiles: readonly AuthProfile[], manifest: AdapterAuthManifest, route: string): AuthProfile[];
686
+
543
687
  /** Guilde AI company platform.
544
688
  *
545
689
  * Authenticates via the AIP-50 service-auth claim ceremony: browser opens,
@@ -570,9 +714,15 @@ declare const BUILTIN_AUTH_PROVIDERS: readonly AuthProviderHandle[];
570
714
  * KeychainStore / MemoryStore / FileStore — built-in CredentialStore backends
571
715
  * resolveStoreRef(spec, server) — map a TokenStoreSpec to a StoreRef
572
716
  * CredentialBroker — path → ready-to-use auth headers
717
+ * AuthProfile / AuthMethod — named, vendor-scoped credential ref
718
+ * listAuthProfiles/getAuthProfile/
719
+ * addAuthProfile/removeAuthProfile — named-profile store CRUD
720
+ * resolveEndpoint/methodsPresentable/
721
+ * eligibleProfiles — (adapter × route) → vendor + the
722
+ * profile eligibility predicate
573
723
  */
574
724
 
575
725
  declare const SPEC_NAME = "agentauth";
576
726
  declare const SPEC_VERSION = "v1";
577
727
 
578
- export { type AuthConfig, type AuthProviderDefinition, type AuthProviderFrontmatter, type AuthProviderHandle, type AuthProviderManifest, BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, CredentialBroker, type CredentialBrokerOptions, type CredentialStore, type DeviceCodeAuthConfig, type DiscoveredEndpoints, DiscoveryError, FLOW_ENGINES, FileStore, type FlowEngine, type FlowId, type FlowResult, type FlowRunOptions, type InstallConfig, KeychainStore, MemoryStore, type PATAuthConfig, type RunFlowOptions, SPEC_NAME, SPEC_VERSION, type ServiceAuthConfig, type StoreRef, type StoredCredential, type TokenStoreSpec, authConfigSchema, authProviderFrontmatterSchema, defineAuthProvider, discoverEndpoints, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProviderIds, listAuthProviders, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, registerAuthProvider, resolveAccount, resolveStoreRef, runAuthFlow, tokenStoreSpecSchema, writeKeychainToken };
728
+ export { type AdapterAuthManifest, type AuthConfig, type AuthMethod, type AuthProfile, type AuthProfilesFile, type AuthProviderDefinition, type AuthProviderFrontmatter, type AuthProviderHandle, type AuthProviderManifest, BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, CredentialBroker, type CredentialBrokerOptions, type CredentialStore, type DeviceCodeAuthConfig, type DiscoveredEndpoints, DiscoveryError, FLOW_ENGINES, FileStore, type FlowEngine, type FlowId, type FlowResult, type FlowRunOptions, type InstallConfig, KeychainStore, MemoryStore, type PATAuthConfig, type RunFlowOptions, SPEC_NAME, SPEC_VERSION, type ServiceAuthConfig, type StoreRef, type StoredCredential, type TokenStoreSpec, addAuthProfile, authConfigSchema, authProfilesPath, authProviderFrontmatterSchema, defineAuthProvider, discoverEndpoints, eligibleProfiles, getAuthProfile, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProfiles, listAuthProviderIds, listAuthProviders, loadAuthProfiles, methodsPresentable, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, registerAuthProvider, removeAuthProfile, resolveAccount, resolveEndpoint, resolveStoreRef, runAuthFlow, tokenStoreSpecSchema, writeKeychainToken };
package/dist/index.mjs CHANGED
@@ -6,7 +6,8 @@ import { execFile } from 'child_process';
6
6
  import { promisify } from 'util';
7
7
  import { createDecipheriv, randomBytes, createCipheriv } from 'crypto';
8
8
  import { readFile, mkdir, writeFile } from 'fs/promises';
9
- import { dirname } from 'path';
9
+ import { dirname, resolve, join } from 'path';
10
+ import { homedir } from 'os';
10
11
 
11
12
  /**
12
13
  * @agentproto/auth v0.1.0-alpha
@@ -443,16 +444,16 @@ async function promptToken(label) {
443
444
  const input = process.stdin;
444
445
  const out = process.stderr;
445
446
  if (!input.isTTY) {
446
- return new Promise((resolve) => {
447
+ return new Promise((resolve2) => {
447
448
  const rl = createInterface({ input, output: out });
448
449
  out.write(`${label}: `);
449
450
  rl.question("", (answer) => {
450
451
  rl.close();
451
- resolve(answer.trim());
452
+ resolve2(answer.trim());
452
453
  });
453
454
  });
454
455
  }
455
- return new Promise((resolve, reject) => {
456
+ return new Promise((resolve2, reject) => {
456
457
  out.write(`${label}: `);
457
458
  const chars = [];
458
459
  input.setRawMode(true);
@@ -470,7 +471,7 @@ async function promptToken(label) {
470
471
  case "\n":
471
472
  out.write("\n");
472
473
  cleanup();
473
- resolve(chars.join("").trim());
474
+ resolve2(chars.join("").trim());
474
475
  return;
475
476
  case "":
476
477
  out.write("\n");
@@ -480,7 +481,7 @@ async function promptToken(label) {
480
481
  case "":
481
482
  out.write("\n");
482
483
  cleanup();
483
- resolve(chars.join("").trim());
484
+ resolve2(chars.join("").trim());
484
485
  return;
485
486
  case "\x7F":
486
487
  // Backspace / Delete
@@ -1163,11 +1164,85 @@ var CredentialBroker = class {
1163
1164
  return headers;
1164
1165
  }
1165
1166
  };
1167
+ var authMethodSchema = z.enum(["oauth-bearer", "api-key"]);
1168
+ var authProfileSchema = z.object({
1169
+ id: z.string(),
1170
+ vendor: z.string(),
1171
+ method: authMethodSchema,
1172
+ credentialRef: z.string(),
1173
+ label: z.string().optional()
1174
+ });
1175
+ var authProfilesFileSchema = z.object({
1176
+ version: z.literal(1),
1177
+ profiles: z.record(z.string(), authProfileSchema)
1178
+ });
1179
+ function emptyFile() {
1180
+ return { version: 1, profiles: {} };
1181
+ }
1182
+ function authProfilesPath() {
1183
+ return resolve(homedir(), ".agentproto", "auth-profiles.json");
1184
+ }
1185
+ async function loadAuthProfiles() {
1186
+ try {
1187
+ const raw = await readFile(authProfilesPath(), "utf8");
1188
+ return authProfilesFileSchema.parse(JSON.parse(raw));
1189
+ } catch {
1190
+ return emptyFile();
1191
+ }
1192
+ }
1193
+ async function writeAuthProfiles(file) {
1194
+ const dir = join(homedir(), ".agentproto");
1195
+ await mkdir(dir, { recursive: true });
1196
+ await writeFile(authProfilesPath(), JSON.stringify(file, null, 2) + "\n", {
1197
+ encoding: "utf8",
1198
+ mode: 384
1199
+ });
1200
+ }
1201
+ async function listAuthProfiles(vendor) {
1202
+ const file = await loadAuthProfiles();
1203
+ const all = Object.values(file.profiles);
1204
+ return vendor === void 0 ? all : all.filter((p) => p.vendor === vendor);
1205
+ }
1206
+ async function getAuthProfile(id) {
1207
+ const file = await loadAuthProfiles();
1208
+ return file.profiles[id];
1209
+ }
1210
+ async function addAuthProfile(profile) {
1211
+ const file = await loadAuthProfiles();
1212
+ file.profiles[profile.id] = profile;
1213
+ await writeAuthProfiles(file);
1214
+ }
1215
+ async function removeAuthProfile(id) {
1216
+ const file = await loadAuthProfiles();
1217
+ if (!(id in file.profiles)) return false;
1218
+ delete file.profiles[id];
1219
+ await writeAuthProfiles(file);
1220
+ return true;
1221
+ }
1222
+
1223
+ // src/eligibility.ts
1224
+ function resolveEndpoint(manifest, route) {
1225
+ const vendor = manifest.vendorByRoute[route];
1226
+ if (vendor === void 0) {
1227
+ throw new Error(
1228
+ `resolveEndpoint: adapter "${manifest.id}" declares no vendor for route "${route}"`
1229
+ );
1230
+ }
1231
+ return { vendor };
1232
+ }
1233
+ function methodsPresentable(manifest, route) {
1234
+ return [...manifest.methodsByRoute[route] ?? []];
1235
+ }
1236
+ function eligibleProfiles(profiles, manifest, route) {
1237
+ const { vendor } = resolveEndpoint(manifest, route);
1238
+ const methods = methodsPresentable(manifest, route);
1239
+ return profiles.filter((p) => p.vendor === vendor && methods.includes(p.method));
1240
+ }
1166
1241
 
1167
1242
  // src/index.ts
1168
1243
  var SPEC_NAME = "agentauth";
1169
1244
  var SPEC_VERSION = "v1";
1170
1245
 
1171
- export { BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, CredentialBroker, DiscoveryError, FLOW_ENGINES, FileStore, KeychainStore, MemoryStore, SPEC_NAME, SPEC_VERSION, authConfigSchema, authProviderFrontmatterSchema, defineAuthProvider, discoverEndpoints, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProviderIds, listAuthProviders, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, registerAuthProvider, resolveAccount, resolveStoreRef, runAuthFlow, tokenStoreSpecSchema, writeKeychainToken };
1246
+ export { BUILTIN_AUTH_PROVIDERS, CeremonyRequiredError, CredentialBroker, DiscoveryError, FLOW_ENGINES, FileStore, KeychainStore, MemoryStore, SPEC_NAME, SPEC_VERSION, addAuthProfile, authConfigSchema, authProfilesPath, authProviderFrontmatterSchema, defineAuthProvider, discoverEndpoints, eligibleProfiles, getAuthProfile, getAuthProvider, guildeAuthProvider, installConfigSchema, listAuthProfiles, listAuthProviderIds, listAuthProviders, loadAuthProfiles, methodsPresentable, parseAuthProviderManifest, parseAuthProviderManifestRaw, readKeychainToken, registerAuthProvider, removeAuthProfile, resolveAccount, resolveEndpoint, resolveStoreRef, runAuthFlow, tokenStoreSpecSchema, writeKeychainToken };
1172
1247
  //# sourceMappingURL=index.mjs.map
1173
1248
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/define-auth-provider.ts","../src/manifest.ts","../src/builtins.ts","../src/registry.ts","../src/http.ts","../src/discover.ts","../src/token-store.ts","../src/store/keychain-store.ts","../src/store/resolve-ref.ts","../src/flow-engines/pat.ts","../src/flow-engines/device-grant.ts","../src/flow-engines/service-auth.ts","../src/flow-engines/device-code.ts","../src/flow-engines/index.ts","../src/run-flow.ts","../src/store/memory-store.ts","../src/store/file-store.ts","../src/broker.ts","../src/index.ts"],"names":["z","promisify","execFile","DEFAULT_POLL_INTERVAL_S","keyOf","headers"],"mappings":";;;;;;;;;;;;;;;AAUO,IAAM,oBAAA,GAAuB,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,wBAAA,CAAyB,IAAA,CAAK,KAAA,EAAO,KAAK,SAAS,CAAA;AACxE,IAAA,IAAI,MAAA,IAAU,OAAA,CAAQ,MAAM,CAAA,EAAG;AAC7B,MAAA,MAAMC,QAAAA,GAAU,aAAA,CAAc,MAAA,CAAO,KAAA,EAAO,OAAO,IAAI,CAAA;AACvD,MAAA,IAAIA,UAAS,OAAOA,QAAAA;AAAA,IACtB;AAEA,IAAA,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,QAAA,EAAU;AAAA,MACzC,MAAA;AAAA,MACA,OAAO,IAAA,CAAK,KAAA;AAAA,MACZ,QAAQ,CAAA,CAAE;AAAA,KACX,CAAA;AACD,IAAA,MAAM,OAAA,GACJ,OAAO,WAAA,KAAgB,MAAA,GACnB,cAAc,MAAA,CAAO,WAAA,EAAa,MAAA,CAAO,SAAS,CAAA,GAClD,MAAA;AACN,IAAA,IAAI,CAAC,OAAA,EAAS;AACZ,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,oCAAoC,UAAU,CAAA,iCAAA;AAAA,OAChD;AAAA,IACF;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;ACjDO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * AIP-50 auth-provider frontmatter / literal Zod schema.\n *\n * Single source of truth for both authoring paths: `defineAuthProvider`\n * (TS literal) and `parseAuthProviderManifest` (.md) run this same schema,\n * so a malformed literal and a malformed manifest fail identically.\n */\n\nimport { z } from \"zod\"\n\nexport const tokenStoreSpecSchema = z\n .object({\n keychain: z.string().min(1),\n path: z.string().min(1).optional(),\n account: z.string().min(1).optional(),\n })\n .strict()\n\nexport const patAuthConfigSchema = z\n .object({\n flow: z.literal(\"pat\"),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const serviceAuthConfigSchema = z\n .object({\n flow: z.literal(\"service-auth\"),\n clientId: z.string().min(1).optional(),\n loginHint: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const deviceCodeAuthConfigSchema = z\n .object({\n flow: z.literal(\"device-code\"),\n clientId: z.string().min(1).optional(),\n scope: z.string().min(1).optional(),\n deviceLabel: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const authConfigSchema = z.discriminatedUnion(\"flow\", [\n patAuthConfigSchema,\n serviceAuthConfigSchema,\n deviceCodeAuthConfigSchema,\n])\n\nexport const installConfigSchema = z\n .object({\n sealKey: z.string().min(1),\n secretBacked: z.string().min(1),\n })\n .strict()\n\nexport const authProviderFrontmatterSchema = z\n .object({\n id: z.string().min(2).max(80),\n description: z.string().min(1).max(2000),\n apiBase: z.string().url(),\n auth: authConfigSchema,\n install: installConfigSchema.optional(),\n // Recommended values \"tunnel\" | \"api\" | \"mcp\" — free-form allowed, not an enum.\n audience: z.string().min(1).optional(),\n })\n .strict()\n .describe(\n \"AIP-50 auth-provider manifest: how a CLI tool authenticates to an API server and (optionally) where to call the AIP-19 provision endpoints.\",\n )\n\nexport type AuthProviderFrontmatter = z.infer<typeof authProviderFrontmatterSchema>\n","/**\n * `defineAuthProvider` — TS-literal authoring path for an auth-provider.\n *\n * Built on `createDoctype` so it gets the cross-AIP invariants: id-pattern,\n * ≤2000-char description, frozen handle, canonical error prefix. Field-level\n * validation uses the shared Zod from `./schema.ts`, so a malformed literal\n * fails with the same diagnostic as a malformed `.md`.\n */\n\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { authProviderFrontmatterSchema } from \"./schema.js\"\nimport type { AuthProviderDefinition, AuthProviderHandle } from \"./types.js\"\n\nexport const defineAuthProvider = createDoctype<\n AuthProviderDefinition,\n AuthProviderHandle\n>({\n aip: 50,\n name: \"authProvider\",\n validate(def) {\n const result = authProviderFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAuthProvider (AIP-50): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n },\n build(def) {\n return {\n ...def,\n auth: Object.freeze({ ...def.auth }),\n install: def.install ? Object.freeze({ ...def.install }) : undefined,\n }\n },\n})\n","/**\n * `.md` authoring path for an auth-provider — parse a frontmatter manifest\n * into a frozen handle. Mirrors `parseRecipeManifest` from AIP-19: gray-matter\n * splits the frontmatter, the shared Zod validates it, `defineAuthProvider`\n * builds the handle so both authoring paths converge on one validated shape.\n *\n * This parser is the extension seam: a host reads its own external `.md`\n * manifests (e.g. vendor-shipped `guilde.auth.md`) and registers them without\n * editing this package.\n */\n\nimport matter from \"gray-matter\"\nimport {\n authProviderFrontmatterSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nexport interface AuthProviderManifest {\n frontmatter: AuthProviderFrontmatter\n body: string\n}\n\nexport function parseAuthProviderManifestRaw(\n source: string,\n): AuthProviderManifest {\n const parsed = matter(source)\n if (Object.keys(parsed.data).length === 0) {\n throw new Error(\"parseAuthProviderManifest: missing or empty frontmatter\")\n }\n const result = authProviderFrontmatterSchema.safeParse(parsed.data)\n if (!result.success) {\n throw new Error(\n `parseAuthProviderManifest: invalid frontmatter — ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n return { frontmatter: result.data, body: parsed.content }\n}\n\n/** Parse an auth-provider `.md` straight to a frozen handle. */\nexport function parseAuthProviderManifest(source: string): AuthProviderHandle {\n const { frontmatter } = parseAuthProviderManifestRaw(source)\n return defineAuthProvider(frontmatter)\n}\n","/**\n * Builtin auth-provider manifests — shipped as TS literals so they bundle\n * into the tsup output with zero filesystem reads at runtime. A host adds more\n * by parsing its own `.md` with `parseAuthProviderManifest` and registering\n * the result via `registerAuthProvider`.\n */\n\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Guilde AI company platform.\n *\n * Authenticates via the AIP-50 service-auth claim ceremony: browser opens,\n * user clicks Approve, bureau stores the oat_* access token.\n * Discovery from /.well-known/oauth-protected-resource supplies live endpoints;\n * the static fields below are the offline fallback. */\nexport const guildeAuthProvider = defineAuthProvider({\n id: \"guilde\",\n description:\n \"Guilde AI company platform. Authenticate via a browser-approve flow — no key to paste.\",\n apiBase: \"https://api.guilde.work\",\n audience: \"api\",\n auth: {\n flow: \"service-auth\",\n clientId: \"agentproto-cli\",\n tokenStore: {\n keychain: \"bureau-guilde\",\n account: \"{server}\",\n },\n },\n install: {\n sealKey: \"/guilde/api/v1/connectors/seal-key\",\n secretBacked: \"/guilde/api/v1/guilds/{guildId}/connectors/secret-backed\",\n },\n})\n\nexport const BUILTIN_AUTH_PROVIDERS: readonly AuthProviderHandle[] = [\n guildeAuthProvider,\n]\n","/**\n * Auth-provider registry — id → handle lookup, pre-seeded with builtins.\n *\n * Mirrors the provision-recipe registry shape (AIP-19). Re-registering an id\n * overrides it (last write wins), so a host can shadow a builtin.\n */\n\nimport { BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nconst _registry = new Map<string, AuthProviderHandle>()\nfor (const p of BUILTIN_AUTH_PROVIDERS) _registry.set(p.id, p)\n\nexport function registerAuthProvider(provider: AuthProviderHandle): void {\n _registry.set(provider.id, provider)\n}\n\nexport function getAuthProvider(id: string): AuthProviderHandle | undefined {\n return _registry.get(id)\n}\n\nexport function listAuthProviders(): AuthProviderHandle[] {\n return [..._registry.values()]\n}\n\nexport function listAuthProviderIds(): string[] {\n return [..._registry.keys()]\n}\n","/**\n * Internal HTTP helpers — not part of the public API.\n *\n * Every network call in this package (discovery, the claim ceremony, token\n * refresh) must be bounded: a hung or slow server MUST NOT stall the CLI\n * indefinitely. `deadlineSignal` combines an optional caller `AbortSignal`\n * with a timeout into one signal to hand to `fetch`.\n *\n * Implemented with a plain `AbortController` + `setTimeout` rather than\n * `AbortSignal.any`/`AbortSignal.timeout` so it works on every runtime that\n * ships `fetch`, without assuming a specific Node minor.\n */\n\n/** Default per-request timeout. Discovery and token calls are small JSON\n * round-trips; 10s is generous without hanging an interactive CLI. */\nexport const DEFAULT_HTTP_TIMEOUT_MS = 10_000\n\n/**\n * AIP-50 §Security: discovery and auth requests MUST use HTTPS, to defeat\n * MITM/TOCTOU on the `.well-known` and token endpoints. Loopback http is\n * allowed — it isn't network-exposed — so local development against a dev\n * server keeps working. Throws on any other insecure URL.\n */\nexport function assertSecureUrl(url: string): void {\n let u: URL\n try {\n u = new URL(url)\n } catch {\n throw new Error(`invalid URL: ${url}`)\n }\n if (u.protocol === \"https:\") return\n const host = u.hostname\n const isLoopback =\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"::1\" ||\n host === \"[::1]\" ||\n host.endsWith(\".localhost\")\n if (u.protocol === \"http:\" && isLoopback) return\n throw new Error(\n `insecure URL '${url}' — AIP-50 requires HTTPS for discovery/auth ` +\n `(loopback http is allowed for local development).`,\n )\n}\n\nexport interface DeadlineHandle {\n /** Signal to pass to `fetch(url, { signal })`. */\n signal: AbortSignal\n /** Cancel the timer + detach the outer listener once the request settles.\n * ALWAYS call this in a `finally` to avoid a dangling timer/listener. */\n clear: () => void\n}\n\n/**\n * Build an `AbortSignal` that fires when EITHER the timeout elapses or the\n * caller's `outer` signal aborts.\n */\nexport function deadlineSignal(\n timeoutMs: number,\n outer?: AbortSignal,\n): DeadlineHandle {\n const ctrl = new AbortController()\n const onAbort = () => ctrl.abort(outer?.reason)\n\n if (outer) {\n if (outer.aborted) ctrl.abort(outer.reason)\n else outer.addEventListener(\"abort\", onAbort, { once: true })\n }\n\n const timer = setTimeout(\n () => ctrl.abort(new Error(`request timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n // Don't let a pending timeout keep the process alive on its own.\n if (typeof timer !== \"number\") timer.unref()\n\n return {\n signal: ctrl.signal,\n clear: () => {\n clearTimeout(timer)\n outer?.removeEventListener(\"abort\", onAbort)\n },\n }\n}\n\n/** `fetch` bounded by `deadlineSignal`. Merges any caller-supplied\n * `init.signal` with the timeout. */\nexport async function fetchWithDeadline(\n url: string,\n init: RequestInit = {},\n timeoutMs: number = DEFAULT_HTTP_TIMEOUT_MS,\n): Promise<Response> {\n const { signal, clear } = deadlineSignal(timeoutMs, init.signal ?? undefined)\n try {\n return await fetch(url, { ...init, signal })\n } finally {\n clear()\n }\n}\n","/**\n * Two-hop discovery per the auth.md standard (AIP-50 §Discovery algorithm),\n * with a second strategy for hosts that don't speak auth.md.\n *\n * Strategy 1 (OAuth PRM chain):\n * Hop 1: GET {apiBase}/.well-known/oauth-protected-resource (PRM, RFC 8414)\n * → extract authorization_servers[0] as authServerBase\n * Hop 2: GET {authServerBase}/.well-known/oauth-authorization-server (AS metadata)\n * → extract token_endpoint + agent_auth block\n *\n * Strategy 2 (agentproto-host.json), tried when strategy 1 fails:\n * GET {apiBase}/.well-known/agentproto-host.json\n * → extract device_authorization_endpoint + token_endpoint\n *\n * Callers MUST catch DiscoveryError and fall back to static manifest config —\n * discovery failures are common (server predates auth.md) and MUST NOT prevent\n * the PAT or other static flows from working.\n */\n\nimport { z } from \"zod\"\nimport type { DiscoveredEndpoints } from \"./types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"./http.js\"\n\nexport class DiscoveryError extends Error {\n readonly serverUrl: string\n constructor(message: string, serverUrl: string) {\n super(`DiscoveryError (${serverUrl}): ${message}`)\n this.name = \"DiscoveryError\"\n this.serverUrl = serverUrl\n }\n}\n\n// Discovery JSON is server-controlled, so it's validated rather than asserted.\n// Everything is optional + `.loose()`: the document evolves, and the required\n// fields are enforced explicitly below with precise DiscoveryError messages.\nconst prmSchema = z\n .object({\n resource: z.string().optional(),\n resource_name: z.string().optional(),\n authorization_servers: z.array(z.string()).optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n })\n .loose()\n\nconst asMetaSchema = z\n .object({\n issuer: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n device_authorization_endpoint: z.string().optional(),\n grant_types_supported: z.array(z.string()).optional(),\n agent_auth: z\n .object({\n skill: z.string().optional(),\n identity_endpoint: z.string().optional(),\n claim_endpoint: z.string().optional(),\n events_endpoint: z.string().optional(),\n identity_types_supported: z.array(z.string()).optional(),\n identity_assertion: z\n .object({ assertion_types_supported: z.array(z.string()).optional() })\n .loose()\n .optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n\nconst hostJsonSchema = z\n .object({\n device_authorization_endpoint: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n })\n .loose()\n\ntype PRMShape = z.infer<typeof prmSchema>\ntype ASMetaShape = z.infer<typeof asMetaSchema>\ntype HostJsonShape = z.infer<typeof hostJsonSchema>\n\nexport interface DiscoverOptions {\n /** Abort the discovery fetches (e.g. on user Ctrl-C). */\n signal?: AbortSignal\n /** Per-hop timeout. Defaults to DEFAULT_HTTP_TIMEOUT_MS. */\n timeoutMs?: number\n}\n\nasync function discoverViaPRM(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n // Hop 1 — PRM\n const prmUrl = `${base}/.well-known/oauth-protected-resource`\n let prm: PRMShape\n try {\n assertSecureUrl(prmUrl)\n const res = await fetchWithDeadline(prmUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `PRM returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n prm = prmSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`PRM fetch failed: ${err}`, base)\n }\n\n const authServerBase = prm.authorization_servers?.[0]?.replace(/\\/$/, \"\")\n if (!authServerBase) {\n throw new DiscoveryError(\n \"PRM missing authorization_servers[0]\",\n base,\n )\n }\n\n // Hop 2 — AS metadata\n const asUrl = `${authServerBase}/.well-known/oauth-authorization-server`\n let as: ASMetaShape\n try {\n assertSecureUrl(asUrl)\n const res = await fetchWithDeadline(asUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `AS metadata returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n as = asMetaSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`AS metadata fetch failed: ${err}`, base)\n }\n\n const tokenEndpoint = as.token_endpoint\n const identityEndpoint = as.agent_auth?.identity_endpoint\n if (!tokenEndpoint) {\n throw new DiscoveryError(\"AS metadata missing token_endpoint\", base)\n }\n if (!identityEndpoint) {\n throw new DiscoveryError(\n \"AS metadata missing agent_auth.identity_endpoint\",\n base,\n )\n }\n\n return {\n resource: prm.resource ?? base,\n resourceName: prm.resource_name,\n authServerBase,\n tokenEndpoint,\n revocationEndpoint: as.revocation_endpoint,\n identityEndpoint,\n claimEndpoint: as.agent_auth?.claim_endpoint,\n deviceAuthorizationEndpoint: as.device_authorization_endpoint,\n identityTypesSupported: as.agent_auth?.identity_types_supported ?? [],\n grantTypesSupported: as.grant_types_supported ?? [],\n }\n}\n\nasync function discoverViaHostJson(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n const url = `${base}/.well-known/agentproto-host.json`\n let doc: HostJsonShape\n try {\n assertSecureUrl(url)\n const res = await fetchWithDeadline(url, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `agentproto-host.json returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n doc = hostJsonSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`agentproto-host.json fetch failed: ${err}`, base)\n }\n\n if (!doc.token_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing token_endpoint\",\n base,\n )\n }\n if (!doc.device_authorization_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing device_authorization_endpoint\",\n base,\n )\n }\n\n return {\n resource: base,\n authServerBase: base,\n tokenEndpoint: doc.token_endpoint,\n revocationEndpoint: doc.revocation_endpoint,\n deviceAuthorizationEndpoint: doc.device_authorization_endpoint,\n identityTypesSupported: [],\n grantTypesSupported: [],\n }\n}\n\nexport async function discoverEndpoints(\n apiBase: string,\n opts: DiscoverOptions = {},\n): Promise<DiscoveredEndpoints> {\n const base = apiBase.replace(/\\/$/, \"\")\n // AIP-50 §Security: HTTPS only (loopback exempt for dev), and never follow\n // redirects on discovery — a 3xx is treated as a failure, not chased to a\n // potentially-rogue endpoint.\n const fetchOpts: RequestInit = {\n signal: opts.signal,\n redirect: \"manual\",\n }\n\n try {\n return await discoverViaPRM(base, fetchOpts, opts)\n } catch (prmErr) {\n // A caller-initiated abort is terminal — don't fire a second round of\n // requests on a signal that has already aborted (its \"abort\" event has\n // already fired once and a fresh listener on it will never see it again,\n // hanging the fallback forever).\n if (opts.signal?.aborted) throw prmErr\n // Second strategy: a host that doesn't speak the auth.md PRM chain may\n // still expose device-code endpoints via agentproto-host.json. If that\n // also fails, surface the ORIGINAL PRM error — it's almost always the\n // more informative one (host.json 404s are the common case).\n try {\n return await discoverViaHostJson(base, fetchOpts, opts)\n } catch {\n throw prmErr\n }\n }\n}\n","/**\n * Keychain helpers — read/write a token in the platform Keychain.\n *\n * Uses the macOS `security` CLI. On non-macOS hosts, callers should swap this\n * module for a platform-appropriate equivalent (libsecret on Linux, Credential\n * Manager on Windows).\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\n\nconst exec = promisify(execFile)\n\n/**\n * Guard the macOS-only backend. Without this, `readKeychainToken` would swallow\n * the missing-`security` error and return undefined on Linux/Windows — making a\n * stored credential look absent and re-prompting on every run — while\n * `writeKeychainToken` would throw an opaque ENOENT. Fail loudly and clearly\n * instead, until a libsecret / Credential Manager backend exists.\n */\nfunction assertKeychainSupported(): void {\n if (process.platform !== \"darwin\") {\n throw new Error(\n `@agentproto/auth token-store: the Keychain backend only supports macOS ` +\n `(got platform \"${process.platform}\"). Provide a libsecret (Linux) or ` +\n `Credential Manager (Windows) implementation to run here.`,\n )\n }\n}\n\n/** Substitute `{server}` template in a tokenStore account spec. */\nexport function resolveAccount(\n account: string | undefined,\n server: string,\n): string {\n if (!account) return server\n return account.replace(\"{server}\", server)\n}\n\n/** Read a token from the Keychain. Returns undefined if not found. */\nexport async function readKeychainToken(\n service: string,\n account: string,\n): Promise<string | undefined> {\n assertKeychainSupported()\n try {\n const { stdout } = await exec(\"security\", [\n \"find-generic-password\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n ])\n const t = stdout.replace(/\\n$/, \"\")\n return t || undefined\n } catch {\n return undefined\n }\n}\n\n/** Write a token to the Keychain (-U updates in place). */\nexport async function writeKeychainToken(\n service: string,\n account: string,\n token: string,\n): Promise<void> {\n assertKeychainSupported()\n await exec(\"security\", [\n \"add-generic-password\",\n \"-U\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n token,\n \"-D\",\n \"agentproto auth token\",\n ])\n}\n","/**\n * KeychainStore — `CredentialStore` backed by the platform Keychain.\n *\n * Wraps the low-level `token-store.ts` helpers (macOS `security` CLI today).\n * The Keychain only holds one opaque string per entry, so `kind`/`expiresAt`/\n * `metadata` are packed into a small JSON envelope that IS that string.\n *\n * Back-compat: an entry written before this store existed (or by any other\n * tool) is a bare token string, not an envelope. `read` falls back to\n * treating the whole string as the value with kind `\"pat\"` — the only flow\n * that pre-dates this store — rather than failing on non-JSON content.\n */\n\nimport { z } from \"zod\"\nimport { readKeychainToken, writeKeychainToken } from \"../token-store.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst envelopeSchema = z.object({\n v: z.string(),\n k: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n e: z.string().optional(),\n m: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport class KeychainStore implements CredentialStore {\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const account = ref.account ?? ref.path\n const raw = await readKeychainToken(ref.path, account)\n if (raw === undefined) return undefined\n\n try {\n const envelope = envelopeSchema.parse(JSON.parse(raw))\n return {\n value: envelope.v,\n kind: envelope.k,\n ...(envelope.e !== undefined ? { expiresAt: envelope.e } : {}),\n ...(envelope.m !== undefined ? { metadata: envelope.m } : {}),\n }\n } catch {\n return { value: raw, kind: \"pat\" }\n }\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const account = ref.account ?? ref.path\n const envelope: z.infer<typeof envelopeSchema> = {\n v: cred.value,\n k: cred.kind,\n ...(cred.expiresAt !== undefined ? { e: cred.expiresAt } : {}),\n ...(cred.metadata !== undefined ? { m: cred.metadata } : {}),\n }\n await writeKeychainToken(ref.path, account, JSON.stringify(envelope))\n }\n}\n","/**\n * Map a provider's `TokenStoreSpec` to a backend-agnostic `StoreRef`.\n *\n * Shared by every flow engine so the `path`/`keychain` back-compat alias and\n * the `{server}` account template are resolved identically everywhere.\n */\n\nimport { resolveAccount } from \"../token-store.js\"\nimport type { TokenStoreSpec } from \"../types.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\n/** When `audience` is declared, it's folded into the physical store key —\n * `${audience}:${path}` — so credentials scoped to different audiences\n * (e.g. \"tunnel\" vs \"api\") never collide under the same slot. Absent\n * `audience` = today's unprefixed path, unchanged. */\nexport function resolveStoreRef(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): StoreRef {\n const path = spec.path ?? spec.keychain\n return {\n path: audience ? `${audience}:${path}` : path,\n account: resolveAccount(spec.account, server),\n }\n}\n\n/** Derive both the audience-prefixed `ref` and the unprefixed `legacyRef` in\n * one call — the pair every flow engine and the broker need for the\n * audience back-compat read (`readStoreRefWithFallback`). When no audience\n * is declared, `legacyRef === ref` (same object), matching `resolveStoreRef`\n * called with `audience` undefined. */\nexport function resolveStoreRefs(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): { ref: StoreRef; legacyRef: StoreRef } {\n const ref = resolveStoreRef(spec, server, audience)\n const legacyRef = audience ? resolveStoreRef(spec, server) : ref\n return { ref, legacyRef }\n}\n\n/**\n * Read through `ref`, falling back once to `legacyRef` on a miss.\n *\n * This is the read half of the audience back-compat rule: a write always\n * targets the audience-prefixed ref, but a credential written before the\n * provider adopted an audience still lives at the unprefixed (legacy) path.\n * Rather than duplicate that fallback at every flow-engine/broker read site,\n * it lives here, next to `resolveStoreRef` — the one place that already\n * knows how prefixed vs. legacy refs are derived. Callers that don't declare\n * an audience pass `ref === legacyRef` (or just call `store.read` directly);\n * this only does extra work when the two refs actually differ.\n */\nexport async function readStoreRefWithFallback(\n store: CredentialStore,\n ref: StoreRef,\n legacyRef: StoreRef,\n): Promise<StoredCredential | undefined> {\n const stored = await store.read(ref)\n if (stored) return stored\n if (ref.path === legacyRef.path && ref.account === legacyRef.account) {\n return undefined\n }\n return store.read(legacyRef)\n}\n","/**\n * PAT flow engine — reads an existing token from the Keychain or prompts for one.\n *\n * This is the \"legacy-compatible\" flow: the user has a personal API key\n * (`gld_*`, `sk-*`, …) and the CLI needs to store/retrieve it. No browser\n * open, no ceremony. Use `service-auth` for the seamless browser-approve path.\n */\n\nimport { createInterface } from \"node:readline\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\n\n/**\n * Read a secret from the terminal WITHOUT echoing it — the typed key must not\n * land on screen or in scrollback. On a TTY we drop to raw mode and render a `*`\n * mask per character. When stdin isn't a TTY (piped input, CI, tests) there's no\n * echo to suppress and no raw mode to enter, so we read a line normally.\n */\nasync function promptToken(label: string): Promise<string> {\n const input = process.stdin\n const out = process.stderr\n\n if (!input.isTTY) {\n return new Promise((resolve) => {\n const rl = createInterface({ input, output: out })\n out.write(`${label}: `)\n rl.question(\"\", (answer) => {\n rl.close()\n resolve(answer.trim())\n })\n })\n }\n\n return new Promise((resolve, reject) => {\n out.write(`${label}: `)\n const chars: string[] = []\n input.setRawMode(true)\n input.resume()\n input.setEncoding(\"utf8\")\n\n const cleanup = () => {\n input.setRawMode(false)\n input.pause()\n input.removeListener(\"data\", onData)\n }\n\n const onData = (chunk: string) => {\n for (const ch of chunk) {\n switch (ch) {\n case \"\\r\":\n case \"\\n\":\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u0003\": // Ctrl-C\n out.write(\"\\n\")\n cleanup()\n reject(new Error(\"auth cancelled\"))\n return\n case \"\\u0004\": // Ctrl-D — treat as end-of-input\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u007f\": // Backspace / Delete\n case \"\\b\":\n if (chars.length > 0) {\n chars.pop()\n out.write(\"\\b \\b\")\n }\n break\n default:\n // Mask printable input; ignore stray control characters.\n if (ch >= \" \") {\n chars.push(ch)\n out.write(\"*\")\n }\n }\n }\n }\n\n input.on(\"data\", onData)\n })\n}\n\nexport const patFlowEngine: FlowEngine = {\n id: \"pat\",\n\n async run(\n provider: AuthProviderHandle,\n _discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"pat\") {\n throw new Error(`patFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n auth.tokenStore,\n opts.server,\n provider.audience,\n )\n\n if (!opts.force) {\n const existing = await readStoreRefWithFallback(store, ref, legacyRef)\n if (existing) {\n return { accessToken: existing.value, tokenKind: \"pat\" }\n }\n }\n\n const token = await promptToken(`${provider.id} personal access token`)\n if (!token) throw new Error(\"no token provided\")\n\n await store.write(ref, { value: token, kind: \"pat\" })\n\n return { accessToken: token, tokenKind: \"pat\" }\n },\n}\n","/**\n * Shared RFC 8628 device-grant polling primitive (internal, not exported from\n * the package root).\n *\n * Both the auth.md claim ceremony (`service-auth.ts`) and the device-code flow\n * poll an OAuth token endpoint with a grant-specific URN until the AS reports\n * success or a terminal error. This module holds that shared poll loop plus\n * the small HTTP/browser helpers both flows need — lifted verbatim from\n * `service-auth.ts` so new flow engines have somewhere to reuse them from.\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\nimport { z } from \"zod\"\nimport { fetchWithDeadline } from \"../http.js\"\n\nconst execAsync = promisify(execFile)\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n\n/** Successful token/refresh/exchange response — the AS minted a credential. */\nexport const tokenSuccessSchema = z\n .object({\n access_token: z.string(),\n token_type: z.string().optional(),\n refresh_token: z.string().optional(),\n identity_assertion: z.string().optional(),\n assertion_expires_in: z.number().optional(),\n assertion_expires: z.string().optional(),\n // device-code flow fields (ignored by service-auth today; see WP-2).\n expires_in: z.number().optional(),\n scope: z.string().optional(),\n subject: z.string().optional(),\n revocation_id: z.string().optional(),\n })\n .loose()\n\n/** OAuth error response (`authorization_pending`, `slow_down`, `access_denied`…). */\nexport const tokenErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional(),\n })\n .loose()\n\n/** A token endpoint reply is either a minted credential or an OAuth error.\n * Success is tried first so a body carrying an access_token never matches the\n * error arm. */\nexport const tokenResponseSchema = z.union([tokenSuccessSchema, tokenErrorSchema])\n\nexport type TokenSuccess = z.infer<typeof tokenSuccessSchema>\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nexport async function openBrowser(url: string): Promise<void> {\n const [cmd, args]: [string, string[]] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? [\"cmd\", [\"/c\", \"start\", url]]\n : [\"xdg-open\", [url]]\n try {\n await execAsync(cmd, args)\n } catch {\n // best-effort — URL already printed to stderr\n }\n}\n\n// NOTE: deliberately does NOT check res.ok — the OAuth device/claim flow returns\n// HTTP 400 with a JSON `{ error }` body for authorization_pending / slow_down,\n// which the poll loop reads as data. Throwing on non-2xx would break polling.\nexport async function postFormOAuth<T>(\n url: string,\n params: Record<string, string>,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n return schema.parse(await res.json())\n}\n\nexport interface DeviceGrantPollOptions {\n /** Token endpoint URL to poll. */\n tokenEndpoint: string\n /** Grant-type URN sent on every poll (e.g. the claim or device_code grant). */\n grantType: string\n /** Token-carrying form params — e.g. `claim_token`/`device_code` plus\n * `client_id`. `grant_type` is added automatically; do not include it here. */\n params: Record<string, string>\n /** Poll interval in seconds; grows by 5s on each `slow_down`. */\n intervalS: number\n /** Approval window in seconds, measured from when polling starts. */\n expiresIn: number\n signal?: AbortSignal\n}\n\n/** RFC 8628 poll loop shared by every grant that polls a token endpoint for\n * user approval (auth.md claim ceremony, device-code). */\nexport async function pollDeviceGrant(\n o: DeviceGrantPollOptions,\n): Promise<TokenSuccess> {\n const deadline = Date.now() + o.expiresIn * 1_000\n let pollMs = o.intervalS * 1_000\n\n while (Date.now() < deadline) {\n if (o.signal?.aborted) throw new Error(\"auth cancelled\")\n await new Promise<void>((r) => setTimeout(r, pollMs))\n\n const data = await postFormOAuth(\n o.tokenEndpoint,\n { grant_type: o.grantType, ...o.params },\n tokenResponseSchema,\n o.signal,\n )\n\n if (!(\"error\" in data)) return data\n\n const pollErr = data.error\n if (pollErr === \"authorization_pending\") continue\n if (pollErr === \"slow_down\") {\n pollMs += 5_000\n continue\n }\n if (pollErr === \"expired_token\") {\n throw new Error(\"auth timeout — claim expired before user approved\")\n }\n if (pollErr === \"access_denied\") {\n throw new Error(\"access denied — user rejected the authorisation request\")\n }\n\n const desc = data.error_description\n throw new Error(`token endpoint error: ${pollErr}${desc ? ` — ${desc}` : \"\"}`)\n }\n\n throw new Error(\"auth timeout — approval window closed\")\n}\n","/**\n * service-auth flow engine — auth.md claim ceremony.\n *\n * Protocol:\n * POST /agent/identity { type:\"service_auth\" }\n * → registration_id + claim_token + user_code + verification_uri\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:workos:agent-auth:grant-type:claim\n * until approved / denied / expired.\n * On success: store the identity_assertion JWT (AIP-50 §Token storage —\n * the assertion is the durable credential; the access_token MUST NOT be\n * persisted, and the claim_token stays in memory only).\n *\n * Subsequent runs skip the ceremony: the stored assertion is exchanged via the\n * jwt-bearer grant for a fresh access_token (\"this IS the refresh path\" — no\n * refresh_token). Only when the assertion is expired/rejected does a new\n * ceremony start.\n *\n * See: https://github.com/workos/auth.md / AIP-50\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst CLAIM_GRANT_TYPE = \"urn:workos:agent-auth:grant-type:claim\"\nconst JWT_BEARER_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:jwt-bearer\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n// (Token success/error schemas live in device-grant.ts, shared with every flow\n// that polls a token endpoint.)\n\nconst identityResponseSchema = z\n .object({\n registration_id: z.string(),\n claim_token: z.string(),\n claim: z\n .object({\n user_code: z.string(),\n verification_uri: z.string(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postJson<T>(\n url: string,\n body: unknown,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return schema.parse(await res.json())\n}\n\n// ── Identity-assertion exchange (jwt-bearer, RFC 7523) ────────────────────────\n//\n// The stored credential IS the identity_assertion JWT. Exchange it at the token\n// endpoint for a fresh, short-lived access token — the AIP-50 refresh path, with\n// no refresh_token involved. Returns null on any error (expired / invalid_grant\n// / server doesn't support the grant) so the caller falls back to a ceremony.\nasync function exchangeAssertion(\n tokenEndpoint: string,\n assertion: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: JWT_BEARER_GRANT_TYPE,\n assertion,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const serviceAuthFlowEngine: FlowEngine = {\n id: \"service-auth\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"service-auth\") {\n throw new Error(`serviceAuthFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"service-auth\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to ServiceAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions\n const identityEndpoint =\n discovered?.identityEndpoint ?? `${server}/agent/identity`\n const tokenEndpoint =\n discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(identityEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Cached path — the stored credential IS the identity_assertion JWT (AIP-50:\n // never the access token, never a refresh token). Exchange it via jwt-bearer\n // for a fresh access token; on failure (expired / invalid_grant) fall through\n // to a full browser ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n const exchanged = await exchangeAssertion(\n tokenEndpoint,\n stored.value,\n clientId,\n opts.signal,\n )\n if (exchanged) {\n // If the server rotated the assertion, persist the new one; otherwise\n // the existing assertion stays valid for the next exchange.\n if (exchanged.identity_assertion) {\n await store.write(ref, {\n value: exchanged.identity_assertion,\n kind: \"assertion\",\n })\n }\n return {\n accessToken: exchanged.access_token,\n ...(exchanged.identity_assertion\n ? { identityAssertion: exchanged.identity_assertion }\n : {}),\n tokenKind: \"oat\",\n }\n }\n }\n }\n\n // 1 — POST /agent/identity to start the claim ceremony\n const identity = await postJson(\n identityEndpoint,\n {\n type: \"service_auth\",\n client_id: clientId,\n ...(config.loginHint ? { login_hint: config.loginHint } : {}),\n },\n identityResponseSchema,\n opts.signal,\n )\n\n const { claim_token, claim } = identity\n const intervalS = claim.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(claim.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${claim.user_code}\\n`)\n process.stderr.write(` URL: ${claim.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(claim.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: CLAIM_GRANT_TYPE,\n params: { claim_token, client_id: clientId },\n intervalS,\n expiresIn: claim.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Store the identity_assertion as the durable credential (AIP-50: the\n // access_token is ephemeral and MUST NOT be persisted; the claim_token\n // was held in memory only). The assertion is re-exchanged via jwt-bearer\n // on the next run.\n const accessToken = tokenResult.access_token\n const assertion = tokenResult.identity_assertion\n\n // Resolve assertion expiry as ISO 8601\n let assertionExpires: string | undefined\n if (tokenResult.assertion_expires) {\n assertionExpires = tokenResult.assertion_expires\n } else if (tokenResult.assertion_expires_in) {\n assertionExpires = new Date(\n Date.now() + tokenResult.assertion_expires_in * 1_000,\n ).toISOString()\n }\n\n if (assertion) {\n await store.write(ref, {\n value: assertion,\n kind: \"assertion\",\n ...(assertionExpires ? { expiresAt: assertionExpires } : {}),\n })\n }\n\n return {\n accessToken,\n identityAssertion: assertion,\n assertionExpires,\n tokenKind: \"oat\",\n }\n },\n}\n","/**\n * device-code flow engine — plain RFC 8628 device-authorization ceremony.\n *\n * Protocol:\n * POST {device_authorization_endpoint} { client_id, scope?, device_label? }\n * → device_code + user_code + verification_uri(_complete) + expires_in\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:ietf:params:oauth:grant-type:device_code\n * until approved / denied / expired.\n * On success: store the access_token as the durable credential (kind:\"daemon\")\n * — unlike service-auth, the access token IS the thing that's persisted;\n * refresh_token/scope/subject/revocation_id ride in `metadata`.\n *\n * Subsequent runs: a fresh stored credential (or one with no expiry) short-\n * circuits the ceremony. An expired credential with a stored refresh_token is\n * exchanged via `grant_type=refresh_token`; on failure (or when no\n * refresh_token was stored) a new ceremony starts.\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"../store/types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\"\nconst REFRESH_GRANT_TYPE = \"refresh_token\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n/** Thrown by the device-code engine when `opts.refreshOnly` is set and no\n * fresh or refreshable credential is available — the only remaining path\n * would be an interactive ceremony, which `refreshOnly` callers explicitly\n * opt out of. Callers (e.g. `serve` boot on a headless host) catch this to\n * fall back to their own non-interactive behavior instead of hanging. */\nexport class CeremonyRequiredError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"CeremonyRequiredError\"\n }\n}\n\n// ── response schema ───────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so the\n// response is validated with Zod rather than asserted. `.loose()` keeps\n// unknown fields the spec may add.\n\nconst deviceAuthorizationResponseSchema = z\n .object({\n device_code: z.string(),\n user_code: z.string(),\n verification_uri: z.string(),\n verification_uri_complete: z.string().optional(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postDeviceAuthorization(\n url: string,\n params: Record<string, string>,\n signal?: AbortSignal,\n) {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return deviceAuthorizationResponseSchema.parse(await res.json())\n}\n\n/** Read a string metadata field without an `as` cast — `metadata` is\n * `Record<string, unknown>`, so every read is a runtime type check. */\nfunction metaString(\n metadata: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const v = metadata?.[key]\n return typeof v === \"string\" ? v : undefined\n}\n\nfunction isExpired(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return false\n const t = Date.parse(cred.expiresAt)\n if (Number.isNaN(t)) return true\n return t <= Date.now()\n}\n\nfunction resultFromStored(cred: StoredCredential): FlowResult {\n const refreshToken = metaString(cred.metadata, \"refreshToken\")\n const scope = metaString(cred.metadata, \"scope\")\n const subject = metaString(cred.metadata, \"subject\")\n const revocationId = metaString(cred.metadata, \"revocationId\")\n return {\n accessToken: cred.value,\n tokenKind: \"daemon\",\n ...(refreshToken ? { refreshToken } : {}),\n ...(scope ? { scope } : {}),\n ...(subject ? { subject } : {}),\n ...(revocationId ? { revocationId } : {}),\n }\n}\n\n/** Refresh via `grant_type=refresh_token`. Returns null on any error\n * (expired / invalid_grant / server doesn't support the grant) so the\n * caller falls back to a full ceremony. */\nasync function refreshAccessToken(\n tokenEndpoint: string,\n refreshToken: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: REFRESH_GRANT_TYPE,\n refresh_token: refreshToken,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\nasync function persistAndResult(\n store: CredentialStore,\n ref: StoreRef,\n o: {\n accessToken: string\n expiresIn?: number\n refreshToken?: string\n scope?: string\n subject?: string\n deviceLabel?: string\n revocationId?: string\n },\n): Promise<FlowResult> {\n const expiresAt = o.expiresIn\n ? new Date(Date.now() + o.expiresIn * 1_000).toISOString()\n : undefined\n\n const metadata: Record<string, unknown> = {\n obtainedAt: new Date().toISOString(),\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.deviceLabel ? { deviceLabel: o.deviceLabel } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n\n await store.write(ref, {\n value: o.accessToken,\n kind: \"daemon\",\n ...(expiresAt ? { expiresAt } : {}),\n metadata,\n })\n\n return {\n accessToken: o.accessToken,\n tokenKind: \"daemon\",\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const deviceCodeFlowEngine: FlowEngine = {\n id: \"device-code\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"device-code\") {\n throw new Error(`deviceCodeFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"device-code\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to DeviceCodeAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions.\n const deviceAuthorizationEndpoint =\n discovered?.deviceAuthorizationEndpoint ?? `${server}/oauth/device`\n const tokenEndpoint = discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(deviceAuthorizationEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Shared by both the ordinary cached path and `refreshOnly`: exchange a\n // stored refresh_token for a fresh access token, persisting the result.\n // Returns null (never throws) on a missing refresh_token or any grant\n // failure, so both callers can decide what to do next.\n async function tryRefresh(stored: StoredCredential): Promise<FlowResult | null> {\n const refreshToken = metaString(stored.metadata, \"refreshToken\")\n if (!refreshToken) return null\n const refreshed = await refreshAccessToken(\n tokenEndpoint,\n refreshToken,\n clientId,\n opts.signal,\n )\n if (!refreshed) return null\n return persistAndResult(store, ref, {\n accessToken: refreshed.access_token,\n expiresIn: refreshed.expires_in,\n refreshToken: refreshed.refresh_token ?? refreshToken,\n scope: refreshed.scope ?? metaString(stored.metadata, \"scope\"),\n subject: refreshed.subject ?? metaString(stored.metadata, \"subject\"),\n deviceLabel:\n config.deviceLabel ?? metaString(stored.metadata, \"deviceLabel\"),\n revocationId:\n refreshed.revocation_id ?? metaString(stored.metadata, \"revocationId\"),\n })\n }\n\n // `refreshOnly` — attempt only the cached/refresh path, never the\n // interactive ceremony. Distinct from the ordinary cached path below so\n // a refresh failure here throws instead of falling through.\n if (opts.refreshOnly) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n }\n throw new CeremonyRequiredError(\n `${provider.id}: no fresh or refreshable device-code credential — an interactive ceremony would be required, but refreshOnly was set`,\n )\n }\n\n // Cached path — the stored credential IS the access token (pat-class\n // persistence). A fresh (or expiry-less) credential short-circuits the\n // ceremony entirely; an expired one with a refresh_token is renewed via\n // grant_type=refresh_token before falling back to a ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n // refresh failed (expired / invalid_grant) — fall through to a ceremony\n }\n }\n\n // 1 — POST the device-authorization endpoint to start the ceremony\n const params: Record<string, string> = { client_id: clientId }\n if (config.scope) params.scope = config.scope\n if (config.deviceLabel) params.device_label = config.deviceLabel\n\n const authz = await postDeviceAuthorization(\n deviceAuthorizationEndpoint,\n params,\n opts.signal,\n )\n\n const intervalS = authz.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(authz.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${authz.user_code}\\n`)\n process.stderr.write(` URL: ${authz.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(authz.verification_uri_complete ?? authz.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: DEVICE_CODE_GRANT_TYPE,\n params: { device_code: authz.device_code, client_id: clientId },\n intervalS,\n expiresIn: authz.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Persist the access token as the durable credential (pat-class).\n return persistAndResult(store, ref, {\n accessToken: tokenResult.access_token,\n expiresIn: tokenResult.expires_in,\n refreshToken: tokenResult.refresh_token,\n scope: tokenResult.scope,\n subject: tokenResult.subject,\n deviceLabel: config.deviceLabel,\n revocationId: tokenResult.revocation_id,\n })\n },\n}\n","/**\n * Flow engine registry — dispatch by `provider.auth.flow`.\n *\n * Add a new engine:\n * 1. Implement `FlowEngine` in a sibling file\n * 2. Add it here — no if/switch chains at call sites\n */\n\nimport type { FlowEngine } from \"../types.js\"\nimport { patFlowEngine } from \"./pat.js\"\nimport { serviceAuthFlowEngine } from \"./service-auth.js\"\nimport { deviceCodeFlowEngine } from \"./device-code.js\"\n\nexport const FLOW_ENGINES: Readonly<Record<string, FlowEngine>> = {\n [patFlowEngine.id]: patFlowEngine,\n [serviceAuthFlowEngine.id]: serviceAuthFlowEngine,\n [deviceCodeFlowEngine.id]: deviceCodeFlowEngine,\n}\n","/**\n * `runAuthFlow` — resolve provider → discover endpoints → dispatch to engine.\n *\n * Discovery is attempted silently; callers receive the result without knowing\n * whether live or static endpoint config was used. The flow engine receives\n * `null` for `discovered` if discovery failed or was not attempted.\n */\n\nimport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nimport { discoverEndpoints, DiscoveryError } from \"./discover.js\"\nimport type {\n AuthProviderHandle,\n DiscoveredEndpoints,\n FlowResult,\n FlowRunOptions,\n} from \"./types.js\"\n\nexport interface RunFlowOptions extends FlowRunOptions {\n /** Pre-resolved endpoints (skip discovery). Pass null to force re-discovery. */\n discovered?: DiscoveredEndpoints | null\n /** Suppress debug output. Default: false. */\n quiet?: boolean\n}\n\nexport async function runAuthFlow(\n provider: AuthProviderHandle,\n opts: RunFlowOptions,\n): Promise<FlowResult> {\n const flowId = provider.auth.flow\n const engine = FLOW_ENGINES[flowId]\n if (!engine) {\n throw new Error(\n `runAuthFlow: unknown flow \"${flowId}\" — registered: ${Object.keys(FLOW_ENGINES).join(\", \")}`,\n )\n }\n\n // Discovery: try unless caller already provided endpoints\n let discovered: DiscoveredEndpoints | null =\n opts.discovered !== undefined ? opts.discovered : null\n\n if (\n discovered === null &&\n (flowId === \"service-auth\" || flowId === \"device-code\")\n ) {\n try {\n discovered = await discoverEndpoints(opts.server, { signal: opts.signal })\n } catch (err) {\n if (!opts.quiet) {\n const msg =\n err instanceof DiscoveryError\n ? err.message\n : `discovery failed: ${err}`\n process.stderr.write(`[auth] ${msg} — using static config\\n`)\n }\n }\n }\n\n return engine.run(provider, discovered, opts)\n}\n","/**\n * MemoryStore — in-process `CredentialStore` backed by a `Map`.\n *\n * Ephemeral: gone when the process exits. Used for tests and short-lived\n * tooling that shouldn't touch a real backend.\n */\n\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path}\u0000${ref.account ?? ref.path}`\n}\n\nexport class MemoryStore implements CredentialStore {\n private readonly entries = new Map<string, StoredCredential>()\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const entry = this.entries.get(keyOf(ref))\n return entry ? { ...entry } : undefined\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n this.entries.set(keyOf(ref), { ...cred })\n }\n\n async delete(ref: StoreRef): Promise<void> {\n this.entries.delete(keyOf(ref))\n }\n}\n","/**\n * FileStore — encrypted-JSON-file `CredentialStore`.\n *\n * Every entry is sealed independently with AES-256-GCM under a key read from\n * `AGENTPROTO_STORE_KEY` (hex or base64, 32 raw bytes). There is no plaintext\n * fallback: a missing or malformed key throws rather than writing credentials\n * to disk in the clear.\n */\n\nimport {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from \"node:crypto\"\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { dirname } from \"node:path\"\nimport { z } from \"zod\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst ALGORITHM = \"aes-256-gcm\"\nconst KEY_ENV_VAR = \"AGENTPROTO_STORE_KEY\"\nconst IV_BYTES = 12\n\nconst sealedEntrySchema = z.object({\n iv: z.string(),\n tag: z.string(),\n ciphertext: z.string(),\n})\ntype SealedEntry = z.infer<typeof sealedEntrySchema>\n\nconst sealedFileSchema = z.record(z.string(), sealedEntrySchema)\n\nconst storedCredentialSchema = z.object({\n value: z.string(),\n kind: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n expiresAt: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path} ${ref.account ?? ref.path}`\n}\n\nfunction isEnoent(err: unknown): boolean {\n return (\n typeof err === \"object\" &&\n err !== null &&\n \"code\" in err &&\n err.code === \"ENOENT\"\n )\n}\n\n/** Decode `AGENTPROTO_STORE_KEY` (hex or base64) into exactly 32 raw bytes. */\nfunction loadKey(): Buffer {\n const raw = process.env[KEY_ENV_VAR]\n if (!raw) {\n throw new Error(\n `FileStore: missing ${KEY_ENV_VAR} — set a 32-byte key (64 hex chars, ` +\n `or base64) to use the encrypted file store. Refusing to store ` +\n `credentials in plaintext.`,\n )\n }\n const key = /^[0-9a-fA-F]{64}$/.test(raw)\n ? Buffer.from(raw, \"hex\")\n : Buffer.from(raw, \"base64\")\n if (key.length !== 32) {\n throw new Error(\n `FileStore: ${KEY_ENV_VAR} must decode to exactly 32 bytes (got ` +\n `${key.length}). Provide a 64-char hex string or base64 encoding 32 bytes.`,\n )\n }\n return key\n}\n\nfunction seal(key: Buffer, plaintext: string): SealedEntry {\n const iv = randomBytes(IV_BYTES)\n const cipher = createCipheriv(ALGORITHM, key, iv)\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ])\n return {\n iv: iv.toString(\"base64\"),\n tag: cipher.getAuthTag().toString(\"base64\"),\n ciphertext: ciphertext.toString(\"base64\"),\n }\n}\n\nfunction unseal(key: Buffer, entry: SealedEntry): string {\n const decipher = createDecipheriv(\n ALGORITHM,\n key,\n Buffer.from(entry.iv, \"base64\"),\n )\n decipher.setAuthTag(Buffer.from(entry.tag, \"base64\"))\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(entry.ciphertext, \"base64\")),\n decipher.final(),\n ])\n return plaintext.toString(\"utf8\")\n}\n\nexport class FileStore implements CredentialStore {\n constructor(private readonly filePath: string) {}\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const key = loadKey()\n const file = await this.readFile()\n const sealed = file[keyOf(ref)]\n if (!sealed) return undefined\n return storedCredentialSchema.parse(JSON.parse(unseal(key, sealed)))\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const key = loadKey()\n const file = await this.readFile()\n file[keyOf(ref)] = seal(key, JSON.stringify(cred))\n await this.writeFile(file)\n }\n\n async delete(ref: StoreRef): Promise<void> {\n const file = await this.readFile()\n delete file[keyOf(ref)]\n await this.writeFile(file)\n }\n\n private async readFile(): Promise<Record<string, SealedEntry>> {\n try {\n const raw = await readFile(this.filePath, \"utf8\")\n return sealedFileSchema.parse(JSON.parse(raw))\n } catch (err) {\n if (isEnoent(err)) return {}\n throw err\n }\n }\n\n private async writeFile(file: Record<string, SealedEntry>): Promise<void> {\n await mkdir(dirname(this.filePath), { recursive: true })\n await writeFile(this.filePath, JSON.stringify(file, null, 2), \"utf8\")\n }\n}\n","/**\n * CredentialBroker — resolve ready-to-use auth headers for a `<providerId>`\n * or `<providerId>/<account>` path, auto-refreshing via the flow engine when\n * the stored credential is missing, expired, or not directly usable.\n *\n * Agent.pw-parity API: callers ask for headers by path and never touch\n * tokens, flows, or the underlying store directly.\n */\n\nimport { runAuthFlow } from \"./run-flow.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"./store/resolve-ref.js\"\nimport type { CredentialStore, StoredCredential } from \"./store/types.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Refresh this long before the actual expiry, so a credential that's about\n * to expire mid-request gets renewed proactively instead of failing. */\nconst EXPIRY_SKEW_MS = 60_000\n\nexport interface CredentialBrokerOptions {\n /** Backend to read cached credentials from and persist refreshed ones to. */\n store: CredentialStore\n /** Provider lookup — pass `getAuthProvider` from the registry, or a custom\n * resolver (e.g. scoped to a single host's providers). */\n getProvider: (id: string) => AuthProviderHandle | undefined\n}\n\ninterface ParsedPath {\n providerId: string\n account?: string\n}\n\n/** Split `\"<providerId>\"` or `\"<providerId>/<account>\"` on the first `/`. */\nfunction parsePath(path: string): ParsedPath {\n const slash = path.indexOf(\"/\")\n if (slash === -1) return { providerId: path }\n return { providerId: path.slice(0, slash), account: path.slice(slash + 1) }\n}\n\n/** `expiresAt` in the future (past the refresh skew), or absent entirely. A\n * malformed `expiresAt` is treated as expired — refresh rather than risk\n * serving a header that a downstream API will reject. */\nfunction isFresh(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return true\n const expiresAtMs = Date.parse(cred.expiresAt)\n if (Number.isNaN(expiresAtMs)) return false\n return expiresAtMs - EXPIRY_SKEW_MS > Date.now()\n}\n\n/** Header map for a credential usable as a bearer token directly, or\n * `undefined` when it isn't. `assertion` is never bearer-usable — it must be\n * exchanged by a flow engine first — so it always falls through to\n * `runAuthFlow`. */\nfunction bearerHeaders(\n value: string,\n kind: StoredCredential[\"kind\"],\n): Record<string, string> | undefined {\n if (kind === \"pat\" || kind === \"oat\" || kind === \"daemon\") {\n return { Authorization: `Bearer ${value}` }\n }\n return undefined\n}\n\nexport class CredentialBroker {\n private readonly store: CredentialStore\n private readonly getProvider: (id: string) => AuthProviderHandle | undefined\n\n constructor(opts: CredentialBrokerOptions) {\n this.store = opts.store\n this.getProvider = opts.getProvider\n }\n\n async resolveHeaders(o: {\n path: string\n server?: string\n signal?: AbortSignal\n /** Audience the caller expects this credential to be scoped to. Checked\n * only when the resolved provider also declares one — see the mismatch\n * error below. Does not itself change which store key is read; the\n * provider's own `audience` (not the caller's) determines that. */\n audience?: string\n }): Promise<Record<string, string>> {\n const { providerId, account } = parsePath(o.path)\n const provider = this.getProvider(providerId)\n if (!provider) {\n throw new Error(`CredentialBroker: unknown auth provider \"${providerId}\"`)\n }\n\n if (\n o.audience !== undefined &&\n provider.audience !== undefined &&\n o.audience !== provider.audience\n ) {\n throw new Error(\n `CredentialBroker: provider \"${providerId}\" is scoped to audience \"${provider.audience}\", requested \"${o.audience}\"`,\n )\n }\n\n const server = o.server ?? provider.apiBase\n const { ref, legacyRef } = resolveStoreRefs(\n provider.auth.tokenStore,\n server,\n provider.audience,\n )\n if (account !== undefined) {\n ref.account = account\n legacyRef.account = account\n }\n\n const stored = await readStoreRefWithFallback(this.store, ref, legacyRef)\n if (stored && isFresh(stored)) {\n const headers = bearerHeaders(stored.value, stored.kind)\n if (headers) return headers\n }\n\n const result = await runAuthFlow(provider, {\n server,\n store: this.store,\n signal: o.signal,\n })\n const headers =\n result.accessToken !== undefined\n ? bearerHeaders(result.accessToken, result.tokenKind)\n : undefined\n if (!headers) {\n throw new Error(\n `CredentialBroker: auth flow for \"${providerId}\" produced no usable access token`,\n )\n }\n return headers\n }\n}\n","/**\n * @agentproto/auth — AIP-50 AUTH.md reference implementation.\n *\n * Public API:\n * defineAuthProvider(def) — TS-literal authoring (frozen handle)\n * parseAuthProviderManifest(source) — .md authoring (gray-matter + Zod)\n * registerAuthProvider(handle) — extend the module-level registry\n * getAuthProvider(id) — lookup by vendor id\n * listAuthProviderIds() — enumerate known providers\n * discoverEndpoints(apiBase) — two-hop PRM → AS metadata discovery\n * runAuthFlow(provider, opts) — resolve + discover + dispatch to engine\n * FLOW_ENGINES — registered flow engines (pat, …)\n * CeremonyRequiredError — thrown by device-code's refreshOnly\n * mode when only an interactive\n * ceremony would satisfy the request\n * writeKeychainToken(svc, acct, t) — persist a credential to Keychain\n * readKeychainToken(svc, acct) — read a credential from Keychain\n * resolveAccount(acct, server) — expand {server} template\n * KeychainStore / MemoryStore / FileStore — built-in CredentialStore backends\n * resolveStoreRef(spec, server) — map a TokenStoreSpec to a StoreRef\n * CredentialBroker — path → ready-to-use auth headers\n */\n\nexport { defineAuthProvider } from \"./define-auth-provider.js\"\nexport {\n parseAuthProviderManifest,\n parseAuthProviderManifestRaw,\n type AuthProviderManifest,\n} from \"./manifest.js\"\nexport {\n registerAuthProvider,\n getAuthProvider,\n listAuthProviders,\n listAuthProviderIds,\n} from \"./registry.js\"\nexport {\n discoverEndpoints,\n DiscoveryError,\n} from \"./discover.js\"\nexport { runAuthFlow, type RunFlowOptions } from \"./run-flow.js\"\nexport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nexport { CeremonyRequiredError } from \"./flow-engines/device-code.js\"\nexport {\n readKeychainToken,\n writeKeychainToken,\n resolveAccount,\n} from \"./token-store.js\"\nexport { KeychainStore } from \"./store/keychain-store.js\"\nexport { MemoryStore } from \"./store/memory-store.js\"\nexport { FileStore } from \"./store/file-store.js\"\nexport { resolveStoreRef } from \"./store/resolve-ref.js\"\nexport type {\n CredentialStore,\n StoreRef,\n StoredCredential,\n} from \"./store/types.js\"\nexport { CredentialBroker, type CredentialBrokerOptions } from \"./broker.js\"\nexport { guildeAuthProvider, BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nexport {\n authProviderFrontmatterSchema,\n authConfigSchema,\n tokenStoreSpecSchema,\n installConfigSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nexport type {\n AuthProviderDefinition,\n AuthProviderHandle,\n AuthConfig,\n PATAuthConfig,\n ServiceAuthConfig,\n DeviceCodeAuthConfig,\n InstallConfig,\n TokenStoreSpec,\n FlowEngine,\n FlowId,\n FlowResult,\n FlowRunOptions,\n DiscoveredEndpoints,\n} from \"./types.js\"\n\nexport const SPEC_NAME = \"agentauth\"\nexport const SPEC_VERSION = \"v1\"\n"]}
1
+ {"version":3,"sources":["../src/schema.ts","../src/define-auth-provider.ts","../src/manifest.ts","../src/builtins.ts","../src/registry.ts","../src/http.ts","../src/discover.ts","../src/token-store.ts","../src/store/keychain-store.ts","../src/store/resolve-ref.ts","../src/flow-engines/pat.ts","../src/flow-engines/device-grant.ts","../src/flow-engines/service-auth.ts","../src/flow-engines/device-code.ts","../src/flow-engines/index.ts","../src/run-flow.ts","../src/store/memory-store.ts","../src/store/file-store.ts","../src/broker.ts","../src/profile-store.ts","../src/eligibility.ts","../src/index.ts"],"names":["z","resolve","promisify","execFile","DEFAULT_POLL_INTERVAL_S","keyOf","headers","readFile","mkdir","writeFile"],"mappings":";;;;;;;;;;;;;;;;AAUO,IAAM,oBAAA,GAAuB,EACjC,MAAA,CAAO;AAAA,EACN,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA,EAC1B,MAAM,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACjC,SAAS,CAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA;AAC7B,CAAC,EACA,MAAA;AAEI,IAAM,mBAAA,GAAsB,EAChC,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,UAAA,EAAY;AACd,CAAC,EACA,MAAA,EAAO;AAEH,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,IAAI,EAAE,EAAA,IAAM,IAAA,CAAK,QAAA,CAAA,EAAW,OAAO,KAAA;AACnC,EAAA,OAAO,IAAA,CAAK,SAAS,EAAE,CAAA;AACvB,EAAA,MAAM,kBAAkB,IAAI,CAAA;AAC5B,EAAA,OAAO,IAAA;AACT;;;AC3CO,SAAS,eAAA,CACd,UACA,KAAA,EACoB;AACpB,EAAA,MAAM,MAAA,GAAS,QAAA,CAAS,aAAA,CAAc,KAAK,CAAA;AAC3C,EAAA,IAAI,WAAW,MAAA,EAAW;AACxB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,0BAAA,EAA6B,QAAA,CAAS,EAAE,CAAA,gCAAA,EAAmC,KAAK,CAAA,CAAA;AAAA,KAClF;AAAA,EACF;AACA,EAAA,OAAO,EAAE,MAAA,EAAO;AAClB;AAMO,SAAS,kBAAA,CACd,UACA,KAAA,EACc;AACd,EAAA,OAAO,CAAC,GAAI,QAAA,CAAS,eAAe,KAAK,CAAA,IAAK,EAAG,CAAA;AACnD;AAKO,SAAS,gBAAA,CACd,QAAA,EACA,QAAA,EACA,KAAA,EACe;AACf,EAAA,MAAM,EAAE,MAAA,EAAO,GAAI,eAAA,CAAgB,UAAU,KAAK,CAAA;AAClD,EAAA,MAAM,OAAA,GAAU,kBAAA,CAAmB,QAAA,EAAU,KAAK,CAAA;AAClD,EAAA,OAAO,QAAA,CAAS,MAAA,CAAO,CAAA,CAAA,KAAK,CAAA,CAAE,MAAA,KAAW,UAAU,OAAA,CAAQ,QAAA,CAAS,CAAA,CAAE,MAAM,CAAC,CAAA;AAC/E;;;ACeO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * AIP-50 auth-provider frontmatter / literal Zod schema.\n *\n * Single source of truth for both authoring paths: `defineAuthProvider`\n * (TS literal) and `parseAuthProviderManifest` (.md) run this same schema,\n * so a malformed literal and a malformed manifest fail identically.\n */\n\nimport { z } from \"zod\"\n\nexport const tokenStoreSpecSchema = z\n .object({\n keychain: z.string().min(1),\n path: z.string().min(1).optional(),\n account: z.string().min(1).optional(),\n })\n .strict()\n\nexport const patAuthConfigSchema = z\n .object({\n flow: z.literal(\"pat\"),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const serviceAuthConfigSchema = z\n .object({\n flow: z.literal(\"service-auth\"),\n clientId: z.string().min(1).optional(),\n loginHint: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const deviceCodeAuthConfigSchema = z\n .object({\n flow: z.literal(\"device-code\"),\n clientId: z.string().min(1).optional(),\n scope: z.string().min(1).optional(),\n deviceLabel: z.string().min(1).optional(),\n tokenStore: tokenStoreSpecSchema,\n })\n .strict()\n\nexport const authConfigSchema = z.discriminatedUnion(\"flow\", [\n patAuthConfigSchema,\n serviceAuthConfigSchema,\n deviceCodeAuthConfigSchema,\n])\n\nexport const installConfigSchema = z\n .object({\n sealKey: z.string().min(1),\n secretBacked: z.string().min(1),\n })\n .strict()\n\nexport const authProviderFrontmatterSchema = z\n .object({\n id: z.string().min(2).max(80),\n description: z.string().min(1).max(2000),\n apiBase: z.string().url(),\n auth: authConfigSchema,\n install: installConfigSchema.optional(),\n // Recommended values \"tunnel\" | \"api\" | \"mcp\" — free-form allowed, not an enum.\n audience: z.string().min(1).optional(),\n })\n .strict()\n .describe(\n \"AIP-50 auth-provider manifest: how a CLI tool authenticates to an API server and (optionally) where to call the AIP-19 provision endpoints.\",\n )\n\nexport type AuthProviderFrontmatter = z.infer<typeof authProviderFrontmatterSchema>\n","/**\n * `defineAuthProvider` — TS-literal authoring path for an auth-provider.\n *\n * Built on `createDoctype` so it gets the cross-AIP invariants: id-pattern,\n * ≤2000-char description, frozen handle, canonical error prefix. Field-level\n * validation uses the shared Zod from `./schema.ts`, so a malformed literal\n * fails with the same diagnostic as a malformed `.md`.\n */\n\nimport { createDoctype } from \"@agentproto/define-doctype\"\nimport { authProviderFrontmatterSchema } from \"./schema.js\"\nimport type { AuthProviderDefinition, AuthProviderHandle } from \"./types.js\"\n\nexport const defineAuthProvider = createDoctype<\n AuthProviderDefinition,\n AuthProviderHandle\n>({\n aip: 50,\n name: \"authProvider\",\n validate(def) {\n const result = authProviderFrontmatterSchema.safeParse(def)\n if (!result.success) {\n throw new Error(\n `defineAuthProvider (AIP-50): ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n },\n build(def) {\n return {\n ...def,\n auth: Object.freeze({ ...def.auth }),\n install: def.install ? Object.freeze({ ...def.install }) : undefined,\n }\n },\n})\n","/**\n * `.md` authoring path for an auth-provider — parse a frontmatter manifest\n * into a frozen handle. Mirrors `parseRecipeManifest` from AIP-19: gray-matter\n * splits the frontmatter, the shared Zod validates it, `defineAuthProvider`\n * builds the handle so both authoring paths converge on one validated shape.\n *\n * This parser is the extension seam: a host reads its own external `.md`\n * manifests (e.g. vendor-shipped `guilde.auth.md`) and registers them without\n * editing this package.\n */\n\nimport matter from \"gray-matter\"\nimport {\n authProviderFrontmatterSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nexport interface AuthProviderManifest {\n frontmatter: AuthProviderFrontmatter\n body: string\n}\n\nexport function parseAuthProviderManifestRaw(\n source: string,\n): AuthProviderManifest {\n const parsed = matter(source)\n if (Object.keys(parsed.data).length === 0) {\n throw new Error(\"parseAuthProviderManifest: missing or empty frontmatter\")\n }\n const result = authProviderFrontmatterSchema.safeParse(parsed.data)\n if (!result.success) {\n throw new Error(\n `parseAuthProviderManifest: invalid frontmatter — ${result.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`,\n )\n }\n return { frontmatter: result.data, body: parsed.content }\n}\n\n/** Parse an auth-provider `.md` straight to a frozen handle. */\nexport function parseAuthProviderManifest(source: string): AuthProviderHandle {\n const { frontmatter } = parseAuthProviderManifestRaw(source)\n return defineAuthProvider(frontmatter)\n}\n","/**\n * Builtin auth-provider manifests — shipped as TS literals so they bundle\n * into the tsup output with zero filesystem reads at runtime. A host adds more\n * by parsing its own `.md` with `parseAuthProviderManifest` and registering\n * the result via `registerAuthProvider`.\n */\n\nimport { defineAuthProvider } from \"./define-auth-provider.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Guilde AI company platform.\n *\n * Authenticates via the AIP-50 service-auth claim ceremony: browser opens,\n * user clicks Approve, bureau stores the oat_* access token.\n * Discovery from /.well-known/oauth-protected-resource supplies live endpoints;\n * the static fields below are the offline fallback. */\nexport const guildeAuthProvider = defineAuthProvider({\n id: \"guilde\",\n description:\n \"Guilde AI company platform. Authenticate via a browser-approve flow — no key to paste.\",\n apiBase: \"https://api.guilde.work\",\n audience: \"api\",\n auth: {\n flow: \"service-auth\",\n clientId: \"agentproto-cli\",\n tokenStore: {\n keychain: \"bureau-guilde\",\n account: \"{server}\",\n },\n },\n install: {\n sealKey: \"/guilde/api/v1/connectors/seal-key\",\n secretBacked: \"/guilde/api/v1/guilds/{guildId}/connectors/secret-backed\",\n },\n})\n\nexport const BUILTIN_AUTH_PROVIDERS: readonly AuthProviderHandle[] = [\n guildeAuthProvider,\n]\n","/**\n * Auth-provider registry — id → handle lookup, pre-seeded with builtins.\n *\n * Mirrors the provision-recipe registry shape (AIP-19). Re-registering an id\n * overrides it (last write wins), so a host can shadow a builtin.\n */\n\nimport { BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\nconst _registry = new Map<string, AuthProviderHandle>()\nfor (const p of BUILTIN_AUTH_PROVIDERS) _registry.set(p.id, p)\n\nexport function registerAuthProvider(provider: AuthProviderHandle): void {\n _registry.set(provider.id, provider)\n}\n\nexport function getAuthProvider(id: string): AuthProviderHandle | undefined {\n return _registry.get(id)\n}\n\nexport function listAuthProviders(): AuthProviderHandle[] {\n return [..._registry.values()]\n}\n\nexport function listAuthProviderIds(): string[] {\n return [..._registry.keys()]\n}\n","/**\n * Internal HTTP helpers — not part of the public API.\n *\n * Every network call in this package (discovery, the claim ceremony, token\n * refresh) must be bounded: a hung or slow server MUST NOT stall the CLI\n * indefinitely. `deadlineSignal` combines an optional caller `AbortSignal`\n * with a timeout into one signal to hand to `fetch`.\n *\n * Implemented with a plain `AbortController` + `setTimeout` rather than\n * `AbortSignal.any`/`AbortSignal.timeout` so it works on every runtime that\n * ships `fetch`, without assuming a specific Node minor.\n */\n\n/** Default per-request timeout. Discovery and token calls are small JSON\n * round-trips; 10s is generous without hanging an interactive CLI. */\nexport const DEFAULT_HTTP_TIMEOUT_MS = 10_000\n\n/**\n * AIP-50 §Security: discovery and auth requests MUST use HTTPS, to defeat\n * MITM/TOCTOU on the `.well-known` and token endpoints. Loopback http is\n * allowed — it isn't network-exposed — so local development against a dev\n * server keeps working. Throws on any other insecure URL.\n */\nexport function assertSecureUrl(url: string): void {\n let u: URL\n try {\n u = new URL(url)\n } catch {\n throw new Error(`invalid URL: ${url}`)\n }\n if (u.protocol === \"https:\") return\n const host = u.hostname\n const isLoopback =\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"::1\" ||\n host === \"[::1]\" ||\n host.endsWith(\".localhost\")\n if (u.protocol === \"http:\" && isLoopback) return\n throw new Error(\n `insecure URL '${url}' — AIP-50 requires HTTPS for discovery/auth ` +\n `(loopback http is allowed for local development).`,\n )\n}\n\nexport interface DeadlineHandle {\n /** Signal to pass to `fetch(url, { signal })`. */\n signal: AbortSignal\n /** Cancel the timer + detach the outer listener once the request settles.\n * ALWAYS call this in a `finally` to avoid a dangling timer/listener. */\n clear: () => void\n}\n\n/**\n * Build an `AbortSignal` that fires when EITHER the timeout elapses or the\n * caller's `outer` signal aborts.\n */\nexport function deadlineSignal(\n timeoutMs: number,\n outer?: AbortSignal,\n): DeadlineHandle {\n const ctrl = new AbortController()\n const onAbort = () => ctrl.abort(outer?.reason)\n\n if (outer) {\n if (outer.aborted) ctrl.abort(outer.reason)\n else outer.addEventListener(\"abort\", onAbort, { once: true })\n }\n\n const timer = setTimeout(\n () => ctrl.abort(new Error(`request timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n // Don't let a pending timeout keep the process alive on its own.\n if (typeof timer !== \"number\") timer.unref()\n\n return {\n signal: ctrl.signal,\n clear: () => {\n clearTimeout(timer)\n outer?.removeEventListener(\"abort\", onAbort)\n },\n }\n}\n\n/** `fetch` bounded by `deadlineSignal`. Merges any caller-supplied\n * `init.signal` with the timeout. */\nexport async function fetchWithDeadline(\n url: string,\n init: RequestInit = {},\n timeoutMs: number = DEFAULT_HTTP_TIMEOUT_MS,\n): Promise<Response> {\n const { signal, clear } = deadlineSignal(timeoutMs, init.signal ?? undefined)\n try {\n return await fetch(url, { ...init, signal })\n } finally {\n clear()\n }\n}\n","/**\n * Two-hop discovery per the auth.md standard (AIP-50 §Discovery algorithm),\n * with a second strategy for hosts that don't speak auth.md.\n *\n * Strategy 1 (OAuth PRM chain):\n * Hop 1: GET {apiBase}/.well-known/oauth-protected-resource (PRM, RFC 8414)\n * → extract authorization_servers[0] as authServerBase\n * Hop 2: GET {authServerBase}/.well-known/oauth-authorization-server (AS metadata)\n * → extract token_endpoint + agent_auth block\n *\n * Strategy 2 (agentproto-host.json), tried when strategy 1 fails:\n * GET {apiBase}/.well-known/agentproto-host.json\n * → extract device_authorization_endpoint + token_endpoint\n *\n * Callers MUST catch DiscoveryError and fall back to static manifest config —\n * discovery failures are common (server predates auth.md) and MUST NOT prevent\n * the PAT or other static flows from working.\n */\n\nimport { z } from \"zod\"\nimport type { DiscoveredEndpoints } from \"./types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"./http.js\"\n\nexport class DiscoveryError extends Error {\n readonly serverUrl: string\n constructor(message: string, serverUrl: string) {\n super(`DiscoveryError (${serverUrl}): ${message}`)\n this.name = \"DiscoveryError\"\n this.serverUrl = serverUrl\n }\n}\n\n// Discovery JSON is server-controlled, so it's validated rather than asserted.\n// Everything is optional + `.loose()`: the document evolves, and the required\n// fields are enforced explicitly below with precise DiscoveryError messages.\nconst prmSchema = z\n .object({\n resource: z.string().optional(),\n resource_name: z.string().optional(),\n authorization_servers: z.array(z.string()).optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n })\n .loose()\n\nconst asMetaSchema = z\n .object({\n issuer: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n device_authorization_endpoint: z.string().optional(),\n grant_types_supported: z.array(z.string()).optional(),\n agent_auth: z\n .object({\n skill: z.string().optional(),\n identity_endpoint: z.string().optional(),\n claim_endpoint: z.string().optional(),\n events_endpoint: z.string().optional(),\n identity_types_supported: z.array(z.string()).optional(),\n identity_assertion: z\n .object({ assertion_types_supported: z.array(z.string()).optional() })\n .loose()\n .optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n\nconst hostJsonSchema = z\n .object({\n device_authorization_endpoint: z.string().optional(),\n token_endpoint: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n })\n .loose()\n\ntype PRMShape = z.infer<typeof prmSchema>\ntype ASMetaShape = z.infer<typeof asMetaSchema>\ntype HostJsonShape = z.infer<typeof hostJsonSchema>\n\nexport interface DiscoverOptions {\n /** Abort the discovery fetches (e.g. on user Ctrl-C). */\n signal?: AbortSignal\n /** Per-hop timeout. Defaults to DEFAULT_HTTP_TIMEOUT_MS. */\n timeoutMs?: number\n}\n\nasync function discoverViaPRM(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n // Hop 1 — PRM\n const prmUrl = `${base}/.well-known/oauth-protected-resource`\n let prm: PRMShape\n try {\n assertSecureUrl(prmUrl)\n const res = await fetchWithDeadline(prmUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `PRM returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n prm = prmSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`PRM fetch failed: ${err}`, base)\n }\n\n const authServerBase = prm.authorization_servers?.[0]?.replace(/\\/$/, \"\")\n if (!authServerBase) {\n throw new DiscoveryError(\n \"PRM missing authorization_servers[0]\",\n base,\n )\n }\n\n // Hop 2 — AS metadata\n const asUrl = `${authServerBase}/.well-known/oauth-authorization-server`\n let as: ASMetaShape\n try {\n assertSecureUrl(asUrl)\n const res = await fetchWithDeadline(asUrl, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `AS metadata returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n as = asMetaSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`AS metadata fetch failed: ${err}`, base)\n }\n\n const tokenEndpoint = as.token_endpoint\n const identityEndpoint = as.agent_auth?.identity_endpoint\n if (!tokenEndpoint) {\n throw new DiscoveryError(\"AS metadata missing token_endpoint\", base)\n }\n if (!identityEndpoint) {\n throw new DiscoveryError(\n \"AS metadata missing agent_auth.identity_endpoint\",\n base,\n )\n }\n\n return {\n resource: prm.resource ?? base,\n resourceName: prm.resource_name,\n authServerBase,\n tokenEndpoint,\n revocationEndpoint: as.revocation_endpoint,\n identityEndpoint,\n claimEndpoint: as.agent_auth?.claim_endpoint,\n deviceAuthorizationEndpoint: as.device_authorization_endpoint,\n identityTypesSupported: as.agent_auth?.identity_types_supported ?? [],\n grantTypesSupported: as.grant_types_supported ?? [],\n }\n}\n\nasync function discoverViaHostJson(\n base: string,\n fetchOpts: RequestInit,\n opts: DiscoverOptions,\n): Promise<DiscoveredEndpoints> {\n const url = `${base}/.well-known/agentproto-host.json`\n let doc: HostJsonShape\n try {\n assertSecureUrl(url)\n const res = await fetchWithDeadline(url, fetchOpts, opts.timeoutMs)\n if (!res.ok) {\n throw new DiscoveryError(\n `agentproto-host.json returned ${res.status} ${res.statusText}`,\n base,\n )\n }\n doc = hostJsonSchema.parse(await res.json())\n } catch (err) {\n if (err instanceof DiscoveryError) throw err\n throw new DiscoveryError(`agentproto-host.json fetch failed: ${err}`, base)\n }\n\n if (!doc.token_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing token_endpoint\",\n base,\n )\n }\n if (!doc.device_authorization_endpoint) {\n throw new DiscoveryError(\n \"agentproto-host.json missing device_authorization_endpoint\",\n base,\n )\n }\n\n return {\n resource: base,\n authServerBase: base,\n tokenEndpoint: doc.token_endpoint,\n revocationEndpoint: doc.revocation_endpoint,\n deviceAuthorizationEndpoint: doc.device_authorization_endpoint,\n identityTypesSupported: [],\n grantTypesSupported: [],\n }\n}\n\nexport async function discoverEndpoints(\n apiBase: string,\n opts: DiscoverOptions = {},\n): Promise<DiscoveredEndpoints> {\n const base = apiBase.replace(/\\/$/, \"\")\n // AIP-50 §Security: HTTPS only (loopback exempt for dev), and never follow\n // redirects on discovery — a 3xx is treated as a failure, not chased to a\n // potentially-rogue endpoint.\n const fetchOpts: RequestInit = {\n signal: opts.signal,\n redirect: \"manual\",\n }\n\n try {\n return await discoverViaPRM(base, fetchOpts, opts)\n } catch (prmErr) {\n // A caller-initiated abort is terminal — don't fire a second round of\n // requests on a signal that has already aborted (its \"abort\" event has\n // already fired once and a fresh listener on it will never see it again,\n // hanging the fallback forever).\n if (opts.signal?.aborted) throw prmErr\n // Second strategy: a host that doesn't speak the auth.md PRM chain may\n // still expose device-code endpoints via agentproto-host.json. If that\n // also fails, surface the ORIGINAL PRM error — it's almost always the\n // more informative one (host.json 404s are the common case).\n try {\n return await discoverViaHostJson(base, fetchOpts, opts)\n } catch {\n throw prmErr\n }\n }\n}\n","/**\n * Keychain helpers — read/write a token in the platform Keychain.\n *\n * Uses the macOS `security` CLI. On non-macOS hosts, callers should swap this\n * module for a platform-appropriate equivalent (libsecret on Linux, Credential\n * Manager on Windows).\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\n\nconst exec = promisify(execFile)\n\n/**\n * Guard the macOS-only backend. Without this, `readKeychainToken` would swallow\n * the missing-`security` error and return undefined on Linux/Windows — making a\n * stored credential look absent and re-prompting on every run — while\n * `writeKeychainToken` would throw an opaque ENOENT. Fail loudly and clearly\n * instead, until a libsecret / Credential Manager backend exists.\n */\nfunction assertKeychainSupported(): void {\n if (process.platform !== \"darwin\") {\n throw new Error(\n `@agentproto/auth token-store: the Keychain backend only supports macOS ` +\n `(got platform \"${process.platform}\"). Provide a libsecret (Linux) or ` +\n `Credential Manager (Windows) implementation to run here.`,\n )\n }\n}\n\n/** Substitute `{server}` template in a tokenStore account spec. */\nexport function resolveAccount(\n account: string | undefined,\n server: string,\n): string {\n if (!account) return server\n return account.replace(\"{server}\", server)\n}\n\n/** Read a token from the Keychain. Returns undefined if not found. */\nexport async function readKeychainToken(\n service: string,\n account: string,\n): Promise<string | undefined> {\n assertKeychainSupported()\n try {\n const { stdout } = await exec(\"security\", [\n \"find-generic-password\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n ])\n const t = stdout.replace(/\\n$/, \"\")\n return t || undefined\n } catch {\n return undefined\n }\n}\n\n/** Write a token to the Keychain (-U updates in place). */\nexport async function writeKeychainToken(\n service: string,\n account: string,\n token: string,\n): Promise<void> {\n assertKeychainSupported()\n await exec(\"security\", [\n \"add-generic-password\",\n \"-U\",\n \"-s\",\n service,\n \"-a\",\n account,\n \"-w\",\n token,\n \"-D\",\n \"agentproto auth token\",\n ])\n}\n","/**\n * KeychainStore — `CredentialStore` backed by the platform Keychain.\n *\n * Wraps the low-level `token-store.ts` helpers (macOS `security` CLI today).\n * The Keychain only holds one opaque string per entry, so `kind`/`expiresAt`/\n * `metadata` are packed into a small JSON envelope that IS that string.\n *\n * Back-compat: an entry written before this store existed (or by any other\n * tool) is a bare token string, not an envelope. `read` falls back to\n * treating the whole string as the value with kind `\"pat\"` — the only flow\n * that pre-dates this store — rather than failing on non-JSON content.\n */\n\nimport { z } from \"zod\"\nimport { readKeychainToken, writeKeychainToken } from \"../token-store.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst envelopeSchema = z.object({\n v: z.string(),\n k: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n e: z.string().optional(),\n m: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport class KeychainStore implements CredentialStore {\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const account = ref.account ?? ref.path\n const raw = await readKeychainToken(ref.path, account)\n if (raw === undefined) return undefined\n\n try {\n const envelope = envelopeSchema.parse(JSON.parse(raw))\n return {\n value: envelope.v,\n kind: envelope.k,\n ...(envelope.e !== undefined ? { expiresAt: envelope.e } : {}),\n ...(envelope.m !== undefined ? { metadata: envelope.m } : {}),\n }\n } catch {\n return { value: raw, kind: \"pat\" }\n }\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const account = ref.account ?? ref.path\n const envelope: z.infer<typeof envelopeSchema> = {\n v: cred.value,\n k: cred.kind,\n ...(cred.expiresAt !== undefined ? { e: cred.expiresAt } : {}),\n ...(cred.metadata !== undefined ? { m: cred.metadata } : {}),\n }\n await writeKeychainToken(ref.path, account, JSON.stringify(envelope))\n }\n}\n","/**\n * Map a provider's `TokenStoreSpec` to a backend-agnostic `StoreRef`.\n *\n * Shared by every flow engine so the `path`/`keychain` back-compat alias and\n * the `{server}` account template are resolved identically everywhere.\n */\n\nimport { resolveAccount } from \"../token-store.js\"\nimport type { TokenStoreSpec } from \"../types.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\n/** When `audience` is declared, it's folded into the physical store key —\n * `${audience}:${path}` — so credentials scoped to different audiences\n * (e.g. \"tunnel\" vs \"api\") never collide under the same slot. Absent\n * `audience` = today's unprefixed path, unchanged. */\nexport function resolveStoreRef(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): StoreRef {\n const path = spec.path ?? spec.keychain\n return {\n path: audience ? `${audience}:${path}` : path,\n account: resolveAccount(spec.account, server),\n }\n}\n\n/** Derive both the audience-prefixed `ref` and the unprefixed `legacyRef` in\n * one call — the pair every flow engine and the broker need for the\n * audience back-compat read (`readStoreRefWithFallback`). When no audience\n * is declared, `legacyRef === ref` (same object), matching `resolveStoreRef`\n * called with `audience` undefined. */\nexport function resolveStoreRefs(\n spec: TokenStoreSpec,\n server: string,\n audience?: string,\n): { ref: StoreRef; legacyRef: StoreRef } {\n const ref = resolveStoreRef(spec, server, audience)\n const legacyRef = audience ? resolveStoreRef(spec, server) : ref\n return { ref, legacyRef }\n}\n\n/**\n * Read through `ref`, falling back once to `legacyRef` on a miss.\n *\n * This is the read half of the audience back-compat rule: a write always\n * targets the audience-prefixed ref, but a credential written before the\n * provider adopted an audience still lives at the unprefixed (legacy) path.\n * Rather than duplicate that fallback at every flow-engine/broker read site,\n * it lives here, next to `resolveStoreRef` — the one place that already\n * knows how prefixed vs. legacy refs are derived. Callers that don't declare\n * an audience pass `ref === legacyRef` (or just call `store.read` directly);\n * this only does extra work when the two refs actually differ.\n */\nexport async function readStoreRefWithFallback(\n store: CredentialStore,\n ref: StoreRef,\n legacyRef: StoreRef,\n): Promise<StoredCredential | undefined> {\n const stored = await store.read(ref)\n if (stored) return stored\n if (ref.path === legacyRef.path && ref.account === legacyRef.account) {\n return undefined\n }\n return store.read(legacyRef)\n}\n","/**\n * PAT flow engine — reads an existing token from the Keychain or prompts for one.\n *\n * This is the \"legacy-compatible\" flow: the user has a personal API key\n * (`gld_*`, `sk-*`, …) and the CLI needs to store/retrieve it. No browser\n * open, no ceremony. Use `service-auth` for the seamless browser-approve path.\n */\n\nimport { createInterface } from \"node:readline\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\n\n/**\n * Read a secret from the terminal WITHOUT echoing it — the typed key must not\n * land on screen or in scrollback. On a TTY we drop to raw mode and render a `*`\n * mask per character. When stdin isn't a TTY (piped input, CI, tests) there's no\n * echo to suppress and no raw mode to enter, so we read a line normally.\n */\nasync function promptToken(label: string): Promise<string> {\n const input = process.stdin\n const out = process.stderr\n\n if (!input.isTTY) {\n return new Promise((resolve) => {\n const rl = createInterface({ input, output: out })\n out.write(`${label}: `)\n rl.question(\"\", (answer) => {\n rl.close()\n resolve(answer.trim())\n })\n })\n }\n\n return new Promise((resolve, reject) => {\n out.write(`${label}: `)\n const chars: string[] = []\n input.setRawMode(true)\n input.resume()\n input.setEncoding(\"utf8\")\n\n const cleanup = () => {\n input.setRawMode(false)\n input.pause()\n input.removeListener(\"data\", onData)\n }\n\n const onData = (chunk: string) => {\n for (const ch of chunk) {\n switch (ch) {\n case \"\\r\":\n case \"\\n\":\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u0003\": // Ctrl-C\n out.write(\"\\n\")\n cleanup()\n reject(new Error(\"auth cancelled\"))\n return\n case \"\\u0004\": // Ctrl-D — treat as end-of-input\n out.write(\"\\n\")\n cleanup()\n resolve(chars.join(\"\").trim())\n return\n case \"\\u007f\": // Backspace / Delete\n case \"\\b\":\n if (chars.length > 0) {\n chars.pop()\n out.write(\"\\b \\b\")\n }\n break\n default:\n // Mask printable input; ignore stray control characters.\n if (ch >= \" \") {\n chars.push(ch)\n out.write(\"*\")\n }\n }\n }\n }\n\n input.on(\"data\", onData)\n })\n}\n\nexport const patFlowEngine: FlowEngine = {\n id: \"pat\",\n\n async run(\n provider: AuthProviderHandle,\n _discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"pat\") {\n throw new Error(`patFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n auth.tokenStore,\n opts.server,\n provider.audience,\n )\n\n if (!opts.force) {\n const existing = await readStoreRefWithFallback(store, ref, legacyRef)\n if (existing) {\n return { accessToken: existing.value, tokenKind: \"pat\" }\n }\n }\n\n const token = await promptToken(`${provider.id} personal access token`)\n if (!token) throw new Error(\"no token provided\")\n\n await store.write(ref, { value: token, kind: \"pat\" })\n\n return { accessToken: token, tokenKind: \"pat\" }\n },\n}\n","/**\n * Shared RFC 8628 device-grant polling primitive (internal, not exported from\n * the package root).\n *\n * Both the auth.md claim ceremony (`service-auth.ts`) and the device-code flow\n * poll an OAuth token endpoint with a grant-specific URN until the AS reports\n * success or a terminal error. This module holds that shared poll loop plus\n * the small HTTP/browser helpers both flows need — lifted verbatim from\n * `service-auth.ts` so new flow engines have somewhere to reuse them from.\n */\n\nimport { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\nimport { z } from \"zod\"\nimport { fetchWithDeadline } from \"../http.js\"\n\nconst execAsync = promisify(execFile)\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n\n/** Successful token/refresh/exchange response — the AS minted a credential. */\nexport const tokenSuccessSchema = z\n .object({\n access_token: z.string(),\n token_type: z.string().optional(),\n refresh_token: z.string().optional(),\n identity_assertion: z.string().optional(),\n assertion_expires_in: z.number().optional(),\n assertion_expires: z.string().optional(),\n // device-code flow fields (ignored by service-auth today; see WP-2).\n expires_in: z.number().optional(),\n scope: z.string().optional(),\n subject: z.string().optional(),\n revocation_id: z.string().optional(),\n })\n .loose()\n\n/** OAuth error response (`authorization_pending`, `slow_down`, `access_denied`…). */\nexport const tokenErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional(),\n })\n .loose()\n\n/** A token endpoint reply is either a minted credential or an OAuth error.\n * Success is tried first so a body carrying an access_token never matches the\n * error arm. */\nexport const tokenResponseSchema = z.union([tokenSuccessSchema, tokenErrorSchema])\n\nexport type TokenSuccess = z.infer<typeof tokenSuccessSchema>\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nexport async function openBrowser(url: string): Promise<void> {\n const [cmd, args]: [string, string[]] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? [\"cmd\", [\"/c\", \"start\", url]]\n : [\"xdg-open\", [url]]\n try {\n await execAsync(cmd, args)\n } catch {\n // best-effort — URL already printed to stderr\n }\n}\n\n// NOTE: deliberately does NOT check res.ok — the OAuth device/claim flow returns\n// HTTP 400 with a JSON `{ error }` body for authorization_pending / slow_down,\n// which the poll loop reads as data. Throwing on non-2xx would break polling.\nexport async function postFormOAuth<T>(\n url: string,\n params: Record<string, string>,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n return schema.parse(await res.json())\n}\n\nexport interface DeviceGrantPollOptions {\n /** Token endpoint URL to poll. */\n tokenEndpoint: string\n /** Grant-type URN sent on every poll (e.g. the claim or device_code grant). */\n grantType: string\n /** Token-carrying form params — e.g. `claim_token`/`device_code` plus\n * `client_id`. `grant_type` is added automatically; do not include it here. */\n params: Record<string, string>\n /** Poll interval in seconds; grows by 5s on each `slow_down`. */\n intervalS: number\n /** Approval window in seconds, measured from when polling starts. */\n expiresIn: number\n signal?: AbortSignal\n}\n\n/** RFC 8628 poll loop shared by every grant that polls a token endpoint for\n * user approval (auth.md claim ceremony, device-code). */\nexport async function pollDeviceGrant(\n o: DeviceGrantPollOptions,\n): Promise<TokenSuccess> {\n const deadline = Date.now() + o.expiresIn * 1_000\n let pollMs = o.intervalS * 1_000\n\n while (Date.now() < deadline) {\n if (o.signal?.aborted) throw new Error(\"auth cancelled\")\n await new Promise<void>((r) => setTimeout(r, pollMs))\n\n const data = await postFormOAuth(\n o.tokenEndpoint,\n { grant_type: o.grantType, ...o.params },\n tokenResponseSchema,\n o.signal,\n )\n\n if (!(\"error\" in data)) return data\n\n const pollErr = data.error\n if (pollErr === \"authorization_pending\") continue\n if (pollErr === \"slow_down\") {\n pollMs += 5_000\n continue\n }\n if (pollErr === \"expired_token\") {\n throw new Error(\"auth timeout — claim expired before user approved\")\n }\n if (pollErr === \"access_denied\") {\n throw new Error(\"access denied — user rejected the authorisation request\")\n }\n\n const desc = data.error_description\n throw new Error(`token endpoint error: ${pollErr}${desc ? ` — ${desc}` : \"\"}`)\n }\n\n throw new Error(\"auth timeout — approval window closed\")\n}\n","/**\n * service-auth flow engine — auth.md claim ceremony.\n *\n * Protocol:\n * POST /agent/identity { type:\"service_auth\" }\n * → registration_id + claim_token + user_code + verification_uri\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:workos:agent-auth:grant-type:claim\n * until approved / denied / expired.\n * On success: store the identity_assertion JWT (AIP-50 §Token storage —\n * the assertion is the durable credential; the access_token MUST NOT be\n * persisted, and the claim_token stays in memory only).\n *\n * Subsequent runs skip the ceremony: the stored assertion is exchanged via the\n * jwt-bearer grant for a fresh access_token (\"this IS the refresh path\" — no\n * refresh_token). Only when the assertion is expired/rejected does a new\n * ceremony start.\n *\n * See: https://github.com/workos/auth.md / AIP-50\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst CLAIM_GRANT_TYPE = \"urn:workos:agent-auth:grant-type:claim\"\nconst JWT_BEARER_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:jwt-bearer\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n// ── response schemas ──────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so every\n// response is validated with Zod rather than asserted. `.loose()` keeps unknown\n// fields the spec may add. The inferred types feed the rest of the engine.\n// (Token success/error schemas live in device-grant.ts, shared with every flow\n// that polls a token endpoint.)\n\nconst identityResponseSchema = z\n .object({\n registration_id: z.string(),\n claim_token: z.string(),\n claim: z\n .object({\n user_code: z.string(),\n verification_uri: z.string(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postJson<T>(\n url: string,\n body: unknown,\n schema: z.ZodType<T>,\n signal?: AbortSignal,\n): Promise<T> {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return schema.parse(await res.json())\n}\n\n// ── Identity-assertion exchange (jwt-bearer, RFC 7523) ────────────────────────\n//\n// The stored credential IS the identity_assertion JWT. Exchange it at the token\n// endpoint for a fresh, short-lived access token — the AIP-50 refresh path, with\n// no refresh_token involved. Returns null on any error (expired / invalid_grant\n// / server doesn't support the grant) so the caller falls back to a ceremony.\nasync function exchangeAssertion(\n tokenEndpoint: string,\n assertion: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: JWT_BEARER_GRANT_TYPE,\n assertion,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const serviceAuthFlowEngine: FlowEngine = {\n id: \"service-auth\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"service-auth\") {\n throw new Error(`serviceAuthFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"service-auth\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to ServiceAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions\n const identityEndpoint =\n discovered?.identityEndpoint ?? `${server}/agent/identity`\n const tokenEndpoint =\n discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(identityEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Cached path — the stored credential IS the identity_assertion JWT (AIP-50:\n // never the access token, never a refresh token). Exchange it via jwt-bearer\n // for a fresh access token; on failure (expired / invalid_grant) fall through\n // to a full browser ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n const exchanged = await exchangeAssertion(\n tokenEndpoint,\n stored.value,\n clientId,\n opts.signal,\n )\n if (exchanged) {\n // If the server rotated the assertion, persist the new one; otherwise\n // the existing assertion stays valid for the next exchange.\n if (exchanged.identity_assertion) {\n await store.write(ref, {\n value: exchanged.identity_assertion,\n kind: \"assertion\",\n })\n }\n return {\n accessToken: exchanged.access_token,\n ...(exchanged.identity_assertion\n ? { identityAssertion: exchanged.identity_assertion }\n : {}),\n tokenKind: \"oat\",\n }\n }\n }\n }\n\n // 1 — POST /agent/identity to start the claim ceremony\n const identity = await postJson(\n identityEndpoint,\n {\n type: \"service_auth\",\n client_id: clientId,\n ...(config.loginHint ? { login_hint: config.loginHint } : {}),\n },\n identityResponseSchema,\n opts.signal,\n )\n\n const { claim_token, claim } = identity\n const intervalS = claim.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(claim.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${claim.user_code}\\n`)\n process.stderr.write(` URL: ${claim.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(claim.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: CLAIM_GRANT_TYPE,\n params: { claim_token, client_id: clientId },\n intervalS,\n expiresIn: claim.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Store the identity_assertion as the durable credential (AIP-50: the\n // access_token is ephemeral and MUST NOT be persisted; the claim_token\n // was held in memory only). The assertion is re-exchanged via jwt-bearer\n // on the next run.\n const accessToken = tokenResult.access_token\n const assertion = tokenResult.identity_assertion\n\n // Resolve assertion expiry as ISO 8601\n let assertionExpires: string | undefined\n if (tokenResult.assertion_expires) {\n assertionExpires = tokenResult.assertion_expires\n } else if (tokenResult.assertion_expires_in) {\n assertionExpires = new Date(\n Date.now() + tokenResult.assertion_expires_in * 1_000,\n ).toISOString()\n }\n\n if (assertion) {\n await store.write(ref, {\n value: assertion,\n kind: \"assertion\",\n ...(assertionExpires ? { expiresAt: assertionExpires } : {}),\n })\n }\n\n return {\n accessToken,\n identityAssertion: assertion,\n assertionExpires,\n tokenKind: \"oat\",\n }\n },\n}\n","/**\n * device-code flow engine — plain RFC 8628 device-authorization ceremony.\n *\n * Protocol:\n * POST {device_authorization_endpoint} { client_id, scope?, device_label? }\n * → device_code + user_code + verification_uri(_complete) + expires_in\n * User approves at verification_uri in browser.\n * Poll POST {token_endpoint} with grant_type=urn:ietf:params:oauth:grant-type:device_code\n * until approved / denied / expired.\n * On success: store the access_token as the durable credential (kind:\"daemon\")\n * — unlike service-auth, the access token IS the thing that's persisted;\n * refresh_token/scope/subject/revocation_id ride in `metadata`.\n *\n * Subsequent runs: a fresh stored credential (or one with no expiry) short-\n * circuits the ceremony. An expired credential with a stored refresh_token is\n * exchanged via `grant_type=refresh_token`; on failure (or when no\n * refresh_token was stored) a new ceremony starts.\n */\n\nimport { z } from \"zod\"\nimport type {\n FlowEngine,\n FlowRunOptions,\n FlowResult,\n AuthProviderHandle,\n DiscoveredEndpoints,\n} from \"../types.js\"\nimport { KeychainStore } from \"../store/keychain-store.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"../store/resolve-ref.js\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"../store/types.js\"\nimport { fetchWithDeadline, assertSecureUrl } from \"../http.js\"\nimport {\n openBrowser,\n postFormOAuth,\n pollDeviceGrant,\n tokenResponseSchema,\n type TokenSuccess,\n} from \"./device-grant.js\"\n\nconst DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\"\nconst REFRESH_GRANT_TYPE = \"refresh_token\"\nconst DEFAULT_POLL_INTERVAL_S = 5\n\n/** Thrown by the device-code engine when `opts.refreshOnly` is set and no\n * fresh or refreshable credential is available — the only remaining path\n * would be an interactive ceremony, which `refreshOnly` callers explicitly\n * opt out of. Callers (e.g. `serve` boot on a headless host) catch this to\n * fall back to their own non-interactive behavior instead of hanging. */\nexport class CeremonyRequiredError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"CeremonyRequiredError\"\n }\n}\n\n// ── response schema ───────────────────────────────────────────────────────────\n//\n// JSON crosses a trust boundary here (the AS controls the bytes), so the\n// response is validated with Zod rather than asserted. `.loose()` keeps\n// unknown fields the spec may add.\n\nconst deviceAuthorizationResponseSchema = z\n .object({\n device_code: z.string(),\n user_code: z.string(),\n verification_uri: z.string(),\n verification_uri_complete: z.string().optional(),\n expires_in: z.number(),\n interval: z.number().optional(),\n })\n .loose()\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nasync function postDeviceAuthorization(\n url: string,\n params: Record<string, string>,\n signal?: AbortSignal,\n) {\n const res = await fetchWithDeadline(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n signal,\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`POST ${url} → ${res.status}: ${text}`)\n }\n return deviceAuthorizationResponseSchema.parse(await res.json())\n}\n\n/** Read a string metadata field without an `as` cast — `metadata` is\n * `Record<string, unknown>`, so every read is a runtime type check. */\nfunction metaString(\n metadata: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const v = metadata?.[key]\n return typeof v === \"string\" ? v : undefined\n}\n\nfunction isExpired(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return false\n const t = Date.parse(cred.expiresAt)\n if (Number.isNaN(t)) return true\n return t <= Date.now()\n}\n\nfunction resultFromStored(cred: StoredCredential): FlowResult {\n const refreshToken = metaString(cred.metadata, \"refreshToken\")\n const scope = metaString(cred.metadata, \"scope\")\n const subject = metaString(cred.metadata, \"subject\")\n const revocationId = metaString(cred.metadata, \"revocationId\")\n return {\n accessToken: cred.value,\n tokenKind: \"daemon\",\n ...(refreshToken ? { refreshToken } : {}),\n ...(scope ? { scope } : {}),\n ...(subject ? { subject } : {}),\n ...(revocationId ? { revocationId } : {}),\n }\n}\n\n/** Refresh via `grant_type=refresh_token`. Returns null on any error\n * (expired / invalid_grant / server doesn't support the grant) so the\n * caller falls back to a full ceremony. */\nasync function refreshAccessToken(\n tokenEndpoint: string,\n refreshToken: string,\n clientId: string,\n signal?: AbortSignal,\n): Promise<TokenSuccess | null> {\n try {\n const data = await postFormOAuth(\n tokenEndpoint,\n {\n grant_type: REFRESH_GRANT_TYPE,\n refresh_token: refreshToken,\n client_id: clientId,\n },\n tokenResponseSchema,\n signal,\n )\n if (\"error\" in data) return null\n return data\n } catch {\n return null\n }\n}\n\nasync function persistAndResult(\n store: CredentialStore,\n ref: StoreRef,\n o: {\n accessToken: string\n expiresIn?: number\n refreshToken?: string\n scope?: string\n subject?: string\n deviceLabel?: string\n revocationId?: string\n },\n): Promise<FlowResult> {\n const expiresAt = o.expiresIn\n ? new Date(Date.now() + o.expiresIn * 1_000).toISOString()\n : undefined\n\n const metadata: Record<string, unknown> = {\n obtainedAt: new Date().toISOString(),\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.deviceLabel ? { deviceLabel: o.deviceLabel } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n\n await store.write(ref, {\n value: o.accessToken,\n kind: \"daemon\",\n ...(expiresAt ? { expiresAt } : {}),\n metadata,\n })\n\n return {\n accessToken: o.accessToken,\n tokenKind: \"daemon\",\n ...(o.refreshToken ? { refreshToken: o.refreshToken } : {}),\n ...(o.scope ? { scope: o.scope } : {}),\n ...(o.subject ? { subject: o.subject } : {}),\n ...(o.revocationId ? { revocationId: o.revocationId } : {}),\n }\n}\n\n// ── engine ───────────────────────────────────────────────────────────────────\n\nexport const deviceCodeFlowEngine: FlowEngine = {\n id: \"device-code\",\n\n async run(\n provider: AuthProviderHandle,\n discovered: DiscoveredEndpoints | null,\n opts: FlowRunOptions,\n ): Promise<FlowResult> {\n const { auth } = provider\n if (auth.flow !== \"device-code\") {\n throw new Error(`deviceCodeFlowEngine: invoked with flow=\"${auth.flow}\"`)\n }\n // `auth.flow === \"device-code\"` is guaranteed by the guard above, so the\n // discriminated union has already narrowed `auth` to DeviceCodeAuthConfig.\n const config = auth\n const clientId = config.clientId ?? \"agentproto-cli\"\n const server = opts.server.replace(/\\/$/, \"\")\n\n // Endpoint resolution — prefer live discovery, fall back to conventions.\n const deviceAuthorizationEndpoint =\n discovered?.deviceAuthorizationEndpoint ?? `${server}/oauth/device`\n const tokenEndpoint = discovered?.tokenEndpoint ?? `${server}/oauth/token`\n\n // AIP-50 §Security: auth requests MUST use HTTPS (loopback exempt for dev).\n assertSecureUrl(deviceAuthorizationEndpoint)\n assertSecureUrl(tokenEndpoint)\n\n const store = opts.store ?? new KeychainStore()\n const { ref, legacyRef } = resolveStoreRefs(\n config.tokenStore,\n server,\n provider.audience,\n )\n\n // Shared by both the ordinary cached path and `refreshOnly`: exchange a\n // stored refresh_token for a fresh access token, persisting the result.\n // Returns null (never throws) on a missing refresh_token or any grant\n // failure, so both callers can decide what to do next.\n async function tryRefresh(stored: StoredCredential): Promise<FlowResult | null> {\n const refreshToken = metaString(stored.metadata, \"refreshToken\")\n if (!refreshToken) return null\n const refreshed = await refreshAccessToken(\n tokenEndpoint,\n refreshToken,\n clientId,\n opts.signal,\n )\n if (!refreshed) return null\n return persistAndResult(store, ref, {\n accessToken: refreshed.access_token,\n expiresIn: refreshed.expires_in,\n refreshToken: refreshed.refresh_token ?? refreshToken,\n scope: refreshed.scope ?? metaString(stored.metadata, \"scope\"),\n subject: refreshed.subject ?? metaString(stored.metadata, \"subject\"),\n deviceLabel:\n config.deviceLabel ?? metaString(stored.metadata, \"deviceLabel\"),\n revocationId:\n refreshed.revocation_id ?? metaString(stored.metadata, \"revocationId\"),\n })\n }\n\n // `refreshOnly` — attempt only the cached/refresh path, never the\n // interactive ceremony. Distinct from the ordinary cached path below so\n // a refresh failure here throws instead of falling through.\n if (opts.refreshOnly) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n }\n throw new CeremonyRequiredError(\n `${provider.id}: no fresh or refreshable device-code credential — an interactive ceremony would be required, but refreshOnly was set`,\n )\n }\n\n // Cached path — the stored credential IS the access token (pat-class\n // persistence). A fresh (or expiry-less) credential short-circuits the\n // ceremony entirely; an expired one with a refresh_token is renewed via\n // grant_type=refresh_token before falling back to a ceremony.\n if (!opts.force) {\n const stored = await readStoreRefWithFallback(store, ref, legacyRef)\n if (stored) {\n if (!isExpired(stored)) {\n return resultFromStored(stored)\n }\n const refreshed = await tryRefresh(stored)\n if (refreshed) return refreshed\n // refresh failed (expired / invalid_grant) — fall through to a ceremony\n }\n }\n\n // 1 — POST the device-authorization endpoint to start the ceremony\n const params: Record<string, string> = { client_id: clientId }\n if (config.scope) params.scope = config.scope\n if (config.deviceLabel) params.device_label = config.deviceLabel\n\n const authz = await postDeviceAuthorization(\n deviceAuthorizationEndpoint,\n params,\n opts.signal,\n )\n\n const intervalS = authz.interval ?? DEFAULT_POLL_INTERVAL_S\n const windowMin = Math.round(authz.expires_in / 60)\n\n // 2 — Print code + open browser\n process.stderr.write(`\\n`)\n process.stderr.write(` Approve ${provider.id} access in your browser\\n\\n`)\n process.stderr.write(` Code: ${authz.user_code}\\n`)\n process.stderr.write(` URL: ${authz.verification_uri}\\n\\n`)\n if (opts.openBrowser !== false) {\n await openBrowser(authz.verification_uri_complete ?? authz.verification_uri)\n }\n process.stderr.write(` Waiting for approval (${windowMin} min)…\\n\\n`)\n\n // 3 — Poll until approved / denied / expired\n const tokenResult = await pollDeviceGrant({\n tokenEndpoint,\n grantType: DEVICE_CODE_GRANT_TYPE,\n params: { device_code: authz.device_code, client_id: clientId },\n intervalS,\n expiresIn: authz.expires_in,\n signal: opts.signal,\n })\n\n // 4 — Persist the access token as the durable credential (pat-class).\n return persistAndResult(store, ref, {\n accessToken: tokenResult.access_token,\n expiresIn: tokenResult.expires_in,\n refreshToken: tokenResult.refresh_token,\n scope: tokenResult.scope,\n subject: tokenResult.subject,\n deviceLabel: config.deviceLabel,\n revocationId: tokenResult.revocation_id,\n })\n },\n}\n","/**\n * Flow engine registry — dispatch by `provider.auth.flow`.\n *\n * Add a new engine:\n * 1. Implement `FlowEngine` in a sibling file\n * 2. Add it here — no if/switch chains at call sites\n */\n\nimport type { FlowEngine } from \"../types.js\"\nimport { patFlowEngine } from \"./pat.js\"\nimport { serviceAuthFlowEngine } from \"./service-auth.js\"\nimport { deviceCodeFlowEngine } from \"./device-code.js\"\n\nexport const FLOW_ENGINES: Readonly<Record<string, FlowEngine>> = {\n [patFlowEngine.id]: patFlowEngine,\n [serviceAuthFlowEngine.id]: serviceAuthFlowEngine,\n [deviceCodeFlowEngine.id]: deviceCodeFlowEngine,\n}\n","/**\n * `runAuthFlow` — resolve provider → discover endpoints → dispatch to engine.\n *\n * Discovery is attempted silently; callers receive the result without knowing\n * whether live or static endpoint config was used. The flow engine receives\n * `null` for `discovered` if discovery failed or was not attempted.\n */\n\nimport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nimport { discoverEndpoints, DiscoveryError } from \"./discover.js\"\nimport type {\n AuthProviderHandle,\n DiscoveredEndpoints,\n FlowResult,\n FlowRunOptions,\n} from \"./types.js\"\n\nexport interface RunFlowOptions extends FlowRunOptions {\n /** Pre-resolved endpoints (skip discovery). Pass null to force re-discovery. */\n discovered?: DiscoveredEndpoints | null\n /** Suppress debug output. Default: false. */\n quiet?: boolean\n}\n\nexport async function runAuthFlow(\n provider: AuthProviderHandle,\n opts: RunFlowOptions,\n): Promise<FlowResult> {\n const flowId = provider.auth.flow\n const engine = FLOW_ENGINES[flowId]\n if (!engine) {\n throw new Error(\n `runAuthFlow: unknown flow \"${flowId}\" — registered: ${Object.keys(FLOW_ENGINES).join(\", \")}`,\n )\n }\n\n // Discovery: try unless caller already provided endpoints\n let discovered: DiscoveredEndpoints | null =\n opts.discovered !== undefined ? opts.discovered : null\n\n if (\n discovered === null &&\n (flowId === \"service-auth\" || flowId === \"device-code\")\n ) {\n try {\n discovered = await discoverEndpoints(opts.server, { signal: opts.signal })\n } catch (err) {\n if (!opts.quiet) {\n const msg =\n err instanceof DiscoveryError\n ? err.message\n : `discovery failed: ${err}`\n process.stderr.write(`[auth] ${msg} — using static config\\n`)\n }\n }\n }\n\n return engine.run(provider, discovered, opts)\n}\n","/**\n * MemoryStore — in-process `CredentialStore` backed by a `Map`.\n *\n * Ephemeral: gone when the process exits. Used for tests and short-lived\n * tooling that shouldn't touch a real backend.\n */\n\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path}\u0000${ref.account ?? ref.path}`\n}\n\nexport class MemoryStore implements CredentialStore {\n private readonly entries = new Map<string, StoredCredential>()\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const entry = this.entries.get(keyOf(ref))\n return entry ? { ...entry } : undefined\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n this.entries.set(keyOf(ref), { ...cred })\n }\n\n async delete(ref: StoreRef): Promise<void> {\n this.entries.delete(keyOf(ref))\n }\n}\n","/**\n * FileStore — encrypted-JSON-file `CredentialStore`.\n *\n * Every entry is sealed independently with AES-256-GCM under a key read from\n * `AGENTPROTO_STORE_KEY` (hex or base64, 32 raw bytes). There is no plaintext\n * fallback: a missing or malformed key throws rather than writing credentials\n * to disk in the clear.\n */\n\nimport {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from \"node:crypto\"\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { dirname } from \"node:path\"\nimport { z } from \"zod\"\nimport type { CredentialStore, StoreRef, StoredCredential } from \"./types.js\"\n\nconst ALGORITHM = \"aes-256-gcm\"\nconst KEY_ENV_VAR = \"AGENTPROTO_STORE_KEY\"\nconst IV_BYTES = 12\n\nconst sealedEntrySchema = z.object({\n iv: z.string(),\n tag: z.string(),\n ciphertext: z.string(),\n})\ntype SealedEntry = z.infer<typeof sealedEntrySchema>\n\nconst sealedFileSchema = z.record(z.string(), sealedEntrySchema)\n\nconst storedCredentialSchema = z.object({\n value: z.string(),\n kind: z.enum([\"pat\", \"assertion\", \"oat\", \"daemon\"]),\n expiresAt: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nfunction keyOf(ref: StoreRef): string {\n return `${ref.path} ${ref.account ?? ref.path}`\n}\n\nfunction isEnoent(err: unknown): boolean {\n return (\n typeof err === \"object\" &&\n err !== null &&\n \"code\" in err &&\n err.code === \"ENOENT\"\n )\n}\n\n/** Decode `AGENTPROTO_STORE_KEY` (hex or base64) into exactly 32 raw bytes. */\nfunction loadKey(): Buffer {\n const raw = process.env[KEY_ENV_VAR]\n if (!raw) {\n throw new Error(\n `FileStore: missing ${KEY_ENV_VAR} — set a 32-byte key (64 hex chars, ` +\n `or base64) to use the encrypted file store. Refusing to store ` +\n `credentials in plaintext.`,\n )\n }\n const key = /^[0-9a-fA-F]{64}$/.test(raw)\n ? Buffer.from(raw, \"hex\")\n : Buffer.from(raw, \"base64\")\n if (key.length !== 32) {\n throw new Error(\n `FileStore: ${KEY_ENV_VAR} must decode to exactly 32 bytes (got ` +\n `${key.length}). Provide a 64-char hex string or base64 encoding 32 bytes.`,\n )\n }\n return key\n}\n\nfunction seal(key: Buffer, plaintext: string): SealedEntry {\n const iv = randomBytes(IV_BYTES)\n const cipher = createCipheriv(ALGORITHM, key, iv)\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ])\n return {\n iv: iv.toString(\"base64\"),\n tag: cipher.getAuthTag().toString(\"base64\"),\n ciphertext: ciphertext.toString(\"base64\"),\n }\n}\n\nfunction unseal(key: Buffer, entry: SealedEntry): string {\n const decipher = createDecipheriv(\n ALGORITHM,\n key,\n Buffer.from(entry.iv, \"base64\"),\n )\n decipher.setAuthTag(Buffer.from(entry.tag, \"base64\"))\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(entry.ciphertext, \"base64\")),\n decipher.final(),\n ])\n return plaintext.toString(\"utf8\")\n}\n\nexport class FileStore implements CredentialStore {\n constructor(private readonly filePath: string) {}\n\n async read(ref: StoreRef): Promise<StoredCredential | undefined> {\n const key = loadKey()\n const file = await this.readFile()\n const sealed = file[keyOf(ref)]\n if (!sealed) return undefined\n return storedCredentialSchema.parse(JSON.parse(unseal(key, sealed)))\n }\n\n async write(ref: StoreRef, cred: StoredCredential): Promise<void> {\n const key = loadKey()\n const file = await this.readFile()\n file[keyOf(ref)] = seal(key, JSON.stringify(cred))\n await this.writeFile(file)\n }\n\n async delete(ref: StoreRef): Promise<void> {\n const file = await this.readFile()\n delete file[keyOf(ref)]\n await this.writeFile(file)\n }\n\n private async readFile(): Promise<Record<string, SealedEntry>> {\n try {\n const raw = await readFile(this.filePath, \"utf8\")\n return sealedFileSchema.parse(JSON.parse(raw))\n } catch (err) {\n if (isEnoent(err)) return {}\n throw err\n }\n }\n\n private async writeFile(file: Record<string, SealedEntry>): Promise<void> {\n await mkdir(dirname(this.filePath), { recursive: true })\n await writeFile(this.filePath, JSON.stringify(file, null, 2), \"utf8\")\n }\n}\n","/**\n * CredentialBroker — resolve ready-to-use auth headers for a `<providerId>`\n * or `<providerId>/<account>` path, auto-refreshing via the flow engine when\n * the stored credential is missing, expired, or not directly usable.\n *\n * Agent.pw-parity API: callers ask for headers by path and never touch\n * tokens, flows, or the underlying store directly.\n */\n\nimport { runAuthFlow } from \"./run-flow.js\"\nimport { resolveStoreRefs, readStoreRefWithFallback } from \"./store/resolve-ref.js\"\nimport type { CredentialStore, StoredCredential } from \"./store/types.js\"\nimport type { AuthProviderHandle } from \"./types.js\"\n\n/** Refresh this long before the actual expiry, so a credential that's about\n * to expire mid-request gets renewed proactively instead of failing. */\nconst EXPIRY_SKEW_MS = 60_000\n\nexport interface CredentialBrokerOptions {\n /** Backend to read cached credentials from and persist refreshed ones to. */\n store: CredentialStore\n /** Provider lookup — pass `getAuthProvider` from the registry, or a custom\n * resolver (e.g. scoped to a single host's providers). */\n getProvider: (id: string) => AuthProviderHandle | undefined\n}\n\ninterface ParsedPath {\n providerId: string\n account?: string\n}\n\n/** Split `\"<providerId>\"` or `\"<providerId>/<account>\"` on the first `/`. */\nfunction parsePath(path: string): ParsedPath {\n const slash = path.indexOf(\"/\")\n if (slash === -1) return { providerId: path }\n return { providerId: path.slice(0, slash), account: path.slice(slash + 1) }\n}\n\n/** `expiresAt` in the future (past the refresh skew), or absent entirely. A\n * malformed `expiresAt` is treated as expired — refresh rather than risk\n * serving a header that a downstream API will reject. */\nfunction isFresh(cred: StoredCredential): boolean {\n if (!cred.expiresAt) return true\n const expiresAtMs = Date.parse(cred.expiresAt)\n if (Number.isNaN(expiresAtMs)) return false\n return expiresAtMs - EXPIRY_SKEW_MS > Date.now()\n}\n\n/** Header map for a credential usable as a bearer token directly, or\n * `undefined` when it isn't. `assertion` is never bearer-usable — it must be\n * exchanged by a flow engine first — so it always falls through to\n * `runAuthFlow`. */\nfunction bearerHeaders(\n value: string,\n kind: StoredCredential[\"kind\"],\n): Record<string, string> | undefined {\n if (kind === \"pat\" || kind === \"oat\" || kind === \"daemon\") {\n return { Authorization: `Bearer ${value}` }\n }\n return undefined\n}\n\nexport class CredentialBroker {\n private readonly store: CredentialStore\n private readonly getProvider: (id: string) => AuthProviderHandle | undefined\n\n constructor(opts: CredentialBrokerOptions) {\n this.store = opts.store\n this.getProvider = opts.getProvider\n }\n\n async resolveHeaders(o: {\n path: string\n server?: string\n signal?: AbortSignal\n /** Audience the caller expects this credential to be scoped to. Checked\n * only when the resolved provider also declares one — see the mismatch\n * error below. Does not itself change which store key is read; the\n * provider's own `audience` (not the caller's) determines that. */\n audience?: string\n }): Promise<Record<string, string>> {\n const { providerId, account } = parsePath(o.path)\n const provider = this.getProvider(providerId)\n if (!provider) {\n throw new Error(`CredentialBroker: unknown auth provider \"${providerId}\"`)\n }\n\n if (\n o.audience !== undefined &&\n provider.audience !== undefined &&\n o.audience !== provider.audience\n ) {\n throw new Error(\n `CredentialBroker: provider \"${providerId}\" is scoped to audience \"${provider.audience}\", requested \"${o.audience}\"`,\n )\n }\n\n const server = o.server ?? provider.apiBase\n const { ref, legacyRef } = resolveStoreRefs(\n provider.auth.tokenStore,\n server,\n provider.audience,\n )\n if (account !== undefined) {\n ref.account = account\n legacyRef.account = account\n }\n\n const stored = await readStoreRefWithFallback(this.store, ref, legacyRef)\n if (stored && isFresh(stored)) {\n const headers = bearerHeaders(stored.value, stored.kind)\n if (headers) return headers\n }\n\n const result = await runAuthFlow(provider, {\n server,\n store: this.store,\n signal: o.signal,\n })\n const headers =\n result.accessToken !== undefined\n ? bearerHeaders(result.accessToken, result.tokenKind)\n : undefined\n if (!headers) {\n throw new Error(\n `CredentialBroker: auth flow for \"${providerId}\" produced no usable access token`,\n )\n }\n return headers\n }\n}\n","/**\n * Named auth-profile store — CRUD over `~/.agentproto/auth-profiles.json`\n * (mode 0600), generalizing `providers-store`'s single-key-per-provider file\n * (`packages/providers-store/src/index.ts:68-90`, `ProviderEntry`/\n * `ProvidersFile`) to N named `AuthProfile`s per vendor, keyed by `id`.\n *\n * This is the profile-metadata store, not the credential store: entries hold\n * `credentialRef` (a pointer), never a secret, so — unlike `FileStore`\n * (`store/file-store.ts`) — this file needs no encryption. Reuses the exact\n * persistence primitives `providers-store` already established (a versioned\n * JSON file under `~/.agentproto/`, `node:fs/promises`, mode 0600) rather\n * than inventing a new format, just relocated to `@agentproto/auth` — the\n * correct home for named profiles per SPEC §1c (`providers.json` is the\n * degenerate one-key-per-provider case this generalizes).\n */\n\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\nimport { z } from \"zod\"\nimport type { AuthMethod, AuthProfile } from \"./profile-types.js\"\n\nconst authMethodSchema = z.enum([\"oauth-bearer\", \"api-key\"]) satisfies z.ZodType<AuthMethod>\n\nconst authProfileSchema = z.object({\n id: z.string(),\n vendor: z.string(),\n method: authMethodSchema,\n credentialRef: z.string(),\n label: z.string().optional(),\n}) satisfies z.ZodType<AuthProfile>\n\nconst authProfilesFileSchema = z.object({\n version: z.literal(1),\n profiles: z.record(z.string(), authProfileSchema),\n})\n\nexport type AuthProfilesFile = z.infer<typeof authProfilesFileSchema>\n\n/** Fresh empty file each call — never share the `profiles` object, or a\n * later mutation leaks into every other load in-process (same defense\n * `providers-store`'s `emptyFile()` establishes). */\nfunction emptyFile(): AuthProfilesFile {\n return { version: 1, profiles: {} }\n}\n\nexport function authProfilesPath(): string {\n return resolve(homedir(), \".agentproto\", \"auth-profiles.json\")\n}\n\nexport async function loadAuthProfiles(): Promise<AuthProfilesFile> {\n try {\n const raw = await readFile(authProfilesPath(), \"utf8\")\n return authProfilesFileSchema.parse(JSON.parse(raw))\n } catch {\n return emptyFile() // ENOENT / malformed → empty\n }\n}\n\nasync function writeAuthProfiles(file: AuthProfilesFile): Promise<void> {\n const dir = join(homedir(), \".agentproto\")\n await mkdir(dir, { recursive: true })\n // mode 0600 so other local users can't read the profile metadata.\n await writeFile(authProfilesPath(), JSON.stringify(file, null, 2) + \"\\n\", {\n encoding: \"utf8\",\n mode: 0o600,\n })\n}\n\n/** List all profiles, optionally filtered to one vendor. */\nexport async function listAuthProfiles(vendor?: string): Promise<AuthProfile[]> {\n const file = await loadAuthProfiles()\n const all = Object.values(file.profiles)\n return vendor === undefined ? all : all.filter(p => p.vendor === vendor)\n}\n\n/** Look up a single profile by id, or undefined if none exists. */\nexport async function getAuthProfile(id: string): Promise<AuthProfile | undefined> {\n const file = await loadAuthProfiles()\n return file.profiles[id]\n}\n\n/** Add (or replace) a profile, keyed by its `id`. */\nexport async function addAuthProfile(profile: AuthProfile): Promise<void> {\n const file = await loadAuthProfiles()\n file.profiles[profile.id] = profile\n await writeAuthProfiles(file)\n}\n\n/** Remove a profile by id. Returns true if it existed. */\nexport async function removeAuthProfile(id: string): Promise<boolean> {\n const file = await loadAuthProfiles()\n if (!(id in file.profiles)) return false\n delete file.profiles[id]\n await writeAuthProfiles(file)\n return true\n}\n","/**\n * (adapter × route) → vendor resolution + the profile eligibility predicate\n * (SPEC §1c, `agentproto-session-config-axes/SPEC.md:102-125`).\n *\n * profile eligible for (adapter, route) iff\n * profile.vendor == resolveEndpoint(adapter, route).vendor\n * AND profile.method ∈ methodsPresentable(adapter, route)\n *\n * `route` is the endpoint selector (SPEC axis #4 — direct vs a gateway mode\n * like `moonshot`/`openrouter`), so access is deliberately downstream of it:\n * which vendor (and thus which profiles) are eligible changes when route\n * changes. `AdapterAuthManifest` is a narrow, package-local projection of\n * exactly what this predicate needs from an adapter's real AIP-45 manifest\n * (`packages/driver/agent-cli/src/types.ts`'s `AgentCliDefinition`) — this\n * package intentionally does not depend on `@agentproto/driver-agent-cli`\n * (wrong dependency direction; drivers consume auth, not vice versa), so the\n * runtime is the one that will later project a real manifest into this\n * shape (out of scope here — foundation only, no live spawn-path wiring).\n *\n * `methodsByRoute` is the static per-vendor method table ADR'd in SPEC §3.4:\n * \"which auth methods this adapter can present for a resolved route.\" It is\n * the derivable replacement for two hand-maintained artifacts SPEC §1c calls\n * out for eventual removal — the per-adapter `authSubscription` boolean\n * (`adapters/claude-code/src/index.ts:90-95`) and curatorial vendor deny\n * lists (`adapters/hermes/HERMES.md:40-42`) — neither of which this PR\n * touches; `authSubscription` stays exactly as-is (see the comment on it in\n * `spawn-defaults.ts:345` — this module is additive, not a replacement).\n *\n * ACP `authenticate` is NOT a live discovery source for this table (the\n * server handler is a stub, `packages/acp/src/server/index.ts:69`) — method\n * discovery is this static table, not runtime negotiation (SPEC §3.7).\n */\n\nimport type { AuthMethod, AuthProfile } from \"./profile-types.js\"\n\n/** A narrow, package-local projection of an adapter's declared auth\n * capability — enough to resolve (adapter, route) → vendor and the auth\n * methods presentable on that route. Not the real AIP-45 manifest type. */\nexport interface AdapterAuthManifest {\n /** Adapter id (e.g. \"claude-code\", \"hermes\"), for error messages only. */\n id: string\n /** route id (e.g. \"direct\", or a gateway mode id like \"moonshot\") →\n * the vendor billed when spawned on that route. */\n vendorByRoute: Readonly<Record<string, string>>\n /** route id → the auth methods this adapter can present when spawned on\n * that route — the method-side of the eligibility predicate. */\n methodsByRoute: Readonly<Record<string, readonly AuthMethod[]>>\n}\n\n/** Resolve which vendor a given (adapter, route) pair bills against. Throws\n * when the manifest declares no vendor for `route` — an unresolvable route\n * is a caller bug (a bad/unknown route id), not a \"no profiles eligible\"\n * case, so this fails loud rather than returning an empty vendor. */\nexport function resolveEndpoint(\n manifest: AdapterAuthManifest,\n route: string,\n): { vendor: string } {\n const vendor = manifest.vendorByRoute[route]\n if (vendor === undefined) {\n throw new Error(\n `resolveEndpoint: adapter \"${manifest.id}\" declares no vendor for route \"${route}\"`,\n )\n }\n return { vendor }\n}\n\n/** Which auth methods `manifest`'s adapter can present on `route`. Empty\n * (never throws) when the route is declared for vendor resolution but has\n * no methods table entry — that's \"no eligible profiles\", a legitimate\n * eligibility outcome, not an error. */\nexport function methodsPresentable(\n manifest: AdapterAuthManifest,\n route: string,\n): AuthMethod[] {\n return [...(manifest.methodsByRoute[route] ?? [])]\n}\n\n/** The eligibility predicate: profiles whose vendor matches the route's\n * resolved endpoint AND whose method the adapter can present on that\n * route. */\nexport function eligibleProfiles(\n profiles: readonly AuthProfile[],\n manifest: AdapterAuthManifest,\n route: string,\n): AuthProfile[] {\n const { vendor } = resolveEndpoint(manifest, route)\n const methods = methodsPresentable(manifest, route)\n return profiles.filter(p => p.vendor === vendor && methods.includes(p.method))\n}\n","/**\n * @agentproto/auth — AIP-50 AUTH.md reference implementation.\n *\n * Public API:\n * defineAuthProvider(def) — TS-literal authoring (frozen handle)\n * parseAuthProviderManifest(source) — .md authoring (gray-matter + Zod)\n * registerAuthProvider(handle) — extend the module-level registry\n * getAuthProvider(id) — lookup by vendor id\n * listAuthProviderIds() — enumerate known providers\n * discoverEndpoints(apiBase) — two-hop PRM → AS metadata discovery\n * runAuthFlow(provider, opts) — resolve + discover + dispatch to engine\n * FLOW_ENGINES — registered flow engines (pat, …)\n * CeremonyRequiredError — thrown by device-code's refreshOnly\n * mode when only an interactive\n * ceremony would satisfy the request\n * writeKeychainToken(svc, acct, t) — persist a credential to Keychain\n * readKeychainToken(svc, acct) — read a credential from Keychain\n * resolveAccount(acct, server) — expand {server} template\n * KeychainStore / MemoryStore / FileStore — built-in CredentialStore backends\n * resolveStoreRef(spec, server) — map a TokenStoreSpec to a StoreRef\n * CredentialBroker — path → ready-to-use auth headers\n * AuthProfile / AuthMethod — named, vendor-scoped credential ref\n * listAuthProfiles/getAuthProfile/\n * addAuthProfile/removeAuthProfile — named-profile store CRUD\n * resolveEndpoint/methodsPresentable/\n * eligibleProfiles — (adapter × route) → vendor + the\n * profile eligibility predicate\n */\n\nexport { defineAuthProvider } from \"./define-auth-provider.js\"\nexport {\n parseAuthProviderManifest,\n parseAuthProviderManifestRaw,\n type AuthProviderManifest,\n} from \"./manifest.js\"\nexport {\n registerAuthProvider,\n getAuthProvider,\n listAuthProviders,\n listAuthProviderIds,\n} from \"./registry.js\"\nexport {\n discoverEndpoints,\n DiscoveryError,\n} from \"./discover.js\"\nexport { runAuthFlow, type RunFlowOptions } from \"./run-flow.js\"\nexport { FLOW_ENGINES } from \"./flow-engines/index.js\"\nexport { CeremonyRequiredError } from \"./flow-engines/device-code.js\"\nexport {\n readKeychainToken,\n writeKeychainToken,\n resolveAccount,\n} from \"./token-store.js\"\nexport { KeychainStore } from \"./store/keychain-store.js\"\nexport { MemoryStore } from \"./store/memory-store.js\"\nexport { FileStore } from \"./store/file-store.js\"\nexport { resolveStoreRef } from \"./store/resolve-ref.js\"\nexport type {\n CredentialStore,\n StoreRef,\n StoredCredential,\n} from \"./store/types.js\"\nexport { CredentialBroker, type CredentialBrokerOptions } from \"./broker.js\"\nexport type { AuthMethod, AuthProfile } from \"./profile-types.js\"\nexport {\n authProfilesPath,\n loadAuthProfiles,\n listAuthProfiles,\n getAuthProfile,\n addAuthProfile,\n removeAuthProfile,\n type AuthProfilesFile,\n} from \"./profile-store.js\"\nexport {\n resolveEndpoint,\n methodsPresentable,\n eligibleProfiles,\n type AdapterAuthManifest,\n} from \"./eligibility.js\"\nexport { guildeAuthProvider, BUILTIN_AUTH_PROVIDERS } from \"./builtins.js\"\nexport {\n authProviderFrontmatterSchema,\n authConfigSchema,\n tokenStoreSpecSchema,\n installConfigSchema,\n type AuthProviderFrontmatter,\n} from \"./schema.js\"\nexport type {\n AuthProviderDefinition,\n AuthProviderHandle,\n AuthConfig,\n PATAuthConfig,\n ServiceAuthConfig,\n DeviceCodeAuthConfig,\n InstallConfig,\n TokenStoreSpec,\n FlowEngine,\n FlowId,\n FlowResult,\n FlowRunOptions,\n DiscoveredEndpoints,\n} from \"./types.js\"\n\nexport const SPEC_NAME = \"agentauth\"\nexport const SPEC_VERSION = \"v1\"\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/auth",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "@agentproto/auth — AIP-50 AUTH.md reference implementation. Auth-provider doctype: how CLI tools and agents authenticate to API servers via a standardized discovery chain and pluggable flow engines, aligned to the WorkOS auth.md open standard.",
5
5
  "keywords": [
6
6
  "agentproto",
@@ -19,7 +19,7 @@
19
19
  "bugs": {
20
20
  "url": "https://github.com/agentproto/ts/issues"
21
21
  },
22
- "license": "MIT",
22
+ "license": "Apache-2.0",
23
23
  "type": "module",
24
24
  "main": "dist/index.mjs",
25
25
  "module": "dist/index.mjs",
@@ -44,7 +44,7 @@
44
44
  "dependencies": {
45
45
  "gray-matter": "^4.0.3",
46
46
  "zod": "^4.4.3",
47
- "@agentproto/define-doctype": "0.1.0"
47
+ "@agentproto/define-doctype": "0.1.1"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/node": "^25.6.2",