@appstrate/afps-shared 0.1.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,190 @@
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 the 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 the 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 any 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
+ Copyright 2025-2026 Appstrate
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,11 @@
1
+ Appstrate AFPS Shared
2
+ Copyright 2026 Appstrate
3
+
4
+ This product includes software developed at Appstrate (https://appstrate.dev/).
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@appstrate/afps-shared",
3
+ "version": "0.1.0",
4
+ "description": "Zero-dependency AFPS helpers shared by @appstrate/core and @appstrate/afps-runtime (companion-file checks, semver resolution, SRI integrity, credential templates, delivery.http projection)",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "bun": ">=1.3.9"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "provenance": true
13
+ },
14
+ "sideEffects": false,
15
+ "author": "Appstrate <hello@appstrate.dev>",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/appstrate/appstrate.git",
19
+ "directory": "packages/afps-shared"
20
+ },
21
+ "homepage": "https://github.com/appstrate/appstrate/tree/main/packages/afps-shared",
22
+ "bugs": {
23
+ "url": "https://github.com/appstrate/appstrate/issues"
24
+ },
25
+ "keywords": [
26
+ "appstrate",
27
+ "afps",
28
+ "semver",
29
+ "integrity",
30
+ "sri"
31
+ ],
32
+ "files": [
33
+ "src",
34
+ "LICENSE",
35
+ "NOTICE"
36
+ ],
37
+ "exports": {
38
+ "./companion-files": "./src/companion-files.ts",
39
+ "./semver-resolve": "./src/semver-resolve.ts",
40
+ "./integrity": "./src/integrity.ts",
41
+ "./credential-template": "./src/credential-template.ts",
42
+ "./delivery-http": "./src/delivery-http.ts",
43
+ "./ssrf": "./src/ssrf.ts",
44
+ "./token-usage": "./src/token-usage.ts"
45
+ },
46
+ "dependencies": {
47
+ "semver": "^7.7.1"
48
+ },
49
+ "devDependencies": {
50
+ "@types/semver": "^7.7.1"
51
+ },
52
+ "peerDependencies": {
53
+ "typescript": "^5"
54
+ },
55
+ "scripts": {
56
+ "typecheck": "tsc --noEmit",
57
+ "check": "tsc --noEmit",
58
+ "test": "bun test"
59
+ }
60
+ }
@@ -0,0 +1,179 @@
1
+ // Copyright 2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Companion-file enforcement shared between the platform's ZIP-import path
6
+ * (`@appstrate/core/zip:parsePackageZip`) and the runtime's bundle loader
7
+ * (`@appstrate/afps-runtime/bundle/build:extractRootFromAfps`).
8
+ *
9
+ * This is the SINGLE source of truth for the §3.3 / §3.4 companion-file
10
+ * invariants. Both `@appstrate/core/companion-files` and
11
+ * `@appstrate/afps-runtime/bundle/companion-files` re-export from here, so
12
+ * the two call sites can never drift.
13
+ */
14
+
15
+ /**
16
+ * Stable, machine-readable companion-file violation reasons.
17
+ */
18
+ export type CompanionViolationReason =
19
+ | "AGENT_MISSING_PROMPT"
20
+ | "AGENT_EMPTY_PROMPT"
21
+ | "SKILL_MISSING_SKILL_MD"
22
+ | "SKILL_MISSING_FRONTMATTER_NAME"
23
+ | "MCP_SERVER_MISSING_ENTRY_POINT";
24
+
25
+ /**
26
+ * Structured error type for callers that want to translate companion-file
27
+ * violations into their own error class (e.g. `PackageZipError` on the
28
+ * platform side, `BundleError` on the runtime side). Throwing is left to
29
+ * the caller so we don't couple this module to a specific error hierarchy.
30
+ */
31
+ export interface CompanionFileViolation {
32
+ /** Stable, machine-readable reason. */
33
+ reason: CompanionViolationReason;
34
+ /** Human-readable description. */
35
+ message: string;
36
+ /** Path the violation refers to, when relevant. */
37
+ path?: string;
38
+ }
39
+
40
+ /**
41
+ * Minimal file-list abstraction. The platform side stores files in a
42
+ * `Record<string, Uint8Array>`; the runtime side stores them in a
43
+ * `Map<string, Uint8Array>`. This adapter lets both call the same checker.
44
+ */
45
+ export interface CompanionFileSource {
46
+ /** Does the archive contain a file at `path`? */
47
+ has(path: string): boolean;
48
+ /** Read bytes at `path`, or undefined when absent. */
49
+ get(path: string): Uint8Array | undefined;
50
+ }
51
+
52
+ /** Build a {@link CompanionFileSource} from a `Map<string, Uint8Array>`. */
53
+ export function companionFilesFromMap(files: Map<string, Uint8Array>): CompanionFileSource {
54
+ return {
55
+ has: (p) => files.has(p),
56
+ get: (p) => files.get(p),
57
+ };
58
+ }
59
+
60
+ /** Build a {@link CompanionFileSource} from a `Record<string, Uint8Array>`. */
61
+ export function companionFilesFromRecord(files: Record<string, Uint8Array>): CompanionFileSource {
62
+ return {
63
+ has: (p) => Object.prototype.hasOwnProperty.call(files, p),
64
+ get: (p) => files[p],
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Validate companion-file presence per AFPS §3.3 / §3.4 for the given
70
+ * package type. Returns the first violation encountered, or `null` when
71
+ * the archive is consistent with the declared type.
72
+ *
73
+ * The check is intentionally minimal and presence-focused:
74
+ * - `agent` → `prompt.md` present at root, non-empty bytes (§3.2).
75
+ * - `skill` → `SKILL.md` present at root, with YAML frontmatter `name`
76
+ * (§3.3). Missing `description` is tolerated per spec.
77
+ * - `mcp-server` → file at `manifest.server.entry_point` present in the
78
+ * archive (§3.4 "self-contained — every runtime dep bundled").
79
+ * - `integration` → no required companion (§3.5).
80
+ * - any other type → no check (caller validates manifest shape).
81
+ *
82
+ * The caller is responsible for throwing whatever error class fits its
83
+ * domain (e.g. `PackageZipError` for HTTP imports, `BundleError` for the
84
+ * runtime loader).
85
+ */
86
+ export function checkCompanionFiles(
87
+ manifest: { type?: unknown; server?: unknown } & Record<string, unknown>,
88
+ files: CompanionFileSource,
89
+ ): CompanionFileViolation | null {
90
+ const type = manifest.type;
91
+
92
+ if (type === "agent") {
93
+ const bytes = files.get("prompt.md");
94
+ if (!bytes) {
95
+ return {
96
+ reason: "AGENT_MISSING_PROMPT",
97
+ message: "agent package must contain prompt.md at the archive root",
98
+ path: "prompt.md",
99
+ };
100
+ }
101
+ if (isEffectivelyEmpty(bytes)) {
102
+ return {
103
+ reason: "AGENT_EMPTY_PROMPT",
104
+ message: "agent prompt.md must not be empty or whitespace-only",
105
+ path: "prompt.md",
106
+ };
107
+ }
108
+ return null;
109
+ }
110
+
111
+ if (type === "skill") {
112
+ const bytes = files.get("SKILL.md");
113
+ if (!bytes) {
114
+ return {
115
+ reason: "SKILL_MISSING_SKILL_MD",
116
+ message: "skill package must contain SKILL.md at the archive root",
117
+ path: "SKILL.md",
118
+ };
119
+ }
120
+ if (!hasFrontmatterName(new TextDecoder().decode(bytes))) {
121
+ return {
122
+ reason: "SKILL_MISSING_FRONTMATTER_NAME",
123
+ message: "skill SKILL.md must declare a 'name' in YAML frontmatter",
124
+ path: "SKILL.md",
125
+ };
126
+ }
127
+ return null;
128
+ }
129
+
130
+ if (type === "mcp-server") {
131
+ const server = manifest.server as { entry_point?: unknown } | undefined;
132
+ const entryPoint = server?.entry_point;
133
+ if (typeof entryPoint !== "string" || entryPoint.length === 0) {
134
+ // Manifest schema validation reports this — surface a structured
135
+ // violation here too so callers that skip schema validation still
136
+ // catch it.
137
+ return {
138
+ reason: "MCP_SERVER_MISSING_ENTRY_POINT",
139
+ message: "mcp-server manifest must declare server.entry_point",
140
+ };
141
+ }
142
+ if (!files.has(entryPoint)) {
143
+ return {
144
+ reason: "MCP_SERVER_MISSING_ENTRY_POINT",
145
+ message: `mcp-server archive missing server.entry_point payload: ${entryPoint}`,
146
+ path: entryPoint,
147
+ };
148
+ }
149
+ return null;
150
+ }
151
+
152
+ // `integration` and unknown/missing types: no companion-file requirement
153
+ // here. The caller's manifest schema check rejects unsupported types.
154
+ return null;
155
+ }
156
+
157
+ function isEffectivelyEmpty(bytes: Uint8Array): boolean {
158
+ if (bytes.length === 0) return true;
159
+ // Avoid decoding very large buffers just to call trim — short-circuit
160
+ // when any byte is not whitespace.
161
+ for (const b of bytes) {
162
+ if (b !== 0x09 && b !== 0x0a && b !== 0x0d && b !== 0x20) return false;
163
+ }
164
+ return true;
165
+ }
166
+
167
+ function hasFrontmatterName(content: string): boolean {
168
+ const fmMatch = content.match(/^---[^\S\n]*\n([\s\S]*?)\n---/);
169
+ if (!fmMatch) return false;
170
+ const fm = fmMatch[1] ?? "";
171
+ const nameMatch = fm.match(/name:[ \t]*(.+)/);
172
+ if (!nameMatch) return false;
173
+ const raw = (nameMatch[1] ?? "").trim();
174
+ if (raw.length === 0) return false;
175
+ // Strip surrounding quotes to mirror extractSkillMeta's stripQuotes.
176
+ const unquoted = /^(['"])(.*)\1$/.exec(raw);
177
+ const value = unquoted ? unquoted[2] : raw;
178
+ return (value ?? "").trim().length > 0;
179
+ }
@@ -0,0 +1,52 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Canonical `{$credential.<field>}` value-template renderer — the SINGLE
6
+ * source of truth, re-exported by `@appstrate/core/credential-template`.
7
+ *
8
+ * AFPS `delivery.http` / `delivery.env` / `delivery.files` value templates
9
+ * reference an auth's decrypted credential bag via the `{$credential.<field>}`
10
+ * syntax. This is a DISTINCT syntax from the `{{var}}` substitution handled by
11
+ * `@appstrate/afps-runtime`'s `substituteVars` — there is exactly ONE
12
+ * implementation per syntax, and this module owns `{$credential.<field>}`.
13
+ *
14
+ * A missing field renders empty (a missing credential field means "no value to
15
+ * inject"). The empty-value behaviour is parametrised:
16
+ * - `emptyAs: "string"` (default) → returns `""` for an all-empty render
17
+ * (the `delivery.http` value-render policy: the caller decides whether to
18
+ * inject an empty header / synthesise a value such as basic-auth).
19
+ * - `emptyAs: "null"` → returns `null` for an all-empty render, so callers
20
+ * can skip env vars / files whose backing credential field is absent
21
+ * (the `delivery.env` / `delivery.files` "field missing → skip" policy).
22
+ */
23
+
24
+ export const CREDENTIAL_REF = /\{\$credential\.([A-Za-z0-9_]+)\}/g;
25
+
26
+ export interface RenderCredentialTemplateOptions {
27
+ /**
28
+ * What an all-empty render resolves to. `"string"` returns `""`; `"null"`
29
+ * returns `null`. Defaults to `"string"`.
30
+ */
31
+ emptyAs?: "string" | "null";
32
+ }
33
+
34
+ export function renderCredentialTemplate(
35
+ template: string,
36
+ credential: Readonly<Record<string, string>>,
37
+ opts?: RenderCredentialTemplateOptions & { emptyAs?: "string" },
38
+ ): string;
39
+ export function renderCredentialTemplate(
40
+ template: string,
41
+ credential: Readonly<Record<string, string>>,
42
+ opts: RenderCredentialTemplateOptions & { emptyAs: "null" },
43
+ ): string | null;
44
+ export function renderCredentialTemplate(
45
+ template: string,
46
+ credential: Readonly<Record<string, string>>,
47
+ opts: RenderCredentialTemplateOptions = {},
48
+ ): string | null {
49
+ const rendered = template.replace(CREDENTIAL_REF, (_m, field: string) => credential[field] ?? "");
50
+ if (opts.emptyAs === "null") return rendered.length === 0 ? null : rendered;
51
+ return rendered;
52
+ }
@@ -0,0 +1,99 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * AFPS `delivery.http` block → resolver-config projection — the SINGLE
6
+ * source of truth, used by both `@appstrate/connect`'s `afps-delivery.ts`
7
+ * and `@appstrate/afps-runtime`'s `resolvers/integration-api-call.ts`.
8
+ *
9
+ * The AFPS `auths.{key}.delivery.http` block (snake_case) is:
10
+ *
11
+ * { in: "header", name } header channel + name
12
+ * { prefix } value prefix, e.g. "Bearer "
13
+ * { value: "{$credential.<field>}" } value template
14
+ * { value: "<template>", encoding } base64-encoded template
15
+ * { allow_server_override } strip caller override when false
16
+ *
17
+ * The value is a TEMPLATE referencing credential fields via the
18
+ * `{$credential.<field>}` syntax. This module is a pure shape projection: it
19
+ * maps the AFPS snake_case block onto the resolver `HttpDeliveryConfig` shape
20
+ * (lowering `{$credential.<field>}` references to the resolver's
21
+ * `valueFrom` field name / `{{field}}` template syntax). The per-auth-type
22
+ * default table, the `basic → base64(user:pass)` fallback, and the base64
23
+ * encoding branch all live in the resolver engine
24
+ * (`@appstrate/afps-runtime/resolvers:resolveHttpDelivery`) — they are NOT
25
+ * re-implemented here.
26
+ */
27
+
28
+ /**
29
+ * Structural subset of the resolver config consumed by
30
+ * `resolveHttpDelivery` (`@appstrate/afps-runtime/resolvers`). Declared here
31
+ * structurally so this zero-dep package does not depend on afps-runtime; the
32
+ * shapes are structurally compatible.
33
+ */
34
+ export interface HttpDeliveryConfig {
35
+ headerName?: string;
36
+ headerPrefix?: string;
37
+ valueFrom?: string | { template: string; encoding?: "base64" };
38
+ allowServerOverride?: boolean;
39
+ }
40
+
41
+ /**
42
+ * Subset of the AFPS `auths.{key}.delivery.http` block (snake_case). `value`
43
+ * is a template; `{$credential.<field>}` references resolve against the auth's
44
+ * credential bag.
45
+ */
46
+ export interface AfpsHttpDelivery {
47
+ /** Delivery channel discriminant — always `"header"` for http delivery. */
48
+ in?: "header";
49
+ /** Header name. */
50
+ name?: string;
51
+ /** Header value prefix, e.g. `"Bearer "`. */
52
+ prefix?: string;
53
+ /** Value template with `{$credential.<field>}` refs. */
54
+ value?: string;
55
+ /** Optional post-render encoding — base64 of the rendered value. */
56
+ encoding?: "base64";
57
+ /** Mirrors manifest; default `false` → proxy strips caller overrides. */
58
+ allow_server_override?: boolean;
59
+ }
60
+
61
+ /** A single `{$credential.<field>}` reference spanning the whole string. */
62
+ const SINGLE_CREDENTIAL_REF = /^\{\$credential\.([A-Za-z0-9_]+)\}$/;
63
+
64
+ /**
65
+ * Project an AFPS `delivery.http` block (snake_case) onto the resolver's
66
+ * {@link HttpDeliveryConfig}. A single `{$credential.<field>}` value (with no
67
+ * encoding) lowers to the bare `valueFrom` field name; anything richer is
68
+ * rewritten to the resolver's `{{field}}` template syntax. Both forms resolve
69
+ * the SAME credential bag with the same "missing field → empty" policy through
70
+ * `resolveHttpDelivery`, so the projection is semantics-preserving.
71
+ *
72
+ * Returns `undefined` when no `delivery.http` block is declared, so the
73
+ * resolver applies its own per-auth-type defaults.
74
+ */
75
+ export function projectHttpDeliveryConfig(
76
+ http: AfpsHttpDelivery | undefined,
77
+ ): HttpDeliveryConfig | undefined {
78
+ if (!http) return undefined;
79
+ const cfg: HttpDeliveryConfig = {};
80
+ if (typeof http.name === "string") cfg.headerName = http.name;
81
+ if (typeof http.prefix === "string") cfg.headerPrefix = http.prefix;
82
+ if (typeof http.allow_server_override === "boolean") {
83
+ cfg.allowServerOverride = http.allow_server_override;
84
+ }
85
+ const value = typeof http.value === "string" ? http.value : undefined;
86
+ if (value !== undefined) {
87
+ const single = value.match(SINGLE_CREDENTIAL_REF);
88
+ if (single && http.encoding === undefined) {
89
+ cfg.valueFrom = single[1]!;
90
+ } else {
91
+ const template = value.replace(
92
+ /\{\$credential\.([A-Za-z0-9_]+)\}/g,
93
+ (_m, field: string) => `{{${field}}}`,
94
+ );
95
+ cfg.valueFrom = http.encoding === "base64" ? { template, encoding: "base64" } : { template };
96
+ }
97
+ }
98
+ return cfg;
99
+ }
@@ -0,0 +1,58 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Subresource Integrity (SRI) primitives — the SINGLE source of truth,
6
+ * re-exported by `@appstrate/core/integrity` (as `computeIntegrity` +
7
+ * `verifyArtifactIntegrity`) and `@appstrate/afps-runtime/bundle/hash`
8
+ * (as `computeIntegrity` + `verifyIntegrity`).
9
+ *
10
+ * Runtime-neutral: uses `node:crypto` (supported under both Node and Bun)
11
+ * so the standalone `afps` CLI and the platform share one implementation.
12
+ */
13
+
14
+ import { createHash, timingSafeEqual } from "node:crypto";
15
+
16
+ /**
17
+ * Compute a Subresource Integrity (SRI) hash for binary data.
18
+ *
19
+ * Returns a string in the canonical SRI form (`sha256-<base64>`), directly
20
+ * usable in `X-Integrity` HTTP headers, HTML `integrity` attributes, and
21
+ * signed bundle manifests.
22
+ *
23
+ * @param data - Binary content to hash.
24
+ * @returns SRI string in the format `"sha256-{base64}"`.
25
+ */
26
+ export function computeIntegrity(data: Uint8Array | Buffer): string {
27
+ const hash = createHash("sha256");
28
+ hash.update(data);
29
+ return `sha256-${hash.digest("base64")}`;
30
+ }
31
+
32
+ /** Result of an integrity verification check. */
33
+ export interface IntegrityCheckResult {
34
+ /** Whether the computed hash matches the expected value. */
35
+ valid: boolean;
36
+ /** The computed SRI hash string. Useful for error reporting. */
37
+ computed: string;
38
+ }
39
+
40
+ /**
41
+ * Verify binary data against an expected SRI hash.
42
+ *
43
+ * Comparison is constant-time when the lengths match — a short-circuit on
44
+ * mismatched lengths is safe because SRI strings of a given algorithm have a
45
+ * fixed length, and the length itself is not a secret.
46
+ *
47
+ * @param data - Binary content to hash.
48
+ * @param expected - Expected SRI string (e.g. `"sha256-…"`).
49
+ */
50
+ export function verifyIntegrity(data: Uint8Array, expected: string): IntegrityCheckResult {
51
+ const computed = computeIntegrity(data);
52
+ if (computed.length !== expected.length) {
53
+ return { valid: false, computed };
54
+ }
55
+ const a = Buffer.from(computed, "utf8");
56
+ const b = Buffer.from(expected, "utf8");
57
+ return { valid: timingSafeEqual(a, b), computed };
58
+ }
@@ -0,0 +1,54 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Generic 3-step semver resolution: exact match → dist-tag → semver range.
6
+ *
7
+ * Pure string-level helper. Callers are responsible for hydrating any
8
+ * associated metadata (id, integrity, …) from the returned version
9
+ * string, and for applying yank policy by pre-filtering the
10
+ * `rangeVersions` and `distTags` inputs accordingly.
11
+ *
12
+ * This is the SINGLE source of truth, re-exported by
13
+ * `@appstrate/core/semver` and `@appstrate/afps-runtime/bundle/semver-resolve`.
14
+ *
15
+ * Conventional yank policy (matches npm/crates.io):
16
+ * - `exactVersions`: include yanked (exact pins always resolve).
17
+ * - `distTags`: exclude tags pointing at yanked versions.
18
+ * - `rangeVersions`: exclude yanked.
19
+ *
20
+ * Returns the matched version string (e.g. `"1.2.3"`) or `null`.
21
+ */
22
+
23
+ import semver from "semver";
24
+
25
+ export function resolveVersionString(
26
+ query: string,
27
+ exactVersions: readonly string[],
28
+ rangeVersions: readonly string[],
29
+ distTags: Readonly<Record<string, string>>,
30
+ ): string | null {
31
+ // 1. Exact match (caller decides whether yanked are included).
32
+ if (semver.valid(query)) {
33
+ return exactVersions.includes(query) ? query : null;
34
+ }
35
+
36
+ // 2. Dist-tag (caller pre-filters out tags pointing at yanked).
37
+ const tagged = distTags[query];
38
+ if (tagged !== undefined) {
39
+ if (rangeVersions.includes(tagged) || exactVersions.includes(tagged)) {
40
+ return tagged;
41
+ }
42
+ // Tag found but the target was filtered out (e.g. yanked) — do
43
+ // not fall through to range resolution; tags are not ranges.
44
+ return null;
45
+ }
46
+
47
+ // 3. Semver range.
48
+ if (semver.validRange(query)) {
49
+ const candidates = rangeVersions.filter((v) => semver.valid(v) !== null);
50
+ return semver.maxSatisfying([...candidates], query);
51
+ }
52
+
53
+ return null;
54
+ }
package/src/ssrf.ts ADDED
@@ -0,0 +1,110 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * SSRF protection — blocks requests targeting private/internal networks.
6
+ *
7
+ * Canonical, zero-dependency source of truth. Re-exported verbatim by
8
+ * `@appstrate/core/ssrf` (so every existing platform consumer keeps its
9
+ * import path) and consumed directly by the shared `api-call-engine` in
10
+ * `@appstrate/afps-runtime` — which cannot depend on `@appstrate/core`
11
+ * (it ships standalone with the `afps` CLI). Living in the leaf
12
+ * `@appstrate/afps-shared` package keeps a single implementation reachable
13
+ * from both the platform/sidecar side and the CLI side without a cycle.
14
+ *
15
+ * Normalizes hostnames through the WHATWG URL parser to defeat bypass techniques:
16
+ * - Numeric IPs: 2130706433, 0x7f000001, 0177.0.0.1 → 127.0.0.1
17
+ * - IPv6 variations: ::ffff:7f00:1, 0:0:0:0:0:ffff:7f00:1 → ::ffff:7f00:1
18
+ * - IPv4-mapped IPv6: ::ffff:169.254.169.254 → ::ffff:a9fe:a9fe
19
+ */
20
+
21
+ /**
22
+ * Check whether a hostname resolves to a private/internal network address.
23
+ * Normalizes through the WHATWG URL parser to defeat bypass techniques
24
+ * (numeric IPs, IPv6 variations, IPv4-mapped IPv6).
25
+ * @param hostname - The hostname or IP address to check
26
+ * @returns true if the host targets a private/internal network and should be blocked
27
+ */
28
+ export function isBlockedHost(hostname: string): boolean {
29
+ let h: string;
30
+ try {
31
+ const stripped = hostname.replace(/^\[|\]$/g, "");
32
+ const urlStr = stripped.includes(":") ? `http://[${stripped}]/` : `http://${stripped}/`;
33
+ h = new URL(urlStr).hostname.toLowerCase();
34
+ // Bun keeps brackets on IPv6 hostnames — strip them for uniform checks
35
+ h = h.replace(/^\[|\]$/g, "");
36
+ // A trailing dot is a valid FQDN form that DNS resolves identically
37
+ // (`metadata.google.internal.`, `localhost.`, `127.0.0.1.`) but would
38
+ // slip past the exact-string host matches and the dotted-IP regex
39
+ // below. Normalize it away so the blocklist can't be bypassed.
40
+ h = h.replace(/\.$/, "");
41
+ } catch {
42
+ return true; // Unparseable hostname = blocked
43
+ }
44
+
45
+ // --- Direct hostname matches ---
46
+ if (h === "localhost" || h === "sidecar" || h === "agent" || h === "host.docker.internal") {
47
+ return true;
48
+ }
49
+ if (h === "metadata.google.internal") return true;
50
+
51
+ // --- IPv4 checks (URL parser normalizes all numeric formats to dotted-decimal) ---
52
+ const ipv4Match = h.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
53
+ if (ipv4Match) {
54
+ const a = parseInt(ipv4Match[1]!, 10);
55
+ const b = parseInt(ipv4Match[2]!, 10);
56
+ if (a === 0) return true; // 0.0.0.0/8
57
+ if (a === 10) return true; // 10.0.0.0/8
58
+ if (a === 127) return true; // 127.0.0.0/8 (full loopback range)
59
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
60
+ if (a === 192 && b === 168) return true; // 192.168.0.0/16
61
+ if (a === 169 && b === 254) return true; // 169.254.0.0/16 (link-local)
62
+ return false;
63
+ }
64
+
65
+ // --- IPv6 checks ---
66
+ if (h.includes(":")) {
67
+ // Loopback (::1) and unspecified (::)
68
+ if (h === "::1" || h === "::") return true;
69
+
70
+ // Link-local (fe80::/10 — fe80:: through febf::)
71
+ if (/^fe[89ab][0-9a-f]:/.test(h)) return true;
72
+
73
+ // Unique local address (fc00::/7 — fc00:: through fdff::)
74
+ if (/^f[cd][0-9a-f]{2}:/.test(h)) return true;
75
+
76
+ // IPv4-mapped IPv6 in hex form (::ffff:HHHH:LLLL)
77
+ // URL parser normalizes ::ffff:127.0.0.1 → ::ffff:7f00:1
78
+ const mappedHex = h.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
79
+ if (mappedHex) {
80
+ const high = parseInt(mappedHex[1]!, 16);
81
+ const low = parseInt(mappedHex[2]!, 16);
82
+ const ipv4 = `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`;
83
+ return isBlockedHost(ipv4);
84
+ }
85
+
86
+ // IPv4-mapped IPv6 in dotted notation (::ffff:d.d.d.d) — some parsers preserve this
87
+ const mappedDot = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
88
+ if (mappedDot) {
89
+ return isBlockedHost(mappedDot[1]!);
90
+ }
91
+ }
92
+
93
+ return false;
94
+ }
95
+
96
+ /** Block requests to private/internal networks. Prevents SSRF to cloud metadata, localhost, etc. */
97
+ export function isBlockedUrl(url: string): boolean {
98
+ let parsed: URL;
99
+ try {
100
+ parsed = new URL(url);
101
+ } catch {
102
+ return true; // Malformed URL = blocked
103
+ }
104
+
105
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
106
+ return true;
107
+ }
108
+
109
+ return isBlockedHost(parsed.hostname);
110
+ }
@@ -0,0 +1,20 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Canonical token-usage shape reported by an LLM provider for a completion.
6
+ *
7
+ * Wire format is snake_case (AFPS `appstrate.metric` event, the platform's
8
+ * `runs.tokenUsage` JSONB column, the runner-event ingestion route, and every
9
+ * cost-accounting consumer). All four fields are OPTIONAL — this is the widest
10
+ * shape and matches wire reality where usage may be partial. It is the single
11
+ * definition re-exported by `@appstrate/core/token-usage`,
12
+ * `@appstrate/shared-types`, `@appstrate/afps-runtime`, the Drizzle schema, the
13
+ * web realtime hooks, and the CLI runner.
14
+ */
15
+ export interface TokenUsage {
16
+ input_tokens?: number;
17
+ output_tokens?: number;
18
+ cache_creation_input_tokens?: number;
19
+ cache_read_input_tokens?: number;
20
+ }