@crewhaus/tool-objectstore 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/README.md CHANGED
@@ -21,12 +21,29 @@ That claim is not left to the reader. The test suite greps this package's own
21
21
  source for `node:http`, `node:net`, `node:fs`, a `fetch` call and the rest, so
22
22
  an edit that adds one fails a test rather than a review.
23
23
 
24
- It holds no credential either. The access key and secret arrive as arguments
25
- from whatever the caller uses for secrets, the secret is consumed by the
26
- signing-key derivation, and it appears in no result, no error and no stack
27
- trace — asserted on both the success and the failure path. The access key ID
28
- *is* in the URL: SigV4 puts it in `X-Amz-Credential` by construction, which is
29
- how the store knows which key to check against. That one is public by design.
24
+ It holds no credential either, and never takes one as an argument. The
25
+ operator names a credential profile in the spec — the environment variables
26
+ that hold the access key id, the secret and, for temporary credentials, the
27
+ session token — and a call picks the profile by name:
28
+
29
+ ```yaml
30
+ tool_config:
31
+ objectstore:
32
+ credentials:
33
+ r2:
34
+ access_key_id_env: R2_ACCESS_KEY_ID
35
+ secret_access_key_env: R2_SECRET_ACCESS_KEY
36
+ # session_token_env: AWS_SESSION_TOKEN # STS only
37
+ ```
38
+
39
+ Before 0.7.1 the secret and the session token were tool arguments, so they sat
40
+ in the model's context, the transcript and the session log. The secret is
41
+ consumed by the signing-key derivation and appears in no result, no error and
42
+ no stack trace — asserted on both the success and the failure path. The access
43
+ key ID *is* in the URL: SigV4 puts it in `X-Amz-Credential` by construction,
44
+ which is how the store knows which key to check against. That one is public by
45
+ design. A session token rides in the URL too (`X-Amz-Security-Token`), and the
46
+ result says so.
30
47
 
31
48
  ## Three things that fail hours later
32
49
 
@@ -169,11 +186,12 @@ the two carrying `!` `'` `(` `)` `*`.
169
186
  "contentType": "application/pdf",
170
187
  "metadata": { "run-id": "r-4412" },
171
188
  "expiresInSeconds": 900,
172
- "accessKeyId": "…",
173
- "secretAccessKey": "…"
189
+ "credentials": "r2"
174
190
  }
175
191
  ```
176
192
 
193
+ `credentials` may be left out when the operator configured exactly one profile.
194
+
177
195
  `signedAt` pins the signing instant, so a URL can be reproduced exactly when
178
196
  somebody asks why theirs stopped working. `includeCanonical` returns the
179
197
  canonical request and string-to-sign, which is what you diff against the
package/dist/index.d.ts CHANGED
@@ -4,6 +4,28 @@ export { _setClock, type Clock } from "./lib/clock";
4
4
  export { PresignError };
5
5
  export { canonicalQuery, encodePath, encodeRfc3986, type QueryParam, } from "./lib/encode";
6
6
  export { ALGORITHM, UNSIGNED_PAYLOAD, type Header, amzTimestamps, canonicalRequest, credentialScope, presign, sign, signedHeaderList, signingKey, stringToSign, } from "./lib/sigv4";
7
+ /** One operator-configured credential: the variables that hold each part. */
8
+ export type CredentialProfile = {
9
+ readonly accessKeyIdEnv: string;
10
+ readonly secretAccessKeyEnv: string;
11
+ readonly sessionTokenEnv?: string;
12
+ };
13
+ /** Where the profiles live in a spec, for messages. */
14
+ export declare const CREDENTIALS_CONFIG_KEY = "tool_config.objectstore.credentials";
15
+ /**
16
+ * Boot seam: the `tool_config.objectstore` (or `objectPresign`) block. Its
17
+ * `credentials` are the ONLY credentials ObjectPresign signs with.
18
+ *
19
+ * ```yaml
20
+ * tool_config:
21
+ * objectstore:
22
+ * credentials:
23
+ * r2:
24
+ * access_key_id_env: R2_ACCESS_KEY_ID
25
+ * secret_access_key_env: R2_SECRET_ACCESS_KEY
26
+ * ```
27
+ */
28
+ export declare function registerObjectStoreConfig(config: unknown): void;
7
29
  export declare const objectPresign: RegisteredTool;
8
30
  /** Every tool this package registers, in the order a catalog should list them. */
9
31
  export declare const OBJECTSTORE_TOOLS: ReadonlyArray<RegisteredTool>;
package/dist/index.js CHANGED
@@ -12,12 +12,19 @@
12
12
  * is why it declares no `ioCapability` — the test suite asserts it, over the
13
13
  * package's own source, so the claim cannot rot.
14
14
  *
15
- * It holds no credential either. The access key and secret arrive as
16
- * arguments from whatever the caller uses for secrets, the secret is consumed
17
- * by the signing-key derivation, and it is referenced in no result, no error
18
- * and no log line. (The access key ID does appear in the URL: SigV4 puts it
19
- * in `X-Amz-Credential` by construction, which is how the store knows which
20
- * key to verify against. That is public by design; the secret is not.)
15
+ * It holds no credential either, and never takes one as an argument. The
16
+ * operator names a credential PROFILE in `tool_config.objectstore.credentials`
17
+ * — the environment variables holding the access key id, the secret and (for
18
+ * STS) the session token — and a call picks a profile by name. 0.7.0 took the
19
+ * secret and the session token as tool arguments, which put them in the
20
+ * model's context, the transcript, every later provider request and the
21
+ * session event log, while this header and the schema said the secret was
22
+ * "not logged" (flag-truth-5#8). The secret is consumed by the signing-key
23
+ * derivation and referenced in no result and no error. (The access key ID
24
+ * does appear in the URL: SigV4 puts it in `X-Amz-Credential` by
25
+ * construction, which is how the store knows which key to verify against.
26
+ * That is public by design; the secret is not. A session token rides in the
27
+ * URL too, as `X-Amz-Security-Token`: SigV4 has nowhere else for it.)
21
28
  *
22
29
  * Three things are easy to get wrong here and all three fail late:
23
30
  *
@@ -30,6 +37,7 @@
30
37
  * Host header and the path, so the style is an argument, never a guess.
31
38
  */
32
39
  import { buildTool } from "@crewhaus/tool-builder";
40
+ import { isEnvName, looksLikePastedSecret, resolveCredentialEnv } from "@crewhaus/tool-safety/env";
33
41
  import { z } from "zod";
34
42
  import { nowMs, parseInstant } from "./lib/clock";
35
43
  import { OPERATIONS, checkHeaderValue, checkOperationFields, metadataHeaders, responseOverrides, } from "./lib/request";
@@ -64,6 +72,131 @@ function checkCredential(name, value) {
64
72
  throw new PresignError(`${name} contains whitespace or a control character`);
65
73
  }
66
74
  }
75
+ /** Where the profiles live in a spec, for messages. */
76
+ export const CREDENTIALS_CONFIG_KEY = "tool_config.objectstore.credentials";
77
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
78
+ /** The profiles from the boot block; none until one is registered. */
79
+ let registeredProfiles = new Map();
80
+ /** One field of a profile, in either spelling, as a variable name, never echoing a pasted value. */
81
+ function envField(block, snake, camel, where, required) {
82
+ const a = block[snake];
83
+ const b = block[camel];
84
+ if (a !== undefined && b !== undefined) {
85
+ throw new PresignError(`${where} sets both ${snake} and ${camel}; keep one`);
86
+ }
87
+ const value = a ?? b;
88
+ if (value === undefined) {
89
+ if (required) {
90
+ throw new PresignError(`${where}.${snake} is required: the NAME of the environment variable that holds it`);
91
+ }
92
+ return undefined;
93
+ }
94
+ if (typeof value !== "string" || !isEnvName(value) || looksLikePastedSecret(value)) {
95
+ const pasted = typeof value === "string" && looksLikePastedSecret(value);
96
+ throw new PresignError(`${where}.${snake} must be the NAME of an environment variable${pasted ? "; it looks like the credential itself, which has not been echoed back — treat it as exposed" : ""}`);
97
+ }
98
+ return value;
99
+ }
100
+ /** The credential profiles a `tool_config` block declares. Throws on a malformed one. */
101
+ function profilesOf(config, where) {
102
+ if (config === undefined || config === null)
103
+ return new Map();
104
+ if (typeof config !== "object" || Array.isArray(config)) {
105
+ throw new PresignError(`${where} must be a mapping with a credentials block`);
106
+ }
107
+ const credentials = config["credentials"];
108
+ if (credentials === undefined)
109
+ return new Map();
110
+ if (typeof credentials !== "object" || credentials === null || Array.isArray(credentials)) {
111
+ throw new PresignError(`${where}.credentials must map a profile name to { access_key_id_env, secret_access_key_env, session_token_env? }`);
112
+ }
113
+ const out = new Map();
114
+ for (const [name, raw] of Object.entries(credentials)) {
115
+ if (!PROFILE_NAME.test(name)) {
116
+ throw new PresignError(`${where}.credentials has a profile name that is not letters, digits, ".", "_" or "-" (at most 64)`);
117
+ }
118
+ const at = `${where}.credentials.${name}`;
119
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
120
+ throw new PresignError(`${at} must be a mapping of environment variable names`);
121
+ }
122
+ const block = raw;
123
+ const known = new Set([
124
+ "access_key_id_env",
125
+ "accessKeyIdEnv",
126
+ "secret_access_key_env",
127
+ "secretAccessKeyEnv",
128
+ "session_token_env",
129
+ "sessionTokenEnv",
130
+ ]);
131
+ const unknown = Object.keys(block).filter((k) => !known.has(k));
132
+ if (unknown.length > 0) {
133
+ throw new PresignError(`${at} holds ${unknown.map((k) => JSON.stringify(k)).join(", ")}; a profile names environment variables only (access_key_id_env, secret_access_key_env, session_token_env) — never the credentials themselves`);
134
+ }
135
+ const sessionTokenEnv = envField(block, "session_token_env", "sessionTokenEnv", at, false);
136
+ out.set(name, {
137
+ accessKeyIdEnv: envField(block, "access_key_id_env", "accessKeyIdEnv", at, true),
138
+ secretAccessKeyEnv: envField(block, "secret_access_key_env", "secretAccessKeyEnv", at, true),
139
+ ...(sessionTokenEnv === undefined ? {} : { sessionTokenEnv }),
140
+ });
141
+ }
142
+ return out;
143
+ }
144
+ /**
145
+ * Boot seam: the `tool_config.objectstore` (or `objectPresign`) block. Its
146
+ * `credentials` are the ONLY credentials ObjectPresign signs with.
147
+ *
148
+ * ```yaml
149
+ * tool_config:
150
+ * objectstore:
151
+ * credentials:
152
+ * r2:
153
+ * access_key_id_env: R2_ACCESS_KEY_ID
154
+ * secret_access_key_env: R2_SECRET_ACCESS_KEY
155
+ * ```
156
+ */
157
+ export function registerObjectStoreConfig(config) {
158
+ registeredProfiles = profilesOf(config, "tool_config.objectstore");
159
+ }
160
+ /**
161
+ * The credentials one call signs with: the profile it named (or the only one),
162
+ * each part read from the variable the operator named — never from the call.
163
+ * A model-pool candidate's own block replaces the boot block for its calls.
164
+ */
165
+ function resolveCredentials(requested, ctx) {
166
+ const profiles = typeof ctx?.toolConfig === "object" && ctx.toolConfig !== null
167
+ ? profilesOf(ctx.toolConfig, "the tool_config block for ObjectPresign")
168
+ : registeredProfiles;
169
+ const names = [...profiles.keys()].sort();
170
+ if (names.length === 0) {
171
+ throw new PresignError(`no credential profile is configured. An operator adds one in ${CREDENTIALS_CONFIG_KEY}, naming the environment variables that hold the access key id, the secret and (for STS) the session token; credentials are never tool arguments`);
172
+ }
173
+ const name = requested ?? (names.length === 1 ? names[0] : undefined);
174
+ if (name === undefined) {
175
+ throw new PresignError(`pass credentials: the profile to sign with, one of ${names.map((n) => JSON.stringify(n)).join(", ")}`);
176
+ }
177
+ const profile = profiles.get(name);
178
+ if (profile === undefined) {
179
+ throw new PresignError(`there is no credential profile ${JSON.stringify(name)} in ${CREDENTIALS_CONFIG_KEY}; the profiles are ${names.map((n) => JSON.stringify(n)).join(", ")}`);
180
+ }
181
+ const read = (env, what, field) => {
182
+ const found = resolveCredentialEnv(env, {
183
+ allowed: [env],
184
+ purpose: `the ${JSON.stringify(name)} profile's ${what}`,
185
+ configKey: `${CREDENTIALS_CONFIG_KEY}.${name}.${field}`,
186
+ });
187
+ if (!found.ok)
188
+ throw new PresignError(found.reason);
189
+ return found.value;
190
+ };
191
+ return {
192
+ profile: name,
193
+ accessKeyId: read(profile.accessKeyIdEnv, "access key id", "access_key_id_env"),
194
+ secretAccessKey: read(profile.secretAccessKeyEnv, "secret access key", "secret_access_key_env"),
195
+ ...(profile.sessionTokenEnv === undefined
196
+ ? {}
197
+ : { sessionToken: read(profile.sessionTokenEnv, "session token", "session_token_env") }),
198
+ };
199
+ }
67
200
  const inputSchema = z
68
201
  .object({
69
202
  operation: z
@@ -84,18 +217,12 @@ const inputSchema = z
84
217
  .describe("the region in the credential scope, e.g. us-east-1, or auto for R2"),
85
218
  bucket: z.string().min(1).max(255),
86
219
  key: z.string().min(1).max(2048).describe("the object key, without a leading slash"),
87
- accessKeyId: z.string().min(1).max(256),
88
- secretAccessKey: z
220
+ credentials: z
89
221
  .string()
90
222
  .min(1)
91
- .max(256)
92
- .describe("used to derive the signing key and nothing else; it is not returned, logged or stored"),
93
- sessionToken: z
94
- .string()
95
- .min(1)
96
- .max(8192)
223
+ .max(64)
97
224
  .optional()
98
- .describe("for temporary credentials (STS); signed into the URL as X-Amz-Security-Token"),
225
+ .describe(`the operator's credential profile to sign with, by name (${CREDENTIALS_CONFIG_KEY}); optional when exactly one is configured. The access key id, secret and session token are read from the environment variables the profile names — they are never arguments`),
99
226
  expiresInSeconds: z
100
227
  .number()
101
228
  .int()
@@ -139,13 +266,13 @@ const inputSchema = z
139
266
  .strict();
140
267
  export const objectPresign = buildTool({
141
268
  name: "ObjectPresign",
142
- description: "Mint a time-limited URL that downloads or uploads one object in an S3-compatible store (AWS S3, Cloudflare R2, MinIO, anything that speaks SigV4). Use it to move a file without the bytes passing through this harness and without handing anyone a long-lived key: the URL grants one operation on one object until it expires, and nothing else. It is pure computation — HMAC-SHA256 over strings, no SDK, no network, no credential kept — so it works offline and the same inputs always produce the same URL. For an upload that pins a content type or metadata, the exact headers come back alongside the URL and MUST be sent byte-identically, or the store answers 403 long after this call succeeded. The addressing style (virtual-hosted or path) is required rather than inferred, because the two sign different requests. The secret key is used to derive the signing key and appears in no output.",
269
+ description: "Mint a time-limited URL that downloads or uploads one object in an S3-compatible store (AWS S3, Cloudflare R2, MinIO, anything that speaks SigV4). Use it to move a file without the bytes passing through this harness and without handing anyone a long-lived key: the URL grants one operation on one object until it expires, and nothing else. It is pure computation (HMAC-SHA256, no SDK, no network, no credential kept), so it works offline and the same inputs give the same URL. For an upload that pins a content type or metadata, the exact headers come back with the URL and MUST be sent byte-identically, or the store answers 403 long after this call succeeded. The addressing style (virtual-hosted or path) is required, never inferred. Credentials are never arguments: the call names one of the operator's credential profiles (tool_config.objectstore.credentials), whose environment variables hold the keys, and the secret key appears in no output.",
143
270
  inputSchema,
144
271
  readOnly: true,
145
272
  concurrencySafe: true,
146
273
  // No scope or ioCapability: this reaches nothing. The package's own test
147
274
  // suite greps its source to keep that true.
148
- execute: async (input) => {
275
+ execute: async (input, ctx) => {
149
276
  const operation = input.operation;
150
277
  const overrides = {
151
278
  responseContentType: input.responseContentType,
@@ -158,10 +285,11 @@ export const objectPresign = buildTool({
158
285
  metadata: input.metadata,
159
286
  overrides,
160
287
  });
161
- checkCredential("accessKeyId", input.accessKeyId);
162
- checkCredential("secretAccessKey", input.secretAccessKey);
163
- if (input.sessionToken !== undefined)
164
- checkCredential("sessionToken", input.sessionToken);
288
+ const creds = resolveCredentials(input.credentials, ctx);
289
+ checkCredential("the access key id", creds.accessKeyId);
290
+ checkCredential("the secret access key", creds.secretAccessKey);
291
+ if (creds.sessionToken !== undefined)
292
+ checkCredential("the session token", creds.sessionToken);
165
293
  if (!/^[a-z0-9][a-z0-9-]*$/.test(input.region)) {
166
294
  throw new PresignError(`region "${input.region}" is not a region name — the credential scope is case-sensitive and matched literally, so "US-East-1" signs cleanly and then fails. Regions are lowercase letters, digits and hyphens (us-east-1, eu-central-1, or auto for R2)`);
167
295
  }
@@ -195,16 +323,16 @@ export const objectPresign = buildTool({
195
323
  canonicalUri: target.canonicalUri,
196
324
  region: input.region,
197
325
  service: SERVICE,
198
- accessKeyId: input.accessKeyId,
199
- secretAccessKey: input.secretAccessKey,
200
- sessionToken: input.sessionToken,
326
+ accessKeyId: creds.accessKeyId,
327
+ secretAccessKey: creds.secretAccessKey,
328
+ sessionToken: creds.sessionToken,
201
329
  epochMs,
202
330
  expiresInSeconds,
203
331
  query: responseOverrides(overrides),
204
332
  headers,
205
333
  });
206
334
  const warnings = [...target.warnings];
207
- if (input.sessionToken !== undefined) {
335
+ if (creds.sessionToken !== undefined) {
208
336
  warnings.push("signed with temporary credentials: the URL also stops working when the session token expires, which is often sooner than expiresAt.");
209
337
  }
210
338
  if (expiresInSeconds > LONG_LIVED_SECONDS) {
@@ -237,7 +365,8 @@ export const objectPresign = buildTool({
237
365
  expiresAt: new Date(epochMs + expiresInSeconds * 1000).toISOString(),
238
366
  expiresInSeconds,
239
367
  curl,
240
- credentials: input.sessionToken === undefined
368
+ credentialProfile: creds.profile,
369
+ credentials: creds.sessionToken === undefined
241
370
  ? "the access key id is inside the URL because SigV4 puts it there; the secret key was used to derive the signing key and appears nowhere in this result"
242
371
  : // The session token is in the URL too, and saying only that the
243
372
  // secret is absent reads as a full account of what is in here.
package/dist/lib/store.js CHANGED
@@ -78,23 +78,33 @@ function isLoopbackHost(hostname) {
78
78
  * Redacting at the point of echo rather than relying on check order, because
79
79
  * check order is exactly what the next edit changes. The host and the path
80
80
  * survive, which is all the message needs to identify what was refused.
81
+ *
82
+ * The userinfo cannot be found by splitting at the first `/`, `?` or `#`: a
83
+ * password may contain any of them (about half of AWS secret keys contain a
84
+ * `/`), and the WHATWG parser ends the authority there, so
85
+ * `https://KEY:SEC/RET@host` is "not a URL" and `https://KEY:1234/RET@host`
86
+ * even parses, with the rest of the secret as its path. So everything up to
87
+ * the LAST `@` is the userinfo. When a `?` or `#` comes before that `@`, the
88
+ * `@` may be inside a password or inside a query value, and nothing after the
89
+ * scheme can be told apart from the secret, so all of it is redacted: an
90
+ * over-redacted refusal costs nothing.
81
91
  */
82
92
  function quoteEndpoint(raw) {
83
93
  const trimmed = raw.trim();
84
94
  const scheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.exec(trimmed);
85
95
  const prefix = scheme === null ? "" : scheme[0];
86
96
  const rest = trimmed.slice(prefix.length);
87
- const cut = rest.search(/[/?#]/);
88
- const authority = cut === -1 ? rest : rest.slice(0, cut);
89
- const at = authority.lastIndexOf("@");
90
- const shown = at === -1 ? authority : `<redacted>@${authority.slice(at + 1)}`;
91
- if (cut === -1)
92
- return `${prefix}${shown}`;
93
- const tail = rest.slice(cut);
94
- const mark = tail.search(/[?#]/);
95
- const path = mark === -1 ? tail : tail.slice(0, mark);
96
- const suffix = mark === -1 ? "" : `${tail[mark]}<redacted>`;
97
- return `${prefix}${shown}${path}${suffix}`;
97
+ const at = rest.lastIndexOf("@");
98
+ if (at === -1)
99
+ return `${prefix}${redactQuery(rest)}`;
100
+ if (/[?#]/.test(rest.slice(0, at)))
101
+ return `${prefix}<redacted>`;
102
+ return `${prefix}<redacted>@${redactQuery(rest.slice(at + 1))}`;
103
+ }
104
+ /** Keep `text` up to its first `?` or `#`, and redact the rest. */
105
+ function redactQuery(text) {
106
+ const mark = text.search(/[?#]/);
107
+ return mark === -1 ? text : `${text.slice(0, mark)}${text[mark]}<redacted>`;
98
108
  }
99
109
  /**
100
110
  * Parse the store's base URL into the pieces the signature needs.
@@ -119,7 +129,7 @@ export function parseEndpoint(raw) {
119
129
  throw new PresignError(`endpoint "${quoteEndpoint(raw)}" uses ${url.protocol} — an object-store endpoint is http or https`);
120
130
  }
121
131
  if (url.username !== "" || url.password !== "") {
122
- throw new PresignError("endpoint carries a username or password — SigV4 credentials go in accessKeyId/secretAccessKey, and a credential in the URL would be signed into the result");
132
+ throw new PresignError("endpoint carries a username or password — a credential in the URL would be signed into the result. Credentials never go in the endpoint or in any argument: the operator names the environment variables that hold them in a tool_config.objectstore.credentials profile, and the call passes that profile's name as `credentials`");
123
133
  }
124
134
  if (url.search !== "" || url.hash !== "") {
125
135
  throw new PresignError(`endpoint "${quoteEndpoint(raw)}" carries a query string or fragment; pass the origin only`);
@@ -129,7 +139,9 @@ export function parseEndpoint(raw) {
129
139
  // and it is refused rather than guessed at: the prefix belongs in the
130
140
  // canonical URI ahead of the bucket, and whether THIS gateway wants it
131
141
  // signed is a fact about the gateway that nothing here can check.
132
- throw new PresignError(`endpoint "${quoteEndpoint(raw)}" has a path ("${url.pathname}") — this tool signs a path built from the bucket and key, so a prefix on the endpoint would be signed twice or not at all. Pass the origin only`);
142
+ // The path is shown only through quoteEndpoint: the parsed pathname can
143
+ // hold the tail of a password (`https://KEY:1234/SECRET@host`).
144
+ throw new PresignError(`endpoint "${quoteEndpoint(raw)}" has a path — this tool signs a path built from the bucket and key, so a prefix on the endpoint would be signed twice or not at all. Pass the origin only`);
133
145
  }
134
146
  if (url.hostname === "")
135
147
  throw new PresignError(`endpoint "${quoteEndpoint(raw)}" has no host`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/tool-objectstore",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Deterministic object-store URL signing: SigV4 presigned GET and PUT, computed offline",
6
6
  "main": "dist/index.js",
@@ -8,20 +8,23 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
12
13
  }
13
14
  },
14
15
  "scripts": {
15
16
  "test": "bun test src"
16
17
  },
17
18
  "dependencies": {
18
- "@crewhaus/errors": "0.7.0",
19
- "@crewhaus/tool-builder": "0.7.0",
20
- "@crewhaus/tool-catalog": "0.7.0",
21
- "@crewhaus/tool-encode": "0.7.0",
19
+ "@crewhaus/errors": "0.8.0",
20
+ "@crewhaus/tool-builder": "0.8.0",
21
+ "@crewhaus/tool-catalog": "0.8.0",
22
+ "@crewhaus/tool-encode": "0.8.0",
23
+ "@crewhaus/tool-safety": "0.8.0",
22
24
  "zod": "^3.23.8"
23
25
  },
24
26
  "devDependencies": {
27
+ "@crewhaus/tool-categories": "workspace:*",
25
28
  "@crewhaus/tool-executor": "workspace:*"
26
29
  },
27
30
  "license": "Apache-2.0",
@@ -42,5 +45,8 @@
42
45
  "publishConfig": {
43
46
  "access": "public"
44
47
  },
45
- "files": ["dist", "README.md", "LICENSE", "NOTICE"]
48
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
49
+ "engines": {
50
+ "bun": ">=1.3.14"
51
+ }
46
52
  }