effect-vercel 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.
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The OIDC token Vercel issues to a deployment.
3
+ *
4
+ * In Functions the token arrives on each request as the `x-vercel-oidc-token`
5
+ * header and rotates, so it is read on every run of `token`/`find`, never
6
+ * cached. In builds and after `vercel env pull` it is `VERCEL_OIDC_TOKEN`.
7
+ * Use it to authenticate to the AI Gateway, or exchange it for cloud
8
+ * credentials (AWS `AssumeRoleWithWebIdentity`, GCP workload identity
9
+ * federation).
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { VercelOidc } from "effect-vercel/oidc"
14
+ * import { Effect, Redacted } from "effect"
15
+ *
16
+ * const program = Effect.gen(function* () {
17
+ * const token = yield* VercelOidc.token
18
+ * // pass Redacted.value(token) as the web identity token
19
+ * })
20
+ * ```
21
+ */
22
+
23
+ import { Config, Data, Effect, Option, Redacted } from "effect"
24
+
25
+ /** The environment variable read when no request carries a token. */
26
+ export const TOKEN_ENV = "VERCEL_OIDC_TOKEN"
27
+
28
+ /** No usable OIDC token. */
29
+ export class VercelOidcError extends Data.TaggedError("VercelOidcError")<{
30
+ readonly message: string
31
+ readonly hints: ReadonlyArray<string>
32
+ readonly cause?: unknown
33
+ }> {}
34
+
35
+ /** How to make a token available. */
36
+ export const hints: ReadonlyArray<string> = [
37
+ "Run on Vercel, where each request carries an OIDC token.",
38
+ `Or run \`vercel env pull\` locally to populate ${TOKEN_ENV}.`,
39
+ ]
40
+
41
+ /**
42
+ * Vercel exposes the current request's context on a well-known global symbol.
43
+ * In Functions, the `x-vercel-oidc-token` header of the request lives there.
44
+ * Mirrors `@vercel/oidc`'s `getVercelOidcTokenSync`, minus the dev-time
45
+ * refresh that package also offers.
46
+ */
47
+ const REQUEST_CONTEXT = Symbol.for("@vercel/request-context")
48
+
49
+ type RequestContext = { readonly headers?: Record<string, string | undefined> }
50
+
51
+ const fromRequestContext = Effect.sync(() => {
52
+ const holder = globalThis as typeof globalThis & {
53
+ [REQUEST_CONTEXT]?: { get?: () => RequestContext | undefined }
54
+ }
55
+ return Option.fromNullishOr(
56
+ holder[REQUEST_CONTEXT]?.get?.()?.headers?.["x-vercel-oidc-token"],
57
+ ).pipe(Option.map(Redacted.make))
58
+ })
59
+
60
+ const fromEnv = Config.option(Config.redacted(TOKEN_ENV)).pipe(
61
+ Effect.catchTag(
62
+ "ConfigError",
63
+ (cause) => new VercelOidcError({ message: `Failed to read ${TOKEN_ENV}.`, hints, cause }),
64
+ ),
65
+ )
66
+
67
+ /**
68
+ * The token if one is available: the request header, else `VERCEL_OIDC_TOKEN`.
69
+ * `None` means neither is set, so a caller can fall back to something else.
70
+ */
71
+ export const find: Effect.Effect<
72
+ Option.Option<Redacted.Redacted<string>>,
73
+ VercelOidcError
74
+ > = Effect.flatMap(fromRequestContext, (found) =>
75
+ Option.isSome(found) ? Effect.succeed(found) : fromEnv,
76
+ )
77
+
78
+ /** Like `find`, but fails when no token is available. */
79
+ export const token: Effect.Effect<Redacted.Redacted<string>, VercelOidcError> = Effect.flatMap(
80
+ find,
81
+ Option.match({
82
+ onNone: () =>
83
+ Effect.fail(new VercelOidcError({ message: "No Vercel OIDC token is available.", hints })),
84
+ onSome: Effect.succeed,
85
+ }),
86
+ )
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Effect `Persistence` backed by the Vercel Runtime Cache, so a
3
+ * `PersistedCache` shares results across Function instances in a region.
4
+ *
5
+ * Outside Vercel, `getCache` falls back to an in-memory cache, so the same
6
+ * layer works in local dev and tests.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { VercelRuntimeCache } from "effect-vercel/runtime-cache"
11
+ * import { Effect } from "effect"
12
+ * import { PersistedCache } from "effect/unstable/persistence"
13
+ *
14
+ * const program = Effect.gen(function* () {
15
+ * const users = yield* PersistedCache.make(fetchUser, {
16
+ * storeId: "users",
17
+ * timeToLive: () => "1 hour",
18
+ * })
19
+ * return yield* users.get(new GetUser({ id: 1 }))
20
+ * }).pipe(Effect.scoped, Effect.provide(VercelRuntimeCache.layer))
21
+ * ```
22
+ */
23
+
24
+ import { createHash } from "node:crypto"
25
+ import { getCache, type RuntimeCache } from "@vercel/functions"
26
+ import { Duration, Effect, Layer } from "effect"
27
+ import { Persistence } from "effect/unstable/persistence"
28
+
29
+ const sha256 = (key: string) => createHash("sha256").update(key).digest("hex")
30
+
31
+ /**
32
+ * A `BackingPersistence` over `cache`.
33
+ *
34
+ * Entries are keyed by the JSON pair `[storeId, key]`, so no two stores share
35
+ * a key. Each entry is tagged with a hash of the store id, since tags are
36
+ * joined with `,` and sent unescaped, and `clear` expires that tag. Entries
37
+ * are sent without a name, so keys don't reach Vercel's o11y or the request
38
+ * headers, where non-Latin-1 characters would make the write fail. TTLs round
39
+ * up to whole seconds, the cache's resolution.
40
+ *
41
+ * `getCache()` hashes keys with a 32-bit hash by default, which can collide.
42
+ * Pass a cache made with a stronger `keyHashFunction`, as `layerBacking` does.
43
+ */
44
+ export const makeBacking = (cache: RuntimeCache): Persistence.BackingPersistence["Service"] =>
45
+ Persistence.BackingPersistence.of({
46
+ make: (storeId) =>
47
+ Effect.sync(() => {
48
+ const prefixed = (key: string) => JSON.stringify([storeId, key])
49
+ const tag = `effect-persistence:${sha256(storeId)}`
50
+
51
+ const get = (key: string) =>
52
+ Effect.tryPromise({
53
+ try: () => cache.get(prefixed(key)),
54
+ catch: (cause) =>
55
+ new Persistence.PersistenceError({ message: `Failed to get key ${key}`, cause }),
56
+ }).pipe(
57
+ Effect.map((value) =>
58
+ typeof value === "object" && value !== null ? value : undefined,
59
+ ),
60
+ )
61
+
62
+ const set = (key: string, value: object, ttl: Duration.Duration | undefined) =>
63
+ Effect.tryPromise({
64
+ try: () =>
65
+ cache.set(prefixed(key), value, {
66
+ name: "",
67
+ tags: [tag],
68
+ ...(ttl && { ttl: Math.max(1, Math.ceil(Duration.toSeconds(ttl))) }),
69
+ }),
70
+ catch: (cause) =>
71
+ new Persistence.PersistenceError({ message: `Failed to set key ${key}`, cause }),
72
+ })
73
+
74
+ return {
75
+ get,
76
+ getMany: (keys) => Effect.forEach(keys, get, { concurrency: "unbounded" }),
77
+ set,
78
+ // Writes run concurrently, so keep only the last entry for each key.
79
+ setMany: (entries) =>
80
+ Effect.forEach(
81
+ new Map(entries.map(([key, value, ttl]) => [key, [value, ttl] as const])),
82
+ ([key, [value, ttl]]) => set(key, value, ttl),
83
+ { concurrency: "unbounded", discard: true },
84
+ ),
85
+ remove: (key) =>
86
+ Effect.tryPromise({
87
+ try: () => cache.delete(prefixed(key)),
88
+ catch: (cause) =>
89
+ new Persistence.PersistenceError({ message: `Failed to remove key ${key}`, cause }),
90
+ }),
91
+ clear: Effect.tryPromise({
92
+ try: () => cache.expireTag(tag),
93
+ catch: (cause) =>
94
+ new Persistence.PersistenceError({ message: `Failed to clear ${storeId}`, cause }),
95
+ }),
96
+ }
97
+ }),
98
+ })
99
+
100
+ /** `BackingPersistence` over `getCache()`, with SHA-256 key hashing. */
101
+ export const layerBacking: Layer.Layer<Persistence.BackingPersistence> = Layer.sync(
102
+ Persistence.BackingPersistence,
103
+ )(() => makeBacking(getCache({ keyHashFunction: sha256 })))
104
+
105
+ /** `Persistence` backed by the Vercel Runtime Cache. */
106
+ export const layer: Layer.Layer<Persistence.Persistence> = Persistence.layer.pipe(
107
+ Layer.provide(layerBacking),
108
+ )
@@ -0,0 +1,2 @@
1
+ export * as AiGateway from "./AiGateway.js"
2
+ export * as AiGatewayCredentials from "./AiGatewayCredentials.js"
package/src/oidc.ts ADDED
@@ -0,0 +1 @@
1
+ export * as VercelOidc from "./VercelOidc.js"
@@ -0,0 +1 @@
1
+ export * as VercelRuntimeCache from "./VercelRuntimeCache.js"