tapimo 0.0.2 → 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.
Files changed (265) hide show
  1. package/README.md +11 -2
  2. package/dist/ApiKey.d.ts +12 -11
  3. package/dist/ApiKey.d.ts.map +1 -1
  4. package/dist/ApiKey.js +10 -12
  5. package/dist/ApiKey.js.map +1 -1
  6. package/dist/ApiKeys.d.ts +139 -0
  7. package/dist/ApiKeys.d.ts.map +1 -0
  8. package/dist/ApiKeys.js +166 -0
  9. package/dist/ApiKeys.js.map +1 -0
  10. package/dist/App.d.ts +920 -910
  11. package/dist/App.d.ts.map +1 -1
  12. package/dist/App.js +36 -12
  13. package/dist/App.js.map +1 -1
  14. package/dist/Handler.d.ts +86 -0
  15. package/dist/Handler.d.ts.map +1 -0
  16. package/dist/Handler.js +83 -0
  17. package/dist/Handler.js.map +1 -0
  18. package/dist/Scope.d.ts +4 -1
  19. package/dist/Scope.d.ts.map +1 -1
  20. package/dist/Scope.js +5 -1
  21. package/dist/Scope.js.map +1 -1
  22. package/dist/Webhooks.d.ts +3 -5
  23. package/dist/Webhooks.d.ts.map +1 -1
  24. package/dist/Webhooks.js +9 -2
  25. package/dist/Webhooks.js.map +1 -1
  26. package/dist/admin/Access.d.ts +1 -3
  27. package/dist/admin/Access.d.ts.map +1 -1
  28. package/dist/admin/Access.js +1 -3
  29. package/dist/admin/Access.js.map +1 -1
  30. package/dist/admin/App.d.ts +98 -209
  31. package/dist/admin/App.d.ts.map +1 -1
  32. package/dist/admin/App.js +2 -4
  33. package/dist/admin/App.js.map +1 -1
  34. package/dist/admin/apps/api-keys.d.ts +7 -5
  35. package/dist/admin/apps/api-keys.d.ts.map +1 -1
  36. package/dist/admin/apps/api-keys.js +8 -9
  37. package/dist/admin/apps/api-keys.js.map +1 -1
  38. package/dist/admin/apps/scopes.d.ts +3 -0
  39. package/dist/admin/apps/scopes.d.ts.map +1 -1
  40. package/dist/admin/apps/verified-tokens.d.ts +101 -215
  41. package/dist/admin/apps/verified-tokens.d.ts.map +1 -1
  42. package/dist/admin/apps/verified-tokens.js +17 -38
  43. package/dist/admin/apps/verified-tokens.js.map +1 -1
  44. package/dist/admin/ui.generated.d.ts +1 -1
  45. package/dist/admin/ui.generated.js +1 -1
  46. package/dist/apps/balances.d.ts +2 -2
  47. package/dist/apps/receipts.d.ts +43 -43
  48. package/dist/apps/tokens.d.ts +454 -454
  49. package/dist/apps/transactions.d.ts +43 -43
  50. package/dist/apps/transfers.d.ts +29 -29
  51. package/dist/apps/webhooks.d.ts +5 -2
  52. package/dist/apps/webhooks.d.ts.map +1 -1
  53. package/dist/apps/webhooks.js +38 -34
  54. package/dist/apps/webhooks.js.map +1 -1
  55. package/dist/{Cli.d.ts → cli/Cli.d.ts} +13 -2
  56. package/dist/cli/Cli.d.ts.map +1 -0
  57. package/dist/cli/Cli.js +19 -0
  58. package/dist/cli/Cli.js.map +1 -0
  59. package/dist/cli/bin.d.ts +3 -0
  60. package/dist/cli/bin.d.ts.map +1 -0
  61. package/dist/cli/bin.js +4 -0
  62. package/dist/cli/bin.js.map +1 -0
  63. package/dist/cli/commands/admin.d.ts +15 -0
  64. package/dist/cli/commands/admin.d.ts.map +1 -0
  65. package/dist/cli/commands/admin.js +60 -0
  66. package/dist/cli/commands/admin.js.map +1 -0
  67. package/dist/cloudflare.d.ts +7 -0
  68. package/dist/cloudflare.d.ts.map +1 -1
  69. package/dist/cloudflare.js +9 -0
  70. package/dist/cloudflare.js.map +1 -1
  71. package/dist/db/Db.d.ts +103 -0
  72. package/dist/db/Db.d.ts.map +1 -0
  73. package/dist/db/Db.js +274 -0
  74. package/dist/db/Db.js.map +1 -0
  75. package/dist/db/Schema.d.ts +88 -0
  76. package/dist/db/Schema.d.ts.map +1 -0
  77. package/dist/db/Schema.js +130 -0
  78. package/dist/db/Schema.js.map +1 -0
  79. package/dist/db/tables/organizations.d.ts +79 -0
  80. package/dist/db/tables/organizations.d.ts.map +1 -0
  81. package/dist/db/tables/organizations.js +81 -0
  82. package/dist/db/tables/organizations.js.map +1 -0
  83. package/dist/db/tables/verifiedTokens.d.ts +53 -0
  84. package/dist/db/tables/verifiedTokens.d.ts.map +1 -0
  85. package/dist/db/tables/verifiedTokens.js +74 -0
  86. package/dist/db/tables/verifiedTokens.js.map +1 -0
  87. package/dist/db/tables/webhookDeliveries.d.ts +71 -0
  88. package/dist/db/tables/webhookDeliveries.d.ts.map +1 -0
  89. package/dist/db/tables/webhookDeliveries.js +119 -0
  90. package/dist/db/tables/webhookDeliveries.js.map +1 -0
  91. package/dist/db/tables/webhookSubscriptions.d.ts +158 -0
  92. package/dist/db/tables/webhookSubscriptions.d.ts.map +1 -0
  93. package/dist/db/tables/webhookSubscriptions.js +272 -0
  94. package/dist/db/tables/webhookSubscriptions.js.map +1 -0
  95. package/dist/handlers/internal/executionError.d.ts +25 -0
  96. package/dist/handlers/internal/executionError.d.ts.map +1 -0
  97. package/dist/handlers/internal/executionError.js +184 -0
  98. package/dist/handlers/internal/executionError.js.map +1 -0
  99. package/dist/handlers/internal/multisig.d.ts +237 -0
  100. package/dist/handlers/internal/multisig.d.ts.map +1 -0
  101. package/dist/handlers/internal/multisig.js +567 -0
  102. package/dist/handlers/internal/multisig.js.map +1 -0
  103. package/dist/handlers/internal/requestListener.d.ts +124 -0
  104. package/dist/handlers/internal/requestListener.d.ts.map +1 -0
  105. package/dist/handlers/internal/requestListener.js +173 -0
  106. package/dist/handlers/internal/requestListener.js.map +1 -0
  107. package/dist/handlers/internal/sponsorship.d.ts +83 -0
  108. package/dist/handlers/internal/sponsorship.d.ts.map +1 -0
  109. package/dist/handlers/internal/sponsorship.js +103 -0
  110. package/dist/handlers/internal/sponsorship.js.map +1 -0
  111. package/dist/handlers/internal/types.d.ts +284 -0
  112. package/dist/handlers/internal/types.d.ts.map +1 -0
  113. package/dist/handlers/internal/types.js +2 -0
  114. package/dist/handlers/internal/types.js.map +1 -0
  115. package/dist/handlers/internal/utils.d.ts +34 -0
  116. package/dist/handlers/internal/utils.d.ts.map +1 -0
  117. package/dist/handlers/internal/utils.js +131 -0
  118. package/dist/handlers/internal/utils.js.map +1 -0
  119. package/dist/handlers/relay.d.ts +119 -0
  120. package/dist/handlers/relay.d.ts.map +1 -0
  121. package/dist/handlers/relay.js +1264 -0
  122. package/dist/handlers/relay.js.map +1 -0
  123. package/dist/index.d.ts +4 -2
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +4 -2
  126. package/dist/index.js.map +1 -1
  127. package/dist/internal/Auth.d.ts +16 -10
  128. package/dist/internal/Auth.d.ts.map +1 -1
  129. package/dist/internal/Auth.js +72 -12
  130. package/dist/internal/Auth.js.map +1 -1
  131. package/dist/internal/RpcSchema.d.ts +10 -0
  132. package/dist/internal/RpcSchema.d.ts.map +1 -0
  133. package/dist/internal/RpcSchema.js +2 -0
  134. package/dist/internal/RpcSchema.js.map +1 -0
  135. package/dist/internal/Store.d.ts +42 -3
  136. package/dist/internal/Store.d.ts.map +1 -1
  137. package/dist/internal/Store.js +65 -3
  138. package/dist/internal/Store.js.map +1 -1
  139. package/dist/internal/VerifiedTokens.d.ts +15 -34
  140. package/dist/internal/VerifiedTokens.d.ts.map +1 -1
  141. package/dist/internal/VerifiedTokens.js +115 -159
  142. package/dist/internal/VerifiedTokens.js.map +1 -1
  143. package/dist/internal/Webhooks.d.ts +49 -35
  144. package/dist/internal/Webhooks.d.ts.map +1 -1
  145. package/dist/internal/Webhooks.js +92 -205
  146. package/dist/internal/Webhooks.js.map +1 -1
  147. package/package.json +7 -2
  148. package/src/ApiKey.test.ts +3 -3
  149. package/src/ApiKey.ts +10 -12
  150. package/src/ApiKeys.test.ts +175 -0
  151. package/src/ApiKeys.ts +205 -0
  152. package/src/App.test-d.ts +1 -1
  153. package/src/App.test.ts +10768 -351
  154. package/src/App.ts +79 -36
  155. package/src/Client.test-d.ts +1 -1
  156. package/src/Handler.ts +154 -0
  157. package/src/Scope.ts +5 -1
  158. package/src/Webhooks.test.ts +8 -7
  159. package/src/Webhooks.ts +11 -5
  160. package/src/admin/Access.ts +1 -3
  161. package/src/admin/App.ts +19 -24
  162. package/src/admin/apps/api-keys.test.ts +19 -18
  163. package/src/admin/apps/api-keys.ts +8 -9
  164. package/src/admin/apps/scopes.test.ts +4 -0
  165. package/src/admin/apps/verified-tokens.test.ts +3 -30
  166. package/src/admin/apps/verified-tokens.ts +17 -36
  167. package/src/admin/ui.generated.ts +1 -1
  168. package/src/apps/balances.test.ts +4 -3
  169. package/src/apps/blocks.test.ts +1 -1
  170. package/src/apps/exchanges.test.ts +1 -1
  171. package/src/apps/indexer.test.ts +1 -1
  172. package/src/apps/receipts.test.ts +1 -1
  173. package/src/apps/rpc.test.ts +100 -10
  174. package/src/apps/tokenlist.test.ts +5 -7
  175. package/src/apps/tokens.test.ts +4 -3
  176. package/src/apps/transactions.test.ts +1 -1
  177. package/src/apps/transfers.test.ts +1 -1
  178. package/src/apps/verified-tokens.test.ts +24 -12
  179. package/src/apps/webhooks.test.ts +130 -143
  180. package/src/apps/webhooks.ts +45 -47
  181. package/src/{Cli.test.ts → cli/Cli.test.ts} +10 -9
  182. package/src/{Cli.ts → cli/Cli.ts} +16 -9
  183. package/src/cli/bin.ts +4 -0
  184. package/src/cli/commands/admin.test.ts +71 -0
  185. package/src/cli/commands/admin.ts +60 -0
  186. package/src/cloudflare.ts +10 -0
  187. package/src/db/Db.test.ts +84 -0
  188. package/src/db/Db.ts +383 -0
  189. package/src/db/Schema.ts +164 -0
  190. package/src/db/tables/organizations.test.ts +124 -0
  191. package/src/db/tables/organizations.ts +127 -0
  192. package/src/db/tables/verifiedTokens.ts +111 -0
  193. package/src/db/tables/webhookDeliveries.ts +159 -0
  194. package/src/db/tables/webhookSubscriptions.ts +358 -0
  195. package/src/handlers/internal/executionError.ts +205 -0
  196. package/src/handlers/internal/multisig.localnet.test.ts +146 -0
  197. package/src/handlers/internal/multisig.test.ts +744 -0
  198. package/src/handlers/internal/multisig.ts +858 -0
  199. package/src/handlers/internal/relay.localnet.test.ts +2035 -0
  200. package/src/handlers/internal/requestListener.ts +273 -0
  201. package/src/handlers/internal/sponsorship.ts +186 -0
  202. package/src/handlers/internal/types.ts +378 -0
  203. package/src/handlers/internal/utils.ts +153 -0
  204. package/src/handlers/relay.ts +1605 -0
  205. package/src/index.ts +4 -2
  206. package/src/internal/Auth.test.ts +21 -21
  207. package/src/internal/Auth.ts +92 -19
  208. package/src/internal/RateLimit.test.ts +1 -1
  209. package/src/internal/RpcSchema.ts +10 -0
  210. package/src/internal/Store.test.ts +98 -10
  211. package/src/internal/Store.ts +112 -6
  212. package/src/internal/VerifiedTokens.test.ts +99 -115
  213. package/src/internal/VerifiedTokens.ts +123 -175
  214. package/src/internal/Webhooks.test.ts +107 -107
  215. package/src/internal/Webhooks.ts +102 -220
  216. package/dist/ApiKeySource.d.ts +0 -166
  217. package/dist/ApiKeySource.d.ts.map +0 -1
  218. package/dist/ApiKeySource.js +0 -234
  219. package/dist/ApiKeySource.js.map +0 -1
  220. package/dist/Cli.d.ts.map +0 -1
  221. package/dist/Cli.js +0 -13
  222. package/dist/Cli.js.map +0 -1
  223. package/seeds/31318/icons/0x20c0000000000000000000000000000000000000.svg +0 -1
  224. package/seeds/31318/icons/0x20c0000000000000000000000000000000000001.svg +0 -1
  225. package/seeds/31318/icons/0x20c0000000000000000000000000000000000002.svg +0 -1
  226. package/seeds/31318/icons/0x20c0000000000000000000000000000000000003.svg +0 -1
  227. package/seeds/31318/verified-tokens.json +0 -30
  228. package/seeds/4217/icons/0x20c0000000000000000000000000000000000000.svg +0 -25
  229. package/seeds/4217/icons/0x20c000000000000000000000048c8f36df1c9a4a.svg +0 -1
  230. package/seeds/4217/icons/0x20c0000000000000000000000520792dcccccccc.svg +0 -1
  231. package/seeds/4217/icons/0x20c0000000000000000000000a6da882d075a4c3.svg +0 -4
  232. package/seeds/4217/icons/0x20c000000000000000000000111111111e910f0f.svg +0 -30
  233. package/seeds/4217/icons/0x20c00000000000000000000014f22ca97301eb73.svg +0 -1
  234. package/seeds/4217/icons/0x20c0000000000000000000001621e21f71cf12fb.svg +0 -1
  235. package/seeds/4217/icons/0x20c0000000000000000000002f52d5cc21a3207b.svg +0 -1
  236. package/seeds/4217/icons/0x20c0000000000000000000003158081efd85bfc2.svg +0 -11
  237. package/seeds/4217/icons/0x20c0000000000000000000003554d28269e0f3c2.svg +0 -1
  238. package/seeds/4217/icons/0x20c000000000000000000000383a23bacb546ab9.svg +0 -1
  239. package/seeds/4217/icons/0x20c00000000000000000000042109aef2f8b28e1.png +0 -0
  240. package/seeds/4217/icons/0x20c0000000000000000000005c0bac7cef389a11.svg +0 -1
  241. package/seeds/4217/icons/0x20c0000000000000000000006fd9a167923ba194.png +0 -0
  242. package/seeds/4217/icons/0x20c0000000000000000000007f7ba549dd0251b9.svg +0 -1
  243. package/seeds/4217/icons/0x20c0000000000000000000008191667423f70e67.svg +0 -5
  244. package/seeds/4217/icons/0x20c0000000000000000000008ee4fcff88888888.svg +0 -1
  245. package/seeds/4217/icons/0x20c0000000000000000000009a4a4b17e0dc6651.svg +0 -1
  246. package/seeds/4217/icons/0x20c000000000000000000000ab02d39df30bd17e.svg +0 -1
  247. package/seeds/4217/icons/0x20c000000000000000000000ae247a1130450f09.svg +0 -1
  248. package/seeds/4217/icons/0x20c000000000000000000000aeed2ec36a54d0e5.svg +0 -1
  249. package/seeds/4217/icons/0x20c000000000000000000000b9537d11c60e8b50.svg +0 -1
  250. package/seeds/4217/icons/0x20c000000000000000000000bd95bfb69fbe6ce3.svg +0 -1
  251. package/seeds/4217/icons/0x20c000000000000000000000c412ec89d0c08be5.svg +0 -1
  252. package/seeds/4217/icons/0x20c000000000000000000000f047dd7018e50367.png +0 -0
  253. package/seeds/4217/verified-tokens.json +0 -177
  254. package/seeds/42431/icons/0x20c0000000000000000000000000000000000000.svg +0 -25
  255. package/seeds/42431/icons/0x20c0000000000000000000000000000000000001.svg +0 -1
  256. package/seeds/42431/icons/0x20c0000000000000000000000000000000000002.svg +0 -1
  257. package/seeds/42431/icons/0x20c0000000000000000000000000000000000003.svg +0 -1
  258. package/seeds/42431/icons/0x20c0000000000000000000009e8d7eb59b783726.svg +0 -1
  259. package/seeds/42431/icons/0x20c000000000000000000000d72572838bbee59c.svg +0 -1
  260. package/seeds/42431/verified-tokens.json +0 -44
  261. package/seeds/openrpc/README.md +0 -27
  262. package/seeds/openrpc/execution-apis.json +0 -8989
  263. package/src/ApiKeySource.test-d.ts +0 -11
  264. package/src/ApiKeySource.test.ts +0 -295
  265. package/src/ApiKeySource.ts +0 -303
@@ -0,0 +1,175 @@
1
+ import * as ApiKeys from './ApiKeys.js'
2
+ import * as Store from './internal/Store.js'
3
+
4
+ describe('resolve', () => {
5
+ test('resolves an unknown token to null', async () => {
6
+ expect(await ApiKeys.resolve(Store.memory(), 'tempo:sk:missing')).toBeNull()
7
+ })
8
+
9
+ test('resolves before expiry, rejects after', async () => {
10
+ vi.useFakeTimers({ now: new Date('2026-01-01T00:00:00.000Z') })
11
+ try {
12
+ const state = Store.memory()
13
+ const { token } = await ApiKeys.mint(state, {
14
+ expiresAt: '2026-01-01T00:01:00.000Z',
15
+ orgId: 'org_a',
16
+ scopes: ['data:read'],
17
+ })
18
+
19
+ expect((await ApiKeys.resolve(state, token))?.orgId).toBe('org_a')
20
+
21
+ // Advance the clock past the expiry.
22
+ vi.setSystemTime(new Date('2026-01-01T00:02:00.000Z'))
23
+ expect(await ApiKeys.resolve(state, token)).toBeNull()
24
+ } finally {
25
+ vi.useRealTimers()
26
+ }
27
+ })
28
+
29
+ test('treats a corrupt record as absent', async () => {
30
+ const state = Store.memory()
31
+ const { token } = await ApiKeys.mint(state, { orgId: 'org_a', scopes: ['data:read'] })
32
+ // Overwrite the stored record (keyed by token hash) with invalid JSON.
33
+ const { keys } = await state.list({ prefix: 'apikey:' })
34
+ await state.put(keys[0]!.name, 'not json')
35
+ expect(await ApiKeys.resolve(state, token)).toBeNull()
36
+ })
37
+
38
+ test('rejects a record with an unknown scope', async () => {
39
+ const state = Store.memory()
40
+ const { token } = await ApiKeys.mint(state, { orgId: 'org_a', scopes: ['data:read'] })
41
+ const { keys } = await state.list({ prefix: 'apikey:' })
42
+ await state.put(
43
+ keys[0]!.name,
44
+ JSON.stringify({
45
+ createdAt: '2026-01-01T00:00:00.000Z',
46
+ id: 'key_x',
47
+ orgId: 'org_a',
48
+ scopes: ['data:read', 'totally:made-up'],
49
+ tokenLast4: 'xxxx',
50
+ }),
51
+ )
52
+ expect(await ApiKeys.resolve(state, token)).toBeNull()
53
+ })
54
+ })
55
+
56
+ // Mock the system clock so timestamps are deterministic without injecting a
57
+ // clock into the module.
58
+ describe('mint', () => {
59
+ beforeEach(() => vi.useFakeTimers({ now: new Date('2026-01-01T00:00:00.000Z') }))
60
+ afterEach(() => vi.useRealTimers())
61
+
62
+ test('mints a key and resolves it', async () => {
63
+ const state = Store.memory()
64
+
65
+ const { record, token } = await ApiKeys.mint(state, {
66
+ createdBy: 'admin@tempo.xyz',
67
+ name: 'CI key',
68
+ orgId: 'org_acme',
69
+ scopes: ['data:read', 'webhooks:write'],
70
+ })
71
+
72
+ expect(token).toMatch(/^tempo:sk:[a-f0-9]{48}$/)
73
+ expect(record.tokenLast4).toBe(token.slice(-4))
74
+ expect({ ...record, id: '<id>', tokenLast4: '<last4>' }).toMatchInlineSnapshot(`
75
+ {
76
+ "createdAt": "2026-01-01T00:00:00.000Z",
77
+ "createdBy": "admin@tempo.xyz",
78
+ "environment": "production",
79
+ "id": "<id>",
80
+ "name": "CI key",
81
+ "orgId": "org_acme",
82
+ "scopes": [
83
+ "data:read",
84
+ "webhooks:write",
85
+ ],
86
+ "tokenLast4": "<last4>",
87
+ }
88
+ `)
89
+
90
+ const resolved = await ApiKeys.resolve(state, token)
91
+ expect(resolved?.orgId).toBe('org_acme')
92
+ expect(resolved?.scopes).toEqual(['data:read', 'webhooks:write'])
93
+ })
94
+
95
+ test('rejects an unknown scope at the write boundary', async () => {
96
+ await expect(
97
+ ApiKeys.mint(Store.memory(), { orgId: 'org_a', scopes: ['totally:made-up' as never] }),
98
+ ).rejects.toThrowError(/invalid API key input/)
99
+ })
100
+ })
101
+
102
+ describe('list', () => {
103
+ beforeEach(() => vi.useFakeTimers({ now: new Date('2026-01-01T00:00:00.000Z') }))
104
+ afterEach(() => vi.useRealTimers())
105
+
106
+ test('lists keys newest first, filtered by org', async () => {
107
+ const state = Store.memory()
108
+
109
+ // Advance the clock between mints so their createdAt timestamps differ and
110
+ // "newest first" is well-defined.
111
+ await ApiKeys.mint(state, { name: 'a', orgId: 'org_a', scopes: ['data:read'] })
112
+ vi.setSystemTime(new Date('2026-01-01T00:00:01.000Z'))
113
+ await ApiKeys.mint(state, { name: 'b', orgId: 'org_b', scopes: ['data:read'] })
114
+
115
+ const all = await ApiKeys.list(state)
116
+ expect(all.map((record) => record.name)).toMatchInlineSnapshot(`
117
+ [
118
+ "b",
119
+ "a",
120
+ ]
121
+ `)
122
+
123
+ const scoped = await ApiKeys.list(state, { orgId: 'org_b' })
124
+ expect(scoped.map((record) => record.orgId)).toMatchInlineSnapshot(`
125
+ [
126
+ "org_b",
127
+ ]
128
+ `)
129
+ })
130
+
131
+ test('excludes a key past its expiry', async () => {
132
+ const state = Store.memory()
133
+
134
+ await ApiKeys.mint(state, {
135
+ expiresAt: '2026-01-01T00:00:30.000Z',
136
+ name: 'short-lived',
137
+ orgId: 'org_a',
138
+ scopes: ['data:read'],
139
+ })
140
+
141
+ expect((await ApiKeys.list(state)).map((record) => record.name)).toMatchInlineSnapshot(`
142
+ [
143
+ "short-lived",
144
+ ]
145
+ `)
146
+
147
+ // Advance the clock past the expiry.
148
+ vi.setSystemTime(new Date('2026-01-01T00:01:00.000Z'))
149
+ expect(await ApiKeys.list(state)).toMatchInlineSnapshot(`[]`)
150
+ })
151
+ })
152
+
153
+ describe('revoke', () => {
154
+ test('revokes a key by id', async () => {
155
+ const state = Store.memory()
156
+
157
+ const { record, token } = await ApiKeys.mint(state, { orgId: 'org_a', scopes: ['data:read'] })
158
+
159
+ expect(await ApiKeys.revoke(state, record.id)).toBe(true)
160
+ expect(await ApiKeys.resolve(state, token)).toBeNull()
161
+ expect(await ApiKeys.revoke(state, record.id)).toBe(false)
162
+ })
163
+
164
+ test('revoke is O(1): deletes the record without scanning the prefix', async () => {
165
+ const state = Store.memory()
166
+
167
+ const { record } = await ApiKeys.mint(state, { orgId: 'org_a', scopes: ['data:read'] })
168
+
169
+ // The id index entry maps id -> record key; revoke uses it directly.
170
+ expect(await ApiKeys.revoke(state, record.id)).toBe(true)
171
+ // Both the record and its id index entry are gone.
172
+ const { keys } = await state.list({ prefix: 'apikey' })
173
+ expect(keys).toMatchInlineSnapshot(`[]`)
174
+ })
175
+ })
package/src/ApiKeys.ts ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * API-key persistence over the app's KV state store (`App.create({ kv })`).
3
+ *
4
+ * Records are keyed by token hash (`ApiKey.keyFor`) — the plaintext token is
5
+ * never stored — and validated against the scope catalog on read; unknown,
6
+ * corrupt, expired, or invalid records resolve to `null`. An `id → recordKey`
7
+ * index makes revoke-by-id O(1). The persisted {@link Record}/{@link
8
+ * MintInput} shapes live here (derived from `ApiKey.schema` so they cannot
9
+ * drift from the resolved shape), while the shared credential primitives
10
+ * (token format/generation, storage-key derivation, redaction) live in
11
+ * `./ApiKey.js`.
12
+ */
13
+
14
+ import * as z from 'zod/mini'
15
+
16
+ import * as ApiKey from './ApiKey.js'
17
+ import type * as Store from './internal/Store.js'
18
+
19
+ /** Zod schemas owned by the API-keys module. */
20
+ export namespace schema {
21
+ /**
22
+ * Fields accepted when minting a key, and the single source of truth for the
23
+ * {@link MintInput} type and `mint` validation. Derived from the resolved
24
+ * `ApiKey.schema` (minus the generated `id`) so the scope vocabulary stays in
25
+ * lockstep with the resolved shape.
26
+ */
27
+ export const MintInput = z.extend(z.omit(ApiKey.schema.ApiKey, { id: true }), {
28
+ createdBy: z
29
+ .optional(z.string())
30
+ .check(z.describe('Identity creating the key (e.g. admin email), recorded for audit.')),
31
+ expiresAt: z
32
+ .optional(z.string())
33
+ .check(z.describe('ISO 8601 expiry timestamp. Omit for a non-expiring key.')),
34
+ // TODO: make required once orgs exist.
35
+ orgId: z.optional(z.string()).check(z.describe('Owning organization id.')),
36
+ })
37
+
38
+ /**
39
+ * A persisted API-key record: the resolved `ApiKey.schema` plus
40
+ * persistence/display fields. Extending the resolved schema keeps the resolved
41
+ * and persisted shapes in lockstep.
42
+ */
43
+ export const Record = z.extend(ApiKey.schema.ApiKey, {
44
+ createdAt: z.string().check(z.describe('ISO 8601 creation timestamp.')),
45
+ createdBy: z.optional(z.string()).check(z.describe('Identity that created the key.')),
46
+ expiresAt: z.optional(z.string()).check(z.describe('ISO 8601 expiry timestamp.')),
47
+ tokenLast4: z.string().check(z.describe('Last 4 chars of the plaintext token.')),
48
+ })
49
+ }
50
+
51
+ /**
52
+ * A durable API-key record as persisted. A superset of the resolved
53
+ * `ApiKey.ApiKey` with provisioning/display metadata. The plaintext token is
54
+ * never stored — records are keyed by its hash (`ApiKey.keyFor`) and carry only
55
+ * `tokenLast4` for display.
56
+ */
57
+ export type Record = z.output<typeof schema.Record>
58
+
59
+ /**
60
+ * Fields accepted when minting a key via {@link mint}. Uses the schema's
61
+ * *input* type so defaulted fields (e.g. `environment`) are optional for
62
+ * callers — the default is applied during `mint`'s validation.
63
+ */
64
+ export type MintInput = z.input<typeof schema.MintInput>
65
+
66
+ /** Result of {@link mint}: the persisted record and its one-time token. */
67
+ export type MintResult = {
68
+ /** The persisted key record (metadata only — never the token). */
69
+ record: Record
70
+ /** The plaintext token, shown once and unrecoverable afterward. */
71
+ token: string
72
+ }
73
+
74
+ /**
75
+ * Mints a key: validates the input (e.g. rejects an unknown scope at the write
76
+ * boundary), persists its hashed record, and returns the record plus the
77
+ * one-time plaintext token (shown once, unrecoverable afterward).
78
+ *
79
+ * @param state - The KV state store holding key records.
80
+ * @param input - The key to mint.
81
+ * @returns The persisted record and its one-time token.
82
+ */
83
+ export async function mint(state: Store.State, input: MintInput): Promise<MintResult> {
84
+ const valid = schema.MintInput.safeParse(input)
85
+ if (!valid.success) throw new Error(`invalid API key input: ${z.prettifyError(valid.error)}`)
86
+ const data = valid.data
87
+
88
+ const time = new Date()
89
+ const token = ApiKey.generateToken(data.environment)
90
+ const recordKey = ApiKey.keyFor(token)
91
+ const id = ApiKey.generateId()
92
+ const record: Record = {
93
+ createdAt: time.toISOString(),
94
+ environment: data.environment,
95
+ id,
96
+ // TODO: drop fallback once a real org concept exists.
97
+ orgId: data.orgId ?? id,
98
+ scopes: data.scopes,
99
+ tokenLast4: token.slice(-4),
100
+ ...(data.createdBy === undefined ? {} : { createdBy: data.createdBy }),
101
+ ...(data.expiresAt === undefined ? {} : { expiresAt: data.expiresAt }),
102
+ ...(data.name === undefined ? {} : { name: data.name }),
103
+ ...(data.rateLimits === undefined ? {} : { rateLimits: data.rateLimits }),
104
+ }
105
+
106
+ // Bound the stored record by its expiry so the backend evicts it natively.
107
+ const ttl =
108
+ data.expiresAt === undefined
109
+ ? undefined
110
+ : Math.max(1, Date.parse(data.expiresAt) - time.getTime())
111
+ await state.put(recordKey, JSON.stringify(record), { ttl })
112
+ // Index `id → recordKey` so revoke-by-id is O(1) (records are keyed by
113
+ // token hash, unrecoverable from the id alone). Shares the record's TTL so
114
+ // both entries expire together.
115
+ await state.put(idKeyFor(record.id), recordKey, { ttl })
116
+ return { record, token }
117
+ }
118
+
119
+ /**
120
+ * Resolves a plaintext API key token to its metadata, or `null`. Expiry is
121
+ * enforced on read — not just via the store's native TTL — so it holds on
122
+ * backends that evict lazily and regardless of TTL granularity.
123
+ *
124
+ * @param state - The KV state store holding key records.
125
+ * @param token - The presented plaintext token.
126
+ * @returns The resolved key metadata, or `null`.
127
+ */
128
+ export async function resolve(state: Store.State, token: string): Promise<ApiKey.ApiKey | null> {
129
+ return read(state, ApiKey.keyFor(token), Date.now())
130
+ }
131
+
132
+ /**
133
+ * Lists key records (metadata only — never tokens), newest first. Expired or
134
+ * catalog-invalid records are skipped.
135
+ *
136
+ * @param state - The KV state store holding key records.
137
+ * @param options - Optional owner filter.
138
+ * @returns The records.
139
+ */
140
+ export async function list(
141
+ state: Store.State,
142
+ options: list.Options = {},
143
+ ): Promise<readonly Record[]> {
144
+ const { keys } = await state.list({ prefix: ApiKey.recordPrefix })
145
+ const records: Record[] = []
146
+ for (const { name } of keys) {
147
+ const record = await read(state, name, Date.now())
148
+ if (record && (!options.orgId || record.orgId === options.orgId)) records.push(record)
149
+ }
150
+ // Newest first; ids are random, so sort by creation time.
151
+ return records.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
152
+ }
153
+
154
+ export declare namespace list {
155
+ /** Options for {@link list}. */
156
+ type Options = {
157
+ /** Restrict results to keys owned by this organization. */
158
+ orgId?: string | undefined
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Revokes a key by id, deleting its record and index entry.
164
+ *
165
+ * @param state - The KV state store holding key records.
166
+ * @param id - The key id (`key_…`).
167
+ * @returns Whether a matching record was deleted.
168
+ */
169
+ export async function revoke(state: Store.State, id: string): Promise<boolean> {
170
+ const recordKey = await state.get(idKeyFor(id))
171
+ if (!recordKey) return false
172
+ await state.delete(recordKey)
173
+ await state.delete(idKeyFor(id))
174
+ return true
175
+ }
176
+
177
+ /**
178
+ * Reads and validates a stored record by storage key. Invalid, corrupt, or
179
+ * expired records (`expiresAt <= now`) resolve to `null`.
180
+ */
181
+ async function read(state: Store.State, key: string, now: number): Promise<Record | null> {
182
+ const raw = await state.get(key)
183
+ if (!raw) return null
184
+ const value = (() => {
185
+ try {
186
+ return JSON.parse(raw) as unknown
187
+ } catch {
188
+ return undefined
189
+ }
190
+ })()
191
+ if (value === undefined) return null
192
+ const parsed = schema.Record.safeParse(value)
193
+ if (!parsed.success) return null
194
+ const record = parsed.data
195
+ if (record.expiresAt !== undefined && Date.parse(record.expiresAt) <= now) return null
196
+ return record
197
+ }
198
+
199
+ /** Storage-key prefix for the `id → recordKey` index. */
200
+ const idPrefix = 'apikey_id:'
201
+
202
+ /** Storage key under which a key's `id → recordKey` index entry is persisted. */
203
+ function idKeyFor(id: string): string {
204
+ return `${idPrefix}${id}`
205
+ }
package/src/App.test-d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { App, Auth } from 'cadent'
1
+ import type { App, Auth } from 'tapimo'
2
2
 
3
3
  describe('App.Endpoint', () => {
4
4
  // Smoke-test that `App.Endpoint` narrows to the inferred route surface so