@coffre/client 0.8.2 → 0.10.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/src/credential.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A credential through coffre's credential proxy, for an app `coffre run`
3
- * started with stand-ins (docs/design/credential-proxy.md): where its
3
+ * started with placeholders (docs/design/credential-proxy.md): where its
4
4
  * client takes no base URL to point at the proxy, or the code is new.
5
5
  *
6
6
  * import { credential } from '@coffre/client/credential';
@@ -8,8 +8,9 @@
8
8
  * const companies = await (await schumann.fetch('/companies?q=acme')).json();
9
9
  *
10
10
  * `coffre run` sets `COFFRE_CREDENTIALS`, each credential's URL on the
11
- * proxy by name, and `COFFRE_HANDLE`, the handle that stands in for the
12
- * environment's values; the proxy injects the key, and the app never holds it.
11
+ * proxy by name, its environment's (`…/use/market/dev/schumann`), and
12
+ * `COFFRE_HANDLE`, the handle that stands in for the environment's values;
13
+ * the proxy injects the key, and the app never holds it.
13
14
  */
14
15
  export type ProxiedCredential = {
15
16
  /** The credential's URL on the proxy: `<url>/<path>` is `<upstream>/<path>`. */
@@ -24,6 +25,12 @@ export type ProxiedCredential = {
24
25
  * browser or anyone to use until then.
25
26
  */
26
27
  presign(path: string, options?: { method?: 'GET' | 'HEAD'; expiresIn?: number; query?: Record<string, string> }): Promise<{ url: string; expiresAt: string }>;
28
+ /**
29
+ * A signature of `message` (a string signs as its UTF-8) by a signer's
30
+ * private key, which stays in coffre: what Node's `crypto.sign(undefined,
31
+ * message, key)` gives, base64url. Each is one use in coffre's log.
32
+ */
33
+ sign(message: Uint8Array | string): Promise<string>;
27
34
  };
28
35
 
29
36
  type Env = Record<string, string | undefined>;
@@ -45,6 +52,15 @@ export function credential(
45
52
  if (typeof url !== 'string' || handle === undefined) {
46
53
  throw new Error(`no credential ${name} here: \`coffre run\` gives the app the credentials its environment holds, which the deployment's proxy names`);
47
54
  }
55
+ /** What the handle asks coffre to make with the environment's values, at the environment's own URL on the proxy, which the credential's is under. */
56
+ const compute = async (asked: unknown) => {
57
+ const answer = await fetcher(url.slice(0, url.lastIndexOf('/')), {
58
+ method: 'POST',
59
+ headers: { authorization: `Bearer ${handle}`, 'content-type': 'application/json' },
60
+ body: JSON.stringify(asked),
61
+ });
62
+ return { answer, body: (await answer.json()) as { url?: string; expiresAt?: string; signature?: string; message?: string } };
63
+ };
48
64
  return {
49
65
  url,
50
66
  fetch: (path, init = {}) => {
@@ -53,15 +69,17 @@ export function credential(
53
69
  return fetcher(`${url}${path.startsWith('/') ? '' : '/'}${path}`, { ...init, headers });
54
70
  },
55
71
  presign: async (path, options = {}) => {
56
- // The environment's own URL on the proxy, which the credential's is under.
57
- const answer = await fetcher(url.slice(0, url.lastIndexOf('/')), {
58
- method: 'POST',
59
- headers: { authorization: `Bearer ${handle}`, 'content-type': 'application/json' },
60
- body: JSON.stringify({ presign: { credential: name, path, ...options } }),
61
- });
62
- const body = (await answer.json()) as { url?: string; expiresAt?: string; message?: string };
72
+ const { answer, body } = await compute({ presign: { credential: name, path, ...options } });
63
73
  if (!answer.ok || body.url === undefined) throw new Error(`coffre presigned nothing: ${body.message ?? answer.status}`);
64
74
  return { url: body.url, expiresAt: body.expiresAt! };
65
75
  },
76
+ sign: async (message) => {
77
+ const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;
78
+ let binary = '';
79
+ for (const byte of bytes) binary += String.fromCharCode(byte);
80
+ const { answer, body } = await compute({ sign: { credential: name, message: btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') } });
81
+ if (!answer.ok || body.signature === undefined) throw new Error(`coffre signed nothing: ${body.message ?? answer.status}`);
82
+ return body.signature;
83
+ },
66
84
  };
67
85
  }
package/src/index.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * its own handling of Cloudflare Access redirects. A request that never
11
11
  * reaches the instance throws `Unreachable`, which says why.
12
12
  */
13
- import type { Api, AuthInfo, BindingPlan, BindingView, DeletionResult, DryRunOutcome, DryRunResult, InheritResult, KeysPlan, SetResult, TokenPlan } from './api.ts';
13
+ import type { Api, AuthInfo, BindingPlan, BindingView, DeletionResult, DryRunOutcome, DryRunResult, InheritResult, KeysPlan, RoleImpact, SetResult, TokenPlan } from './api.ts';
14
14
  import { Unreachable } from './reach.ts';
15
15
 
16
16
  export type {
@@ -29,7 +29,9 @@ export type {
29
29
  DismissedKey,
30
30
  DryRunOutcome,
31
31
  DryRunResult,
32
+ EnvironmentView,
32
33
  IdentityRow,
34
+ ImpactLine,
33
35
  InheritResult,
34
36
  KeysPlan,
35
37
  ListedReference,
@@ -42,6 +44,9 @@ export type {
42
44
  ProjectSummary,
43
45
  ReferenceView,
44
46
  RemovedMember,
47
+ RoleImpact,
48
+ RolesView,
49
+ RoleView,
45
50
  SecretKey,
46
51
  SecretVersion,
47
52
  SessionRow,
@@ -110,6 +115,14 @@ function place(path: string): { project: string; environment: string; key: strin
110
115
  return { project, environment, key };
111
116
  }
112
117
 
118
+ /** A role's change confirmed: an instance role's, and the `revision` of the policy its preview answered with. */
119
+ type Confirmed = { instance?: boolean; revision?: string };
120
+
121
+ /** `?revision=57.3f9a0c2e81b4d7a6`, or nothing for a change asked without its preview. */
122
+ function asPreviewed(revision: string | undefined): string {
123
+ return revision === undefined ? '' : `?revision=${encodeURIComponent(revision)}`;
124
+ }
125
+
113
126
  export function createClient(options: ClientOptions) {
114
127
  const origin = options.url.replace(/\/+$/, '');
115
128
  const transport =
@@ -196,6 +209,12 @@ export function createClient(options: ClientOptions) {
196
209
  call('PUT /projects/:project/:environment', place(path), input),
197
210
  update: (path: string, patch: RouteInput<'PATCH /projects/:project/:environment'>) =>
198
211
  call('PATCH /projects/:project/:environment', place(path), patch),
212
+ /**
213
+ * Protected, a person holds their role's protected column there
214
+ * (docs/design/roles.md); whoever manages the project's environments
215
+ * protects one, and only an Owner of the whole instance unprotects it.
216
+ */
217
+ protect: (path: string, on = true) => call('PATCH /projects/:project/:environment', place(path), { protected: on }),
199
218
  /** What deleting an archived environment would erase and revoke; changes nothing. */
200
219
  previewDelete: (path: string) => {
201
220
  const [method, route] = address('DELETE /projects/:project/:environment', place(path));
@@ -293,7 +312,7 @@ export function createClient(options: ClientOptions) {
293
312
  },
294
313
 
295
314
  /**
296
- * Handles: stand-ins a person's app holds in place of an environment's
315
+ * Handles: placeholders a person's app holds in place of an environment's
297
316
  * values, which only the credential proxy (`/use`) takes. The value is
298
317
  * in the answer, and only there; it is revoked as a token is.
299
318
  */
@@ -395,6 +414,40 @@ export function createClient(options: ClientOptions) {
395
414
  disconnect: (id: string) => call('DELETE /apps/:id', { id }),
396
415
  },
397
416
 
417
+ /**
418
+ * The instance's roles, in two columns, an environment's that is not
419
+ * protected and one's that is (docs/design/roles.md). Any member lists
420
+ * them; an Owner of the whole instance edits them. `instance` is about
421
+ * instance roles, a person's across every project in their scope.
422
+ */
423
+ roles: {
424
+ list: () => call('GET /roles', {}),
425
+ /** What defining the role so would do to everyone it reaches; changes nothing. */
426
+ preview: (role: string, definition: RouteInput<'PUT /roles/:role'>, { instance = false } = {}) => {
427
+ const [method, route] = instance ? address('PUT /instance-roles/:role', { role }) : address('PUT /roles/:role', { role });
428
+ return send(method, `${route}?dryRun=1`, definition) as Promise<RoleImpact>;
429
+ },
430
+ /**
431
+ * A built-in role edited, or one an Owner makes. With its preview's
432
+ * `revision`, made as previewed, or refused (409 `policy_changed`)
433
+ * if the policy changed since: preview it again.
434
+ */
435
+ set: (role: string, definition: RouteInput<'PUT /roles/:role'>, { instance = false, revision }: Confirmed = {}) => {
436
+ const [method, route] = instance ? address('PUT /instance-roles/:role', { role }) : address('PUT /roles/:role', { role });
437
+ return send(method, `${route}${asPreviewed(revision)}`, definition) as Promise<{ role: RouteOutput<'GET /roles'>['roles'][number] | null }>;
438
+ },
439
+ /** What putting it back as it ships, or deleting one an Owner made, would do; changes nothing. */
440
+ previewReset: (role: string, { instance = false } = {}) => {
441
+ const [method, route] = instance ? address('DELETE /instance-roles/:role', { role }) : address('DELETE /roles/:role', { role });
442
+ return send(method, `${route}?dryRun=1`, undefined) as Promise<RoleImpact>;
443
+ },
444
+ /** A built-in role back as it ships; one an Owner made, deleted, while no grant names it. With its preview's `revision`, as `set`. */
445
+ reset: (role: string, { instance = false, revision }: Confirmed = {}) => {
446
+ const [method, route] = instance ? address('DELETE /instance-roles/:role', { role }) : address('DELETE /roles/:role', { role });
447
+ return send(method, `${route}${asPreviewed(revision)}`, undefined) as Promise<{ role: RouteOutput<'GET /roles'>['roles'][number] | null }>;
448
+ },
449
+ },
450
+
398
451
  /** The instance's settings, for those who run it: where people set up service accounts themselves. */
399
452
  settings: {
400
453
  get: () => call('GET /settings', {}),
package/src/routes.ts CHANGED
@@ -44,6 +44,7 @@ export function getCalls({ places, secrets, members, services }: Subjects): GetC
44
44
  'GET /members/:member/bindings': services.map((member) => ({ params: { member } })),
45
45
  'GET /workloads/lookup': [{ params: {}, input: { github: 'acme/api' } }],
46
46
  'GET /workloads/repositories': [{ params: {} }],
47
+ 'GET /roles': [{ params: {} }],
47
48
  'GET /settings': [{ params: {} }],
48
49
  'GET /sessions': [{ params: {} }],
49
50
  'GET /identities': [{ params: {} }],
@@ -107,6 +108,11 @@ const EVERY_ROUTE: { [K in RouteKey]: true } = {
107
108
  'DELETE /members/:member/bindings/:id': true,
108
109
  'GET /workloads/lookup': true,
109
110
  'GET /workloads/repositories': true,
111
+ 'GET /roles': true,
112
+ 'PUT /roles/:role': true,
113
+ 'DELETE /roles/:role': true,
114
+ 'PUT /instance-roles/:role': true,
115
+ 'DELETE /instance-roles/:role': true,
110
116
  'GET /settings': true,
111
117
  'PUT /settings': true,
112
118
  'PATCH /access/:member': true,