@yaks/secrets 0.0.0-stage → 0.2.36

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 (73) hide show
  1. package/LICENSE +202 -0
  2. package/_dist/graph.d.ts +9 -0
  3. package/_dist/graph.d.ts.map +1 -0
  4. package/_dist/mod.d.ts +67 -0
  5. package/_dist/mod.d.ts.map +1 -0
  6. package/_dist/op.d.ts +37 -0
  7. package/_dist/op.d.ts.map +1 -0
  8. package/_dist/plugin.d.ts +19 -0
  9. package/_dist/plugin.d.ts.map +1 -0
  10. package/_dist/records.d.ts +11 -0
  11. package/_dist/records.d.ts.map +1 -0
  12. package/_dist/ref.d.ts +4 -0
  13. package/_dist/ref.d.ts.map +1 -0
  14. package/_dist/reveal.d.ts +14 -0
  15. package/_dist/reveal.d.ts.map +1 -0
  16. package/_dist/sealed.d.ts +10 -0
  17. package/_dist/sealed.d.ts.map +1 -0
  18. package/_dist/sentinel.d.ts +9 -0
  19. package/_dist/sentinel.d.ts.map +1 -0
  20. package/_dist/signed.d.ts +16 -0
  21. package/_dist/signed.d.ts.map +1 -0
  22. package/_dist/vault.d.ts +49 -0
  23. package/_dist/vault.d.ts.map +1 -0
  24. package/_dist/views.d.ts +3 -0
  25. package/_dist/views.d.ts.map +1 -0
  26. package/_dist/vocab.d.ts +6 -0
  27. package/_dist/vocab.d.ts.map +1 -0
  28. package/deno.json +1 -0
  29. package/graph.js +12 -0
  30. package/graph.js.map +1 -0
  31. package/graph.ts +21 -0
  32. package/mod.js +67 -0
  33. package/mod.js.map +1 -0
  34. package/mod.ts +83 -0
  35. package/op.js +170 -0
  36. package/op.js.map +1 -0
  37. package/op.ts +188 -0
  38. package/package.json +51 -4
  39. package/plugin.js +429 -0
  40. package/plugin.js.map +1 -0
  41. package/plugin.ts +464 -0
  42. package/reads.js +51 -0
  43. package/reads.js.map +1 -0
  44. package/reads.ts +56 -0
  45. package/records.js +45 -0
  46. package/records.js.map +1 -0
  47. package/records.ts +58 -0
  48. package/ref.js +7 -0
  49. package/ref.js.map +1 -0
  50. package/ref.ts +11 -0
  51. package/reveal.js +50 -0
  52. package/reveal.js.map +1 -0
  53. package/reveal.ts +98 -0
  54. package/sealed.js +35 -0
  55. package/sealed.js.map +1 -0
  56. package/sealed.ts +31 -0
  57. package/sentinel.js +66 -0
  58. package/sentinel.js.map +1 -0
  59. package/sentinel.ts +97 -0
  60. package/signed.js +107 -0
  61. package/signed.js.map +1 -0
  62. package/signed.ts +151 -0
  63. package/vault.js +67 -0
  64. package/vault.js.map +1 -0
  65. package/vault.ts +130 -0
  66. package/views.js +27 -0
  67. package/views.js.map +1 -0
  68. package/views.ts +34 -0
  69. package/vocab.js +16 -0
  70. package/vocab.js.map +1 -0
  71. package/vocab.json +36 -0
  72. package/vocab.ts +17 -0
  73. package/README.md +0 -3
package/ref.js ADDED
@@ -0,0 +1,7 @@
1
+ // What a kept 1Password reference looks like. Pure, so every reader of a
2
+ // secret can tell a reference from a value without loading the `op` reader.
3
+ /** Whether a written value is a reference rather than a value: `op://` and at
4
+ * least vault, item and field. Spaces are fine — it is an argument, never a
5
+ * shell word — but a control character is not. */ export let isOpRef = (value)=>value.startsWith('op://') && // deno-lint-ignore no-control-regex
6
+ !/[\u0000-\u001f\u007f]/.test(value) && value.slice(5).split('/').filter((s)=>s.length > 0).length >= 3;
7
+ //# sourceMappingURL=ref.js.map
package/ref.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ref.js","sources":["./ref.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,4EAA4E;AAE5E;;gDAEgD,GAChD,OAAO,IAAI,UAAU,CAAC,QACpB,MAAM,UAAU,CAAC,YACjB,oCAAoC;EACpC,CAAC,wBAAwB,IAAI,CAAC,UAC9B,MAAM,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,MAAM,CAAC,CAAC,IAAM,EAAE,MAAM,GAAG,GAAG,MAAM,IAAI,EAAC"}
package/ref.ts ADDED
@@ -0,0 +1,11 @@
1
+ // What a kept 1Password reference looks like. Pure, so every reader of a
2
+ // secret can tell a reference from a value without loading the `op` reader.
3
+
4
+ /** Whether a written value is a reference rather than a value: `op://` and at
5
+ * least vault, item and field. Spaces are fine — it is an argument, never a
6
+ * shell word — but a control character is not. */
7
+ export let isOpRef = (value: string): boolean =>
8
+ value.startsWith('op://') &&
9
+ // deno-lint-ignore no-control-regex
10
+ !/[\u0000-\u001f\u007f]/.test(value) &&
11
+ value.slice(5).split('/').filter((s) => s.length > 0).length >= 3
package/reveal.js ADDED
@@ -0,0 +1,50 @@
1
+ // Trusted code reads a value from the vault at the moment it uses it. A name
2
+ // the vault has no value for falls back to the source its host lends. A kept
3
+ // 1Password reference stays unresolved: servers have no 1Password sign-in, and only a
4
+ // person's interactive command reads references through opRead.
5
+ import { after } from "@yaks/fp";
6
+ import { isOpRef } from "./ref.js";
7
+ import { secretEids } from "./sealed.js";
8
+ import { sentinel } from "./sentinel.js";
9
+ // An unresolved reference must neither become an outgoing credential nor
10
+ // select a different credential from the environment.
11
+ let valueOf = (kept, name, s)=>{
12
+ if (kept?.op) return undefined;
13
+ let value = kept?.value ?? s.env?.(name);
14
+ return value && isOpRef(value) ? undefined : value;
15
+ };
16
+ export let found = (vault, eids)=>{
17
+ let [eid, ...rest] = eids;
18
+ return eid ? after(vault.read(eid), (kept)=>kept ?? found(vault, rest)) : undefined;
19
+ };
20
+ /** A secret's value, by name. */ export let reveal = (vault, name, s = {})=>after(found(vault, secretEids(name)), (kept)=>valueOf(kept, name, s));
21
+ /** Read selected secrets by name, keeping each value's outcome independent.
22
+ * Both current and legacy addresses share the same storage lookup. */ export let reveals = async (vault, names, s = {})=>{
23
+ let addresses = [
24
+ ...new Set(names)
25
+ ].map((name)=>({
26
+ name,
27
+ eids: secretEids(name)
28
+ }));
29
+ if (!addresses.length) return new Map();
30
+ let rows = await vault.readMany?.(addresses.flatMap(({ eids })=>eids));
31
+ let source = rows ? {
32
+ read: (eid)=>{
33
+ let row = rows.get(eid);
34
+ if (row?.status == 'rejected') throw row.reason;
35
+ return row?.value;
36
+ }
37
+ } : vault;
38
+ let values = await Promise.allSettled(addresses.map(async ({ name, eids })=>valueOf(await found(source, eids), name, s)));
39
+ return new Map(addresses.map(({ name }, i)=>[
40
+ name,
41
+ values[i]
42
+ ]));
43
+ };
44
+ /** The sentinel for a secret, by name: its handle hashed under the vault's
45
+ * salt (./sentinel.ts). A name nothing was written for has none. A secret
46
+ * kept as several named parts (a connection's fields) has one for each
47
+ * `part`, its handle and the part's name hashed together; a handle holds no
48
+ * `#`, so none is another's. */ export let sentinelOf = (vault, name, part)=>Promise.resolve(found(vault, secretEids(name))).then(async (kept)=>kept ? sentinel(await vault.salt(), part == null ? kept.handle : `${kept.handle}#${part}`) : undefined);
49
+ /** A secret's value, by name, answered on the spot. */ export let peek = (vault, name, s = {})=>valueOf(secretEids(name).map((eid)=>vault.read(eid)).find(Boolean), name, s);
50
+ //# sourceMappingURL=reveal.js.map
package/reveal.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reveal.js","sources":["./reveal.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,sFAAsF;AACtF,gEAAgE;AAEhE,SAAS,KAAK,wBAA6B;AAC3C,SAAS,OAAO,mBAAkB;AAClC,SAAS,UAAU,sBAAqB;AACxC,SAAS,QAAQ,wBAAuB;AAQxC,yEAAyE;AACzE,sDAAsD;AACtD,IAAI,UAAU,CAAC,MAA0B,MAAc;EACrD,IAAI,MAAM,IAAI,OAAO;EACrB,IAAI,QAAQ,MAAM,SAAS,EAAE,GAAG,GAAG;EACnC,OAAO,SAAS,QAAQ,SAAS,YAAY;AAC/C;AAEA,OAAO,IAAI,QAAQ,CACjB,OACA;EAEA,IAAI,CAAC,KAAK,GAAG,KAAK,GAAG;EACrB,OAAO,MACH,MAAM,MAAM,IAAI,CAAC,MAAM,CAAC,OAAS,QAAQ,MAAM,OAAO,SACtD;AACN,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QAAQ,WAAW,MAAM,GAAG,CAAC,CAAC,MAAQ,MAAM,IAAI,CAAC,MAAM,IAAI,CAAC,UAAU,MAAM,GAAE"}
package/reveal.ts ADDED
@@ -0,0 +1,98 @@
1
+ // Trusted code reads a value from the vault at the moment it uses it. A name
2
+ // the vault has no value for falls back to the source its host lends. A kept
3
+ // 1Password reference stays unresolved: servers have no 1Password sign-in, and only a
4
+ // person's interactive command reads references through opRead.
5
+
6
+ import { after } from '@yaks/fp'
7
+ import { isOpRef } from './ref.js'
8
+ import { secretEids } from './sealed.js'
9
+ import { sentinel } from './sentinel.js'
10
+ import type { Local, Sealed, Vault } from './vault.ts'
11
+
12
+ /** Where a name absent from the vault may be found. */
13
+ export type Sources = {
14
+ env?: (name: string) => string | undefined
15
+ }
16
+
17
+ // An unresolved reference must neither become an outgoing credential nor
18
+ // select a different credential from the environment.
19
+ let valueOf = (kept: Sealed | undefined, name: string, s: Sources) => {
20
+ if (kept?.op) return undefined
21
+ let value = kept?.value ?? s.env?.(name)
22
+ return value && isOpRef(value) ? undefined : value
23
+ }
24
+
25
+ export let found = (
26
+ vault: Pick<Vault, 'read'>,
27
+ eids: string[],
28
+ ): ReturnType<Vault['read']> => {
29
+ let [eid, ...rest] = eids
30
+ return eid
31
+ ? after(vault.read(eid), (kept) => kept ?? found(vault, rest))
32
+ : undefined
33
+ }
34
+
35
+ /** A secret's value, by name. */
36
+ export let reveal = (
37
+ vault: Vault,
38
+ name: string,
39
+ s: Sources = {},
40
+ ): string | undefined | Promise<string | undefined> =>
41
+ after(found(vault, secretEids(name)), (kept) => valueOf(kept, name, s))
42
+
43
+ /** Read selected secrets by name, keeping each value's outcome independent.
44
+ * Both current and legacy addresses share the same storage lookup. */
45
+ export let reveals = async (
46
+ vault: Vault,
47
+ names: Iterable<string>,
48
+ s: Sources = {},
49
+ ): Promise<Map<string, PromiseSettledResult<string | undefined>>> => {
50
+ let addresses = [...new Set(names)].map((name) => ({
51
+ name,
52
+ eids: secretEids(name),
53
+ }))
54
+ if (!addresses.length) return new Map()
55
+ let rows = await vault.readMany?.(addresses.flatMap(({ eids }) => eids))
56
+ let source = rows
57
+ ? {
58
+ read: (eid: string) => {
59
+ let row = rows.get(eid)
60
+ if (row?.status == 'rejected') throw row.reason
61
+ return row?.value
62
+ },
63
+ }
64
+ : vault
65
+ let values = await Promise.allSettled(
66
+ addresses.map(async ({ name, eids }) =>
67
+ valueOf(await found(source, eids), name, s)
68
+ ),
69
+ )
70
+ return new Map(addresses.map(({ name }, i) => [name, values[i]]))
71
+ }
72
+
73
+ /** The sentinel for a secret, by name: its handle hashed under the vault's
74
+ * salt (./sentinel.ts). A name nothing was written for has none. A secret
75
+ * kept as several named parts (a connection's fields) has one for each
76
+ * `part`, its handle and the part's name hashed together; a handle holds no
77
+ * `#`, so none is another's. */
78
+ export let sentinelOf = (
79
+ vault: Vault,
80
+ name: string,
81
+ part?: string,
82
+ ): Promise<string | undefined> =>
83
+ Promise.resolve(found(vault, secretEids(name))).then(async (kept) =>
84
+ kept
85
+ ? sentinel(
86
+ await vault.salt(),
87
+ part == null ? kept.handle : `${kept.handle}#${part}`,
88
+ )
89
+ : undefined
90
+ )
91
+
92
+ /** A secret's value, by name, answered on the spot. */
93
+ export let peek = (
94
+ vault: Local,
95
+ name: string,
96
+ s: Sources = {},
97
+ ): string | undefined =>
98
+ valueOf(secretEids(name).map((eid) => vault.read(eid)).find(Boolean), name, s)
package/sealed.js ADDED
@@ -0,0 +1,35 @@
1
+ // The bundles that write and forget a secret, exported as
2
+ // `@yaks/secrets/sealed`: pure data, so a page can write one without loading
3
+ // what reads a value back from the vault or the environment (./reveal.ts).
4
+ import { eidOf, identityEid } from "@yaks/graph/identity";
5
+ import { secretsDoc } from "./vocab.js";
6
+ /** The entity a secret is: its id is derived from its name, so one name is
7
+ * one secret and nobody has to look an id up. */ export let secretEid = (name)=>identityEid('secret', [
8
+ name
9
+ ]);
10
+ let current = eidOf(secretsDoc, 'secret');
11
+ /** The two addresses of a named secret during the migration: every lookup
12
+ * and removal by name goes through these, so a secret is found at whichever
13
+ * one it is kept. */ export let secretEids = (name)=>[
14
+ ...new Set([
15
+ current(name),
16
+ secretEid(name)
17
+ ])
18
+ ];
19
+ /** The bundle that writes a secret: its value, or an `op://` reference. The
20
+ * graph keeps the handle; the vault keeps what it stands for. */ export let sealed = (name, value)=>({
21
+ entity: {
22
+ eid: secretEid(name)
23
+ },
24
+ secret: {
25
+ name,
26
+ value
27
+ }
28
+ });
29
+ /** The bundles that forget one, value and all, at either of its eids. */ export let unsealed = (name)=>secretEids(name).map((eid)=>({
30
+ entity: {
31
+ eid
32
+ },
33
+ tombstone: {}
34
+ }));
35
+ //# sourceMappingURL=sealed.js.map
package/sealed.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sealed.js","sources":["./sealed.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,6EAA6E;AAC7E,2EAA2E;AAG3E,SAAS,KAAK,EAAE,WAAW,oCAAyC;AACpE,SAAS,UAAU,qBAAoB;AAEvC;+CAC+C,GAC/C,OAAO,IAAI,YAAY,CAAC,OAAsB,YAAY,UAAU;IAAC;GAAK,EAAC;AAE3E,IAAI,UAAU,MAAM,YAAY;AAEhC;;mBAEmB,GACnB,OAAO,IAAI,aAAa,CACtB,OACU;OAAI,IAAI,IAAI;MAAC,QAAQ;MAAO,UAAU;KAAM;GAAE,CAAA;AAE1D;+DAC+D,GAC/D,OAAO,IAAI,SAAS,CAAC,MAAc,QAA0B,CAAC;IAC5D,QAAQ;MAAE,KAAK,UAAU;IAAM;IAC/B,QAAQ;MAAE;MAAM;IAAM;EACxB,CAAC,EAAC;AAEF,uEAAuE,GACvE,OAAO,IAAI,WAAW,CAAC,OACrB,WAAW,MAAM,GAAG,CAAC,CAAC,MAAQ,CAAC;MAAE,QAAQ;QAAE;MAAI;MAAG,WAAW,CAAC;IAAE,CAAC,GAAE"}
package/sealed.ts ADDED
@@ -0,0 +1,31 @@
1
+ // The bundles that write and forget a secret, exported as
2
+ // `@yaks/secrets/sealed`: pure data, so a page can write one without loading
3
+ // what reads a value back from the vault or the environment (./reveal.ts).
4
+
5
+ import type { Bundle, Eid } from 'jsr:@yaks/graph@0.2.36'
6
+ import { eidOf, identityEid } from '@yaks/graph/identity'
7
+ import { secretsDoc } from './vocab.js'
8
+
9
+ /** The entity a secret is: its id is derived from its name, so one name is
10
+ * one secret and nobody has to look an id up. */
11
+ export let secretEid = (name: string): Eid => identityEid('secret', [name])
12
+
13
+ let current = eidOf(secretsDoc, 'secret')
14
+
15
+ /** The two addresses of a named secret during the migration: every lookup
16
+ * and removal by name goes through these, so a secret is found at whichever
17
+ * one it is kept. */
18
+ export let secretEids = (
19
+ name: string,
20
+ ): Eid[] => [...new Set([current(name), secretEid(name)])]
21
+
22
+ /** The bundle that writes a secret: its value, or an `op://` reference. The
23
+ * graph keeps the handle; the vault keeps what it stands for. */
24
+ export let sealed = (name: string, value: string): Bundle => ({
25
+ entity: { eid: secretEid(name) },
26
+ secret: { name, value },
27
+ })
28
+
29
+ /** The bundles that forget one, value and all, at either of its eids. */
30
+ export let unsealed = (name: string): Bundle[] =>
31
+ secretEids(name).map((eid) => ({ entity: { eid }, tombstone: {} }))
package/sentinel.js ADDED
@@ -0,0 +1,66 @@
1
+ // The two strings that stand for a secret's value, and why there are two.
2
+ //
3
+ // The handle is what the graph keeps where a value was written: a random token,
4
+ // minted the first time a secret is written and kept for as long as it lives.
5
+ // Writing a new value — a rotation, a refreshed token — puts it behind the same
6
+ // handle. It is 256 random bits and says nothing about the value, so two
7
+ // secrets holding one value never share one. Anyone may read it: an agent, a
8
+ // config, a backup.
9
+ //
10
+ // The sentinel is what code that calls out is handed, and the only string a
11
+ // swap on the way out may ever replace with the value: the handle, hashed under
12
+ // the vault's salt. The salt never leaves the vault, so nobody reading the
13
+ // graph can compute a sentinel from a handle, and a bundle carrying handles
14
+ // around — a sync, an answer, a request that happens to quote one — is never
15
+ // swapped for a key by accident. It follows the handle, so it too survives a
16
+ // rotation.
17
+ //
18
+ // Each has its own prefix: how a reader tells a handle from a written value (a
19
+ // write carrying a handle is somebody writing back what they read, and changes
20
+ // nothing), and how a swap finds a sentinel in a request.
21
+ import { toBase64url } from "@yaks/fp";
22
+ /** What every handle starts with. */ export let PREFIX = 'yak_secret_';
23
+ /** What every sentinel starts with. */ export let SENTINEL = 'yak_sentinel_';
24
+ /** Whether a string is a handle rather than a value. */ export let isHandle = (s)=>s.startsWith(PREFIX);
25
+ /** A new handle: the prefix and 256 random bits. */ export let handle = ()=>PREFIX + toBase64url(crypto.getRandomValues(new Uint8Array(32)));
26
+ let keys = new WeakMap();
27
+ let signing = (salt)=>{
28
+ let kept = keys.get(salt);
29
+ if (kept && kept.bytes.length == salt.length && kept.bytes.every((b, i)=>b == salt[i])) return kept;
30
+ let bytes = salt.slice();
31
+ let key = crypto.subtle.importKey('raw', bytes, {
32
+ name: 'HMAC',
33
+ hash: 'SHA-256'
34
+ }, false, [
35
+ 'sign'
36
+ ]);
37
+ let next = {
38
+ bytes,
39
+ key,
40
+ sentinels: new Map()
41
+ };
42
+ keys.set(salt, next);
43
+ return next;
44
+ };
45
+ /** The sentinel for a handle, under a vault's salt. */ export let sentinel = async (salt, handle)=>{
46
+ let state = signing(salt);
47
+ let found = state.sentinels.get(handle);
48
+ if (found) return await found;
49
+ // Only deterministic public stand-ins are remembered. The vault remains
50
+ // authoritative for which handle exists and what credential it holds.
51
+ let made = state.key.then((key)=>crypto.subtle.sign('HMAC', key, new TextEncoder().encode(handle))).then((mac)=>SENTINEL + toBase64url(new Uint8Array(mac)));
52
+ if (state.sentinels.size >= 128) {
53
+ state.sentinels.delete(state.sentinels.keys().next().value);
54
+ }
55
+ state.sentinels.set(handle, made);
56
+ made.catch(()=>{
57
+ if (state.sentinels.get(handle) == made) state.sentinels.delete(handle);
58
+ });
59
+ return await made;
60
+ };
61
+ // A sentinel as it appears in text: the prefix and a SHA-256 in base64url.
62
+ let FOUND = new RegExp(`${SENTINEL}[\\w-]{43}`, 'g');
63
+ /** Every sentinel a text carries. */ export let sentinels = (text)=>text.match(FOUND) ?? [];
64
+ /** The text with each sentinel `values` has a value for replaced by it,
65
+ * verbatim: the swap on the way out. */ export let swap = (text, values)=>text.replace(FOUND, (s)=>values.get(s) ?? s);
66
+ //# sourceMappingURL=sentinel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sentinel.js","sources":["./sentinel.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,gFAAgF;AAChF,yEAAyE;AACzE,6EAA6E;AAC7E,oBAAoB;AACpB,EAAE;AACF,4EAA4E;AAC5E,gFAAgF;AAChF,2EAA2E;AAC3E,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,YAAY;AACZ,EAAE;AACF,+EAA+E;AAC/E,+EAA+E;AAC/E,0DAA0D;AAE1D,SAAS,WAAW,wBAA6B;AAEjD,mCAAmC,GACnC,OAAO,IAAI,SAAS,cAAa;AAEjC,qCAAqC,GACrC,OAAO,IAAI,WAAW,gBAAe;AAErC,sDAAsD,GACtD,OAAO,IAAI,WAAW,CAAC,IAAuB,EAAE,UAAU,CAAC,QAAO;AAElE,kDAAkD,GAClD,OAAO,IAAI,SAAS,IAClB,SAAS,YAAY,OAAO,eAAe,CAAC,IAAI,WAAW,MAAK;AAUlE,IAAI,OAAO,IAAI;AACf,IAAI,UAAU,CAAC;EACb,IAAI,OAAO,KAAK,GAAG,CAAC;EACpB,IACE,QAAQ,KAAK,KAAK,CAAC,MAAM,IAAI,KAAK,MAAM,IACxC,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC,GAAG,IAAM,KAAK,IAAI,CAAC,EAAE,GACvC,OAAO;EACT,IAAI,QAAQ,KAAK,KAAK;EACtB,IAAI,MAAM,OAAO,MAAM,CAAC,SAAS,CAC/B,OACA,OACA;IAAE,MAAM;IAAQ,MAAM;EAAU,GAChC,OACA;IAAC;GAAO;EAEV,IAAI,OAAO;IAAE;IAAO;IAAK,WAAW,IAAI;EAA+B;EACvE,KAAK,GAAG,CAAC,MAAM;EACf,OAAO;AACT;AAEA,qDAAqD,GACrD,OAAO,IAAI,WAAW,OACpB,MACA;EAEA,IAAI,QAAQ,QAAQ;EACpB,IAAI,QAAQ,MAAM,SAAS,CAAC,GAAG,CAAC;EAChC,IAAI,OAAO,OAAO,MAAM;EACxB,wEAAwE;EACxE,sEAAsE;EACtE,IAAI,OAAO,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,MACzB,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,KAAK,IAAI,cAAc,MAAM,CAAC,UACzD,IAAI,CAAC,CAAC,MAAQ,WAAW,YAAY,IAAI,WAAW;EACtD,IAAI,MAAM,SAAS,CAAC,IAAI,IAAI,KAAK;IAC/B,MAAM,SAAS,CAAC,MAAM,CAAC,MAAM,SAAS,CAAC,IAAI,GAAG,IAAI,GAAG,KAAK;EAC5D;EACA,MAAM,SAAS,CAAC,GAAG,CAAC,QAAQ;EAC5B,KAAK,KAAK,CAAC;IACT,IAAI,MAAM,SAAS,CAAC,GAAG,CAAC,WAAW,MAAM,MAAM,SAAS,CAAC,MAAM,CAAC;EAClE;EACA,OAAO,MAAM;AACf,EAAC;AAED,2EAA2E;AAC3E,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,UAAU,CAAC,EAAE;AAEhD,mCAAmC,GACnC,OAAO,IAAI,YAAY,CAAC,OAA2B,KAAK,KAAK,CAAC,UAAU,EAAE,CAAA;AAE1E;sCACsC,GACtC,OAAO,IAAI,OAAO,CAAC,MAAc,SAC/B,KAAK,OAAO,CAAC,OAAO,CAAC,IAAM,OAAO,GAAG,CAAC,MAAM,GAAE"}
package/sentinel.ts ADDED
@@ -0,0 +1,97 @@
1
+ // The two strings that stand for a secret's value, and why there are two.
2
+ //
3
+ // The handle is what the graph keeps where a value was written: a random token,
4
+ // minted the first time a secret is written and kept for as long as it lives.
5
+ // Writing a new value — a rotation, a refreshed token — puts it behind the same
6
+ // handle. It is 256 random bits and says nothing about the value, so two
7
+ // secrets holding one value never share one. Anyone may read it: an agent, a
8
+ // config, a backup.
9
+ //
10
+ // The sentinel is what code that calls out is handed, and the only string a
11
+ // swap on the way out may ever replace with the value: the handle, hashed under
12
+ // the vault's salt. The salt never leaves the vault, so nobody reading the
13
+ // graph can compute a sentinel from a handle, and a bundle carrying handles
14
+ // around — a sync, an answer, a request that happens to quote one — is never
15
+ // swapped for a key by accident. It follows the handle, so it too survives a
16
+ // rotation.
17
+ //
18
+ // Each has its own prefix: how a reader tells a handle from a written value (a
19
+ // write carrying a handle is somebody writing back what they read, and changes
20
+ // nothing), and how a swap finds a sentinel in a request.
21
+
22
+ import { toBase64url } from '@yaks/fp'
23
+
24
+ /** What every handle starts with. */
25
+ export let PREFIX = 'yak_secret_'
26
+
27
+ /** What every sentinel starts with. */
28
+ export let SENTINEL = 'yak_sentinel_'
29
+
30
+ /** Whether a string is a handle rather than a value. */
31
+ export let isHandle = (s: string): boolean => s.startsWith(PREFIX)
32
+
33
+ /** A new handle: the prefix and 256 random bits. */
34
+ export let handle = (): string =>
35
+ PREFIX + toBase64url(crypto.getRandomValues(new Uint8Array(32)))
36
+
37
+ // A vault keeps its salt, so importing its HMAC key is setup shared by every
38
+ // handle under it. Copy the bytes used for the import: callers can change a
39
+ // salt buffer, and that must select a new key even while an import is pending.
40
+ type Signing = {
41
+ bytes: Uint8Array
42
+ key: Promise<CryptoKey>
43
+ sentinels: Map<string, Promise<string>>
44
+ }
45
+ let keys = new WeakMap<Uint8Array, Signing>()
46
+ let signing = (salt: Uint8Array): Signing => {
47
+ let kept = keys.get(salt)
48
+ if (
49
+ kept && kept.bytes.length == salt.length &&
50
+ kept.bytes.every((b, i) => b == salt[i])
51
+ ) return kept
52
+ let bytes = salt.slice()
53
+ let key = crypto.subtle.importKey(
54
+ 'raw',
55
+ bytes as BufferSource,
56
+ { name: 'HMAC', hash: 'SHA-256' },
57
+ false,
58
+ ['sign'],
59
+ )
60
+ let next = { bytes, key, sentinels: new Map<string, Promise<string>>() }
61
+ keys.set(salt, next)
62
+ return next
63
+ }
64
+
65
+ /** The sentinel for a handle, under a vault's salt. */
66
+ export let sentinel = async (
67
+ salt: Uint8Array,
68
+ handle: string,
69
+ ): Promise<string> => {
70
+ let state = signing(salt)
71
+ let found = state.sentinels.get(handle)
72
+ if (found) return await found
73
+ // Only deterministic public stand-ins are remembered. The vault remains
74
+ // authoritative for which handle exists and what credential it holds.
75
+ let made = state.key.then((key) =>
76
+ crypto.subtle.sign('HMAC', key, new TextEncoder().encode(handle))
77
+ ).then((mac) => SENTINEL + toBase64url(new Uint8Array(mac)))
78
+ if (state.sentinels.size >= 128) {
79
+ state.sentinels.delete(state.sentinels.keys().next().value!)
80
+ }
81
+ state.sentinels.set(handle, made)
82
+ made.catch(() => {
83
+ if (state.sentinels.get(handle) == made) state.sentinels.delete(handle)
84
+ })
85
+ return await made
86
+ }
87
+
88
+ // A sentinel as it appears in text: the prefix and a SHA-256 in base64url.
89
+ let FOUND = new RegExp(`${SENTINEL}[\\w-]{43}`, 'g')
90
+
91
+ /** Every sentinel a text carries. */
92
+ export let sentinels = (text: string): string[] => text.match(FOUND) ?? []
93
+
94
+ /** The text with each sentinel `values` has a value for replaced by it,
95
+ * verbatim: the swap on the way out. */
96
+ export let swap = (text: string, values: Map<string, string>): string =>
97
+ text.replace(FOUND, (s) => values.get(s) ?? s)
package/signed.js ADDED
@@ -0,0 +1,107 @@
1
+ // A value nobody but the holder of a secret can have written, exported as
2
+ // `@yaks/secrets/signed`: the bearer tokens a server mints and later trusts
3
+ // with no store and no round trip. A token is `<body>.<mac>`: the body is
4
+ // base64url JSON, the mac HMAC-SHA256 over the body text.
5
+ //
6
+ // Every token is signed for a label, and every open names the one label it
7
+ // accepts. Each label signs under its own key, the HMAC of the label under the
8
+ // secret, so one secret serves many kinds of token and a token signed for one
9
+ // label fails the mac as any other. What a token carries is the caller's to
10
+ // shape, and its expiry is the caller's to check.
11
+ //
12
+ // WebCrypto only, so the same file runs in a Worker, in Deno, and in a browser.
13
+ import { fromBase64url, toBase64url } from "@yaks/fp";
14
+ let enc = new TextEncoder();
15
+ let dec = new TextDecoder();
16
+ /** HMAC-SHA256, the one algorithm every key here is for. */ export let HMAC = {
17
+ name: 'HMAC',
18
+ hash: 'SHA-256'
19
+ };
20
+ // Keys made once in an isolate and shared by signing and verification: a key
21
+ // is a WebCrypto call or three, and every request with a token needs one. The
22
+ // key is kept, not the promise of it, so no request waits on work another
23
+ // request started.
24
+ let keys = new Map();
25
+ let kept = async (id, make)=>{
26
+ let got = keys.get(id);
27
+ if (!got) keys.set(id, got = await make());
28
+ return got;
29
+ };
30
+ /** The secret's own key, kept apart from every label's key made under it. */ export let secretKey = (secret)=>kept(JSON.stringify([
31
+ secret
32
+ ]), ()=>crypto.subtle.importKey('raw', enc.encode(secret), HMAC, false, [
33
+ 'sign',
34
+ 'verify'
35
+ ]));
36
+ /** The label's own key: HMAC-SHA256 of the label under the secret. */ export let labelKey = (secret, label)=>kept(JSON.stringify([
37
+ label,
38
+ secret
39
+ ]), async ()=>crypto.subtle.importKey('raw', await crypto.subtle.sign('HMAC', await secretKey(secret), enc.encode(label)), HMAC, false, [
40
+ 'sign',
41
+ 'verify'
42
+ ]));
43
+ // Every token a key signed or verified, by its body. Signing is
44
+ // deterministic, so a body has one mac under a key: a repeat signs nothing,
45
+ // and an open of the exact token reuses the verification. Count and length
46
+ // bound the memory per key; the WeakMap lets it go with the key. Values and
47
+ // expiry decisions are never kept.
48
+ let known = new WeakMap();
49
+ let knownLimit = 256;
50
+ let tokenLimit = 4096;
51
+ let remember = (k, body, token)=>{
52
+ if (token.length > tokenLimit) return;
53
+ let seen = known.get(k);
54
+ if (!seen) known.set(k, seen = new Map());
55
+ seen.delete(body);
56
+ seen.set(body, token);
57
+ if (seen.size > knownLimit) seen.delete(seen.keys().next().value);
58
+ };
59
+ /** A token for `value` under a key from `labelKey` or `secretKey`. */ export let signedWith = async (k, value)=>{
60
+ let body = toBase64url(enc.encode(JSON.stringify(value)));
61
+ let token = known.get(k)?.get(body);
62
+ if (!token) {
63
+ let mac = await crypto.subtle.sign('HMAC', k, enc.encode(body));
64
+ token = `${body}.${toBase64url(new Uint8Array(mac))}`;
65
+ }
66
+ remember(k, body, token);
67
+ return token;
68
+ };
69
+ /** The value under a mac this key made, written as signing writes it, or
70
+ * null. A miss uses WebCrypto's constant-time verify; a hit reuses its result
71
+ * and parses the value afresh. */ export let openedWith = async (k, token)=>{
72
+ let dot = token.lastIndexOf('.');
73
+ if (dot < 0) return null;
74
+ let body = token.slice(0, dot);
75
+ try {
76
+ if (known.get(k)?.get(body) != token) {
77
+ // The mac's text must be the one signing wrote. A 32-byte mac is 43
78
+ // characters whose last carries two padding bits the decoder ignores,
79
+ // and the decoder takes padding and spaces too, so several texts name
80
+ // the same bytes: without this, a token with its last character edited
81
+ // still opened.
82
+ let text = token.slice(dot + 1);
83
+ let mac = fromBase64url(text);
84
+ if (toBase64url(mac) != text) return null;
85
+ let ok = await crypto.subtle.verify('HMAC', k, mac, enc.encode(body));
86
+ if (!ok) return null;
87
+ }
88
+ remember(k, body, token);
89
+ return JSON.parse(dec.decode(fromBase64url(body)));
90
+ } catch {
91
+ return null;
92
+ }
93
+ };
94
+ /** A token carrying `value`, signed for `label` under `secret`. */ export let signed = async (label, value, secret)=>signedWith(await labelKey(secret, label), value);
95
+ /** What a token carries, or null for anything but a well-formed token signed
96
+ * for this label under this secret. */ export let opened = async (label, token, secret)=>openedWith(await labelKey(secret, label), token);
97
+ /** What a token says it carries, read without the secret and so unverified:
98
+ * for a client to say whose token it holds and when it dies, never to trust. */ export let claimed = (token)=>{
99
+ let dot = token.lastIndexOf('.');
100
+ if (dot < 0) return null;
101
+ try {
102
+ return JSON.parse(dec.decode(fromBase64url(token.slice(0, dot))));
103
+ } catch {
104
+ return null;
105
+ }
106
+ };
107
+ //# sourceMappingURL=signed.js.map
package/signed.js.map ADDED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