The Coline App SDK: apps, tools, file types and surfaces that run inside Coline workspaces, and public websites with Coline Sites. TypeScript, with an in-memory test workspace. MIT.
| 4 | export const COLINE_TIMESTAMP_HEADER = "x-coline-timestamp"; |
| 5 | export const COLINE_DELIVERY_HEADER = "x-coline-delivery-id"; |
| 6 |
| 7 | function normalizeSecret(secret: string): string { |
| 8 | if (!secret || secret.trim().length < 16) { |
| 9 | throw new Error("Signing secret must be at least 16 characters."); |
| 10 | } |
| 11 |
| 12 | return secret; |
| 13 | } |
| 14 |
| 15 | async function importHmacKey(secret: string) { |
| 16 | return crypto.subtle.importKey( |
| 17 | "raw", |
| 18 | encoder.encode(normalizeSecret(secret)), |
| 19 | { name: "HMAC", hash: "SHA-256" }, |
| 20 | false, |
| 21 | ["sign", "verify"], |
| 22 | ); |
| 23 | } |
| 24 |
| 25 | function toHex(buffer: ArrayBuffer): string { |
| 26 | return [...new Uint8Array(buffer)] |
| 27 | .map((byte) => byte.toString(16).padStart(2, "0")) |
| 28 | .join(""); |
| 29 | } |
| 30 |
| 31 | export function buildSigningPayload(params: { |
| 32 | timestamp: string; |
| 33 | body: string; |
| 34 | }): string { |
| 35 | return `${params.timestamp}.${params.body}`; |
| 36 | } |
| 37 |
| 38 | export async function signAppRequest(params: { |
| 39 | secret: string; |
| 40 | timestamp: string; |
| 41 | body: string; |
| 42 | }): Promise<string> { |
| 43 | const key = await importHmacKey(params.secret); |
| 44 | const payload = buildSigningPayload({ |
| 45 | timestamp: params.timestamp, |
| 46 | body: params.body, |
| 47 | }); |
| 48 |
| 49 | const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload)); |
| 50 | return toHex(signature); |
| 51 | } |
| 52 |
| 53 | export async function createSignedAppRequestHeaders(params: { |
| 54 | secret: string; |
| 55 | body: string; |
| 56 | deliveryId: string; |
| 57 | timestamp?: string; |
| 58 | }): Promise<Record<string, string>> { |
| 59 | const timestamp = params.timestamp ?? new Date().toISOString(); |
| 60 | const signature = await signAppRequest({ |
| 61 | secret: params.secret, |
| 62 | timestamp, |
| 63 | body: params.body, |
| 64 | }); |
| 65 |
| 66 | return { |
| 67 | [COLINE_SIGNATURE_HEADER]: signature, |
| 68 | [COLINE_TIMESTAMP_HEADER]: timestamp, |
| 69 | [COLINE_DELIVERY_HEADER]: params.deliveryId, |
| 70 | }; |
| 71 | } |
| 72 |
| 73 | export async function verifyAppRequestSignature(params: { |
| 74 | secret: string; |
| 75 | timestamp: string; |
| 76 | body: string; |
| 77 | signature: string; |
| 78 | }): Promise<boolean> { |
| 79 | const expected = await signAppRequest({ |
| 80 | secret: params.secret, |
| 81 | timestamp: params.timestamp, |
| 82 | body: params.body, |
| 83 | }); |
| 84 |
| 85 | return expected === params.signature; |
| 86 | } |
| 87 |