@coffre/core 0.15.0 → 0.16.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.
Files changed (70) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-CgQTlUMz.js → access-CF8UG59J.js} +70 -95
  3. package/dist/{access-DqLJjnLM.d.ts → access-ERdGGHG7.d.ts} +45 -64
  4. package/dist/access.d.ts +2 -2
  5. package/dist/access.js +2 -2
  6. package/dist/envelope.d.ts +28 -9
  7. package/dist/envelope.js +25 -8
  8. package/dist/identity.d.ts +3 -1018
  9. package/dist/identity.js +885 -623
  10. package/dist/index-DuG9p3GH.d.ts +1233 -0
  11. package/dist/kek.d.ts +10 -16
  12. package/dist/kek.js +26 -41
  13. package/dist/log.d.ts +114 -0
  14. package/dist/log.js +291 -0
  15. package/dist/mcp.d.ts +27 -4
  16. package/dist/mcp.js +31 -10
  17. package/dist/recipe-BgJpmJum.d.ts +128 -0
  18. package/dist/recipe.d.ts +2 -127
  19. package/dist/{registry-D7X-x202.d.ts → registry-B7_LUDsJ.d.ts} +30 -5
  20. package/dist/schemas.d.ts +14 -12
  21. package/dist/schemas.js +16 -14
  22. package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
  23. package/dist/vault.d.ts +1771 -1419
  24. package/dist/vault.js +96 -302
  25. package/dist/{workloads-D049JH0M.d.ts → workloads-CW2dK4AW.d.ts} +1 -9
  26. package/dist/workloads.d.ts +2 -2
  27. package/dist/workloads.js +1 -9
  28. package/package.json +7 -7
  29. package/src/access.ts +63 -95
  30. package/src/changes/access.ts +140 -0
  31. package/src/changes/freezes.ts +40 -0
  32. package/src/changes/mcp.ts +150 -0
  33. package/src/changes/places.ts +219 -0
  34. package/src/changes/secrets.ts +235 -0
  35. package/src/changes/signin.ts +197 -0
  36. package/src/changes/workloads.ts +166 -0
  37. package/src/context.ts +18 -2
  38. package/src/envelope.ts +35 -12
  39. package/src/identity/auth.ts +11 -3
  40. package/src/identity/aws.ts +62 -0
  41. package/src/identity/github-app.ts +45 -24
  42. package/src/identity/index.ts +3 -2
  43. package/src/identity/{profile-rules.ts → profiles.ts} +1 -9
  44. package/src/identity/proofs.ts +306 -0
  45. package/src/identity/signin/config.ts +1 -1
  46. package/src/identity/tokens.ts +10 -3
  47. package/src/identity/verifier.ts +73 -14
  48. package/src/identity/workload-token.ts +4 -0
  49. package/src/identity/workloads.ts +0 -11
  50. package/src/kek/aws-kms.ts +18 -13
  51. package/src/kek/check.ts +16 -46
  52. package/src/kek/index.ts +2 -2
  53. package/src/kek/types.ts +15 -3
  54. package/src/log/index.ts +7 -0
  55. package/src/{audit → log}/tiles.ts +18 -49
  56. package/src/{audit → log}/tree.ts +2 -2
  57. package/src/mcp.ts +36 -9
  58. package/src/schemas.ts +15 -12
  59. package/src/vault.ts +251 -1150
  60. package/dist/merkle.d.ts +0 -456
  61. package/dist/merkle.js +0 -964
  62. package/src/answers.ts +0 -209
  63. package/src/audit/leaf.ts +0 -81
  64. package/src/audit/merkle.ts +0 -13
  65. package/src/audit/note.ts +0 -187
  66. package/src/audit/pair.ts +0 -86
  67. package/src/audit/verify.ts +0 -393
  68. package/src/audit/witness.ts +0 -50
  69. package/src/checkpoint.ts +0 -22
  70. package/src/identity/run-proof.ts +0 -159
@@ -0,0 +1,166 @@
1
+ import type { CallerIdentity } from '../identity/aws.ts';
2
+ import type { VerifiedUnder } from '../identity/proofs.ts';
3
+ import type { Issued } from './signin.ts';
4
+
5
+ /**
6
+ * The changes of workloads signing in (`packages/vault/src/ops/workloads.ts`,
7
+ * docs/design/0.16.md, "A workload signing in").
8
+ */
9
+ export type WorkloadChanges = TokenExchange | WorkloadSignin | WorkloadRenew | TokenBind | TokenUnbind;
10
+
11
+ export type WorkloadAnswers = {
12
+ 'token.exchange': Exchanged;
13
+ 'workload.signin': Session;
14
+ 'workload.renew': Renewed;
15
+ 'token.bind': Bound;
16
+ 'token.unbind': { binding: string };
17
+ };
18
+
19
+ /** The workloads' changes nobody asks: a CI run, or a workload signing in, has no credential yet, only its platform's proof. */
20
+ export type WorkloadsUnasked = 'token.exchange' | 'workload.signin';
21
+
22
+ /**
23
+ * A CI run trades its platform's ID token for a service token of five
24
+ * minutes, issued by the oldest of the service's bindings with no policy
25
+ * that takes it.
26
+ *
27
+ * - `token` is the ID token itself, which the vault reads its claims
28
+ * from: the app verified its signature under `under`, the issuer and
29
+ * the address of its keys, and the vault takes that on its word. For a
30
+ * binding that carries its keys, `under.jwksUri` is theirs,
31
+ * `sha256:<hex>`, and the vault verifies the signature itself, under the
32
+ * keys on its own row.
33
+ * - `publicUrl` is the app's own, which a CI run's token names as its
34
+ * audience.
35
+ * - `credential` is the SHA-256 of the token the app drew, lowercase hex.
36
+ *
37
+ * Refused (docs/design/0.16.md, "A refusal"): `no_match`, `audience`,
38
+ * `expired`, `too_old`, `malformed`, `replayed`, `unknown_signer`, and
39
+ * `tampered` for a binding or the service's row written behind the vault.
40
+ * A refusal writes nothing and is not logged.
41
+ */
42
+ export type TokenExchange = { op: 'token.exchange'; service: string; token: string; under: VerifiedUnder; publicUrl: string; credential: string };
43
+
44
+ /** The token made, and the binding that issued it, by which the app counts a binding's rate. */
45
+ export type Exchanged = Issued & { binding: string };
46
+
47
+ /**
48
+ * A workload's proof, by its kind: a platform's ID token, with the keys the
49
+ * app verified it under (`token.exchange`'s `token` and `under`), or STS's
50
+ * answer to the `GetCallerIdentity` request the workload signed, which the
51
+ * app checked whole and sent.
52
+ */
53
+ export type WorkloadProof = { oidc: { token: string; under: VerifiedUnder } } | { aws: CallerIdentity };
54
+
55
+ /**
56
+ * A workload trades its proof for a session bound to a key it holds,
57
+ * issued by the oldest of the service's bindings with a policy, of that
58
+ * proof's profiles, that takes it.
59
+ *
60
+ * - `key` is the thumbprint of the key the request's own proof (RFC 9449)
61
+ * named, which the app held to the request: the session is that key's
62
+ * alone, and a token whose audience names a key names this one.
63
+ * - `publicUrl` and `credential` as for `token.exchange`.
64
+ *
65
+ * Refused as `token.exchange` is, and `frozen` for a service, a binding or
66
+ * every workload a manager froze, as 0.14 refused it. A binding whose
67
+ * sources the request comes from outside, or that lists reads where the
68
+ * deployment lets none (`noReads`), is `no_match`. A refusal writes nothing
69
+ * and is not logged.
70
+ */
71
+ export type WorkloadSignin = { op: 'workload.signin'; service: string; proof: WorkloadProof; key: string; publicUrl: string; credential: string };
72
+
73
+ /**
74
+ * The session made: its token's expiry, an hour on or its hard end, and
75
+ * that hard end; the environments it reaches as of now, by id, as its row
76
+ * lists them, which the app names by path; and the binding that issued it,
77
+ * by which the app counts a binding's rate.
78
+ */
79
+ export type Session = Issued & { binding: string; notAfter: string; places: string[] };
80
+
81
+ /**
82
+ * A workload's session moves its own expiry on, by its key's proof: an
83
+ * hour from now, never past its hard end. A frozen session renews, so that
84
+ * lifting the freeze restores it; one stopped for any other reason, or
85
+ * narrowed from another, does not. Refused `expired` within five seconds of
86
+ * its expiry, so that a renewal that comes late revives nothing.
87
+ */
88
+ export type WorkloadRenew = { op: 'workload.renew' };
89
+
90
+ /** The session's expiry, moved on, or as it was at its hard end. */
91
+ export type Renewed = { expiresAt: string };
92
+
93
+ /**
94
+ * A binding to make, as 0.14's `POST /members/:m/bindings` took it, and
95
+ * checked as it did (`checkBinding`, `checkPolicy`, the profile's rule):
96
+ *
97
+ * - `keys`: where its issuer's keys are, the address the app's discovery
98
+ * found (a URN profile's, its issuer), which the vault takes on the
99
+ * app's word and seals; or the keys themselves, uploaded, a JWKS the
100
+ * vault checks and keeps (`uploadedKeys`).
101
+ * - `policy`: a workload's binding's, null for one a CI run's exchange
102
+ * takes (a bearer profile's; under `useOnly`, every binding is a
103
+ * workload's). Its `reads` name each environment by path, and its keys
104
+ * by name or `"*"`, which the vault finds and seals by id.
105
+ * - `scope`: what its credentials reach, by path, as a service token's
106
+ * (`token.create`); null for what the bindings it replaces reached, of
107
+ * what the service still holds, or else all the service holds.
108
+ * - `replaces`: the live bindings it takes the place of, by id. Those of
109
+ * its issuer whose keys are elsewhere go too (`keys_moved`).
110
+ * - `only`: true when `replaces` is all it may end, as an approval page
111
+ * listed them: one of its issuer's whose keys are elsewhere and that it
112
+ * does not name refuses `stale`, and nothing is made.
113
+ */
114
+ export type NewBinding = {
115
+ profile: string;
116
+ issuer: string | null;
117
+ claims: Record<string, unknown>;
118
+ keys: { uri: string } | { jwks: unknown };
119
+ policy: Record<string, unknown> | null;
120
+ scope: Record<string, string> | null;
121
+ label: string | null;
122
+ replaces: string[];
123
+ only?: boolean;
124
+ };
125
+
126
+ /**
127
+ * Trust a workload as a service (`binding`), or give its bindings on an
128
+ * issuer new keys, uploaded (`keys`): each is replaced by one the same but
129
+ * for its keys, reaching what it did of what the service still holds.
130
+ * Whoever manages the service (`managesService`), each grant of the scope
131
+ * one they could give it and it holds (`issuesCredential`); its sensitive
132
+ * values only where an Owner of the project binds it (`ownsProject`). A
133
+ * binding is never edited: a replaced one is revoked, and the credentials
134
+ * it issued end with it.
135
+ *
136
+ * Refused: `unauthenticated` and a stopped caller's words; `no_access`,
137
+ * for one who does not manage the service, or a place not found or beyond
138
+ * them; `unknown_principal`, a service that is not active; `tampered`, any
139
+ * row read that is not the vault's; `invalid`, a role that is none there, a
140
+ * read outside the scope or of a key the environment does not hold, a
141
+ * policy its reads break, uploaded keys that are no JWKS, or replaced
142
+ * bindings that reach nothing the service still holds or a place with two
143
+ * roles; `no_grants`, a scope with nothing to reach; `not_owner_issued`, a
144
+ * sensitive key read where no Owner of its project binds; `no_reads`, reads
145
+ * where the deployment lets none; `unknown_binding`, a binding replaced
146
+ * that is not live, or no binding on the issuer whose keys are replaced;
147
+ * `keys_differ`, other bindings on the issuer whose keys are elsewhere,
148
+ * uploaded on one side; `same_keys`, keys the bindings carry already;
149
+ * `too_many_bindings`, past `MAX_BINDINGS` live.
150
+ */
151
+ export type TokenBind = { op: 'token.bind'; member: string } & ({ binding: NewBinding } | { keys: { issuer: string; jwks: unknown } });
152
+
153
+ /**
154
+ * The bindings made, each with what it reaches by path and role and the
155
+ * places of those whose sensitive values it will not read (`withheld`:
156
+ * each holds one of a project no Owner of which binds it, R32), and the
157
+ * bindings revoked, by id.
158
+ */
159
+ export type Bound = { bindings: { id: string; scope: Record<string, string>; withheld: string[] }[]; replaced: string[] };
160
+
161
+ /**
162
+ * Remove a binding: whoever manages its service. Its row is revoked, and
163
+ * the credentials it issued end with it. Refused `unknown_binding` for
164
+ * one that is not a live binding of the service, and as `token.bind` is.
165
+ */
166
+ export type TokenUnbind = { op: 'token.unbind'; member: string; binding: string };
package/src/context.ts CHANGED
@@ -18,6 +18,11 @@ import { createHash } from 'node:crypto';
18
18
  * docs/design/credential-proxy.md, section 2): a forged owner or sensitivity
19
19
  * column fails to open, rather than granting. The value's own ciphertext
20
20
  * binds the ids alone, so a version made sensitive keeps its ciphertext.
21
+ *
22
+ * From envelope version 2 the wrap names the version's number too,
23
+ * `version`: a version's row copied over another of the same secret, an old
24
+ * value put back as the current one, does not open either. And whether the
25
+ * value is plain, `plain`, as it names whether it is sensitive.
21
26
  */
22
27
  export type SecretContext = {
23
28
  projectId: string;
@@ -27,6 +32,15 @@ export type SecretContext = {
27
32
  owner?: string;
28
33
  /** A sensitive value's: never handed back to a person (`sensitive` in @coffre/core/vault). Absent otherwise, never false. */
29
34
  sensitive?: true;
35
+ /**
36
+ * A plain value's, one marked not secret, which whoever lists its
37
+ * environment sees: never sensitive too. From envelope version 2, so that
38
+ * a secret relabelled plain, to be handed to whoever reads plain values,
39
+ * does not open. Absent otherwise, never false.
40
+ */
41
+ plain?: true;
42
+ /** The version's number among its secret's, from 1. Absent in the wrap of a value written before envelope version 2. */
43
+ version?: number;
30
44
  };
31
45
 
32
46
  /**
@@ -44,7 +58,7 @@ function assertUuid(value: string, field: string): void {
44
58
  }
45
59
  }
46
60
 
47
- /** Throw unless every field is a lowercase UUID, an owner a lowercase SHA-256, and `sensitive` true if there. */
61
+ /** Throw unless every field is a lowercase UUID, an owner a lowercase SHA-256, `sensitive` and `plain` true if there and never both, and a version a number from 1. */
48
62
  export function checkContext(ctx: SecretContext): void {
49
63
  assertUuid(ctx.projectId, 'projectId');
50
64
  assertUuid(ctx.environmentId, 'environmentId');
@@ -53,6 +67,8 @@ export function checkContext(ctx: SecretContext): void {
53
67
  throw new Error(`context.owner must be a lowercase SHA-256, got: ${String(ctx.owner)}`);
54
68
  }
55
69
  if (ctx.sensitive !== undefined && ctx.sensitive !== true) throw new Error(`context.sensitive is true or absent, got: ${String(ctx.sensitive)}`);
70
+ if (ctx.plain !== undefined && (ctx.plain !== true || ctx.sensitive === true)) throw new Error(`context.plain is true or absent, and never with sensitive, got: ${String(ctx.plain)}`);
71
+ if (ctx.version !== undefined && !(Number.isSafeInteger(ctx.version) && ctx.version > 0)) throw new Error(`context.version is a version's number, from 1, got: ${String(ctx.version)}`);
56
72
  }
57
73
 
58
74
  const OWNER_RE = /^[0-9a-f]{64}$/;
@@ -76,7 +92,7 @@ export function ownerKey(member: string): string {
76
92
  export function encodeAad(ctx: SecretContext): Buffer {
77
93
  checkContext(ctx);
78
94
  return Buffer.from(
79
- `${AAD_VERSION}|${ctx.projectId}|${ctx.environmentId}|${ctx.secretId}${ctx.owner === undefined ? '' : `|owner:${ctx.owner}`}${ctx.sensitive === true ? '|sensitive' : ''}`,
95
+ `${AAD_VERSION}|${ctx.projectId}|${ctx.environmentId}|${ctx.secretId}${ctx.owner === undefined ? '' : `|owner:${ctx.owner}`}${ctx.sensitive === true ? '|sensitive' : ''}${ctx.plain === true ? '|plain' : ''}${ctx.version === undefined ? '' : `|version:${ctx.version}`}`,
80
96
  'utf8',
81
97
  );
82
98
  }
package/src/envelope.ts CHANGED
@@ -10,10 +10,22 @@ const IV_BYTES = 12;
10
10
  const TAG_BYTES = 16;
11
11
 
12
12
  /**
13
- * Current envelope format version. Stored on every row so the format can change
14
- * without a bulk re-encryption.
13
+ * The envelope's format, stored on every row so that it can change without a
14
+ * bulk re-encryption. The two differ in what the wrap of a value's key
15
+ * names (`SecretContext`). In 1, all 0.14 wrote, its secret, a personal
16
+ * config's owner and whether it is sensitive. In 2 the version's number
17
+ * too, and whether the value is plain: without the number, a database
18
+ * writer could copy a secret's old version over its current one, and it
19
+ * would open.
20
+ *
21
+ * `seal` writes format 2 and `open` reads nothing else. Were format 1 still
22
+ * read, a row of 0.14's kept aside could be put back over any later version
23
+ * of its secret, relabelled 1, and open. The vault's adoption of a 0.14
24
+ * database wraps every key again under its number, with the registry's own
25
+ * `unwrap` and `wrap`: the ciphertext stays. From then on a format-1 row
26
+ * with a key to open is one nobody wrote.
15
27
  */
16
- export const ENVELOPE_VERSION = 1;
28
+ export const ENVELOPE_VERSION = 2;
17
29
 
18
30
  /**
19
31
  * One sealed secret value, exactly as it is stored in `secret_versions`.
@@ -33,8 +45,11 @@ export type Envelope = {
33
45
  ciphertext: Buffer;
34
46
  };
35
47
 
36
- /** The part of an envelope the data key produces: everything but the wrapped key. */
37
- export type Sealed = Pick<Envelope, 'envelopeVersion' | 'iv' | 'authTag' | 'ciphertext'>;
48
+ /**
49
+ * The part of an envelope the data key produces. It has no format of its
50
+ * own: an envelope's format is its wrap's, which whoever wraps the key says.
51
+ */
52
+ export type Sealed = Pick<Envelope, 'iv' | 'authTag' | 'ciphertext'>;
38
53
 
39
54
  /** A fresh data key. One per version, so no key ever encrypts two values. */
40
55
  export function freshDek(): Buffer {
@@ -51,7 +66,7 @@ export function encrypt(plaintext: Buffer, ctx: SecretIds, dek: Buffer): Sealed
51
66
  const cipher = createCipheriv('aes-256-gcm', dek, iv);
52
67
  cipher.setAAD(valueAad(ctx));
53
68
  const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
54
- return { envelopeVersion: ENVELOPE_VERSION, iv, authTag: cipher.getAuthTag(), ciphertext };
69
+ return { iv, authTag: cipher.getAuthTag(), ciphertext };
55
70
  }
56
71
 
57
72
  /**
@@ -61,9 +76,6 @@ export function encrypt(plaintext: Buffer, ctx: SecretIds, dek: Buffer): Sealed
61
76
  * ciphertext across environments fail closed.
62
77
  */
63
78
  export function decrypt(envelope: Sealed, ctx: SecretIds, dek: Buffer): Buffer {
64
- if (envelope.envelopeVersion !== ENVELOPE_VERSION) {
65
- throw new Error(`unsupported envelope version: ${envelope.envelopeVersion}`);
66
- }
67
79
  if (envelope.iv.length !== IV_BYTES) {
68
80
  throw new Error('envelope IV has the wrong length');
69
81
  }
@@ -83,6 +95,9 @@ function valueAad(ctx: SecretIds): Buffer {
83
95
  return encodeAad({ projectId: ctx.projectId, environmentId: ctx.environmentId, secretId: ctx.secretId });
84
96
  }
85
97
 
98
+ /** A version's context as 0.16 writes and reads it: its number is in the wrap. */
99
+ export type NumberedContext = SecretContext & { version: number };
100
+
86
101
  /**
87
102
  * Encrypt a secret value under a fresh DEK, and wrap that DEK under the
88
103
  * registry's primary KEK: `encrypt` and the wrap in one, where both halves
@@ -90,15 +105,17 @@ function valueAad(ctx: SecretIds): Buffer {
90
105
  */
91
106
  export async function seal(
92
107
  plaintext: Buffer,
93
- ctx: SecretContext,
108
+ ctx: NumberedContext,
94
109
  keks: KekRegistry,
95
110
  ): Promise<Envelope> {
111
+ requireNumber(ctx);
96
112
  const dek = freshDek();
97
113
  try {
98
114
  const sealed = encrypt(plaintext, ctx, dek);
99
115
  const wrapped = await keks.wrap(dek, ctx);
100
116
  return {
101
117
  ...sealed,
118
+ envelopeVersion: ENVELOPE_VERSION,
102
119
  kekProvider: wrapped.kekProvider,
103
120
  kekId: wrapped.kekId,
104
121
  kekVersion: wrapped.kekVersion,
@@ -109,15 +126,16 @@ export async function seal(
109
126
  }
110
127
  }
111
128
 
112
- /** Unwrap the envelope's DEK under the registry and decrypt: `decrypt` and the unwrap in one. */
129
+ /** Unwrap the envelope's DEK under the registry and decrypt: `decrypt` and the unwrap in one. Format 2 only (`ENVELOPE_VERSION`). */
113
130
  export async function open(
114
131
  envelope: Envelope,
115
- ctx: SecretContext,
132
+ ctx: NumberedContext,
116
133
  keks: KekRegistry,
117
134
  ): Promise<Buffer> {
118
135
  if (envelope.envelopeVersion !== ENVELOPE_VERSION) {
119
136
  throw new Error(`unsupported envelope version: ${envelope.envelopeVersion}`);
120
137
  }
138
+ requireNumber(ctx);
121
139
  const dek = await keks.unwrap(
122
140
  {
123
141
  kekProvider: envelope.kekProvider,
@@ -133,3 +151,8 @@ export async function open(
133
151
  dek.fill(0);
134
152
  }
135
153
  }
154
+
155
+ /** The type says it, and a caller that is not typed is told. */
156
+ function requireNumber(ctx: SecretContext): void {
157
+ if (ctx.version === undefined) throw new Error("a value is sealed and opened under its version's number");
158
+ }
@@ -1,4 +1,4 @@
1
- import { defineSignin, type McpOptions, type SigninConfig, type WorkloadsOptions } from './signin/config.ts';
1
+ import { defineSignin, lifetime, type McpOptions, type SigninConfig, type WorkloadsOptions } from './signin/config.ts';
2
2
  import type { SigninProvider } from './signin/types.ts';
3
3
  import type { AccessVerifierConfig } from './types.ts';
4
4
 
@@ -21,6 +21,8 @@ export type AuthConfig =
21
21
  | {
22
22
  mode: 'cloudflare';
23
23
  access: AccessVerifierConfig;
24
+ /** How long the coffre session a browser signs in to behind Access lasts, at most: Access is still asked on every request. */
25
+ browserSessionHours: number;
24
26
  };
25
27
 
26
28
  /**
@@ -62,11 +64,16 @@ function checkAudience(audience: string): string {
62
64
  /**
63
65
  * Cloudflare Access in front of coffre: every request carries Access's
64
66
  * signed assertion, checked against the team's keys and the application's
65
- * AUD tag.
67
+ * AUD tag. A browser's first request signs its person in to a session of
68
+ * coffre's, which every later one shows beside the assertion; the CLI and
69
+ * machines are not served behind Access yet.
66
70
  *
67
71
  * cloudflareAccess({ teamDomain: 'acme.cloudflareaccess.com', audience: env.ACCESS_AUD })
72
+ *
73
+ * `browserSessionHours`: the longest that session lasts, 12 hours unless
74
+ * set, at most a week. Access's own session is the one people see.
68
75
  */
69
- export function cloudflareAccess(options: { teamDomain: string; audience: string }): Auth {
76
+ export function cloudflareAccess(options: { teamDomain: string; audience: string; browserSessionHours?: number }): Auth {
70
77
  const domain = options.teamDomain.trim();
71
78
  const issuerUrl = httpsOrigin('the Access team domain', domain.includes('://') ? domain : `https://${domain}`);
72
79
  if (
@@ -84,6 +91,7 @@ export function cloudflareAccess(options: { teamDomain: string; audience: string
84
91
  jwksUrl: `${issuer}/cdn-cgi/access/certs`,
85
92
  audience: checkAudience(options.audience.trim()),
86
93
  },
94
+ browserSessionHours: lifetime(options.browserSessionHours, 'browserSessionHours', 12, 24 * 7),
87
95
  };
88
96
  return { resolve: () => config };
89
97
  }
@@ -0,0 +1,62 @@
1
+ import { oldestMatching, policyOf, type ExchangeRefused, type ProofBinding } from './proofs.ts';
2
+ import { PROFILE_URNS } from './workloads.ts';
3
+
4
+ /**
5
+ * The `aws` proof's answer, held to a service's bindings
6
+ * (docs/design/workload-access.md, section 4.3; docs/design/0.16.md, "A
7
+ * workload signing in"). The app checks the request the workload signed,
8
+ * a `GetCallerIdentity` naming this instance and the session's key, sends
9
+ * it to STS, and hands the vault STS's answer, on its word: which account,
10
+ * and whose credentials. The vault says which binding that is.
11
+ */
12
+
13
+ /** What STS says signed the request: `GetCallerIdentityResult`'s three fields. */
14
+ export type CallerIdentity = { account: string; arn: string; userId: string };
15
+
16
+ /** An assumed role's session, as a binding names its role: by account and the role's unique ID, which a role made again under the same name does not keep. */
17
+ export type AwsIdentity = { account: string; roleId: string; arn: string; role: string; session: string };
18
+
19
+ const ACCOUNT = /^\d{12}$/;
20
+ const ASSUMED_ROLE = /^arn:aws:sts::(\d{12}):assumed-role\/([\w+=,.@-]{1,64})\/([\w+=,.@-]{2,64})$/;
21
+ const ROLE_SESSION = /^(AROA[A-Z0-9]{8,124}):([\w+=,.@-]{2,64})$/;
22
+
23
+ /**
24
+ * The role a caller's identity is a session of, or why none: an account's
25
+ * root, a federated user and an IAM user are `no_match`, since each means a
26
+ * long-lived key on disk, which a workload does not hold, and so is any
27
+ * other partition than `aws`. An answer whose account, ARN and user ID
28
+ * disagree is no answer STS gives: `malformed` (0.14's server took it as
29
+ * STS unavailable).
30
+ */
31
+ export function assumedRole(identity: CallerIdentity): AwsIdentity | ExchangeRefused {
32
+ if (!ACCOUNT.test(identity.account)) return { refused: 'malformed' };
33
+ // Only an assumed role's session is one: a root's `arn:aws:iam::<account>:root`, a federated user's, an IAM user's (`AIDA…`) are not.
34
+ const role = ASSUMED_ROLE.exec(identity.arn);
35
+ const session = ROLE_SESSION.exec(identity.userId);
36
+ if (role === null || session === null) return { refused: 'no_match' };
37
+ if (role[1] !== identity.account || session[2] !== role[3]) return { refused: 'malformed' };
38
+ return { account: identity.account, roleId: session[1]!, arn: identity.arn, role: role[2]!, session: role[3]! };
39
+ }
40
+
41
+ /** The claims an `aws` binding matches, as the proof makes them. */
42
+ export function awsClaims(identity: AwsIdentity): { account: string; role_id: string } {
43
+ return { account: identity.account, role_id: identity.roleId };
44
+ }
45
+
46
+ /**
47
+ * STS's answer held to a service's bindings: the oldest `aws` binding with
48
+ * a policy that names its role's account and unique ID, and the claims the
49
+ * session's entry gives, the role's ARN and session name with them. The
50
+ * request named the session's key and this instance under its signature,
51
+ * so nothing is spent, and nothing but its binding's hours ends the
52
+ * session early.
53
+ */
54
+ export function matchAwsAnswer<B extends ProofBinding>(answer: CallerIdentity, bindings: readonly B[]): { binding: B; claims: Record<string, string> } | ExchangeRefused {
55
+ const candidates = bindings.filter((binding) => binding.profile === 'aws' && binding.issuer === PROFILE_URNS.aws && policyOf(binding) != null);
56
+ if (candidates.length === 0) return { refused: 'no_match' };
57
+ const identity = assumedRole(answer);
58
+ if ('refused' in identity) return identity;
59
+ const binding = oldestMatching(candidates, awsClaims(identity));
60
+ if (binding === null) return { refused: 'no_match' };
61
+ return { binding, claims: { ...awsClaims(identity), arn: identity.arn, session: identity.session } };
62
+ }
@@ -113,19 +113,27 @@ export class GitHubApp {
113
113
  return this.clientId === null || this.#clientSecret === null ? null : { clientId: this.clientId, clientSecret: this.#clientSecret };
114
114
  }
115
115
 
116
- /** Every repository of every account the app is installed on, as many as `MAX_LISTING_REQUESTS` reach. */
117
- async repositories(): Promise<GitHubAppRepositories> {
116
+ /**
117
+ * Every repository of every account the app is installed on, as many as
118
+ * `MAX_LISTING_REQUESTS` reach. `signal` ends every request still going
119
+ * when it aborts, and the listing with `GitHubAppUnavailable`: the caller's
120
+ * deadline for the whole of it, beside each request's own.
121
+ */
122
+ async repositories(options: { signal?: AbortSignal } = {}): Promise<GitHubAppRepositories> {
123
+ // One installation's failure fails the listing, and ends its siblings' requests, settled before it answers.
124
+ const failed = new AbortController();
125
+ const signal = options.signal === undefined ? failed.signal : AbortSignal.any([options.signal, failed.signal]);
118
126
  // Every request the listing makes spends from it, tokens and retries included.
119
127
  const budget: Budget = { left: MAX_LISTING_REQUESTS };
120
- this.#app ??= await this.#appInfo(budget);
121
- const { installations, more } = await this.#installations(budget);
128
+ this.#app ??= await this.#appInfo(budget, signal);
129
+ const { installations, more } = await this.#installations(budget, signal);
122
130
  let truncated = more;
123
131
  /** An installation's repositories, its first page paid from `own`, and the rest from what the listing has left. */
124
132
  const list = async (installation: Installation, own: Budget): Promise<GitHubRepository[]> => {
125
133
  const repositories: GitHubRepository[] = [];
126
134
  try {
127
135
  for (let page = 1; ; page++) {
128
- const body = record(await this.#asInstallation(installation.id, `/installation/repositories?per_page=${PAGE}&page=${page}`, { budget: own }));
136
+ const body = record(await this.#asInstallation(installation.id, `/installation/repositories?per_page=${PAGE}&page=${page}`, { budget: own, signal }));
129
137
  const items = Array.isArray(body.repositories) ? body.repositories : [];
130
138
  repositories.push(...items.flatMap((item) => repository(item) ?? []));
131
139
  const total = typeof body.total_count === 'number' ? body.total_count : 0;
@@ -154,7 +162,15 @@ export class GitHubApp {
154
162
  break;
155
163
  }
156
164
  rest = rest.slice(wave.length);
157
- listed.push(...(await Promise.all(wave.map(({ installation, own }) => list(installation, own)))));
165
+ // The first to fail says why, once every other has settled: those it ended fail only for it.
166
+ const failures: unknown[] = [];
167
+ const pages = await Promise.all(wave.map(({ installation, own }) => list(installation, own).catch((error: unknown) => {
168
+ failures.push(error);
169
+ failed.abort();
170
+ return [];
171
+ })));
172
+ if (failures.length > 0) throw failures[0];
173
+ listed.push(...pages);
158
174
  for (const { own } of wave) budget.left += own.left;
159
175
  }
160
176
  const byId = new Map(listed.flat().map((each) => [each.repositoryId, each]));
@@ -166,22 +182,23 @@ export class GitHubApp {
166
182
  };
167
183
  }
168
184
 
169
- /** `owner/name`'s IDs, when the app is installed on it; null when it is not, its installation is suspended, or GitHub knows no such repository. */
170
- async repository(fullName: string): Promise<GitHubRepository | null> {
171
- const { id, suspended_at: suspended } = record(await this.#asApp(`/repos/${fullName}/installation`, { missing: true }));
185
+ /** `owner/name`'s IDs, when the app is installed on it; null when it is not, its installation is suspended, or GitHub knows no such repository. `signal` as for `repositories`. */
186
+ async repository(fullName: string, options: { signal?: AbortSignal } = {}): Promise<GitHubRepository | null> {
187
+ const { signal } = options;
188
+ const { id, suspended_at: suspended } = record(await this.#asApp(`/repos/${fullName}/installation`, { missing: true, signal }));
172
189
  if (typeof id !== 'number' || (suspended !== null && suspended !== undefined)) return null;
173
- return repository(await this.#asInstallation(id, `/repos/${fullName}`, { missing: true }));
190
+ return repository(await this.#asInstallation(id, `/repos/${fullName}`, { missing: true, signal }));
174
191
  }
175
192
 
176
- async #appInfo(budget: Budget): Promise<GitHubAppRepositories['app']> {
177
- const app = record(await this.#asApp('/app', { budget }));
193
+ async #appInfo(budget: Budget, signal: AbortSignal | undefined): Promise<GitHubAppRepositories['app']> {
194
+ const app = record(await this.#asApp('/app', { budget, signal }));
178
195
  if (typeof app.name !== 'string' || typeof app.html_url !== 'string') throw new GitHubAppUnavailable('GitHub answered /app without the app');
179
196
  return { name: app.name, installUrl: `${app.html_url}/installations/new` };
180
197
  }
181
198
 
182
199
  /** The installations not suspended, of the first page: `more` when there may be others. */
183
- async #installations(budget: Budget): Promise<{ installations: Installation[]; more: boolean }> {
184
- const answer = await this.#asApp(`/app/installations?per_page=${PAGE}`, { budget });
200
+ async #installations(budget: Budget, signal: AbortSignal | undefined): Promise<{ installations: Installation[]; more: boolean }> {
201
+ const answer = await this.#asApp(`/app/installations?per_page=${PAGE}`, { budget, signal });
185
202
  const items = Array.isArray(answer) ? answer : [];
186
203
  const installations = items.flatMap((item): Installation[] => {
187
204
  const { id, account, suspended_at: suspended } = record(item);
@@ -191,18 +208,18 @@ export class GitHubApp {
191
208
  return { installations: installations.sort((a, b) => a.account.localeCompare(b.account)), more: items.length >= PAGE };
192
209
  }
193
210
 
194
- async #asApp(path: string, options: { missing?: boolean; budget?: Budget } = {}): Promise<unknown> {
211
+ async #asApp(path: string, options: Asked = {}): Promise<unknown> {
195
212
  return this.#call(path, { method: 'GET', token: await this.#jwt(), ...options });
196
213
  }
197
214
 
198
215
  /** As the installation, with its token; once more with a fresh one should GitHub refuse the one kept (the app was reinstalled, say). */
199
- async #asInstallation(id: number, path: string, options: { missing?: boolean; budget?: Budget } = {}): Promise<unknown> {
216
+ async #asInstallation(id: number, path: string, options: Asked = {}): Promise<unknown> {
200
217
  const kept = this.#kept(id);
201
218
  const fresh = kept === null;
202
- const token = kept ?? (await this.#issueToken(id, options.budget));
219
+ const token = kept ?? (await this.#issueToken(id, options));
203
220
  const answer = await this.#call(path, { method: 'GET', token, ...options, refused: !fresh });
204
221
  if (answer !== REFUSED) return answer;
205
- return this.#call(path, { method: 'GET', token: await this.#issueToken(id, options.budget), ...options });
222
+ return this.#call(path, { method: 'GET', token: await this.#issueToken(id, options), ...options });
206
223
  }
207
224
 
208
225
  /** The installation's token, while it has more than `TOKEN_MARGIN_MS` to live. */
@@ -212,9 +229,9 @@ export class GitHubApp {
212
229
  }
213
230
 
214
231
  /** https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app */
215
- async #issueToken(id: number, budget?: Budget): Promise<string> {
232
+ async #issueToken(id: number, { budget, signal }: Asked): Promise<string> {
216
233
  this.#tokens.delete(id);
217
- const answer = record(await this.#call(`/app/installations/${id}/access_tokens`, { method: 'POST', token: await this.#jwt(), budget }));
234
+ const answer = record(await this.#call(`/app/installations/${id}/access_tokens`, { method: 'POST', token: await this.#jwt(), budget, signal }));
218
235
  const expiresAt = typeof answer.expires_at === 'string' ? Date.parse(answer.expires_at) : NaN;
219
236
  if (typeof answer.token !== 'string' || !Number.isFinite(expiresAt)) throw new GitHubAppUnavailable('GitHub issued no installation token');
220
237
  this.#tokens.set(id, { token: answer.token, expiresAt });
@@ -239,16 +256,17 @@ export class GitHubApp {
239
256
  * `SPENT` when none is left. A 404 is null where `missing` allows it; a
240
257
  * 401 is `REFUSED` where `refused` asks, for a token to be issued again;
241
258
  * any other answer than a 2xx says GitHub's status and the path, and a
242
- * redirect is never followed.
259
+ * redirect is never followed. It ends at its own deadline, or at the
260
+ * caller's `signal`, whichever comes first.
243
261
  */
244
- async #call(path: string, request: { method: 'GET' | 'POST'; token: string; missing?: boolean; refused?: boolean; budget?: Budget }): Promise<unknown> {
262
+ async #call(path: string, request: Asked & { method: 'GET' | 'POST'; token: string; refused?: boolean }): Promise<unknown> {
245
263
  if (request.budget !== undefined && !spend(request.budget)) throw SPENT;
246
264
  let response: Response;
247
265
  try {
248
266
  response = await this.#fetch(`${this.apiUrl}${path}`, {
249
267
  method: request.method,
250
268
  redirect: 'manual',
251
- signal: AbortSignal.timeout(DEADLINE_MS),
269
+ signal: request.signal === undefined ? AbortSignal.timeout(DEADLINE_MS) : AbortSignal.any([AbortSignal.timeout(DEADLINE_MS), request.signal]),
252
270
  headers: {
253
271
  accept: 'application/vnd.github+json',
254
272
  authorization: `Bearer ${request.token}`,
@@ -257,7 +275,7 @@ export class GitHubApp {
257
275
  },
258
276
  });
259
277
  } catch (cause) {
260
- throw new GitHubAppUnavailable('GitHub could not be reached', { cause });
278
+ throw new GitHubAppUnavailable(request.signal?.aborted === true ? 'GitHub did not answer in time' : 'GitHub could not be reached', { cause });
261
279
  }
262
280
  if (response.ok) {
263
281
  try {
@@ -274,6 +292,9 @@ export class GitHubApp {
274
292
  }
275
293
  }
276
294
 
295
+ /** What a request is asked with: a 404 as null, the listing's budget, the caller's deadline. */
296
+ type Asked = { missing?: boolean; budget?: Budget; signal?: AbortSignal };
297
+
277
298
  /** A kept token GitHub refused. */
278
299
  const REFUSED = Symbol('refused');
279
300
  /** A listing's requests, left to make: an installation's own reserve first, then the listing's. */
@@ -1,10 +1,11 @@
1
1
  // `@coffre/core/identity`: who is asking, and how coffre's sign-in finds out.
2
2
  export * from './auth.ts';
3
+ export * from './aws.ts';
3
4
  export * from './constraints.ts';
4
5
  export * from './dpop.ts';
5
6
  export * from './github-app.ts';
6
- export * from './profile-rules.ts';
7
- export * from './run-proof.ts';
7
+ export * from './profiles.ts';
8
+ export * from './proofs.ts';
8
9
  export * from './signin/index.ts';
9
10
  export * from './tokens.ts';
10
11
  export * from './types.ts';
@@ -1,12 +1,4 @@
1
- import {
2
- BindingInvalid,
3
- claimAt,
4
- KEY_NAMING_PROFILES,
5
- type BindingClaims,
6
- type BindingPolicy,
7
- type CheckedBinding,
8
- type WorkloadProfile,
9
- } from './workloads.ts';
1
+ import { BindingInvalid, claimAt, KEY_NAMING_PROFILES, type BindingClaims, type BindingPolicy, type CheckedBinding, type WorkloadProfile } from './workloads.ts';
10
2
 
11
3
  /**
12
4
  * What each platform's binding and tokens must say beyond the claims a