@coffre/core 0.10.2 → 0.12.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.
@@ -18,6 +18,7 @@
18
18
  * one of the deployment's own, in the same list.
19
19
  */
20
20
  import { GitHubApp, pkcs8Of, type GitHubAppOptions } from '../github-app.ts';
21
+ import type { WorkloadAlert } from '../workloads.ts';
21
22
  import { GitHubSigninProvider } from './github.ts';
22
23
  import { OidcSigninProvider } from './oidc.ts';
23
24
  import type { SigninBrand, SigninProvider } from './types.ts';
@@ -105,6 +106,18 @@ export type WorkloadsOptions = {
105
106
  * and only public ones' IDs are looked up.
106
107
  */
107
108
  github?: GitHubApp;
109
+ /**
110
+ * Leaves services nothing but key-bound sessions (docs/design/
111
+ * workload-access.md, section 6.3): no service token is issued or taken,
112
+ * and `/api/auth/oidc` answers 410. Its sessions still read their
113
+ * bindings' listed `reads`. Taken, and not yet enforced: that design's PR
114
+ * 1a does.
115
+ */
116
+ useOnly?: boolean;
117
+ /** Stricter still: no binding may list `reads`, so services read plain values only. Taken, and not yet enforced (PR 1a). */
118
+ noReads?: boolean;
119
+ /** The deployment's own delivery of a workload's alerts, called in the background after the response: a Slack webhook, a pager. */
120
+ alert?: (alert: WorkloadAlert) => unknown;
108
121
  };
109
122
 
110
123
  /** Cloudflare's rate-limiting binding, as coffre calls it; `processLimits()` has the same shape. */
@@ -112,7 +125,14 @@ export type RateLimiter = { limit(options: { key: string }): Promise<{ success:
112
125
 
113
126
  export type WorkloadLimits = { perSource: RateLimiter; total: RateLimiter };
114
127
 
115
- export type WorkloadsConfig = { allowLoopback: boolean; limits: WorkloadLimits; github: GitHubApp | null };
128
+ export type WorkloadsConfig = {
129
+ allowLoopback: boolean;
130
+ limits: WorkloadLimits;
131
+ github: GitHubApp | null;
132
+ useOnly: boolean;
133
+ noReads: boolean;
134
+ alert: ((alert: WorkloadAlert) => unknown) | null;
135
+ };
116
136
 
117
137
  /**
118
138
  * MCP clients, Claude among them, acting as the people who connect them,
@@ -423,7 +443,18 @@ function workloadsConfig(options: WorkloadsOptions, publicUrl: string): Workload
423
443
  if (app !== undefined && app.apiUrl !== 'https://api.github.com' && !isLoopback(new URL(app.apiUrl))) {
424
444
  throw new Error('workloads.github is for github.com: GitHub Enterprise Server is not supported yet; sign in with its app, and leave workloads.github out');
425
445
  }
426
- return { allowLoopback: loopback, limits: options.limits, github: app ?? null };
446
+ for (const flag of ['useOnly', 'noReads'] as const) {
447
+ if (options[flag] !== undefined && typeof options[flag] !== 'boolean') throw new Error(`workloads.${flag} is true or false`);
448
+ }
449
+ if (options.alert !== undefined && typeof options.alert !== 'function') throw new Error('workloads.alert is a function, given each alert');
450
+ return {
451
+ allowLoopback: loopback,
452
+ limits: options.limits,
453
+ github: app ?? null,
454
+ useOnly: options.useOnly === true,
455
+ noReads: options.noReads === true,
456
+ alert: options.alert ?? null,
457
+ };
427
458
  }
428
459
 
429
460
  /** A deployment's own provider is checked like coffre's: it is only typed, not trusted. */
@@ -36,8 +36,11 @@ export function seal(key: Uint8Array, value: unknown, ttlSeconds: number, now =
36
36
  /** The sealed value, or null when it is malformed, forged, tampered with or expired. */
37
37
  export function unseal<T>(key: Uint8Array, sealed: string | undefined | null, now = Date.now()): T | null {
38
38
  if (!sealed?.startsWith(`${VERSION}.`)) return null;
39
- const raw = Buffer.from(sealed.slice(VERSION.length + 1), 'base64url');
40
- if (raw.length <= IV_BYTES + TAG_BYTES) return null;
39
+ const body = sealed.slice(VERSION.length + 1);
40
+ const raw = Buffer.from(body, 'base64url');
41
+ // The decoder skips what is not base64url and a last character's unused
42
+ // bits, so only the spelling `seal` writes opens: one string per value.
43
+ if (raw.length <= IV_BYTES + TAG_BYTES || raw.toString('base64url') !== body) return null;
41
44
  try {
42
45
  const decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, IV_BYTES));
43
46
  decipher.setAAD(Buffer.from(VERSION));
@@ -5,7 +5,12 @@ import { createHash, randomBytes } from 'node:crypto';
5
5
  * service tokens, personal tokens, which act as the person who made
6
6
  * them within the scope they named, and handles, which reach nothing but
7
7
  * the credential proxy (`@coffre/server/plugins/credential-proxy`): the
8
- * placeholder a person's app holds in place of a secret's value.
8
+ * placeholder a person's app holds in place of a secret's value. And a
9
+ * workload's sessions, which are bound to its key and useless without a
10
+ * proof it signs (docs/design/workload-access.md, section 5), and the
11
+ * enrollment codes CI mints for platforms that sign nothing, which are no
12
+ * credential at all: they buy a session at `/api/auth/workload`, and every
13
+ * other route refuses one.
9
14
  *
10
15
  * A token is a kind prefix and 32 random bytes, e.g.
11
16
  * `coffre_cli_Qm9Y...`. The prefix tells a person (or a secret scanner) what a
@@ -14,19 +19,24 @@ import { createHash, randomBytes } from 'node:crypto';
14
19
  * right tool here, unlike for passwords: 256 bits of randomness leave nothing
15
20
  * to brute-force.
16
21
  */
17
- export type CredentialKind = 'browser' | 'cli' | 'service' | 'personal' | 'handle';
22
+ export type CredentialKind = 'browser' | 'cli' | 'service' | 'personal' | 'handle' | 'workload';
18
23
 
19
- const PREFIX: Record<CredentialKind, string> = {
24
+ /** What a token's prefix says it is: a credential, or an enrollment code. */
25
+ export type TokenKind = CredentialKind | 'enrollment';
26
+
27
+ const PREFIX: Record<TokenKind, string> = {
20
28
  browser: 'coffre_web_',
21
29
  cli: 'coffre_cli_',
22
30
  service: 'coffre_svc_',
23
31
  personal: 'coffre_pat_',
24
32
  handle: 'coffre_use_',
33
+ workload: 'coffre_wl_',
34
+ enrollment: 'coffre_enr_',
25
35
  };
26
36
 
27
- const TOKEN = /^coffre_(web|cli|svc|pat|use)_[A-Za-z0-9_-]{43}$/;
37
+ const TOKEN = /^coffre_(web|cli|svc|pat|use|wl|enr)_[A-Za-z0-9_-]{43}$/;
28
38
 
29
- export function generateToken(kind: CredentialKind): string {
39
+ export function generateToken(kind: TokenKind): string {
30
40
  return PREFIX[kind] + randomBytes(32).toString('base64url');
31
41
  }
32
42
 
@@ -39,9 +49,9 @@ export function isCoffreToken(value: string): boolean {
39
49
  * The kind a token's prefix says, before any lookup. Its hash covers the
40
50
  * prefix, so a token found under its hash is the kind it says.
41
51
  */
42
- export function tokenKind(token: string): CredentialKind | null {
52
+ export function tokenKind(token: string): TokenKind | null {
43
53
  if (!TOKEN.test(token)) return null;
44
- return (Object.keys(PREFIX) as CredentialKind[]).find((kind) => token.startsWith(PREFIX[kind])) ?? null;
54
+ return (Object.keys(PREFIX) as TokenKind[]).find((kind) => token.startsWith(PREFIX[kind])) ?? null;
45
55
  }
46
56
 
47
57
  export function hashToken(token: string): Buffer {
@@ -24,8 +24,8 @@ function asNonEmptyString(value: unknown): string | null {
24
24
  /**
25
25
  * Verifies Cloudflare Access JWTs.
26
26
  *
27
- * Signature and claim verification for the TanStack request boundary. The
28
- * boundary also rejects `x-middleware-subrequest` before calling this verifier.
27
+ * Signature and claim verification of the token Access sends with each
28
+ * request.
29
29
  */
30
30
  export class AccessIdentityVerifier implements IdentityVerifier {
31
31
  readonly #config: AccessVerifierConfig;
@@ -99,12 +99,15 @@ export function decodeWorkloadToken(token: string): DecodedToken {
99
99
  * the issuer exactly; `exp`, `nbf` and `iat` within the tolerance, `iat` at
100
100
  * most an hour old; and the audience, this instance's public URL alone.
101
101
  * With `maxLifetime`, in seconds, a token whose `exp` is further than that
102
- * from its `iat` is refused too. Returns the verified claims.
102
+ * from its `iat` is refused too. With `maxAge: null`, its `iat` may be any
103
+ * age, and its own `exp` alone ends it: a token its platform hands out
104
+ * again for hours, a managed identity's (docs/design/workload-access.md,
105
+ * section 4.2). Returns the verified claims.
103
106
  */
104
107
  export async function verifyWorkloadToken(
105
108
  token: string,
106
109
  keys: JSONWebKeySet,
107
- expected: { issuer: string; audience: string; now: Date; maxLifetime?: number },
110
+ expected: { issuer: string; audience: string; now: Date; maxLifetime?: number; maxAge?: null },
108
111
  ): Promise<JWTPayload & DecodedToken['claims']> {
109
112
  const options = {
110
113
  algorithms: [...WORKLOAD_ALGORITHMS],
@@ -121,7 +124,7 @@ export async function verifyWorkloadToken(
121
124
  if (!(error instanceof errors.JWKSMultipleMatchingKeys)) throw refusalOf(error);
122
125
  payload = await anyKey(token, error, options);
123
126
  }
124
- const issued = issuedRefusal(payload.iat!, expected.now.getTime() / 1000);
127
+ const issued = issuedRefusal(payload.iat!, expected.now.getTime() / 1000, expected.maxAge === null ? Infinity : MAX_TOKEN_AGE_SECONDS);
125
128
  if (issued !== null) throw issued;
126
129
  if (expected.maxLifetime !== undefined && payload.exp! - payload.iat! > expected.maxLifetime) {
127
130
  throw new WorkloadTokenRefused('too_long', `the token lives longer than ${expected.maxLifetime / 60} minutes, from its iat to its exp: ask for a shorter one`);
@@ -135,13 +138,13 @@ export async function verifyWorkloadToken(
135
138
 
136
139
  /**
137
140
  * Why a token issued at `iat` may not be exchanged at `now`, both in
138
- * seconds, or null: issued an hour ago at most, exactly, and no further
139
- * ahead than the clock tolerance. Verification and the exchange's commit
140
- * both ask it.
141
+ * seconds, or null: issued `maxAge` seconds ago at most, an hour unless
142
+ * said, exactly, and no further ahead than the clock tolerance.
143
+ * Verification and the exchange's commit both ask it.
141
144
  */
142
- export function issuedRefusal(iat: number, now: number): WorkloadTokenRefused | null {
143
- if (now - iat > MAX_TOKEN_AGE_SECONDS) {
144
- return new WorkloadTokenRefused('too_old', `the token was issued more than ${MAX_TOKEN_AGE_SECONDS / 60} minutes ago`);
145
+ export function issuedRefusal(iat: number, now: number, maxAge = MAX_TOKEN_AGE_SECONDS): WorkloadTokenRefused | null {
146
+ if (now - iat > maxAge) {
147
+ return new WorkloadTokenRefused('too_old', `the token was issued more than ${maxAge / 60} minutes ago`);
145
148
  }
146
149
  if (iat - now > CLOCK_TOLERANCE_SECONDS) return new WorkloadTokenRefused('too_old', 'the token says it was issued in the future');
147
150
  return null;